// Regex to match opening tags excluding and
const tagRegex = /<(?!(script|style)\b)(\w[\w-])[^>]>/i;
const match = content.match(tagRegex);
if (!match) {
throw new Error(No valid wrapper tag found in ${path.basename(filePath)});
}
let tagName = match[2];
// If the tag name does not contain a hyphen, append '-cat'
if (!tagName.includes('-')) {
tagName = ${tagName}-cat;
}
// Extract the inner HTML of the first valid wrapper tag
const innerContentRegex = new RegExp(<${match[2]}[^>]*>([\\s\\S]*?)<\\/${match[2]}>, 'i');
const innerMatch = content.match(innerContentRegex);
// Regex to match the 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 tag
const innerContentRegex = new RegExp(<page[^>]*>([\\s\\S]*?)<\\/page>, 'i');
const innerMatch = content.match(innerContentRegex);
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();
Assistant
// 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 tag doesn't contain '-', append '-cat'
if (!tag.includes('-')) {
tag = ${tag}-cat;
}
if (availableComponents.has(tag)) {
usedComponents.add(tag);
}
}
});
return usedComponents;
}
/**
Detect all tags in the provided HTML contents and extract their routes.
@param {Array} htmlContents - Array of HTML file contents.
@returns {Array} - Array of routes found in tags.
*/
function detectLoadRoutes(htmlContents) {
const loadRoutes = [];
// Regex to match 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;
}
/**
Generate the registration script for the used components.
@param {Map<string, string>} components - Map of tagName to template.
@returns {string} - JavaScript code for registering components.
*/
function generateRegistrationScript(components) {
let script = '';
@param {string} indexPath - Path to the index.html file.
@returns {Promise} - 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');
// -----------------------
// 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 template
const parsedComponents = new Set(); // To track parsed components
// Parse each component file
for (const file of compFiles) {
try {
const { tagName, template } = await parseComponent(file);
if (!parsedComponents.has(tagName)) {
componentMap.set(tagName, template);
parsedComponents.add(tagName);
console.log(🔍 Parsed 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 page content
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.);
}
routeMap.set(route, content);
console.log(📄 Mapped route "${route}" to ${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
// -----------------------
// 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});
}
}
// 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(', ')});
}
// Read all .html files and prepare to replace tags
// We will compile each .html file separately and map them to routes
// For simplicity, let's assume that there's a main 'index.html' which is the entry point
// and it contains tags for different routes.
// Alternatively, if multiple HTML files are to be compiled for different routes,
// this can be adjusted accordingly.
// For this implementation, we'll proceed with the main 'index.html' containing tags.
// Detect all routes in all HTML files
const loadRoutes = detectLoadRoutes(htmlContents);
// Prepare a map of route to page content
// Verify that each load route exists in the routeMap
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}".);
}
});
// Now, replace tags in indexContent with the corresponding page content
const loadTagRegex = /<load\s+[^>]route="'["'][^>]>/gi;
indexContent = indexContent.replace(loadTagRegex, (match, p1) => {
const route = p1;
if (routeMap.has(route)) {
console.log(🔄 Injecting content for route "${route}");
return routeMap.get(route);
} else {
console.warn(⚠️ No content found for route "${route}". Keeping <load> tag.);
return match; // Keep the tag if no content is found
}
});
if (registrationScript.trim()) {
// Inject the registration script before the closing tag
const scriptTag = <script> ${registrationScript} </script> ;
code
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 registration scripts.');
Certainly! Based on your requirements, we'll enhance the existing compiler.js to fully parse .comp.html files, extract HTML, script, and style sections, identify reactive expressions, and generate fully functional web components as demonstrated in your compilation format sample.
Below is the complete compiler.js that accomplishes the following:
Parsing .comp.html Files: Extracts HTML, <script>, and <style> sections. Identifies reactive expressions within attributes and text nodes formatted as {expression}.
Generating Class Structures: Creates ES6 classes for each component, initializes default values, and attaches a Shadow DOM.
Building the DOM Programmatically: Converts extracted HTML into JavaScript code using document.createElement and DocumentFragment. Caches node references for elements with reactive expressions.
Creating Getters and Setters: Generates getters and setters for each reactive property to ensure DOM updates upon property changes.
Implementing Event Listeners: Parses event listener definitions from the <script> section and attaches them appropriately.
Compiling and Injecting Components: Compiles all components, detects their usage across HTML files, and injects the necessary registration scripts into the index.html.
javascript
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string }>} - Component details.
*/
async function parseComponent(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the outermost tag name
const tagRegex = /<\s*([\w-]+)(\s+[^>]*)?>/i;
const tagMatch = content.match(tagRegex);
if (!tagMatch) {
throw new Error(`No valid root tag found in ${path.basename(filePath)}`);
}
let tagName = tagMatch[1];
// Ensure the tag name contains a hyphen
if (!tagName.includes('-')) {
tagName = `${tagName}-cat`;
}
// Extract HTML content inside the root tag
const htmlRegex = new RegExp(`<${tagMatch[1]}[^>]*>([\\s\\S]*?)<\\/${tagMatch[1]}>`, 'i');
const htmlMatch = content.match(htmlRegex);
const htmlContent = htmlMatch ? htmlMatch[1].trim() : '';
// Extract <script> section
const scriptRegex = /<script[^>]*>([\s\S]*?)<\/script>/i;
const scriptMatch = content.match(scriptRegex);
const scriptContent = scriptMatch ? scriptMatch[1].trim() : '';
// Extract <style> section
const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/i;
const styleMatch = content.match(styleRegex);
const styleContent = styleMatch ? styleMatch[1].trim() : '';
return {
tagName,
html: htmlContent,
script: scriptContent,
style: styleContent
};
}
/**
* Identify reactive expressions within a string.
* @param {string} str - The string to search for expressions.
* @returns {Array<string>} - Array of expression names.
*/
function identifyExpressions(str) {
const exprRegex = /\{([\w$]+)\}/g;
const expressions = [];
let match;
while ((match = exprRegex.exec(str)) !== null) {
expressions.push(match[1]);
}
return expressions;
}
/**
* Generate the class name in PascalCase from a tag name.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase class name.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Escape backticks in templates to avoid breaking template literals.
* @param {string} str - The template string.
* @returns {string} - Escaped string.
*/
function escapeBackticks(str) {
return str.replace(/`/g, '\\`');
}
/**
* 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, tagName) => {
script += `
${classCode}
customElements.define('${tagName}', ${toPascalCase(tagName)});
`;
});
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 project directory
const compFiles = glob.sync('**/*.comp.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'] // Adjust ignore patterns as needed
});
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)) {
console.log(`ℹ️ Component <${tagName}> from ${path.relative(projectRoot, file)} has already been parsed.`);
continue;
}
// Identify expressions in HTML
const expressions = identifyExpressions(html);
// Parse script to extract properties and methods
const scriptLines = script.split('\n').map(line => line.trim()).filter(line => line);
const properties = [];
const methods = [];
scriptLines.forEach(line => {
// Match variable declarations: let name = 'value';
const varMatch = line.match(/^let\s+([\w$]+)\s*=\s*['"`](.*)['"`];?$/);
if (varMatch) {
properties.push({ name: varMatch[1], value: varMatch[2] });
return;
}
// Match function declarations: function funcName() { ... }
const funcMatch = line.match(/^function\s+([\w$]+)\s*\(([^)]*)\)\s*\{([\s\S]*)\}$/);
if (funcMatch) {
const [, funcName, params, body] = funcMatch;
methods.push({ name: funcName, params, body });
return;
}
});
// Generate class code
const className = toPascalCase(tagName);
let classCode = `class ${className} extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = \`${escapeBackticks(prop.value)}\`;\n`;
});
// Build DOM
classCode += `
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${escapeBackticks(style)}
\`;
fragment.appendChild(style);
`;
}
// Parse HTML and generate DOM creation code
const domCode = generateDOMCode(html);
classCode += domCode;
classCode += `
this.shadowRoot.appendChild(fragment);
}
connectedCallback() {
`;
// Attach event listeners
methods.forEach(method => {
// Find event listeners in the DOM (e.g., onclick="methodName")
// This implementation assumes that event listeners are specified with standard DOM event attributes
// e.g., onclick="handleClick"
// Extract all elements with event attributes and attach listeners
});
// Attach event listeners based on methods
// For simplicity, we'll parse the methods and assume that event listeners are defined in the HTML with attributes like onclick="methodName"
// This requires that during DOM generation, we store references to elements that have event listeners
// Assuming that _eventListeners is an array of { element: reference, event: 'click', handler: 'methodName' }
// We'll have to implement this during DOM generation
// For this implementation, let's assume that event listeners are already attached during _buildDOM
// Alternatively, you can enhance the DOM generation to collect event listeners and attach them here
classCode += ` }
disconnectedCallback() {
// Clean up event listeners if necessary
}
`;
// Generate getters and setters for properties
properties.forEach(prop => {
// Getter
classCode += ` get ${prop.name}() {
return this._${prop.name};
}
set ${prop.name}(value) {
if (this._${prop.name} !== value) {
this._${prop.name} = value;
this._update${toPascalCase(prop.name)}();
}
}
`;
// Update method
classCode += ` _update${toPascalCase(prop.name)}() {
if (this._${prop.name}Node) {
this._${prop.name}Node.textContent = \`${escapeBackticks('{')}${prop.name}${escapeBackticks('}')}\`.replace('{${prop.name}}', this._${prop.name});
}
if (this._${prop.name}Attr) {
this._${prop.name}Attr.value = this._${prop.name};
}
}
`;
});
// Add methods
methods.forEach(method => {
classCode += ` ${method.name}(${method.params}) {
${method.body.split('\n').map(line => ' ' + line).join('\n')}
}
`;
});
classCode += `}\n`;
// Store the compiled class code
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
console.log(`🔍 Parsed and compiled component: <${tagName}> from ${path.relative(projectRoot, file)}`);
} catch (error) {
console.error(`❌ Failed to parse ${file}: ${error.message}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components found to compile.');
}
// -----------------------
// Step 2: 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}`);
}
}
// 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 3: Generate Registration Script
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map())
);
// -----------------------
// Step 4: 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 registration scripts.');
}
// -----------------------
// Step 5: Handle <load> Tags and Inject Page Content
// -----------------------
// Find and replace <load route="..."> tags with corresponding page content
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
// Process <load> tags in the index.html
indexContent = indexContent.replace(loadTagRegex, (match, route) => {
// Path to the page content
const pageFilePath = path.join(projectRoot, `${route}.page.html`);
if (fs.existsSync(pageFilePath)) {
const pageContent = fs.readFileSync(pageFilePath, 'utf-8');
console.log(`🔄 Injected content for route "${route}"`);
return pageContent;
} else {
console.error(`❌ No page found for route "${route}".`);
return match; // Keep the <load> tag if no content is found
}
});
// -----------------------
// Step 6: Return Compiled Content
// -----------------------
return indexContent;
}
/**
* 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 tag doesn't contain '-', append '-cat'
if (!tag.includes('-')) {
tag = `${tag}-cat`;
}
if (availableComponents.has(tag)) {
usedComponents.add(tag);
}
}
});
return usedComponents;
}
/**
* Generate DOM creation code from HTML.
* This is a simplistic parser and may need enhancements for complex HTML structures.
* @param {string} html - The inner HTML string of the component.
* @returns {string} - JavaScript code for building the DOM.
*/
function generateDOMCode(html) {
// This function parses the HTML and generates JavaScript code using document.createElement
// For demonstration purposes, this is a rudimentary parser and may not handle all HTML features.
// For a more robust solution, consider using an HTML parser library.
// Split the HTML into lines and parse manually
const lines = html.split('\n').map(line => line.trim()).filter(line => line);
let code = '';
// Stack to manage element hierarchy
const stack = [];
lines.forEach(line => {
const openingTagMatch = line.match(/^<([a-zA-Z][\w-]*)([^>]*)>/);
const closingTagMatch = line.match(/^<\/([a-zA-Z][\w-]*)>/);
const selfClosingTagMatch = line.match(/^<([a-zA-Z][\w-]*)([^>]*)\/>/);
if (selfClosingTagMatch) {
const [ , tagName, attrs ] = selfClosingTagMatch;
const varName = generateVarName(tagName);
code += ` const ${varName} = document.createElement('${tagName}');\n`;
// Handle attributes
const attrRegex = /([a-zA-Z-:]+)="([^"]+)"/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrs)) !== null) {
const [ , attrName, attrValue ] = attrMatch;
if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerMatch = attrValue.match(/^([a-zA-Z][\w$]*)\((.*)\)$/);
if (handlerMatch) {
const handlerName = handlerMatch[1];
const handlerArgs = handlerMatch[2];
code += ` ${varName}.addEventListener('${event}', this.${handlerName}.bind(this));\n`;
} else {
code += ` ${varName}.addEventListener('${event}', this.${attrValue}.bind(this));\n`;
}
} else {
// Check for reactive expressions in attributes
const exprMatch = attrValue.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Attr = ${varName}.setAttribute('${attrName}', \`\${this.${exprName}}\`);\n`;
} else {
code += ` ${varName}.setAttribute('${attrName}', \`${escapeBackticks(attrValue)}\`);\n`;
}
}
}
stack[stack.length - 1].appendChild(varName);
stack.push({ tagName, varName });
stack.pop(); // Self-closing tag, no need to keep in stack
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
} else if (openingTagMatch) {
const [ , tagName, attrs ] = openingTagMatch;
const varName = generateVarName(tagName);
code += ` const ${varName} = document.createElement('${tagName}');\n`;
// Handle attributes
const attrRegex = /([a-zA-Z-:]+)="([^"]+)"/g;
let attrMatch;
while ((attrMatch = attrRegex.exec(attrs)) !== null) {
const [ , attrName, attrValue ] = attrMatch;
if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerMatch = attrValue.match(/^([a-zA-Z][\w$]*)\((.*)\)$/);
if (handlerMatch) {
const handlerName = handlerMatch[1];
const handlerArgs = handlerMatch[2];
code += ` ${varName}.addEventListener('${event}', this.${handlerName}.bind(this));\n`;
} else {
code += ` ${varName}.addEventListener('${event}', this.${attrValue}.bind(this));\n`;
}
} else {
// Check for reactive expressions in attributes
const exprMatch = attrValue.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Attr = ${varName}.setAttribute('${attrName}', \`\${this.${exprName}}\`);\n`;
} else {
code += ` ${varName}.setAttribute('${attrName}', \`${escapeBackticks(attrValue)}\`);\n`;
}
}
}
// Handle text content or child elements
// This simplistic parser assumes that text nodes come immediately after the opening tag
// For complex HTML structures, consider using a proper HTML parser
const textMatch = line.match(/^<[\w-]+[^>]*>\s*(.*?)\s*$/);
if (textMatch && textMatch[1]) {
const textContent = textMatch[1];
// Check for reactive expressions in text
const exprMatch = textContent.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
code += ` this._${exprName}Node = document.createTextNode(\`\${this.${exprName}}\`);\n`;
code += ` ${varName}.appendChild(this._${exprName}Node);\n`;
} else {
code += ` ${varName}.textContent = \`${escapeBackticks(textContent)}\`;\n`;
}
}
// Append to parent
if (stack.length === 0) {
code += ` fragment.appendChild(${varName});\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
}
// Push to stack
stack.push({ tagName, varName });
} else if (closingTagMatch) {
// Pop the last element from the stack
stack.pop();
} else {
// Handle text nodes outside of tags
const textContent = line;
// Check for reactive expressions in text
const exprMatch = textContent.match(/^\{([\w$]+)\}$/);
if (exprMatch) {
const exprName = exprMatch[1];
const varName = generateVarName('text');
code += ` const ${varName} = document.createTextNode(\`\${this.${exprName}}\`);\n`;
code += ` this._${exprName}Node = ${varName};\n`;
if (stack.length === 0) {
code += ` fragment.appendChild(${varName});\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(${varName});\n`;
}
} else {
code += ` const textNode = document.createTextNode(\`${escapeBackticks(textContent)}\`);\n`;
if (stack.length === 0) {
code += ` fragment.appendChild(textNode);\n`;
} else {
code += ` ${stack[stack.length - 1].varName}.appendChild(textNode);\n`;
}
}
}
});
return code;
}
/**
* Generate a unique variable name based on the tag name.
* @param {string} tagName - The tag name of the element.
* @returns {string} - A unique variable name.
*/
function generateVarName(tagName) {
// Simple counter-based variable name generation
if (!generateVarName.counter) {
generateVarName.counter = {};
}
if (!generateVarName.counter[tagName]) {
generateVarName.counter[tagName] = 1;
} else {
generateVarName.counter[tagName]++;
}
return `${tagName.replace(/-/g, '_')}_${generateVarName.counter[tagName]}`;
}
module.exports = { compile };
Explanation of Enhancements
Component Parsing (parseComponent):
Tag Extraction: Identifies the root tag of the component and ensures it follows the custom element naming convention (contains a hyphen).
Section Extraction: Separates the HTML, <script>, and <style> sections for further processing.
Expression Identification (identifyExpressions):
Detects expressions within {} in both attributes and text nodes to facilitate reactive bindings.
DOM Generation (generateDOMCode):
Converts the extracted HTML into JavaScript code using document.createElement.
Handles attributes, including reactive expressions and event listeners.
Caches references to DOM nodes that are bound to reactive properties for efficient updates.
Class Code Generation:
Constructor: Initializes reactive properties and attaches the Shadow DOM.
_buildDOM: Constructs the component's DOM structure programmatically.
Getters and Setters: For each reactive property, getters and setters are created to manage state and update the DOM when properties change.
Methods: Any methods defined in the <script> section are added to the class, allowing interaction through event listeners.
Event Listener Implementation:
Parses event attributes (e.g., onclick="handleClick()") and attaches corresponding event listeners in the generated class.
Registration Script:
Compiles all used components and injects their registration scripts into the index.html before the closing </body> tag.
Handling <load> Tags:
Replaces <load route="..."> tags in index.html with the corresponding .page.html content based on the route, facilitating simple client-side routing.
Running the Compiler:
Ensure you have fs-extra and glob installed:
bash
npm install fs-extra glob
Then, you can use the compiler in a build script or directly via Node.js:
javascript
Notes and Considerations
HTML Parsing: The generateDOMCode function provided is a basic parser. For complex HTML structures, it's recommended to use a robust HTML parsing library (e.g., htmlparser2) to accurately convert HTML to JavaScript DOM manipulation code.
Reactive Updates: The current implementation assumes that reactive expressions are only used in text nodes and attributes. If deeper reactivity or more complex binding is required, further enhancements will be necessary.
Event Handling: Event listeners are parsed from attributes like onclick. Ensure that method names correspond to those defined in the <script> section of the component.
Error Handling: The compiler includes basic error logging. Depending on your needs, you might want to implement more sophisticated error handling and user feedback mechanisms.
Performance: For large projects with many components, consider optimizing the compiler for performance, possibly by caching parsed components or implementing incremental builds.
This enhanced compiler.js should provide a solid foundation for building and compiling your custom web components from .comp.html files, enabling a streamlined development workflow.