To accomplish this task, we'll need to modify the current compiler workflow to handle pages similarly to components, but with some key differences:
-
Parsing Pages as Classes: We'll modify the parsePage function to parse .page.html files into a structure similar to components, extracting the HTML, script, and style sections.
-
Generating Page Classes: We'll create a generatePageClassCode function that compiles the parsed page into a JavaScript class. Unlike components, these classes won't be custom elements but will contain methods like show() to manage their display.
-
Random Class Names: For pages, we'll generate random class names since the class is associated with the route/path rather than a specific name.
-
Router Class: We'll implement a Router class that manages the routing logic. It will instantiate the appropriate page class and invoke its show() method when a <load route="..."> is detected.
-
Compiler Modifications: We'll adjust the compile function to process pages accordingly, generate the router code, and inject everything into the final output.
Let's proceed step by step.
1. Modify parsePage to Parse Pages like Components
First, we'll update the parsePage function to extract the tag name (we can use a default like <page>), HTML, script, and style sections from the .page.html files.
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const { parseDocument } = require('htmlparser2');
/**
* Parse a page file to extract the route, 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=["']([^"']+)["'][^>]*>([\s\S]*?)<\/page>/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];
const innerContent = match[2];
// 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 htmlContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
return {
route,
html: htmlContent,
script: scriptContent,
style: styleContent,
};
}
module.exports = {
parsePage,
};
2. Generate Page Class Code
We'll create a new function generatePageClassCode in component.js (or in a new file if preferred) to handle the generation of page classes.
// cat/src/component.js
// ... existing code ...
/**
* Generate the class code for a page.
* @param {object} page - Page details.
* @returns {string} - The compiled page class code.
*/
function generatePageClassCode({ className, html, style, properties, methods }) {
let classCode = `class ${className} {
constructor() {
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = ${prop.value};
`;
});
classCode += `
this._element = null;
}
show(container) {
this._element = container || document.body;
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.appendChild(fragment);
}
`;
// Generate getters, setters, methods, and event handling
// Similar to `generateClassCode` for components
// ...
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classCode += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
classCode += `}
`;
return classCode;
}
module.exports = {
// ... existing exports ...
generatePageClassCode,
};
3. Generate Random Class Names
We'll update the compiler to generate random class names for pages.
// cat/src/compiler.js
// ... existing code ...
const crypto = require('crypto'); // For generating random class names
function generateRandomClassName() {
return 'Page_' + crypto.randomBytes(6).toString('hex');
}
4. Implement the Router Class
We'll create a Router class that manages the page instances and triggers their show() methods upon detecting a <load route="..."> in the HTML.
// cat/src/router.js
class Router {
constructor(pages) {
this.pages = pages; // Map of route to page class instances
}
loadRoute(route, container) {
const PageClass = this.pages.get(route);
if (PageClass) {
const pageInstance = new PageClass();
pageInstance.show(container);
} else {
console.error(`No page found for route: ${route}`);
}
}
init() {
// Detect all <load route="..."> elements and replace them
document.querySelectorAll('load[route]').forEach(loadElement => {
const route = loadElement.getAttribute('route');
const container = loadElement.parentElement;
this.loadRoute(route, container);
loadElement.remove(); // Remove the <load> element after processing
});
}
}
module.exports = {
Router,
};
5. Modify the Compiler to Process Pages and Generate Router Code
Now, we'll adjust the compile function to process pages similarly to components, generate page classes with random names, and generate the router code.
// cat/src/compiler.js
// ... existing code ...
const { Router } = require('./router'); // Import Router class
async function compile(indexPath) {
// ... existing code ...
// -----------------------
// Step 2: Process Pages
// -----------------------
// Find all .page.html files in the project directory
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const pageClassMap = new Map(); // Map of route to page class code
const classNames = new Set(); // To ensure class names are unique
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parsePage(file);
// Generate random class name
let className;
do {
className = generateRandomClassName();
} while (classNames.has(className));
classNames.add(className);
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate page class code
const classCode = generatePageClassCode({
className,
html,
style,
properties,
methods,
});
pageClassMap.set(route, { className, classCode });
console.log(`📄 Compiled page for route "${route}" into class ${className} from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (pageClassMap.size === 0) {
console.warn('⚠️ No pages found to compile.');
}
// ... existing code ...
// -----------------------
// Step 4: Handle <load> Tags and Generate Router Code
// -----------------------
// Detect all <load> routes in all HTML files
const loadRoutes = detectLoadRoutes(htmlContents);
// Verify that each load route exists in the pageClassMap
loadRoutes.forEach(route => {
if (!pageClassMap.has(route)) {
console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`);
}
});
// Generate the router code
let routerScript = '';
// Import the Router class or include its code directly
routerScript += `
class Router {
constructor(pages) {
this.pages = pages; // Map of route to page class constructors
}
loadRoute(route, container) {
const PageClass = this.pages.get(route);
if (PageClass) {
const pageInstance = new PageClass();
pageInstance.show(container);
} else {
console.error(\`No page found for route: \${route}\`);
}
}
init() {
// Detect all <load route="..."> elements and replace them
document.querySelectorAll('load[route]').forEach(loadElement => {
const route = loadElement.getAttribute('route');
const container = loadElement.parentElement;
this.loadRoute(route, container);
loadElement.remove(); // Remove the <load> element after processing
});
}
}
`;
// Prepare pages map for the router
routerScript += `
const pages = new Map();
`;
pageClassMap.forEach(({ className }, route) => {
routerScript += `pages.set('${route}', ${className});
`;
});
routerScript += `
const router = new Router(pages);
document.addEventListener('DOMContentLoaded', () => {
router.init();
});
`;
// -----------------------
// Step 5: Generate Registration Script for Components and Pages
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// Include page class codes
pageClassMap.forEach(({ classCode }) => {
registrationScript += `
${classCode}
`;
});
// Include router script
registrationScript += `
${routerScript}
`;
// ... existing code to inject registrationScript into indexContent ...
// ... existing code ...
return indexContent;
}
module.exports = { compile };
6. Update generateRegistrationScript Function
We'll adjust the generateRegistrationScript function to handle both components and pages.
/**
* Generate the registration script for the used components and pages.
* @param {Map<string, string>} components - Map of tagName to compiled class code.
* @returns {string} - JavaScript code for registering components and pages.
*/
function generateRegistrationScript(components) {
let script = '';
components.forEach((classCode) => {
script += `
${classCode}
`;
});
// The pages' class codes are now included in the main compiler function since they have random class names
// and their instantiation is handled by the Router
return script;
}
7. Adjust the HTML Processing
Since the <load> tags are now handled at runtime by the Router, we no longer need to replace them in the HTML during compilation. We can remove the step that replaces <load> tags in the compile function.
In the compile function, remove or comment out the code that replaces <load> tags with content.
8. Final Compiler Code Snippet
Below is the updated compile function with all changes incorporated.
// cat/src/compiler.js
// ... existing code ...
const crypto = require('crypto');
/**
* Generate a random class name for pages.
* @returns {string} - Random class name.
*/
function generateRandomClassName() {
return 'Page_' + crypto.randomBytes(6).toString('hex');
}
/**
* 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
// -----------------------
// ... existing code to process components ...
// -----------------------
// Step 2: Process Pages
// -----------------------
// Find all .page.html files in the project directory
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const pageClassMap = new Map(); // Map of route to page class code
const classNames = new Set(); // To ensure class names are unique
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parsePage(file);
// Generate random class name
let className;
do {
className = generateRandomClassName();
} while (classNames.has(className));
classNames.add(className);
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate page class code
const classCode = generatePageClassCode({
className,
html,
style,
properties,
methods,
});
pageClassMap.set(route, { className, classCode });
console.log(`📄 Compiled page for route "${route}" into class ${className} from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (pageClassMap.size === 0) {
console.warn('⚠️ No pages found to compile.');
}
// -----------------------
// Step 3: Detect Used Components
// -----------------------
// ... existing code ...
// -----------------------
// Step 4: Handle <load> Tags and Generate Router Code
// -----------------------
// Detect all <load> routes in all HTML files
const loadRoutes = detectLoadRoutes(htmlContents);
// Verify that each load route exists in the pageClassMap
loadRoutes.forEach(route => {
if (!pageClassMap.has(route)) {
console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`);
}
});
// Generate the router code
let routerScript = `
class Router {
constructor(pages) {
this.pages = pages; // Map of route to page class constructors
}
loadRoute(route, container) {
const PageClass = this.pages.get(route);
if (PageClass) {
const pageInstance = new PageClass();
pageInstance.show(container);
} else {
console.error(\`No page found for route: \${route}\`);
}
}
init() {
// Detect all <load route="..."> elements and replace them
document.querySelectorAll('load[route]').forEach(loadElement => {
const route = loadElement.getAttribute('route');
const container = loadElement.parentElement;
this.loadRoute(route, container);
loadElement.remove(); // Remove the <load> element after processing
});
}
}
`;
// Prepare pages map for the router
routerScript += `
const pages = new Map();
`;
pageClassMap.forEach(({ className }, route) => {
routerScript += `pages.set('${route}', ${className});
`;
});
routerScript += `
const router = new Router(pages);
document.addEventListener('DOMContentLoaded', () => {
router.init();
});
`;
// -----------------------
// Step 5: Generate Registration Script for Components and Pages
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// Include page class codes
pageClassMap.forEach(({ classCode }) => {
registrationScript += `
${classCode}
`;
});
// Include router script
registrationScript += `
${routerScript}
`;
// -----------------------
// Step 6: Inject Registration Script
// -----------------------
if (registrationScript.trim()) {
// 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 scripts.');
}
// -----------------------
// Step 7: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };
9. Remove Unnecessary Steps
Since the <load> tags are now handled at runtime by the Router, we can remove or adjust the following:
-
In the compile function, remove the code that replaces <load> tags with page content during compilation.
-
Ensure that the detectLoadRoutes function only collects routes for validation purposes and doesn't alter the HTML content.
10. Update detectLoadRoutes if Necessary
If detectLoadRoutes is no longer needed or needs adjustment, update it accordingly.
// cat/src/page.js
/**
* Detect all <load> routes in the provided HTML contents and extract their routes.
* @param {Array<string>} htmlContents - Array of HTML file contents.
* @returns {Set<string>} - Set of routes found in <load> tags.
*/
function detectLoadRoutes(htmlContents) {
const loadRoutes = new Set();
// 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.add(route);
}
});
return loadRoutes;
}
module.exports = {
parsePage,
detectLoadRoutes
};
Summary
By making these changes, we've modified the compiler to:
-
Parse .page.html files similarly to components, extracting HTML, script, and style.
-
Generate page classes with random names that have a show() method to render themselves.
-
Implement a Router class that instantiates the appropriate page class and displays it when a <load route="..."> is encountered.
-
Adjust the compilation process to include the generated page classes and router code in the final output.
-
Handle dynamic expressions, properties, methods, getters, and setters within the pages similarly to components.
Optional Enhancements
-
Dynamic Loading: If desired, the router can be enhanced to support dynamic route changes, handle hash routing, or support more advanced features.
-
Error Handling: Improve error messages and handling when routes or pages are missing.
-
Caching: Implement caching in the Router to avoid re-rendering pages unnecessarily.
Feel free to adjust the code to fit the specific needs of your project or to further enhance its functionality.