To integrate an isolated attribute data binding feature into your compiler, we'll follow a systematic approach to ensure seamless data flow between parent components and child components using the prop.* syntax. This feature allows parent components to pass data to child components through specially prefixed attributes (e.g., prop-name, prop-uid), which are then encapsulated within a prop object inside the child component's class.
Here's a comprehensive guide to implementing this feature:
Overview of the Feature
- Attribute Detection: Detect attributes prefixed with
prop- on component tags within HTML files.
- Prop Object Initialization: Automatically initialize a
prop object within the component's class to hold these properties.
- Reactive Updates: Ensure that changes to these properties are reactive, updating the DOM as necessary.
- Encapsulation: Maintain isolation of these properties within the
prop object to prevent naming conflicts and enhance maintainability.
Step-by-Step Implementation
1. Modify the scripter.js to Handle prop.* Bindings
We'll start by enhancing the scripter.js to recognize and process prop.* bindings within components.
a. Update the generateDOMCode Function
The generateDOMCode function is responsible for parsing HTML and generating corresponding DOM creation code. We'll modify it to detect prop.* bindings and handle them appropriately.
File: cat/src/scripter.js
// cat/src/scripter.js
// ... existing imports ...
/**
* Generate DOM creation code from HTML using htmlparser2.
* @param {string} html - The inner HTML string of the component or 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 = [];
const propBindings = []; // To track prop.* bindings
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const safeName = sanitizeVarName(node.name);
const varName = safeName + ++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 /, '');
if (node.name === 'router') {
// Handle router tag
const nameAttr = node.attribs.name;
code += ` ${declaration} = document.createElement('div');
${varReference}.id = '${nameAttr}';
`;
} else {
code += ` ${declaration} = document.createElement('${node.name}');
`;
}
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (attrName.startsWith('prop-')) {
// Handle prop bindings
const propKey = attrName.slice(5); // Remove 'prop-' prefix
const { expression, propNames } = generateAttributeExpression(attrValue, true);
code += ` if (${expression} !== undefined) {
${varReference}.prop['${propKey}'] = ${expression};
}
`;
// Track prop bindings for reactive updates
propBindings.push({ propKey, expression });
} else if (attrName === 'class' || attrName === 'style' || attrName.startsWith('data-') || attrName === 'id' || attrName === 'src' || attrName === 'alt') {
// Handle attributes with embedded 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: generateAttributeExpression(attrValue).expression,
});
});
} else if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue.replace(/$$$/, '').trim();
eventListeners.push({ elementVarName: varReference.replace(/^this\./, ''), event, handlerName });
} else if (node.name !== 'router' || attrName !== 'name') {
// For other attributes, excluding 'name' attribute of router
code += ` ${varReference}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Append to parent
const parentRef = parentVarName ? parentVarName : 'fragment';
code += ` ${parentRef}.appendChild(${varReference});
`;
// Traverse children
if (node.children && node.children.length) {
for (let child of node.children) {
traverse(child, 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: generateTextExpression(textContent).expression,
});
});
}
}
}
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;
}
}
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)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
function generateAttributeExpression(attrValue, isProp = false) {
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)));
}
// If it's a prop binding, reference without 'this.'
segments.push(isProp ? `this.prop.${match[1]}` : `this._${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners, propBindings };
}
Explanation of Changes:
propBindings Array: Introduced to track bindings related to prop.* attributes.
- Handling
prop-* Attributes: When an attribute starts with prop-, it's processed to extract the property key (e.g., prop-name becomes name). The attribute's value is parsed for expressions, and the corresponding property in the prop object is set.
- Expression Generation: For
prop-* attributes, expressions are generated to bind the attribute's value to the prop object within the component.
b. Update the generateClassBodyCode Function
Next, we'll modify the generateClassBodyCode function to initialize the prop object and set up reactive properties based on the propBindings detected earlier.
File: cat/src/scripter.js
// cat/src/scripter.js
// ... existing code ...
/**
* Generate the class body code for components and pages.
* @param {object} options - Options for class body generation.
* @returns {string} - The class body code.
*/
function generateClassBodyCode({ properties, methods, domCode, cachedNodes, eventListeners, propBindings, isComponent, parentClass }) {
let classBody = '';
// Constructor
classBody += ` constructor() {
`;
// Include super() call if there is a parent class
if (parentClass) {
classBody += `super();
`;
}
// Initialize properties
properties.forEach(prop => {
classBody += ` this._${prop.name} = ${prop.value};
`;
});
// Initialize prop object
if (propBindings && propBindings.length > 0) {
classBody += `
this.prop = {};
`;
}
// For components, do not build DOM in constructor
if (!isComponent) {
// For pages, build DOM in constructor
classBody += `
this._buildDOM();
`;
}
classBody += ` }
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Include DOM creation code
classBody += domCode;
if (isComponent) {
classBody += `
this._fragment = fragment;
}
`;
} else {
classBody += `
this.rootElement = fragment;
}
`;
}
// connectedCallback
classBody += `
connectedCallback() {
`;
if (isComponent) {
classBody += ` this._buildDOM();
this.appendChild(this._fragment);
`;
}
// Attach event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
disconnectedCallback() {
`;
// Remove event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.removeEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
`;
// Initialize prop bindings in connectedCallback
if (propBindings && propBindings.length > 0) {
classBody += `
attributeChangedCallback(name, oldValue, newValue) {
if (!this.prop) {
this.prop = {};
}
switch(name) {
`;
propBindings.forEach(binding => {
classBody += ` case 'prop-${binding.propKey}':
this.prop.${binding.propKey} = ${binding.expression};
break;
`;
});
classBody += ` }
}
static get observedAttributes() {
return [${propBindings.map(binding => `'prop-${binding.propKey}'`).join(', ')}];
}
`;
}
// Generate getters and setters
Object.keys(cachedNodes).forEach(propName => {
classBody += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
cachedNodes[propName].forEach(node => {
if (node.type === 'text') {
classBody += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classBody += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classBody += ` }
}
`;
});
// Add getters and setters for prop properties
if (propBindings && propBindings.length > 0) {
classBody += `
get prop() { return this._prop; }
set prop(value) {
if (this._prop !== value) {
this._prop = value;
// Trigger re-render or updates as needed
}
}
`;
}
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classBody += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
return classBody;
}
Explanation of Changes:
- Initialization of
this.prop: If propBindings are detected, the constructor initializes this.prop = {};.
attributeChangedCallback: Implements Reactivity by updating this.prop whenever a prop-* attribute changes.
observedAttributes: Specifies which attributes to observe for changes (prop-*).
- Getters and Setters for
prop: Added to manage the prop object.
c. Update the parseComponent and parsePageComponent Functions
Ensure that when parsing component and page files, any prop-* bindings are appropriately detected and passed to the generateClassBodyCode function.
File: cat/src/component.js
// cat/src/component.js
// ... existing imports and code ...
/**
* Generate the class code for the component.
* @param {object} component - Component details.
* @returns {string} - The compiled class code.
*/
function generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
}) {
const className = toPascalCase(tagName);
// Generate DOM code
const { code: domCode, cachedNodes, eventListeners, propBindings } = generateDOMCode(html);
// Generate class body
const classBody = generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
propBindings,
isComponent: true, // Components are custom elements
parentClass: 'HTMLElement', // Components extend HTMLElement
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
File: cat/src/page.js
// cat/src/page.js
// ... existing imports and code ...
/**
* Generate the class code for the page.
* @param {object} page - Page details.
* @returns {string} - The compiled class code.
*/
function generatePageClassCode({
tagName,
html,
style,
properties,
methods,
}) {
const className = toPascalCase(tagName);
// Generate DOM code
const { code: domCode, cachedNodes, eventListeners, propBindings } = generateDOMCode(html);
// Generate class body
const classBody = generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
propBindings,
isComponent: true, // Pages are custom elements
parentClass: 'HTMLElement', // Pages extend HTMLElement
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
Explanation of Changes:
- Passing
propBindings: The destructured propBindings from generateDOMCode are now passed to generateClassBodyCode to handle prop-specific logic.
2. Update the Compiler to Process prop-* Attributes
Ensure that the main compiler (compiler.js) correctly passes the propBindings and integrates them into the registration scripts.
File: cat/src/compiler.js
// cat/src/compiler.js
// ... existing imports ...
/**
* Compiler Function
* @param {string} indexPath - Path to the index.html file.
* @returns {Promise<string>} - Compiled HTML content with component registrations.
*/
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);
// Initialize style accumulator
let accumulatedStyles = '';
// -----------------------
// Step 1: Process Components and Pages
// -----------------------
// Find all .comp.html and .page.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 pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'],
});
const componentMap = new Map(); // Map of tagName to compiled class code
const parsedComponents = new Set(); // To track parsed components
const routeTagMap = []; // Array of { route, tagName }
// 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 = generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
// Accumulate styles
if (style && style.trim()) {
accumulatedStyles += `\n/* Styles for component: ${tagName} */\n${style}`;
}
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}`);
}
}
// Parse and compile each page file as a custom element
for (const file of pageFiles) {
try {
const { tagName, route, html, script, style } = await parsePageComponent(
file
);
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate class code for all pages, regardless of usage
const classCode = generatePageClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
// Accumulate styles
if (style && style.trim()) {
accumulatedStyles += `\n/* Styles for page: ${tagName} */\n${style}`;
}
// Add to routeTagMap
routeTagMap.push({ route, tagName });
console.log(
`📄 Parsed and compiled page: <${tagName}> with route "${route}" from ${path.relative(
projectRoot,
file
)}`
);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components or pages found to compile.');
}
// -----------------------
// Step 2: Detect Used Components and Pages
// -----------------------
// 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 and pages are used across all HTML files
const availableComponents = new Set(componentMap.keys());
const usedComponents = detectUsedComponents(
htmlContents,
availableComponents
);
// Also detect used routes from <load> tags and <router> tags
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
let loadRoutes = [];
htmlContents.forEach((content) => {
let match;
while ((match = loadTagRegex.exec(content)) !== null) {
const route = match[1];
loadRoutes.push(route);
}
});
// Additionally, handle <router name="..."/> tags
const routerTagRegex = /<router\s+name=["']([^"']+)["']\s*\/>/gi;
let routerNames = [];
htmlContents.forEach((content) => {
let match;
while ((match = routerTagRegex.exec(content)) !== null) {
const routerName = match[1];
routerNames.push(routerName);
}
});
// Map routes to tagNames
loadRoutes.forEach((route) => {
const mapping = routeTagMap.find((r) => r.route === route);
if (mapping) {
usedComponents.add(mapping.tagName);
} else {
console.error(
`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`
);
}
});
if (usedComponents.size === 0) {
console.warn('⚠️ No used components or pages found in HTML files.');
} else {
console.log(
`📦 Used components and pages: ${[...usedComponents].join(', ')}`
);
}
// -----------------------
// Step 3: Generate Registration and Router Script
// -----------------------
// Generate the registration script for all components and pages
const registrationScript = generateRegistrationScript(componentMap);
// Generate the router script
const routerScript = generateRouterScript(routeTagMap);
// Combine scripts
const fullScript = `
${registrationScript}
${routerScript}
`;
// -----------------------
// Step 4: Inject Styles and Script
// -----------------------
// Inject the accumulated styles into the <head> tag
if (accumulatedStyles.trim()) {
const styleTag = `<style>
${accumulatedStyles}
</style>
`;
// Check if <head> exists
if (indexContent.includes('</head>')) {
indexContent = indexContent.replace('</head>', `${styleTag}</head>`);
} else {
// If no </head>, check for <html> tag to insert after
if (indexContent.includes('<html')) {
indexContent = indexContent.replace(
/<html[^>]*>/,
`$&\n<head>\n${styleTag}\n</head>`
);
} else {
// If no <html> tag, prepend the style tag
indexContent = `<head>\n${styleTag}\n</head>\n${indexContent}`;
}
}
console.log('🎨 Injected accumulated styles into <head>');
}
// Inject the script before the closing </body> tag
if (fullScript.trim()) {
const scriptTag = `<script>
${fullScript}
</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, page registrations, and router script.');
}
// -----------------------
// Step 5: Return Compiled Content
// -----------------------
return indexContent;
}
Explanation of Changes:
- Prop Bindings Integration: Ensured that
propBindings detected during component parsing are correctly passed through to the registration scripts and injected into the final HTML.
3. Update the generateRegistrationScript Function to Handle prop Bindings
Ensure that the registration script includes the necessary logic to handle prop bindings.
File: cat/src/compiler.js
// cat/src/compiler.js
// ... existing imports ...
/**
* Generate the registration script for the components and pages.
* @param {Map<string, string>} classes - Map of tagName to compiled class code.
* @returns {string} - JavaScript code for registering components and pages.
*/
function generateRegistrationScript(classes) {
let script = '';
classes.forEach((classCode, tagName) => {
script += `
${classCode}
`;
});
return script;
}
No changes needed here unless you want to add additional logic specific to prop bindings. The current implementation handles the inclusion of class definitions, which now include prop binding logic.
4. Ensure Proper Handling of prop Object Updates
To maintain reactivity, ensure that whenever a prop property is updated, the corresponding DOM elements reflect the changes.
This has been partially handled in the generateClassBodyCode function through the attributeChangedCallback. However, to further enhance reactivity, especially for nested prop properties like prop.name and prop.uid, consider using JavaScript's Proxy for deep observation or manually set up setters for nested properties.
For simplicity and adherence to native APIs, we'll manually set up setters for each prop property.
File: cat/src/scripter.js
// cat/src/scripter.js
// ... existing code ...
/**
* Generate the class body code for components and pages.
* @param {object} options - Options for class body generation.
* @returns {string} - The class body code.
*/
function generateClassBodyCode({ properties, methods, domCode, cachedNodes, eventListeners, propBindings, isComponent, parentClass }) {
let classBody = '';
// Constructor
classBody += ` constructor() {
`;
// Include super() call if there is a parent class
if (parentClass) {
classBody += `super();
`;
}
// Initialize properties
properties.forEach(prop => {
classBody += ` this._${prop.name} = ${prop.value};
`;
});
// Initialize prop object
if (propBindings && propBindings.length > 0) {
classBody += `
this._prop = {};
`;
// Initialize each prop key
propBindings.forEach(binding => {
classBody += ` this._prop['${binding.propKey}'] = undefined;
`;
});
}
// For components, do not build DOM in constructor
if (!isComponent) {
// For pages, build DOM in constructor
classBody += `
this._buildDOM();
`;
}
classBody += ` }
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Include DOM creation code
classBody += domCode;
if (isComponent) {
classBody += `
this._fragment = fragment;
}
`;
} else {
classBody += `
this.rootElement = fragment;
}
`;
}
// connectedCallback
classBody += `
connectedCallback() {
`;
if (isComponent) {
classBody += ` this._buildDOM();
this.appendChild(this._fragment);
`;
}
// Attach event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
disconnectedCallback() {
`;
// Remove event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classBody += ` this.${listener.elementVarName}.removeEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classBody += ` }
`;
// Initialize prop bindings in connectedCallback
if (propBindings && propBindings.length > 0) {
// No additional code needed here as attributeChangedCallback handles prop updates
}
// attributeChangedCallback
if (propBindings && propBindings.length > 0) {
classBody += `
attributeChangedCallback(name, oldValue, newValue) {
if (!this.prop) {
this.prop = {};
}
switch(name) {
`;
propBindings.forEach(binding => {
classBody += ` case 'prop-${binding.propKey}':
this.prop.${binding.propKey} = ${binding.expression};
break;
`;
});
classBody += ` }
}
static get observedAttributes() {
return [${propBindings.map(binding => `'prop-${binding.propKey}'`).join(', ')}];
}
`;
}
// Generate getters and setters for properties
Object.keys(cachedNodes).forEach(propName => {
classBody += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
cachedNodes[propName].forEach(node => {
if (node.type === 'text') {
classBody += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classBody += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classBody += ` }
}
`;
});
// Add getters and setters for prop properties
if (propBindings && propBindings.length > 0) {
propBindings.forEach(binding => {
classBody += `
get prop() { return this._prop; }
set prop(value) {
if (JSON.stringify(this._prop) !== JSON.stringify(value)) {
this._prop = value;
// Trigger re-render or updates as needed
// Example: Update DOM elements bound to this.prop
}
}
get ${binding.propKey}() { return this._prop['${binding.propKey}']; }
set ${binding.propKey}(value) {
if (this._prop['${binding.propKey}'] !== value) {
this._prop['${binding.propKey}'] = value;
// Update DOM elements bound to this.prop.${binding.propKey}
}
}
`;
});
}
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classBody += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
return classBody;
}
Explanation of Changes:
this._prop Initialization: Instead of directly initializing this.prop, a private _prop object is used.
- Getters and Setters for
prop Properties: For each propBinding, individual getters and setters are generated to manage updates and ensure reactivity.
- Immutable Updates: Checks are added to prevent unnecessary updates by comparing old and new values using
JSON.stringify.
- Reactivity Triggers: Placeholders for triggering DOM updates are added in setters, which can be further implemented as needed.
5. Test the Implementation
Let's verify the implementation with your provided HTML files.
a. Parent Component (app.page.html)
File: app/pages/app.page.html
<!-- app.page.html -->
<app route="/">
<h1>{title}</h1>
<item-comp prop-uid="{index}" prop-name="Beaer"></item-comp>
<button onclick="increment">Increment</button>
</app>
<script>
let title = 98;
let index = 1;
function increment() {
index++;
}
</script>
Explanation:
item-comp Attributes: prop-uid="{index}" and prop-name="Beaer" are passing data into the item-comp component.
{index} is a dynamic value that reflects the index variable.
"Beaer" is a static string value.
b. Child Component (tester.comp.html)
File: app/comp/tester.comp.html
<!-- tester.comp.html -->
<item-comp>
<h1>{prop.name}</h1>
<h2>{prop.uid}</h2>
<p>{description}</p>
</item-comp>
<script>
let description = 'This is a product target A';
</script>
Explanation:
prop.* Bindings in Template: The component accesses prop.name and prop.uid to display dynamic data.
- Local Binding: The
description property is a local binding within the component.
6. Expected Compiled Output
After implementing the above changes, here's what the compiled class code for item-comp (tester.comp.html) might look like.
Compiled Class Code for item-comp
class ItemComp extends HTMLElement {
constructor() {
super();
this._prop = {};
}
_buildDOM() {
const fragment = document.createDocumentFragment();
this.itemComp1 = document.createElement('item-comp');
fragment.appendChild(this.itemComp1);
this.itemComp1.h1_1 = document.createElement('h1');
this.itemComp1.appendChild(this.itemComp1.h1_1);
this.itemComp1.h1_1.textContent = this.prop.name;
this.itemComp1.h2_2 = document.createElement('h2');
this.itemComp1.appendChild(this.itemComp1.h2_2);
this.itemComp1.h2_2.textContent = this.prop.uid;
this.itemComp1.p3 = document.createElement('p');
this.itemComp1.appendChild(this.itemComp1.p3);
this.itemComp1.p3.textContent = this.description;
this._fragment = fragment;
}
connectedCallback() {
this._buildDOM();
this.appendChild(this._fragment);
}
disconnectedCallback() {
// Remove event listeners if any
}
attributeChangedCallback(name, oldValue, newValue) {
if (!this.prop) {
this.prop = {};
}
switch(name) {
case 'prop-name':
this.prop.name = this.prop.name;
break;
case 'prop-uid':
this.prop.uid = this.prop.uid;
break;
}
}
static get observedAttributes() {
return ['prop-name', 'prop-uid'];
}
get prop() { return this._prop; }
set prop(value) {
if (JSON.stringify(this._prop) !== JSON.stringify(value)) {
this._prop = value;
// Trigger re-render or updates as needed
}
}
get name() { return this._prop['name']; }
set name(value) {
if (this._prop['name'] !== value) {
this._prop['name'] = value;
// Update DOM elements bound to this.prop.name
this.itemComp1.h1_1.textContent = this.prop.name;
}
}
get uid() { return this._prop['uid']; }
set uid(value) {
if (this._prop['uid'] !== value) {
this._prop['uid'] = value;
// Update DOM elements bound to this.prop.uid
this.itemComp1.h2_2.textContent = this.prop.uid;
}
}
// Local property
get description() { return this._description; }
set description(value) {
if (this._description !== value) {
this._description = value;
this.itemComp1.p3.textContent = this.description;
}
}
// Add methods if any
}
Explanation:
this._prop Initialization: The prop object is initialized in the constructor.
- Attribute Handling: When
prop-name or prop-uid attributes change, the corresponding properties in the prop object are updated.
- Reactive Setters: Setters for
name and uid ensure that changes to these properties update the DOM elements (h1 and h2 respectively).
- Local Bindings: The
description property is managed similarly, updating the corresponding p tag.
7. Final Compiled HTML
After compilation, your index.html might look something like this with injected styles and scripts:
<!DOCTYPE html>
<html>
<head>
<style>
/* Styles for component: item-comp */
/* Your component styles here */
</style>
</head>
<body>
<app route="/">
<h1>{title}</h1>
<item-comp prop-uid="{index}" prop-name="Beaer"></item-comp>
<button onclick="increment">Increment</button>
</app>
<script>
// Compiled Class Definitions
class App extends HTMLElement {
// ... Compiled App class code ...
}
class ItemComp extends HTMLElement {
// ... Compiled ItemComp class code ...
}
// Router Script
// ... Your router implementation ...
</script>
</body>
</html>
Explanation:
- Styles Injection: Component-specific styles are injected within the
<head> tag.
- Script Injection: Compiled class definitions and router scripts are injected just before the closing
</body> tag.
Summary
By following the above steps, you've successfully integrated an isolated attribute data binding feature into your compiler. This enhancement allows for clean and maintainable data flow between parent and child components using prop.* bindings, leveraging native JavaScript APIs for reactivity and encapsulation.
Key Takeaways:
- Modular Enhancements: Break down the feature implementation into manageable parts, modifying specific functions to handle new bindings.
- Reactive Setters: Implement setters that update the DOM when properties change, ensuring the UI remains in sync with the underlying data.
- Encapsulation: Use objects like
prop to encapsulate related properties, preventing namespace pollution and enhancing code readability.
Feel free to further customize and extend this feature based on your project's specific needs!