Detect used components in the provided HTML contents by parsing the HTML tags.
@param {Array} htmlContents - Array of HTML file contents.
@param {Set} availableComponents - Set of all available component tag names.
@returns {Set} - 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;
}
/**
Compiler Function
@param {string} indexPath - Path to the index.html file.
@returns {Promise} - Compiled HTML content with component and page registrations.
*/
async function compile(indexPath) {
// Read the index.html content
let indexContent = await fs.readFile(indexPath, 'utf-8');
// -----------------------
// 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}`);
}
Assistant
}
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/**']
});
// Initialize pageCounter
let pageCounter = 1;
const pageClassMap = new Map(); // Map of route to page class details
const pageHtmlContents = []; // For component usage detection
let collectedPageStyles = ''; // Collect styles from all pages
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parsePageComponent(file);
const className = `_Page${pageCounter++}`;
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate class code
const classCode = generatePageClassCode({
className,
html,
style,
properties,
methods,
});
pageClassMap.set(route, { className, classCode });
console.log(`📄 Parsed and compiled page: ${className} for route "${route}" from ${path.relative(projectRoot, file)}`);
// Collect html content
pageHtmlContents.push(html);
// Collect styles
if (style) {
collectedPageStyles += style + '\n';
}
} 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
// -----------------------
// 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});
}
}
// Combine with pages' html content
const allHtmlContents = htmlContents.concat(pageHtmlContents);
// Detect which components are used across all HTML files and page html
const availableComponents = new Set(componentMap.keys());
const usedComponents = detectUsedComponents(allHtmlContents, availableComponents);
if (usedComponents.size === 0) {
console.warn('⚠️ No used components found in HTML files.');
} else {
console.log(📦 Used components: ${[...usedComponents].join(', ')});
}
// Find all and tags in indexContent
const loadTagRegex = /<load\s+[^>](route|name)="'["'][^>]>/gi;
const loadRoutes = [];
let match;
while ((match = loadTagRegex.exec(indexContent)) !== null) {
const attrType = match[1];
const value = match[2];
if (attrType === 'route') {
loadRoutes.push(value);
}
}
// 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}".);
}
});
if (collectedPageStyles.trim()) {
const styleTag = <style> ${collectedPageStyles} </style> ;
// Inject the style tag into <head>
if (indexContent.includes('</head>')) {
indexContent = indexContent.replace('</head>', `${styleTag}</head>`);
console.log('🎨 Injected page styles into <head>.');
} else {
// If no </head> tag, prepend the styles
indexContent = styleTag + '\n' + indexContent;
}
if (registrationScript.trim()) {
// Inject the registration script before the closing 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.');
// 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 sections
const scriptRegex = /([\s\S]*?)</script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(content)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all sections
const styleRegex = /([\s\S]*?)</style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all and tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
Sanitize a string to be a valid JavaScript identifier.
@param {string} name - The original name.
@returns {string} - Sanitized identifier.
*/
function sanitizeVariableName(name) {
// Replace invalid characters with underscores
let sanitized = name.replace(/[^A-Za-z0-9_$]/g, '');
// If the name starts with a digit, prefix with underscore
if (/^\d/.test(sanitized)) {
sanitized = '' + sanitized;
}
return sanitized;
}
/**
Generate the class code for the 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(); ;
Transform method body to replace variable references with 'this.' prefix.
@param {string} body - The method body.
@param {Array} 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 component.
@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 sanitizedTagName = sanitizeVariableName(node.name);
const varName = sanitizedTagName + ++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}');
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;
}
}
function generateAttributeExpression(attrValue) {
const exprRegex = /{([\w$]+)}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
// Extract the tag with route attribute
const pageRegex = /<page\s+[^>]route="'["'][^>]>([\s\S]*?)</page>/;
const pageMatch = content.match(pageRegex);
if (!pageMatch) {
throw new Error(Invalid page structure or missing route attribute in ${path.basename(filePath)});
}
const route = pageMatch[1];
let innerContent = pageMatch[2];
// Extract all sections
const scriptRegex = /([\s\S]*?)</script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(content)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all sections
const styleRegex = /([\s\S]*?)</style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all and tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
// Process tags to replace with wrappers at build time
function replaceLoadTags(html) {
return html.replace(/<load\s+[^>]name\s=\s*"'["'][^>]*/?>/gi, function(match, p1) {
// Replace with
return <div data-load-name="${p1}"></div>;
});
}
// Add mount and unmount methods
classCode += `
mount(container) {
if (!this._element) {
this._buildDOM();
}
// Clear the container and append the page content
container.innerHTML = '';
container.appendChild(this._element);
// Register containers and setup route handlers
classCode += `
// Register containers from this page with the Router
if (typeof appRouter !== 'undefined') {
appRouter.registerContainersFrom(this._element);
appRouter.setupRouteHandlers(this._element);
}
}
// Unregister containers from the Router
classCode += `
// Unregister containers from this page
if (typeof appRouter !== 'undefined') {
appRouter.unregisterContainersFrom(this._element);
}
// Remove the element from the container
// Since we're clearing the container's innerHTML in mount, this may not be necessary
}
}
`;
classCode += }\n;
return classCode;
}
/**
Generate the Router class code.
@param {Map<string, {className: string, classCode: string}>} pageClassMap - Map of route to page class details.
@returns {string} - The Router class code.
*/
function generateRouterClassCode(pageClassMap) {
// Generate list of routes and page class names
let routesArray = [];
let routerClassCode = `
class Router {
constructor() {
this.routes = ${routesList};
this.containers = {}; // Cache for load containers
this.pageInstances = {}; // Cache for mounted page instances per container
document.addEventListener('DOMContentLoaded', () => {
this.initializeLoadContainers();
this.setupRouteHandlers();
this.loadDefaultContent();
});
}
initializeLoadContainers() {
const loadTags = document.querySelectorAll('load');
loadTags.forEach(loadTag => {
const loadName = loadTag.getAttribute('name');
const route = loadTag.getAttribute('route');
if (loadName) {
// This load acts as a wrapper
const wrapper = document.createElement('div');
wrapper.setAttribute('data-load-name', loadName);
loadTag.replaceWith(wrapper);
this.containers[loadName] = wrapper;
// If route is specified, load the page into the wrapper
if (route) {
this.loadContentIntoContainer(route, loadName);
}
} else if (route) {
// This load should be replaced immediately by the page content
const routeEntry = this.routes.find(r => r.route === route);
if (routeEntry) {
const pageInstance = new routeEntry.pageClass();
pageInstance._element = null; // Ensure the DOM is built fresh
pageInstance._buildDOM();
loadTag.replaceWith(pageInstance._element);
// Register containers and setup handlers within the replaced content
this.registerContainersFrom(pageInstance._element);
this.setupRouteHandlers(pageInstance._element);
} else {
console.warn(\`No page found for route "\${route}"\`);
}
} else {
console.warn('<load> tag must have either a name or a route attribute.');
}
});
loadContentIntoContainer(route, loadName) {
const container = this.containers[loadName];
if (!container) {
console.warn(`No container found with name "${loadName}"`);
return;
}
const routeEntry = this.routes.find(r => r.route === route);
if (routeEntry) {
// Unmount previous page instance if exists
const prevInstance = this.pageInstances[loadName];
if (prevInstance) {
prevInstance.unmount();
}
const pageInstance = new routeEntry.pageClass();
pageInstance.mount(container);
this.pageInstances[loadName] = pageInstance;
} else {
console.warn(\`No page found for route "\${route}"\`);
}
}
loadDefaultContent() {
// For each container, find the element with 'current' attribute
for (const loadName in this.containers) {
const container = this.containers[loadName];
const currentElement = document.querySelector(`[route][load="${loadName}"][current]`);
if (currentElement) {
const route = currentElement.getAttribute('route');
this.loadContentIntoContainer(route, loadName);
} else if (!container.innerHTML.trim()) {
// If container is empty and no current element, you may define a default route
}
}
}
updateCurrentAttribute(clickedElement, loadName) {
// Remove 'current' attribute from all elements with the same loadName
const elements = document.querySelectorAll(`[route][load="${loadName}"]`);
elements.forEach(el => {
el.removeAttribute('current');
});
// Add 'current' attribute to the clicked element
clickedElement.setAttribute('current', '');
I'm dealing with a problem, if a tag it's defined in a nested .html file, it's not loading the content inside. Consider after compilation, the load tags are compiled into a div, or replaced, depends of how used the load tag. So, please do a depth analysis and understand why it's happening, and which is the most optimal solution. Don't output code, focus on deep understanding, and find a solution.
The issue you're experiencing arises from how the <load> tags inside nested .html files (in your case, within components) are being handled during compilation and runtime. Specifically, when a <load name="name" /> tag is defined inside a component's template, it's not loading the intended content after compilation.
Understanding the Problem:
Compilation Phase:
In Pages: During the compilation of pages (.page.html files), the <load> tags are being processed by the parsePageComponent function in cat/src/page.js. The function replaceLoadTags replaces all <load name="..."/> tags with <div data-load-name="..."></div>.
In Components: In contrast, the parseComponent function in cat/src/component.js does not process or replace <load> tags within components' templates. This means that when components are compiled, any <load> tags inside them remain unchanged in the generated code.
Runtime Phase:
Router Initialization: The Router class's initializeLoadContainers method is called once during the DOMContentLoaded event. It searches for <load> elements in the main document (using document.querySelectorAll('load')) to set up containers and route handlers.
Components' Shadow DOM: When components are instantiated and connected to the DOM, their templates (including any <load> tags) are encapsulated within their Shadow DOMs. Shadow DOM content is not accessible via document.querySelectorAll, which means the router's initialization process doesn't find and process <load> tags inside components.
Resulting Issue:
<load> tags within components' Shadow DOMs are not being processed by the router.
Consequently, the associated content is not loaded into these <load> placeholders inside components.
Optimal Solution:
To resolve this, you need to ensure that <load> tags within components are both:
Replaced appropriately during compilation, so they become recognized placeholders.
Registered with the router during runtime, so the content can be loaded into them.
Steps to Implement the Solution:
Modify the Component Parser to Process <load> Tags:
Update parseComponent Function:
In cat/src/component.js, after extracting and cleaning the inner content of the component, introduce a replaceLoadTags function similar to the one used in parsePageComponent.
// Process <load name="..."/> tags to replace with wrappers at build time
function replaceLoadTags(html) {
return html.replace(/<load\s+[^>]*name\s*=\s*["']([^"']+)["'][^>]*\/?>/gi, function(match, p1) {
// Replace with <div data-load-name="p1"></div>
return `<div data-load-name="${p1}"></div>`;
});
}
// Update innerContent
innerContent = replaceLoadTags(innerContent);
This ensures that any <load name="..."/> tags within components are replaced with <div data-load-name="..."></div> during compilation, making them consistent with how pages handle <load> tags.
Register Load Containers Within Components at Runtime:
Update generateClassCode Function:
In the generated class code for components (still in cat/src/component.js), modify the connectedCallback method to include the registration of load containers and setup of route handlers.
After existing code in connectedCallback, add:
connectedCallback() {
// ... existing connectedCallback code ...
// Register containers and setup route handlers within the shadow DOM
if (typeof appRouter !== 'undefined') {
appRouter.registerContainersFrom(this.shadowRoot);
appRouter.setupRouteHandlers(this.shadowRoot);
}
}
This ensures that when the component is connected to the DOM, it notifies the router about any load containers within its shadow DOM.
Ensure Router Can Access Shadow DOM Elements:
Open Shadow DOM:
Confirm that components are attaching their shadow DOM in open mode, which allows external scripts (like the router) to access their shadow roots:
this.attachShadow({ mode: 'open' });
Modify Router Methods if Necessary:
Explanation of Why This Solution Works:
Consistent Handling of <load> Tags:
By processing <load> tags in both pages and components during compilation, you ensure that all placeholders are standardized and can be uniformly handled at runtime.
Visibility of Load Containers to the Router:
By registering containers from the component's shadow DOM, you're making the router aware of these containers. This overcomes the limitation of the router not being able to query into shadow DOMs during its initial setup.
Dynamic Registration Upon Component Connection:
Components may be added to the DOM after the initial router setup. By including the registration code in connectedCallback, you ensure that any load containers within components are registered whenever the component becomes active in the DOM.
Conclusion:
The core issue stems from the fact that <load> tags inside components are not being processed during compilation and are hidden within shadow DOMs at runtime. By standardizing the processing of <load> tags across pages and components and ensuring that the router is made aware of new load containers within components' shadow DOMs when they are connected, you solve the problem of content not loading inside nested <load> placeholders.
This solution maintains encapsulation principles, leverages the existing router infrastructure, and provides a scalable approach for any number of components containing <load> placeholders.
Not yet included in a published release.
The registerContainersFrom and setupRouteHandlers functions in the router should be able to accept a root element from which they query for containers and route handlers.
These methods already accept an element parameter, so no changes are needed if you're passing this.shadowRoot.