To accommodate the new requirements for handling *.page.html files, we will make several key updates to your project's build pipeline. Here's an overview of the changes:
-
Clone the Components Compilation Pipeline for Pages: We'll extend the existing component.js functionality to handle pages, ensuring that pages have similar structures and features post-compilation.
-
Encapsulate Pages in Classes: Each *.page.html file will be compiled into a unique class following the naming convention _Page{number}.
-
Generate and Inject a Router Class: A Router class will be generated during the compilation process, which manages the registration and rendering of pages based on the current route. This class will be injected into index.html.
-
Update compiler.js: The compiler will now process both components and pages, compile them appropriately, and handle the injection of scripts into index.html.
Let's dive into the detailed implementation of these changes.
1. Update component.js to Support Page Compilation
First, we'll enhance component.js to include functionality for compiling pages. We'll introduce a new function generatePageClassCode to handle page-specific class generation.
// cat/src/component.js
const fs = require('fs-extra');
const path = require('path');
const acorn = require('acorn'); // Import Acorn for JavaScript parsing
const { parseDocument } = require('htmlparser2');
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string }>} - Component details.
*/
async function parseComponent(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the outermost tag name and inner HTML
const componentRegex = /<([\w-]+)>([\s\S]*?)<\/\1>/;
const componentMatch = content.match(componentRegex);
if (!componentMatch) {
throw new Error(`Invalid component structure in ${path.basename(filePath)}`);
}
const tagName = componentMatch[1];
let innerContent = componentMatch[2];
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(content)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all <style> sections
const styleRegex = /<style>([\s\S]*?)<\/style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all <script> and <style> tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
return {
tagName,
html: innerContent,
script: scriptContent,
style: styleContent,
};
}
/**
* Parse a page file to extract route, className, HTML, script, and style sections.
* @param {string} filePath - Path to the .page.html file.
* @param {number} pageNumber - Unique number for the page class.
* @returns {Promise<{ route: string, className: string, html: string, script: string, style: string }>} - Page details.
*/
async function parsePage(filePath, pageNumber) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the <page> tag with route attribute
const pageTagRegex = /<page\s+[^>]*route=["']([^"']+)["'][^>]*>([\s\S]*?)<\/page>/i;
const pageMatch = content.match(pageTagRegex);
if (!pageMatch) {
throw new Error(`No valid <page> tag with 'route' attribute found in ${path.basename(filePath)}`);
}
const route = pageMatch[1];
const innerContent = pageMatch[2].trim();
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(innerContent)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all <style> sections
const styleRegex = /<style>([\s\S]*?)<\/style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(innerContent)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all <script> and <style> tags from innerContent
const html = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
const className = `_Page${pageNumber}`;
return {
route,
className,
html,
script: scriptContent,
style: styleContent,
};
}
/**
* Generate the class code for a component.
* @param {object} component - Component details.
* @returns {string} - The compiled class code.
*/
function generateClassCode({ tagName, html, style, properties, methods }) {
const className = toPascalCase(tagName);
let classCode = `class ${className} extends HTMLElement {
constructor() {
super();
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = ${prop.value};
`;
});
classCode += `
this.attachShadow({ mode: 'open' });
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${style}
\`;
fragment.appendChild(style);
`;
}
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
`;
// Attach event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classCode += ` }
disconnectedCallback() {
`;
// Remove event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVarName}.removeEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classCode += ` }
`;
// Generate getters and setters
Object.keys(cachedNodes).forEach(propName => {
const nodes = cachedNodes[propName];
classCode += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
nodes.forEach(node => {
if (node.type === 'text') {
classCode += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classCode += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classCode += ` }
}
`;
});
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classCode += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
classCode += `}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
/**
* Generate the class code for a page.
* @param {object} page - Page details.
* @returns {string} - The compiled class code.
*/
function generatePageClassCode({ className, html, style, properties, methods }) {
let classCode = `class ${className} {
constructor() {
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${style}
\`;
fragment.appendChild(style);
`;
}
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
this.element = fragment;
}
render(parent) {
parent.appendChild(this.element);
}
`;
// Generate getters and setters
Object.keys(cachedNodes).forEach(propName => {
const nodes = cachedNodes[propName];
classCode += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
nodes.forEach(node => {
if (node.type === 'text') {
classCode += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classCode += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classCode += ` }
}
`;
});
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classCode += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
classCode += `}
// No need to define as custom element
`;
return classCode;
}
/**
* Convert a kebab-case or other tag name to PascalCase for class naming.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase string.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Escape backticks in templates to avoid breaking template literals.
* @param {string} str - The template string.
* @returns {string} - Escaped string.
*/
function escapeBackticks(str) {
return str.replace(/`/g, '\\`');
}
/**
* Transform method body to replace variable references with 'this.' prefix.
* @param {string} body - The method body.
* @param {Array<string>} propNames - The property names to replace.
* @returns {string} - The transformed method body.
*/
function transformMethodBody(body, propNames) {
let transformedBody = body;
propNames.forEach(propName => {
// Replace assignments like 'propName = value;' with 'this.propName = value;'
const assignRegex = new RegExp(`([^\\.\\w$])${propName}\\s*=`, 'g');
transformedBody = transformedBody.replace(assignRegex, `$1this.${propName} =`);
// Replace variable references with 'this.propName'
const varRegex = new RegExp(`([^\\.\\w$])${propName}([^\\w$])`, 'g');
transformedBody = transformedBody.replace(varRegex, `$1this.${propName}$2`);
});
// Ensure braces are correctly balanced and formatted
transformedBody = transformedBody.trim();
// Remove extra outer braces if they exist
if (transformedBody.startsWith('{') && transformedBody.endsWith('}')) {
transformedBody = transformedBody.slice(1, -1).trim();
}
// Properly indent the method body
transformedBody = transformedBody
.split('\n')
.map(line => ' ' + line.trim())
.join('\n');
return transformedBody;
}
/**
* Generate DOM creation code from HTML using htmlparser2.
* @param {string} html - The inner HTML string.
* @returns {object} - Object containing generated code, cached nodes, and event listeners.
*/
function generateDOMCode(html) {
const dom = parseDocument(html).children; // Array of DOM nodes
let code = '';
let varCounter = 0;
const cachedNodes = {}; // For properties to nodes
const eventListeners = [];
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const varName = node.name + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (needsReference(node)) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
code += ` ${declaration} = document.createElement('${node.name}');
`;
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (attrName === 'class' || attrName === 'style' || attrName.startsWith('data-') || attrName === 'id' || attrName === 'src' || attrName === 'alt') {
// Handle attributes with embedded expressions
const { expression, propNames } = generateAttributeExpression(attrValue);
code += ` ${varReference}.setAttribute('${attrName}', ${expression});
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'attribute',
elementVarName: varReference.replace(/^this\./, ''),
attrName: attrName,
expression: generateAttributeExpression(attrValue).expression,
});
});
} else if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue.replace(/\(\)$/, '').trim();
eventListeners.push({ elementVarName: varReference.replace(/^this\./, ''), event, handlerName });
} else {
// For other attributes
code += ` ${varReference}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Append to parent
const parentRef = parentVarName ? parentVarName : 'fragment';
code += ` ${parentRef}.appendChild(${varReference});
`;
// Traverse children
if (node.children && node.children.length) {
for (let child of node.children) {
traverse(child, varReference);
}
}
} else if (node.type === 'text') {
const textContent = node.data;
if (textContent.trim()) {
// Handle text nodes with expressions
const { expression, propNames } = generateTextExpression(textContent);
const varName = 'textNode' + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (expression.includes('this._')) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
code += ` ${declaration} = document.createTextNode(${expression});
`;
code += ` ${parentVarName}.appendChild(${varReference});
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'text',
varName: varReference.replace(/^this\./, ''),
expression: generateTextExpression(textContent).expression,
});
});
}
}
}
function needsReference(node) {
// Determines if the element needs to be assigned to 'this.'
// Elements that are:
// - Targets of event listeners
// - Contain reactive expressions
// Need to be accessible outside of _buildDOM
if (node.attribs) {
const hasEventListener = Object.keys(node.attribs).some(attr => attr.startsWith('on'));
const hasReactiveAttr = Object.values(node.attribs).some(value => /\{([\w$]+)\}/.test(value));
if (hasEventListener || hasReactiveAttr) {
return true;
}
}
if (node.children && node.children.some(child => child.type === 'text' && /\{([\w$]+)\}/.test(child.data))) {
return true;
}
return false;
}
function generateTextExpression(textContent) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(textContent)) !== null) {
if (match.index > lastIndex) {
segments.push(JSON.stringify(textContent.slice(lastIndex, match.index)));
}
segments.push(`this._${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(JSON.stringify(textContent.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
function generateAttributeExpression(attrValue) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(attrValue)) !== null) {
if (match.index > lastIndex) {
segments.push(JSON.stringify(attrValue.slice(lastIndex, match.index)));
}
segments.push(`this._${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners };
}
module.exports = {
parseComponent,
parsePage,
toPascalCase,
escapeBackticks,
generateClassCode,
generatePageClassCode,
transformMethodBody,
generateDOMCode
};
Explanation:
-
parsePage Function:
- Purpose: Parses a
.page.html file to extract the route, class name, HTML content, script, and style.
- Process:
- Extracts the
<page> tag with the route attribute.
- Removes
<script> and <style> tags from the inner content to isolate the HTML structure.
- Generates a unique class name following the
_Page{number} convention.
-
generatePageClassCode Function:
- Purpose: Generates the JavaScript class code for a page.
- Differences from
generateClassCode:
- Pages are not custom elements; hence, they don't extend
HTMLElement.
- Pages have a
render method to append their content to a parent element.
- Usage: Similar to components, but tailored for page-specific functionalities.
-
Reusability:
- Shared utility functions like
toPascalCase, transformMethodBody, and generateDOMCode are reused for both components and pages.
2. Update page.js to Facilitate Page Compilation
We'll extend page.js to handle the compilation of pages into classes and assist in generating the Router class.
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { parsePage, generatePageClassCode } = require('./component'); // Reuse functions from component.js
/**
* Compile all .page.html files into JavaScript classes.
* @param {string} projectRoot - The root directory of the project.
* @returns {Promise<{ pages: Array, routerEntries: Array }>} - Compiled pages and router entries.
*/
async function compilePages(projectRoot) {
// Find all .page.html files in the project directory
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const pages = [];
const routerEntries = [];
let pageNumber = 1; // To generate unique class names
for (const file of pageFiles) {
try {
const { route, className, html, script, style } = await parsePage(file, pageNumber);
const { properties, methods } = parseScript(script); // Assuming parseScript is exported
const classCode = generatePageClassCode({
className,
html,
style,
properties,
methods,
});
pages.push(classCode);
routerEntries.push({ route, className });
console.log(`🔍 Parsed and compiled page: [Route: ${route}] -> Class: ${className} from ${path.relative(projectRoot, file)}`);
pageNumber++;
} catch (error) {
console.error(`❌ Failed to parse ${file}: ${error.message}`);
}
}
if (pages.length === 0) {
console.warn('⚠️ No pages found to compile.');
}
return { pages, routerEntries };
}
/**
* Generate the Router class code.
* @param {Array} routerEntries - Array of route and className objects.
* @returns {string} - The compiled Router class code.
*/
function generateRouterClassCode(routerEntries) {
let classCode = `class Router {
constructor() {
this.routes = {
`;
routerEntries.forEach(entry => {
classCode += ` "${entry.route}": ${entry.className},
`;
});
classCode += ` };
}
init() {
document.querySelectorAll('load[route]').forEach(loadElement => {
const route = loadElement.getAttribute('route');
const PageClass = this.routes[route];
if (PageClass) {
const pageInstance = new PageClass();
pageInstance.render(loadElement);
} else {
console.warn(\`⚠️ No page found for route "\${route}".\`);
}
});
}
}
const router = new Router();
window.addEventListener('DOMContentLoaded', () => {
router.init();
});
`;
return classCode;
}
module.exports = {
compilePages,
generateRouterClassCode
};
Explanation:
-
compilePages Function:
- Purpose: Compiles all
.page.html files into JavaScript classes.
- Process:
- Iterates through each
.page.html file.
- Parses each file to extract necessary details.
- Generates the corresponding class code.
- Collects router entries mapping routes to class names for Router initialization.
-
generateRouterClassCode Function:
- Purpose: Generates the
Router class responsible for managing page rendering based on routes.
- Functionality:
- Maintains a
routes object mapping routes to their respective page classes.
- On initialization, it searches for all
<load route="path"> elements in the DOM and renders the corresponding page by instantiating the associated class.
-
Assumptions:
parseScript function is available and exported from component.js. If not, ensure to export it or implement it within page.js.
3. Update compiler.js to Integrate Page Compilation and Router Generation
We'll modify compiler.js to handle both components and pages, compile them, and inject the necessary scripts into index.html.
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { parseComponent, parseScript, generateClassCode, transformMethodBody, generateDOMCode, parsePage, generatePageClassCode } = require('./component');
const { compilePages, generateRouterClassCode } = require('./page.js');
const { parseDocument } = require('htmlparser2');
/**
* Detect used components in the provided HTML contents by parsing the HTML tags.
* @param {Array<string>} htmlContents - Array of HTML file contents.
* @param {Set<string>} availableComponents - Set of all available component tag names.
* @returns {Set<string>} - Set of used component tag names.
*/
function detectUsedComponents(htmlContents, availableComponents) {
const usedComponents = new Set();
// Regex to match all tags in the HTML
const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
htmlContents.forEach(content => {
let match;
while ((match = tagRegex.exec(content)) !== null) {
let tag = match[1];
if (availableComponents.has(tag)) {
usedComponents.add(tag);
}
}
});
return usedComponents;
}
/**
* Generate the registration script for the used components.
* @param {Map<string, string>} components - Map of tagName to compiled class code.
* @returns {string} - JavaScript code for registering components.
*/
function generateRegistrationScript(components) {
let script = '';
components.forEach((classCode) => {
script += `
${classCode}
`;
});
return script;
}
/**
* Compiler Function
* @param {string} indexPath - Path to the index.html file.
* @returns {Promise<string>} - Compiled HTML content with component registrations and page injections.
*/
async function compile(indexPath) {
// Read the index.html content
let indexContent = await fs.readFile(indexPath, 'utf-8');
// Define project root
const projectRoot = path.dirname(indexPath);
// -----------------------
// Step 1: Process Components
// -----------------------
// Find all .comp.html files in the project directory
const compFiles = glob.sync('**/*.comp.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'] // Ignore node_modules and cat directory to prevent recursion
});
const componentMap = new Map(); // Map of tagName to compiled class code
const parsedComponents = new Set(); // To track parsed components
// Parse and compile each component file
for (const file of compFiles) {
try {
const { tagName, html, script, style } = await parseComponent(file);
if (!parsedComponents.has(tagName)) {
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate class code
const classCode = generateClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
console.log(`🔍 Parsed and compiled component: <${tagName}> from ${path.relative(projectRoot, file)}`);
} else {
console.log(`ℹ️ Component <${tagName}> from ${path.relative(projectRoot, file)} has already been parsed.`);
}
} catch (error) {
console.error(`❌ Failed to parse ${file}: ${error.message}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components found to compile.');
}
// -----------------------
// Step 2: Process Pages
// -----------------------
const { pages: compiledPages, routerEntries } = await compilePages(projectRoot);
// -----------------------
// Step 3: Detect Used Components
// -----------------------
// Find all .html files in the project directory for usage detection
const htmlFiles = glob.sync('**/*.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const htmlContents = [];
for (const file of htmlFiles) {
try {
const content = await fs.readFile(file, 'utf-8');
htmlContents.push(content);
} catch (error) {
console.error(`❌ Failed to read HTML file ${file}: ${error.message}`);
}
}
// Detect which components are used across all HTML files
const availableComponents = new Set(componentMap.keys());
const usedComponents = detectUsedComponents(htmlContents, availableComponents);
if (usedComponents.size === 0) {
console.warn('⚠️ No used components found in HTML files.');
} else {
console.log(`📦 Used components: ${[...usedComponents].join(', ')}`);
}
// -----------------------
// Step 4: Handle <load> Tags and Inject Page Content
// -----------------------
// Detect all <load> routes in all HTML files
const loadRoutes = detectLoadRoutes(htmlContents);
// Prepare a map of route to page content
// Verify that each load route exists in the routerEntries
loadRoutes.forEach(route => {
const pageEntry = routerEntries.find(entry => entry.route === route);
if (!pageEntry) {
console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`);
}
});
// The new approach replaces <load route="..."> with a placeholder for the Router to instantiate
// Therefore, we no longer inject static content but rely on the Router to handle it
// -----------------------
// Step 5: Generate and Inject Registration and Page Scripts
// -----------------------
let registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// Add compiled pages
registrationScript += `
// Compiled Pages
${compiledPages.join('\n')}
// Router Class
${generateRouterClassCode(routerEntries)}
`;
// Inject the registration script before the closing </body> tag
const scriptTag = `<script>
${registrationScript}
</script>
`;
if (indexContent.includes('</body>')) {
indexContent = indexContent.replace('</body>', `${scriptTag}</body>`);
} else {
// If no </body> tag, append the script at the end
indexContent += `\n${scriptTag}`;
}
console.log('📝 Injected component and page registration scripts, including Router.');
// -----------------------
// Step 6: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };
Explanation:
-
Processing Components and Pages:
- Components: The existing pipeline remains unchanged. Components are parsed, compiled into classes, and their class codes are stored in
componentMap.
- Pages: Leveraging the updated
page.js, all .page.html files are compiled into classes. The Router entries mapping routes to class names are collected for Router initialization.
-
Detecting Used Components:
- Scans all HTML files to identify which components are actually used, ensuring that only necessary component scripts are injected.
-
Handling <load> Tags:
- Old Approach: Previously,
<load route="..."> tags were replaced with static HTML content during compilation.
- New Approach: Now,
<load route="..."> tags remain as placeholders. The Router class will handle the instantiation and rendering of the appropriate page classes at runtime.
-
Generating and Injecting Scripts:
- Component Scripts: Only the used components' class codes are included.
- Page Scripts: All compiled page class codes are appended.
- Router Script: The generated
Router class code is appended.
- All these scripts are injected into
index.html within a single <script> tag just before the closing </body> tag.
-
Logging:
- Comprehensive console logs are added to assist in debugging and to confirm successful compilation steps.
4. Final Steps and Considerations
a. Ensure All Necessary Functions Are Exported
Make sure that all functions used across modules are properly exported. For instance, if parseScript is defined in component.js and used in page.js, ensure it's exported:
// At the end of component.js
module.exports = {
parseComponent,
parsePage,
toPascalCase,
escapeBackticks,
generateClassCode,
generatePageClassCode,
transformMethodBody,
generateDOMCode,
parseScript // Ensure this is exported
};
b. Update package.json if Necessary
If you introduce new dependencies (e.g., acorn for JavaScript parsing), ensure they're listed in your package.json. You can install them using:
npm install acorn
c. Example of a Compiled Page Class
After compilation, a *.page.html file like:
<page route="/home">
<div>
<h1>{title}</h1>
<button onClick="handleClick">Click Me</button>
</div>
<script>
function handleClick() {
this.title = "Clicked!";
}
</script>
<style>
h1 {
color: blue;
}
</style>
</page>
Will be compiled into:
class _Page1 {
constructor() {
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
const style = document.createElement('style');
style.textContent = `
h1 {
color: blue;
}
`;
fragment.appendChild(style);
const div1 = document.createElement('div');
const h11 = document.createElement('h1');
h11.textContent = this._title;
div1.appendChild(h11);
this.button1 = document.createElement('button');
this.button1.setAttribute('onClick', 'handleClick');
this.button1.textContent = "Click Me";
div1.appendChild(this.button1);
fragment.appendChild(div1);
this.element = fragment;
}
render(parent) {
parent.appendChild(this.element);
}
get title() { return this._title; }
set title(value) {
if (this._title !== value) {
this._title = value;
this.h11.textContent = this._title;
}
}
handleClick() {
this.title = "Clicked!";
}
}
And the Router class will manage the rendering:
class Router {
constructor() {
this.routes = {
"/home": _Page1,
};
}
init() {
document.querySelectorAll('load[route]').forEach(loadElement => {
const route = loadElement.getAttribute('route');
const PageClass = this.routes[route];
if (PageClass) {
const pageInstance = new PageClass();
pageInstance.render(loadElement);
} else {
console.warn(`⚠️ No page found for route "${route}".`);
}
});
}
}
const router = new Router();
window.addEventListener('DOMContentLoaded', () => {
router.init();
});
d. Example index.html After Compilation
Before compilation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My App</title>
</head>
<body>
<load route="/home"></load>
</body>
</html>
After compilation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My App</title>
</head>
<body>
<load route="/home"></load>
<script>
// Compiled Components
class MyComponent extends HTMLElement {
/* ... component code ... */
}
// Compiled Pages
class _Page1 {
/* ... page code as shown above ... */
}
// Router Class
class Router {
/* ... router code as shown above ... */
}
const router = new Router();
window.addEventListener('DOMContentLoaded', () => {
router.init();
});
</script>
</body>
</html>
e. Handling Events in Pages
Ensure that event handlers defined in the <script> sections of pages are correctly bound. In the compiled page class, event listeners should be set up to reference class methods. This is already handled in the generateDOMCode function, where event listeners are attached in the _buildDOM method.
5. Testing the Implementation
To verify that the updates work as intended:
- Add a Page: Create a new
.page.html file, e.g., home.page.html.
<page route="/home">
<div>
<h1>{title}</h1>
<button onClick="handleClick">Click Me</button>
</div>
<script>
function handleClick() {
this.title = "Clicked!";
}
</script>
<style>
h1 {
color: blue;
}
</style>
</page>
- Add a Load Tag in
index.html:
<load route="/home"></load>
-
Run the Compiler: Ensure your build script runs compiler.js and outputs the modified index.html.
-
Serve the Project: Open index.html in a browser. Upon clicking the "Click Me" button, the title should change to "Clicked!", demonstrating the reactive property and event handling.
By following the above steps, you've successfully extended your project's build pipeline to handle page compilation, class generation, and routing, laying a solid foundation for further enhancements.