To accomplish the tasks you've outlined, we'll need to enhance your existing project structure and compilation process to handle .page.html files similarly to components. However, instead of compiling them into custom elements, we'll generate JavaScript classes. Additionally, we'll implement a Router class responsible for managing page navigation based on <load route="path"> tags.
Here's a comprehensive guide to achieving this, including detailed explanations and code snippets.
1. Project Structure Enhancement
First, ensure your project structure accommodates both components and pages. Update your project directory as follows:
project-root/
├── cat/
│ ├── bin/
│ │ └── cat.js
│ └── src/
│ ├── compiler.js
│ ├── component.js
│ └── page.js
├── pages/
│ └── home.page.html
│ └── about.page.html
├── components/
│ └── header.comp.html
│ └── footer.comp.html
├── index.html
├── package.json
└── cat.config.json
pages/: Directory to store all .page.html files.
components/: Directory to store all .comp.html files (if not already present).
2. Parsing and Compiling .page.html Files
We'll extend the existing page.js and component.js to handle page files similarly to components but with distinctions suitable for pages.
2.1. Update page.js
Enhance page.js to parse .page.html files and generate corresponding JavaScript classes.
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const acorn = require('acorn'); // JavaScript parser
const { parseDocument } = require('htmlparser2');
/**
* Parse a page file to extract the route and its content.
* @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');
// Extract the outermost <page> tag and its attributes
const pageTagRegex = /<page\s+([^>]*)>([\s\S]*?)<\/page>/i;
const match = content.match(pageTagRegex);
if (!match) {
throw new Error(`Invalid page structure in ${path.basename(filePath)}`);
}
const attributes = parseAttributes(match[1]);
const route = attributes.route;
if (!route) {
throw new Error(`Missing 'route' attribute in <page> tag in ${path.basename(filePath)}`);
}
const innerContent = match[2].trim();
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/gi;
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>/gi;
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,
};
}
/**
* Parse HTML attributes into an object.
* @param {string} attrString - Attribute string from HTML tag.
* @returns {object} - Parsed attributes.
*/
function parseAttributes(attrString) {
const attrs = {};
const attrRegex = /(\w+)="([^"]+)"/g;
let match;
while ((match = attrRegex.exec(attrString)) !== null) {
attrs[match[1]] = match[2];
}
return attrs;
}
/**
* 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 file path to a PascalCase class name.
* @param {string} filePath - The file path.
* @returns {string} - PascalCase class name.
*/
function generateClassName(filePath) {
const baseName = path.basename(filePath, '.page.html');
return baseName
.split(/[^a-zA-Z0-9]/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Generate the class code for the page.
* @param {object} page - Page details.
* @param {string} className - The class name.
* @returns {string} - The compiled class code.
*/
function generatePageClass({ route, html, script, style }, className) {
const { properties, methods } = parseScript(script);
let classCode = `class ${className} {
constructor() {
this._route = '${route}';
this._init();
}
_init() {
// Create root element
this.root = document.createElement('div');
`;
// Apply styles if any
if (style) {
classCode += `
const style = document.createElement('style');
style.textContent = \`
${style}
\`;
this.root.appendChild(style);
`;
}
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
}
show() {
this.root.style.display = 'block';
}
hide() {
this.root.style.display = 'none';
}
`;
// 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 = this.${node.expression};
`;
} else if (node.type === 'attribute') {
classCode += ` this.${node.elementVarName}.setAttribute('${node.attrName}', this.${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 += `}
`;
return classCode;
}
/**
* 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(`(?<!\\.)\\b${propName}\\s*=`, 'g');
transformedBody = transformedBody.replace(assignRegex, `this.${propName} =`);
// Replace variable references with 'this.propName'
const varRegex = new RegExp(`(?<!\\.)\\b${propName}\\b`, 'g');
transformedBody = transformedBody.replace(varRegex, `this.${propName}`);
});
// Ensure braces are correctly balanced and formatted
transformedBody = transformedBody.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 component/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 = '';
let varCounter = 0;
const cachedNodes = {}; // For properties to nodes
const eventListeners = [];
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const varName = node.name.replace(/-/g, '') + ++varCounter;
// Decide whether to assign to a class property or a local variable
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.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue.replace(/\(\)$/, '').trim();
eventListeners.push({ elementVarName: varReference.replace(/^this\./, ''), event, handlerName });
continue;
}
if (/\{[\w$]+\}/.test(attrValue)) {
// Attribute with dynamic 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: `\`${attrValue.replace(/\{([\w$]+)\}/g, '${this.$1}')}\``, // Template literal
});
});
} else {
// Static attribute
code += ` ${varReference}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Handle child elements
if (node.children && node.children.length) {
node.children.forEach(child => traverse(child, varReference));
}
// Append to parent
if (parentVarName) {
code += ` ${parentVarName}.appendChild(${varReference});
`;
} else {
// If no parent, append to root
code += ` this.root.appendChild(${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: `\`${textContent.replace(/\{([\w$]+)\}/g, '${this.$1}')}\``, // Template literal
});
});
}
}
}
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 _init
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)));
}
if (segments.length === 0) {
segments.push('""');
}
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)));
}
if (segments.length === 0) {
segments.push('""');
}
return {
expression: segments.join(' + '),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners };
}
module.exports = {
parsePage,
parseAttributes,
parseScript,
generateClassName,
generatePageClass,
transformMethodBody,
generateDOMCode
};
Explanation of Enhancements:
-
Parsing .page.html Files:
- The
parsePage function reads a .page.html file, extracts the <page> tag, and retrieves the route, html, script, and style sections.
- It ensures that each page has a unique
route attribute.
-
Generating Class Names:
- The
generateClassName function converts the filename to a PascalCase class name. For example, home.page.html becomes Home.
-
Generating Page Classes:
- The
generatePageClass function creates a JavaScript class for each page.
- The class includes:
- A constructor that initializes properties and builds the DOM.
- Methods like
show and hide to control the visibility of the page.
- Getters and setters for reactive properties.
- Custom methods defined within the
<script> section of the .page.html file.
-
Handling Dynamic Expressions:
- The
generateDOMCode function processes the HTML, handles dynamic expressions within {} braces, and sets up reactive bindings for properties.
- It supports dynamic attributes and text content.
2.2. Update component.js
While component.js primarily handles custom elements, ensure it can coexist with page.js without conflicts. You might not need significant changes here, but ensure utility functions like generateDOMCode are compatible with both components and pages.
3. Enhancing the Compiler to Handle Pages and Generate Router
Next, we'll modify compiler.js to process .page.html files, generate corresponding classes, and create a Router class.
3.1. Update compiler.js
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { parseComponent, parseScript, generateClassCode, transformMethodBody, generateDOMCode } = require('./component');
const { parsePage, generateClassName, generatePageClass, transformMethodBody: transformPageMethodBody } = require('./page');
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 components directory
const compFiles = glob.sync('components/**/*.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
// -----------------------
// Find all .page.html files in the pages directory
const pageFiles = glob.sync('pages/**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const pageMap = new Map(); // Map of route to page class code
const routeMap = new Map(); // Map of route to class name
const parsedPages = new Set(); // To track parsed pages
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parsePage(file);
if (!parsedPages.has(route)) {
const className = generateClassName(file);
const classCode = generatePageClass({ route, html, script, style }, className);
pageMap.set(route, classCode);
routeMap.set(route, className);
parsedPages.add(route);
console.log(`📝 Parsed and compiled page for route "${route}" from ${path.relative(projectRoot, file)}`);
} else {
console.warn(`⚠️ Duplicate route "${route}" found in ${path.relative(projectRoot, file)}. Skipping.`);
}
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (pageMap.size === 0) {
console.warn('⚠️ No pages found to compile.');
}
// -----------------------
// Step 3: Detect Used Components
// -----------------------
// Find all .html files in the project directory for usage detection (excluding .comp.html and .page.html)
const htmlFiles = glob.sync('**/*.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**', 'components/**/*.comp.html', 'pages/**/*.page.html']
});
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
// -----------------------
// Find all <load route="..."> tags in index.html
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
const loadRoutes = [];
let match;
while ((match = loadTagRegex.exec(indexContent)) !== null) {
const route = match[1];
loadRoutes.push(route);
}
// Prepare the list of routes to be handled by the Router
const registeredRoutes = Array.from(routeMap.keys());
// Warn if any <load> tag routes do not have corresponding pages
loadRoutes.forEach(route => {
if (!routeMap.has(route)) {
console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`);
}
});
// Remove all <load> tags from indexContent as the Router will manage page injections
indexContent = indexContent.replace(/<load\s+[^>]*route=["'][^"']+["'][^>]*>/gi, '');
// -----------------------
// Step 5: Generate Registration Script for Components and Pages
// -----------------------
const componentsScript = generateRegistrationScript(componentMap);
const pagesScript = `
/* Page Classes */
${Array.from(pageMap.values()).join('\n')}
/* Router Class */
class Router {
constructor(routes) {
this.routes = routes;
this.pages = {};
this.currentRoute = null;
this.init();
}
init() {
// Instantiate all pages
for (const route in this.routes) {
const pageClass = this.routes[route];
this.pages[route] = new window[pageClass]();
// Initially hide all pages
this.pages[route].hide();
// Append to body
document.body.appendChild(this.pages[route].root);
}
// Handle initial load
window.addEventListener('load', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
// Handle hash changes
window.addEventListener('hashchange', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
}
handleRoute(route) {
if (this.currentRoute === route) return;
if (this.pages[route]) {
if (this.currentRoute && this.pages[this.currentRoute]) {
this.pages[this.currentRoute].hide();
}
this.pages[route].show();
this.currentRoute = route;
} else {
console.warn(\`Route "\${route}" is not registered.\`);
}
}
}
// Initialize Router with routes
const router = new Router(${JSON.stringify(routeMap, null, 2)});
`;
// Total registration script
const registrationScript = `
<script>
${componentsScript}
${pagesScript}
</script>
`;
// -----------------------
// Step 6: Inject Registration Script into index.html
// -----------------------
if (registrationScript.trim()) {
// Inject the registration script before the closing </body> tag
if (indexContent.includes('</body>')) {
indexContent = indexContent.replace('</body>', `${registrationScript}\n</body>`);
} else {
// If no </body> tag, append the script at the end
indexContent += `\n${registrationScript}`;
}
console.log('📝 Injected component and page registration scripts.');
}
// -----------------------
// Step 7: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };
Explanation of Enhancements:
-
Processing Pages:
- Parsing
.page.html Files: The compiler now searches the pages/ directory for all .page.html files. Each file is parsed to extract the route, html, script, and style sections.
- Generating Page Classes: For each page, a unique class is generated using the
generatePageClass function from page.js. These classes are stored in the pageMap.
-
Handling <load> Tags:
- The compiler scans
index.html for all <load route="path"> tags.
- It verifies that each route specified in a
<load> tag corresponds to a compiled page. If not, it logs an error.
- All
<load> tags are removed from index.html since the Router will handle page injections dynamically.
-
Generating the Router Class:
- A
Router class is dynamically generated and injected into index.html.
- The
Router handles:
- Instantiating all page classes.
- Managing the display of pages based on URL hash changes.
- Ensuring only the active page is visible at any given time.
-
Injecting Scripts:
- Both component registration scripts and page class definitions, along with the
Router class, are injected into index.html within a <script> tag before the closing </body> tag.
4. Sample Router Implementation
Here's a closer look at the generated Router class and how it manages page navigation:
class Router {
constructor(routes) {
this.routes = routes;
this.pages = {};
this.currentRoute = null;
this.init();
}
init() {
// Instantiate all pages
for (const route in this.routes) {
const pageClass = this.routes[route];
this.pages[route] = new window[pageClass]();
// Initially hide all pages
this.pages[route].hide();
// Append to body
document.body.appendChild(this.pages[route].root);
}
// Handle initial load
window.addEventListener('load', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
// Handle hash changes
window.addEventListener('hashchange', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
}
handleRoute(route) {
if (this.currentRoute === route) return;
if (this.pages[route]) {
if (this.currentRoute && this.pages[this.currentRoute]) {
this.pages[this.currentRoute].hide();
}
this.pages[route].show();
this.currentRoute = route;
} else {
console.warn(`Route "${route}" is not registered.`);
}
}
}
// Initialize Router with routes
const router = new Router({
"/": "Home",
"/about": "About"
});
Key Functionalities:
5. Example .page.html Files
Create sample page files to demonstrate the functionality.
5.1. Home Page (home.page.html)
<page route="/">
<style>
.home {
padding: 20px;
background-color: #f0f0f0;
}
</style>
<div class="home">
<h1>Welcome to the Home Page</h1>
<p>{welcomeMessage}</p>
<button onclick="changeMessage()">Change Message</button>
</div>
<script>
let welcomeMessage = "Hello, World!";
function changeMessage() {
this.welcomeMessage = "Message Updated!";
}
</script>
</page>
5.2. About Page (about.page.html)
<page route="/about">
<style>
.about {
padding: 20px;
background-color: #e0e0e0;
}
</style>
<div class="about">
<h1>About Us</h1>
<p>{aboutText}</p>
</div>
<script>
let aboutText = "We are a company dedicated to excellence.";
function updateAbout(newText) {
this.aboutText = newText;
}
</script>
</page>
6. Running the Compiler
Ensure your compiler.js is properly exported and executed. Here's an example of how you might set up your cat.js (assuming it's the entry point) to invoke the compiler.
// cat/bin/cat.js
const path = require('path');
const { compile } = require('../src/compiler');
async function build() {
const indexPath = path.join(__dirname, '../../index.html');
try {
const compiledContent = await compile(indexPath);
// Write the compiled content to a distribution file
const distPath = path.join(__dirname, '../../dist/index.html');
await fs.ensureDir(path.dirname(distPath));
await fs.writeFile(distPath, compiledContent, 'utf-8');
console.log('✅ Compilation successful. Output at dist/index.html');
} catch (error) {
console.error(`Compilation failed: ${error.message}`);
}
}
build();
Explanation:
- The
build function invokes the compile function with the path to index.html.
- The compiled HTML content is written to a
dist/ directory for deployment.
7. Final index.html Example
Here's how your final index.html might look after compilation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cat Project</title>
</head>
<body>
<!-- Original content of index.html -->
<!-- <load> tags have been removed and Router manages page injections -->
<!-- Injected Scripts -->
<script>
/* Component Classes */
class Header extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._title = "Default Title";
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
const style = document.createElement('style');
style.textContent = `
h1 {
color: blue;
}
`;
fragment.appendChild(style);
const h1 = document.createElement('h1');
h1.textContent = this._title;
fragment.appendChild(h1);
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
this.h1.addEventListener('click', this.handleClick.bind(this));
}
disconnectedCallback() {
this.h1.removeEventListener('click', this.handleClick.bind(this));
}
get title() { return this._title; }
set title(value) {
if (this._title !== value) {
this._title = value;
this.h1.textContent = this._title;
}
}
handleClick() {
console.log('Header clicked!');
}
}
customElements.define('header-component', Header);
/* Page Classes */
class Home {
constructor() {
this._route = '/';
this._init();
}
_init() {
// Create root element
this.root = document.createElement('div');
const style = document.createElement('style');
style.textContent = `
.home {
padding: 20px;
background-color: #f0f0f0;
}
`;
this.root.appendChild(style);
const div1 = document.createElement('div');
div1.setAttribute('class', 'home');
this.root.appendChild(div1);
const h11 = document.createElement('h1');
h11.textContent = "Welcome to the Home Page";
div1.appendChild(h11);
const p1 = document.createElement('p');
p1.textContent = `${this.welcomeMessage}`;
div1.appendChild(p1);
const button1 = document.createElement('button');
button1.textContent = "Change Message";
button1.addEventListener('click', this.changeMessage.bind(this));
div1.appendChild(button1);
}
show() {
this.root.style.display = 'block';
}
hide() {
this.root.style.display = 'none';
}
get welcomeMessage() { return this._welcomeMessage; }
set welcomeMessage(value) {
if (this._welcomeMessage !== value) {
this._welcomeMessage = value;
this.p1.textContent = `${this.welcomeMessage}`;
}
}
changeMessage() {
this.welcomeMessage = "Message Updated!";
}
}
class About {
constructor() {
this._route = '/about';
this._init();
}
_init() {
// Create root element
this.root = document.createElement('div');
const style = document.createElement('style');
style.textContent = `
.about {
padding: 20px;
background-color: #e0e0e0;
}
`;
this.root.appendChild(style);
const div1 = document.createElement('div');
div1.setAttribute('class', 'about');
this.root.appendChild(div1);
const h11 = document.createElement('h1');
h11.textContent = "About Us";
div1.appendChild(h11);
const p1 = document.createElement('p');
p1.textContent = `${this.aboutText}`;
div1.appendChild(p1);
}
show() {
this.root.style.display = 'block';
}
hide() {
this.root.style.display = 'none';
}
get aboutText() { return this._aboutText; }
set aboutText(value) {
if (this._aboutText !== value) {
this._aboutText = value;
this.p1.textContent = `${this.aboutText}`;
}
}
updateAbout(newText) {
this.aboutText = newText;
}
}
/* Router Class */
class Router {
constructor(routes) {
this.routes = routes;
this.pages = {};
this.currentRoute = null;
this.init();
}
init() {
// Instantiate all pages
for (const route in this.routes) {
const pageClass = this.routes[route];
this.pages[route] = new window[pageClass]();
// Initially hide all pages
this.pages[route].hide();
// Append to body
document.body.appendChild(this.pages[route].root);
}
// Handle initial load
window.addEventListener('load', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
// Handle hash changes
window.addEventListener('hashchange', () => {
this.handleRoute(window.location.hash.slice(1) || '/');
});
}
handleRoute(route) {
if (this.currentRoute === route) return;
if (this.pages[route]) {
if (this.currentRoute && this.pages[this.currentRoute]) {
this.pages[this.currentRoute].hide();
}
this.pages[route].show();
this.currentRoute = route;
} else {
console.warn(`Route "${route}" is not registered.`);
}
}
}
// Initialize Router with routes
const router = new Router({
"/": "Home",
"/about": "About"
});
</script>
</body>
</html>
Key Points:
- Components Registration: Custom elements like
<header-component> are defined and registered.
- Page Classes: Each page has its own class (e.g.,
Home, About) with methods to show/hide the page and handle dynamic content.
- Router Initialization: The
Router is initialized with all available routes, managing page visibility based on the URL hash.
8. Navigating Between Pages
To navigate between pages, you can use anchor tags with hash routes. For example:
<nav>
<a href="#/">Home</a>
<a href="#/about">About Us</a>
</nav>
Clicking these links will trigger the Router to display the corresponding page.
9. Handling Dynamic Content and Methods
Dynamic expressions within {} in your .page.html files are automatically transformed into reactive bindings within the generated classes. Here's how it works:
-
Dynamic Text Content:
- Example:
<p>{welcomeMessage}</p> becomes a paragraph that displays the value of this.welcomeMessage.
- When
this.welcomeMessage is updated via a setter, the text content of the paragraph updates automatically.
-
Dynamic Attributes:
- Example:
<img src="{imageSource}" alt="Profile Picture"> dynamically sets the src attribute based on this.imageSource.
- Updating
this.imageSource via a setter will automatically update the src attribute of the image.
-
Custom Methods:
- Defined within the
<script> section, methods like changeMessage can manipulate properties and, consequently, the DOM.
10. Summary
By following the steps above, you've successfully enhanced your project to:
- Treat
.page.html files similarly to components but compile them into JavaScript classes.
- Generate dynamic classes with getters, setters, and custom methods based on the page's
<script> section.
- Implement a
Router class that manages page navigation by listening to <load route="path"> tags and URL hash changes.
- Ensure dynamic content within pages is reactive, updating the DOM seamlessly when underlying properties change.
This architecture promotes modularity, scalability, and maintainability, allowing you to efficiently manage both components and pages within your project.
Further Enhancements
To further improve your framework, consider implementing the following features:
- Nested Routing: Allow routes to have nested paths for more complex navigation structures.
- Route Guards: Implement authentication checks before navigating to certain routes.
- Lazy Loading: Dynamically load page classes only when their routes are accessed to improve initial load times.
- State Management: Integrate a state management system to handle shared states across different pages and components.
- Error Handling Pages: Create dedicated error pages (e.g., 404 Not Found) to handle invalid routes gracefully.
Implementing these features can provide a more robust and user-friendly application experience.