To accomplish the task of updating page.js to compile {filename}.page.html files similarly to components, the following enhancements have been made:
-
Parsing Enhanced Pages: The parsePage function now extracts the <script> and <style> sections from the .page.html files, in addition to the route and inner content.
-
JavaScript Class Generation: A new function generatePageClass is introduced to transform the parsed page content into a JavaScript class. This class includes dynamic expressions, getters, setters, and custom methods derived from the <script> section.
-
Router Class Generation: The generateRouterClass function generates a Router class that maps routes to their corresponding page classes. This router is responsible for constructing and rendering the appropriate page when a <load> tag is encountered.
-
Style Injection: All extracted <style> sections from the pages are concatenated and injected into the <head> of index.html during the build process.
-
Integration with Compiler: The compiled page classes and the router class are integrated into the overall compilation process handled by compiler.js.
Below is the updated page.js file reflecting these changes:
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const acorn = require('acorn'); // For JavaScript parsing
const { parseDocument } = require('htmlparser2');
/**
* Parse a page file to extract the route, inner HTML, script, and style sections.
* @param {string} filePath - Path to the .page.html file.
* @returns {Promise<{ route: string, html: string, script: string, style: string }>} - Page details.
*/
async function parsePage(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Regex to match the <page> tag and extract the route attribute
const pageTagRegex = /<page\s+[^>]*route=["']([^"']+)["'][^>]*>/i;
const match = content.match(pageTagRegex);
if (!match) {
throw new Error(`No valid <page> tag with 'route' attribute found in ${path.basename(filePath)}`);
}
const route = match[1];
// Extract the inner HTML of the <page> tag
const innerContentRegex = new RegExp(`<page[^>]*>([\\s\\S]*?)<\\/page>`, 'i');
const innerMatch = content.match(innerContentRegex);
const pageContent = innerMatch ? innerMatch[1].trim() : '';
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/gi;
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>/gi;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
return {
route,
html: pageContent,
script: scriptContent,
style: styleContent,
};
}
/**
* Detect all <load> tags in the provided HTML contents and extract their routes.
* @param {Array<string>} htmlContents - Array of HTML file contents.
* @returns {Array<string>} - Array of routes found in <load> tags.
*/
function detectLoadRoutes(htmlContents) {
const loadRoutes = [];
// Regex to match <load route="..."> tags
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
htmlContents.forEach(content => {
let match;
while ((match = loadTagRegex.exec(content)) !== null) {
const route = match[1];
loadRoutes.push(route);
}
});
return loadRoutes;
}
/**
* Parse the script content to extract properties and methods.
* @param {string} script - The script content.
* @returns {{ properties: Array, methods: Array }} - Parsed properties and methods.
*/
function parseScript(script) {
const properties = [];
const methods = [];
try {
// Parse the script content into an AST
const ast = acorn.parse(script, { ecmaVersion: 2020, locations: true });
ast.body.forEach(node => {
if (node.type === 'VariableDeclaration') {
node.declarations.forEach(declarator => {
if (declarator.id.type === 'Identifier') {
const varName = declarator.id.name;
const varValue = script.substring(declarator.init.start, declarator.init.end);
properties.push({ name: varName, value: varValue });
}
});
} else if (node.type === 'FunctionDeclaration') {
const funcName = node.id.name;
const params = node.params.map(param => script.substring(param.start, param.end)).join(', ');
const body = script.substring(node.body.start, node.body.end);
methods.push({ name: funcName, params, body });
}
});
} catch (error) {
console.error(`Error parsing script: ${error.message}`);
}
return { properties, methods };
}
/**
* 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) {
// Generate a random identifier to ensure uniqueness
const randomPart = Math.random().toString(36).substring(2, 8);
const baseName = tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
return `${baseName}Page_${randomPart}`;
}
/**
* Generate the class code for the page.
* @param {object} page - Page details.
* @returns {string} - The compiled class code.
*/
function generatePageClass({ className, html, script }) {
const { properties, methods } = parseScript(script);
let classCode = `class ${className} {
constructor() {
this._properties = {};
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = ${prop.value};
`;
});
classCode += `
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
fragment.appendChild(this.dom);
this.rendered = false;
this.element = fragment;
}
render(container) {
if (!this.rendered) {
container.appendChild(this.element);
this.rendered = true;
this.connectedCallback();
}
}
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 += `}\n\n`;
return classCode;
}
/**
* Generate a Router class that maps routes to page classes.
* @param {Map<string, string>} routeMap - Map of route to className.
* @returns {string} - The Router class code.
*/
function generateRouterClass(routeMap) {
let routerCode = `class Router {
constructor() {
window.addEventListener('hashchange', this.handleRouteChange.bind(this));
this.handleRouteChange(); // Handle the initial route
}
handleRouteChange() {
const route = window.location.hash.slice(1) || '/';
const container = document.getElementById('app') || document.body;
// Clear existing content
container.innerHTML = '';
switch(route) {
`;
routeMap.forEach((className, route) => {
routerCode += ` case '${route}':
const page_${className} = new ${className}();
page_${className}.render(container);
break;
`;
});
routerCode += ` default:
console.error(\`No route found for "\${route}"\`);
}
}
}\n\n`;
routerCode += `const router = new Router();\n`;
return routerCode;
}
/**
* 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 of the page.
* @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 = ` this.dom = document.createDocumentFragment();
`;
let varCounter = 0;
const cachedNodes = {}; // For properties to nodes
const eventListeners = [];
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const varName = `el${++varCounter}`;
code += ` const ${varName} = document.createElement('${node.name}');
`;
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (attrName.startsWith('@')) {
// Event listener shorthand, e.g., @click="handler"
const event = attrName.slice(1);
const handlerName = attrValue.replace(/\(\)$/, '').trim();
eventListeners.push({ elementVarName: varName, event, handlerName });
} else if (/\{[\w$]+\}/.test(attrValue)) {
// Attribute with dynamic expression
const { expression, propNames } = generateAttributeExpression(attrValue);
code += ` ${varName}.setAttribute('${attrName}', \`${expression}\`);
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'attribute',
elementVarName: varName,
attrName: attrName,
expression: expression,
});
});
} else {
// Static attribute
code += ` ${varName}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Append to parent
const parentRef = parentVarName ? parentVarName : 'this.dom';
code += ` ${parentRef}.appendChild(${varName});
`;
// Traverse children
if (node.children && node.children.length) {
node.children.forEach(child => traverse(child, varName));
}
} else if (node.type === 'text') {
const textContent = node.data;
if (textContent.trim()) {
// Handle text nodes with expressions
const { expression, propNames } = generateTextExpression(textContent);
const varName = `text${++varCounter}`;
code += ` const ${varName} = document.createTextNode(\`${expression}\`);
`;
code += ` ${parentVarName}.appendChild(${varName});
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'text',
varName: varName,
expression: expression,
});
});
}
}
}
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(textContent.slice(lastIndex, match.index));
}
segments.push('${this._' + match[1] + '}');
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(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(attrValue.slice(lastIndex, match.index));
}
segments.push('${this._' + match[1] + '}');
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(attrValue.slice(lastIndex));
}
return {
expression: segments.join(''),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners };
}
/**
* Compile all .page.html files and generate corresponding JavaScript classes and router.
* @param {string} projectRoot - The root directory of the project.
* @returns {Promise<{ pageClasses: Array<string>, routerClass: string, styles: string }>} - Compiled pages, router, and styles.
*/
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 compiledPages = [];
const routeMap = new Map();
let aggregatedStyles = '';
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parsePage(file);
// Generate a unique class name for the page
const baseName = path.basename(file, '.page.html');
const className = toPascalCase(baseName);
// Generate class code
const classCode = generatePageClass({ className, html, script });
compiledPages.push(classCode);
// Map route to class name
routeMap.set(route, className);
// Aggregate styles
if (style) {
aggregatedStyles += `\n/* Styles for route: ${route} */\n${style}\n`;
}
console.log(`🔍 Parsed and compiled page: Route "${route}" from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (compiledPages.length === 0) {
console.warn('⚠️ No pages found to compile.');
}
// Generate Router class
const routerClass = generateRouterClass(routeMap);
return {
pageClasses: compiledPages,
routerClass,
styles: aggregatedStyles,
};
}
module.exports = {
parsePage,
detectLoadRoutes,
compilePages
};
Explanation of Changes:
-
Enhanced parsePage Function:
- Now extracts
<script> and <style> sections along with the route and inner HTML.
-
generatePageClass Function:
- Transforms the parsed page content into a JavaScript class.
- Handles dynamic text and attribute expressions.
- Sets up getters and setters for reactive properties.
- Binds event listeners as specified in the HTML.
-
generateRouterClass Function:
- Creates a
Router class that listens to hash changes in the URL.
- Maps each route to its corresponding compiled page class.
- Renders the appropriate page based on the current route.
-
generateDOMCode Function:
- Transforms the inner HTML of the page into DOM manipulation code.
- Handles dynamic expressions within text and attributes.
- Sets up references for reactive updates and event listeners.
-
compilePages Function:
- Orchestrates the compilation of all
.page.html files.
- Generates the necessary JavaScript classes and the router.
- Aggregates all styles for injection into
index.html.
-
Style Handling:
- All extracted styles from pages are aggregated and can be injected into the
<head> of index.html during the build process.
-
Logging:
- Informative console logs have been added for easier debugging and tracking of the compilation process.
Notes:
-
Random Class Names: To ensure uniqueness, class names are augmented with a random string. This prevents naming collisions especially when multiple pages might have the same base name.
-
Dynamic Expressions: The code handles dynamic expressions within text nodes and attributes using template literals, ensuring that any {property} is correctly interpolated.
-
Event Listeners: Event listeners are parsed from attributes prefixed with @, following the convention (e.g., @click="handleClick").
-
Router Initialization: The Router class is instantiated at the end of the compilation process to ensure that routing is set up as soon as the application loads.
Integration with compiler.js
To complete the setup, ensure that compiler.js imports and utilizes the compilePages function to integrate the compiled pages and router into the final build. Additionally, inject the aggregated styles into index.html. Here's a brief snippet illustrating how this can be done within compiler.js:
// Inside compiler.js
const { compile } = require('./compiler'); // Existing compiler functions
const { compilePages } = require('./page'); // Import the new compilePages function
async function compile(projectRoot, indexPath) {
// ... existing compilation steps
// Compile pages
const { pageClasses, routerClass, styles } = await compilePages(projectRoot);
// Inject compiled page classes and router into indexContent
const registrationScript = `
<script>
${pageClasses.join('\n')}
${routerClass}
</script>
`;
if (registrationScript.trim()) {
// Inject the registration script before the closing </body> tag
const scriptTag = registrationScript;
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 page registration scripts.');
}
// Inject styles into <head>
if (styles.trim()) {
const styleTag = `<style>\n${styles}\n</style>\n`;
if (indexContent.includes('</head>')) {
indexContent = indexContent.replace('</head>', `${styleTag}</head>`);
} else {
// If no </head> tag, append the styles at the beginning
indexContent = `${styleTag}\n${indexContent}`;
}
console.log('🎨 Injected styles into <head>.');
}
// ... rest of the compilation steps
return indexContent;
}
module.exports = { compile };
Final Project Structure
After these modifications, your project structure will look like this:
project-root/
├── cat/
│ ├── bin/
│ │ └── cat.js
│ └── src/
│ ├── compiler.js
│ ├── component.js
│ └── page.js
├── index.html
├── package.json
└── cat.config.json
Testing the Changes
To ensure that the updated page.js functions correctly:
-
Create Sample .page.html Files:
-
Run the Compiler:
- Execute your build process (e.g.,
npm run build or the equivalent command) to invoke the updated compiler.js.
-
Verify index.html:
- Check that the compiled JavaScript classes and router are injected correctly.
- Ensure that styles are present within the
<head> section.
-
Test Routing:
- Open
index.html in a browser.
- Navigate between routes using the URL hash (e.g.,
http://localhost/#/home) and verify that the corresponding pages render as expected.
These updates should provide a robust framework for compiling pages with dynamic content, reactive properties, and routing capabilities, similar to how components are handled within your project.