To enhance the Cat Framework with page routing and dynamic content loading using .page.html files, we'll follow the requirements and implementation steps you've outlined. Below is a comprehensive guide, including code snippets, to achieve this functionality.
Table of Contents
- Overview
- 1. Modifying
component.js
- 2. Creating
router.js
- 3. Updating
compiler.js
- 4. Enhancing
page.js
- 5. Example
.page.html File
- 6. Final Project Structure
- 7. Testing the Implementation
Overview
We'll implement the following features:
- Component Handling: Continue handling
.comp.html files as custom elements.
- Page Routing: Introduce
.page.html files that represent different routes.
- Router Class: Manage route-to-page mappings and render pages dynamically.
- Compiler Enhancements: Compile
.page.html files appropriately and integrate the router into the final HTML.
1. Modifying component.js
a. Generating Random Class Names for Pages
First, we'll add a utility function to generate random class names. Then, we'll modify the generateClassCode function to handle both components and pages based on a parameter.
// 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');
/**
* Generate a random class name for pages.
* @returns {string} - Random class name.
*/
function generateRandomClassName() {
const randomNum = Math.floor(Math.random() * 100000);
return `Page_${randomNum}`;
}
/**
* 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('');
}
/**
* Generate the class code for the component or page.
* @param {object} component - Component or page details.
* @param {boolean} isPage - Flag indicating if it's a page.
* @returns {string} - The compiled class code.
*/
function generateClassCode({ tagName, html, style, properties, methods }, isPage = false) {
const className = isPage ? generateRandomClassName() : 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
classCode += `
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 += `}
`;
if (!isPage) {
// Register as custom element
classCode += `
customElements.define('${tagName}', ${className});
`;
} else {
// Export the class for Router to use
classCode += `
export { ${className} };
`;
}
return classCode;
}
// ... Rest of the code remains unchanged
module.exports = {
parseComponent,
parseScript,
toPascalCase,
escapeBackticks,
generateClassCode,
transformMethodBody,
generateDOMCode,
generateRandomClassName // Exported for use in page.js
};
b. Handling Pages Differently
Ensure that when compiling .page.html files, the generateClassCode function is called with the isPage flag set to true. We'll handle this in compiler.js.
2. Creating router.js
Create a new file router.js under cat/src/. This class will manage route registrations and handle rendering of pages based on the current route.
// cat/src/router.js
class Router {
constructor(routes) {
this.routes = routes; // { route: PageClass }
this.loadElements = document.querySelectorAll('load[route]');
this.init();
}
init() {
// Initial load
this.renderPages();
// Listen to hash changes for routing
window.addEventListener('hashchange', () => {
this.renderPages();
});
}
getCurrentRoute() {
return window.location.hash.slice(1) || '/';
}
renderPages() {
const currentRoute = this.getCurrentRoute();
this.loadElements.forEach(loadEl => {
const route = loadEl.getAttribute('route');
if (route === currentRoute) {
// Clear previous content
loadEl.innerHTML = '';
// Instantiate the page and append
const PageClass = this.routes[route];
if (PageClass) {
const pageInstance = new PageClass();
loadEl.appendChild(pageInstance);
} else {
console.error(`No page class found for route: ${route}`);
}
}
});
}
}
export { Router };
Note: Since .page.html classes are not registered as custom elements and are exported, we need to use ES Modules (import/export). Ensure that your final HTML supports modules.
3. Updating compiler.js
We need to modify compiler.js to handle .page.html files differently from .comp.html files, generate the Router class, and inject the Router initialization into the final HTML.
a. Update compiler.js to Compile .page.html Files
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { parseComponent, parseScript, generateClassCode, transformMethodBody, generateDOMCode, generateRandomClassName } = require('./component');
const { parsePage, detectLoadRoutes } = require('./page');
const { parseDocument } = require('htmlparser2');
const { Router } = require('./router'); // Import Router for compilation
/**
* Detect used components in the provided HTML contents by parsing the HTML tags.
* ... (existing code)
*/
/**
* Generate the registration script for the used components.
* ... (existing code)
*/
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/**']
});
const componentMap = new Map(); // Map of tagName to compiled class code
const parsedComponents = new Set();
for (const file of compFiles) {
try {
const { tagName, html, script, style } = await parseComponent(file);
if (!parsedComponents.has(tagName)) {
const { properties, methods } = parseScript(script);
const classCode = generateClassCode({
tagName,
html,
style,
properties,
methods,
}, false); // false indicates it's a component
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 project directory
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const routeMap = new Map(); // Map of route to PageClass
const pageClasses = {}; // { route: PageClassName }
for (const file of pageFiles) {
try {
const { route, content } = await parsePage(file);
if (routeMap.has(route)) {
console.warn(`⚠️ Duplicate route "${route}" found in ${path.relative(projectRoot, file)}. Overwriting previous route.`);
}
// Parse the .page.html content
const { tagName, html, script, style } = await parseComponent(file, true); // true indicates it's a page
const { properties, methods } = parseScript(script);
const classCode = generateClassCode({
tagName,
html,
style,
properties,
methods,
}, true); // true indicates it's a page
// Generate a unique class name for the page
const pageClassNameMatch = classCode.match(/class\s+(\w+)\s+extends/);
const pageClassName = pageClassNameMatch ? pageClassNameMatch[1] : generateRandomClassName();
routeMap.set(route, pageClassName);
pageClasses[route] = classCode;
console.log(`📄 Parsed and compiled page for route "${route}" from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (routeMap.size === 0) {
console.warn('⚠️ No pages found to map routes.');
}
// -----------------------
// Step 3: Detect Used Components
// -----------------------
// (existing code remains unchanged)
// -----------------------
// Step 4: Handle <load> Tags and Inject Page Content
// -----------------------
// (existing code remains unchanged)
// -----------------------
// Step 5: Generate Registration and Page Scripts
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// Combine all page classes
let pagesScript = '';
Object.values(pageClasses).forEach(pageClassCode => {
pagesScript += `
${pageClassCode}
`;
});
// Generate Router class registration
const routerScript = `
import { Router } from './router.js';
${Object.keys(routeMap).map(route => {
const className = routeMap.get(route);
return `import { ${className} } from './router.js';`;
}).join('\n')}
const routes = {
${Array.from(routeMap.entries()).map(([route, className]) => {
return `'${route}': ${className}`;
}).join(',\n ')}
};
document.addEventListener('DOMContentLoaded', () => {
const router = new Router(routes);
});
`;
// Combine all scripts
const combinedScript = `
${registrationScript}
${pagesScript}
`;
// Inject scripts before closing </body> tag
if (indexContent.includes('</body>')) {
indexContent = indexContent.replace('</body>', `
<script type="module">
${combinedScript}
${routerScript}
</script>
</body>`);
} else {
// If no </body> tag, append the script at the end
indexContent += `
<script type="module">
${combinedScript}
${routerScript}
</script>`;
}
console.log('📝 Injected component registration and router scripts.');
// -----------------------
// Step 6: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };
b. Explanation of Changes
-
Processing .page.html Files: Similar to components, but with differences:
- Random Class Names: Each page gets a unique class name.
- No Registration as Custom Elements: Pages are not registered as custom elements.
- Exported Classes: Pages are exported for the router to instantiate.
-
Combining Scripts:
- Component Registration: All component classes are compiled and their registration scripts are generated.
- Page Classes: All page classes are compiled and included.
- Router Initialization: The router is initialized with the route-to-class mapping.
-
Script Injection:
- All combined scripts are injected into the final
index.html before the closing </body> tag with type="module" to support ES Modules.
4. Enhancing page.js
Update the parsePage function to support generating random class names and ensure it returns necessary details for compilation.
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { generateRandomClassName } = require('./component');
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* Modified to handle pages differently if isPage flag is true.
* @param {string} filePath - Path to the .comp.html or .page.html file.
* @param {boolean} isPage - Flag indicating if it's a page.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string }>} - Component or Page details.
*/
async function parseComponent(filePath, isPage = false) {
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 ${isPage ? 'page' : '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 the route and its content.
* @param {string} filePath - Path to the .page.html file.
* @returns {Promise<{ route: string, content: 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() : '';
// For pages, the tagName can be a generic identifier or derived from filename
const tagName = `page-${route.replace(/[^a-zA-Z0-9]/g, '-')}`;
return { route, content: pageContent, tagName };
}
module.exports = {
parsePage,
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;
}
};
b. Explanation of Changes
- Enhanced
parseComponent: Now accepts an isPage flag to differentiate between component and page parsing.
- Dynamic Tag Name for Pages: Assigns a unique tag name for pages based on the route.
- Exported Utility Function:
generateRandomClassName is exported from component.js for use in page.js.
5. Example .page.html File
Here's an example of how a .page.html file should be structured.
<!-- project-root/home.page.html -->
<page route="/home">
<div>
<h1>Welcome to the Home Page</h1>
<p>Hello, {username}!</p>
<button onclick="handleLogout()">Logout</button>
</div>
</page>
- Elements:
- Root Tag:
<page> with a route attribute specifying the URL fragment.
- Dynamic Expressions:
{username} will be dynamically replaced based on the property's value.
- Event Handlers:
onclick attributes to handle user interactions.
6. Final Project Structure
After implementing the changes, your project structure should look like this:
project-root/
├── cat/
│ ├── bin/
│ │ └── cat.js
│ └── src/
│ ├── compiler.js
│ ├── component.js
│ ├── page.js
│ └── router.js
├── index.html
├── package.json
└── cat.config.json
7. Testing the Implementation
a. Sample index.html
Ensure your index.html has <load> tags where you want dynamic content to be loaded.
<!-- project-root/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cat Framework App</title>
</head>
<body>
<nav>
<a href="#/home">Home</a>
<a href="#/about">About</a>
</nav>
<load route="/home"></load>
<load route="/about"></load>
<!-- The compiler will inject scripts here -->
</body>
</html>
b. Building the Project
Assuming you have a build script in your package.json that runs the compiler, execute:
npm run build
This should generate a compiled index.html with all necessary scripts injected.
c. Running the Project
You can serve the index.html using a simple HTTP server. For example:
npx serve .
Navigate to http://localhost:5000 (or the port provided) and test the routing by clicking on the navigation links.
Additional Considerations
-
ES Module Support: Ensure that your development and production environments support ES Modules since router.js and page classes use import/export.
-
Hash-Based Routing: The router uses hash-based routing (window.location.hash). Ensure that URLs follow the # syntax, e.g., http://localhost:5000/#/home.
-
Dynamic Expressions Security: Be cautious with dynamic expressions to prevent injection attacks. Always sanitize inputs if necessary.
-
Error Handling: Enhance error handling in the router and compiler to provide better debugging information.
-
Styling and Assets: Ensure that styles and assets referenced in components and pages are correctly handled during compilation.
By following the above steps, you should have successfully enhanced the Cat Framework to support page routing and dynamic content loading using .page.html files. This setup allows you to create modular, maintainable, and scalable web applications.