To integrate the isolated attribute data binding feature into your compiler, you'll need to extend the existing parsing and code generation logic to handle prop-{key} attributes and bind them to a prop object within your component classes. This will allow you to seamlessly bind attributes to properties and reflect them within the component's DOM.
Here's a step-by-step guide to implementing this feature, including necessary code modifications:
1. Parsing prop-{key} Attributes
First, update the parseComponent function in component.js to detect and extract prop-{key} attributes from the component's HTML. These attributes will be used to initialize the prop object in the component class.
Modify parseComponent in component.js
// cat/src/component.js
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* Also extract prop-{key} attributes for data binding.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string, props: Array<string> }>} - Component details.
*/
async function parseComponent(filePath) {
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 component structure in ${path.basename(filePath)}`
);
}
let tagName = componentMatch[1];
const attributesString = componentMatch[2];
let innerContent = componentMatch[3];
// Adjust tagName if it doesn't have a hyphen
if (!tagName.includes('-')) {
tagName = `${tagName}-comp`;
}
// 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();
// Extract prop-{key} attributes
const propAttrRegex = /prop-([\w-]+)\s*=\s*["']([^"']+)["']/g;
let props = [];
while ((match = propAttrRegex.exec(attributesString)) !== null) {
props.push({
key: match[1],
value: match[2], // Initial binding expression or static value
});
}
return {
tagName,
html: innerContent,
script: scriptContent,
style: styleContent,
props, // Add props to the returned object
};
}
Explanation:
- Extracting
prop-{key} Attributes: The regex /prop-([\w-]+)\s*=\s*["']([^"']+)["']/g captures all attributes starting with prop- and extracts their keys and values.
- Storing Props: The extracted props are stored as an array of objects with
key and value, which will be used later to generate the prop object in the class.
2. Generating the prop Object in the Component Class
Next, update the generateComponentClassCode function to incorporate the prop object based on the parsed prop-{key} attributes. This object will contain getters and setters that bind to the component's attributes.
Modify generateComponentClassCode in component.js
// cat/src/component.js
/**
* 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,
props, // Receive props
}) {
const className = toPascalCase(tagName);
// Generate DOM code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
// Generate class body
const classBody = generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
isComponent: true, // Components are custom elements
parentClass: 'HTMLElement', // Components extend HTMLElement
props, // Pass props for prop object generation
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
Update generateClassBodyCode in scripter.js
Now, update the generateClassBodyCode function in scripter.js to handle the prop object creation, including attribute reflection and property bindings.
// cat/src/scripter.js
/**
* 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,
isComponent,
parentClass,
props, // Receive props
}) {
let classBody = '';
// Static get observedAttributes if props exist
if (props && props.length > 0) {
classBody += `
static get observedAttributes() {
return [${props.map(p => `'prop-${p.key}'`).join(', ')}];
}
`;
}
// 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 props object
if (props && props.length > 0) {
classBody += ` this.prop = {};
`;
props.forEach(p => {
const sanitizedKey = sanitizeVarName(p.key);
classBody += ` this.prop.${sanitizedKey} = this.getAttribute('prop-${p.key}') || ${p.value};
`;
});
}
// For components, do not build DOM in constructor
if (!isComponent) {
// For pages, build DOM in constructor
classBody += `
this._buildDOM();
`;
}
classBody += ` }
attributeChangedCallback(name, oldValue, newValue) {
if (name.startsWith('prop-')) {
const propName = name.slice(5);
this.prop[propName] = newValue;
}
}
_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 += ` }
`;
// Generate getters and setters for regular properties
Object.keys(cachedNodes).forEach(propName => {
const nodes = cachedNodes[propName];
classBody += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
nodes.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 += ` }
}
`;
});
// Generate getters and setters for props
if (props && props.length > 0) {
props.forEach(p => {
const sanitizedKey = sanitizeVarName(p.key);
classBody += `
get ${sanitizedKey}() { return this.prop.${sanitizedKey}; }
set ${sanitizedKey}(value) {
if (this.prop.${sanitizedKey} !== value) {
this.prop.${sanitizedKey} = value;
this.setAttribute('prop-${p.key}', value);
}
}
`;
});
}
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classBody += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
return classBody;
}
Explanation:
-
Observed Attributes:
- If
prop attributes are present, observedAttributes is defined to listen for changes in these attributes.
- This allows the
attributeChangedCallback to react to changes in prop-{key} attributes.
-
Constructor Enhancements:
- Initializes a
prop object within the constructor.
- Assigns initial values to
prop keys based on the prop-{key} attributes or default values provided in the component.
-
Attribute Changed Callback:
- Updates the
prop object when any prop-{key} attribute changes.
-
Property Getters and Setters for Props:
- Generates getters and setters for each
prop.{key} to enable binding between attributes and properties.
- The setter updates both the
prop object and the corresponding attribute, ensuring synchronization.
3. Handling prop.{key} Bindings in the DOM
Now, ensure that any {prop.key} bindings within the component's HTML are correctly processed and updated when the corresponding prop values change.
Update generateDOMCode in scripter.js
Modify the generateDOMCode function to detect and handle {prop.key} bindings within text nodes and attributes.
// cat/src/scripter.js
/**
* 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 = [];
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-')) {
// Skip prop- attributes as they are handled separately
continue;
}
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: `this.prop.${sanitizeVarName(propName)}`, // Updated to use prop
});
});
} 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.prop.')) {
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: `this.prop.${sanitizeVarName(propName)}`, // Updated to use prop
});
});
}
}
}
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)));
}
// Support nested properties like {prop.name}
const fullProp = match[1];
const sanitizedProp = sanitizeVarName(fullProp);
segments.push(`this.${fullProp}`);
propNames.push(fullProp);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(JSON.stringify(textContent.slice(lastIndex)));
}
// Combine segments with ' + '
const expression = segments.join(' + ') || '""';
return {
expression,
propNames,
};
}
function generateAttributeExpression(attrValue) {
const exprRegex = /\{([\w$.]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(attrValue)) !== null) {
if (match.index > lastIndex) {
segments.push(JSON.stringify(attrValue.slice(lastIndex, match.index)));
}
// Support nested properties like {prop.name}
const fullProp = match[1];
const sanitizedProp = sanitizeVarName(fullProp);
segments.push(`this.${fullProp}`);
propNames.push(fullProp);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
// Combine segments with ' + '
const expression = segments.join(' + ') || '""';
return {
expression,
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners };
}
Explanation:
-
Handling prop.{key} Bindings:
- The
{prop.key} syntax is detected using the regex /\{([\w$.]+)\}/g.
- These bindings are converted to
this.prop.key in the generated JavaScript, ensuring that they reference the correct properties within the prop object.
-
Caching Nodes for Reactive Updates:
- Nodes containing
prop bindings are cached to allow for dynamic updates when the prop values change.
- The
cachedNodes object maps each prop key to its corresponding DOM nodes, enabling efficient updates.
-
Refactoring Expressions:
- Expressions are updated to reference the
prop object (this.prop.key) instead of standalone properties.
4. Ensuring Reactive Updates with Property Setters
To make sure that changes to the prop object automatically reflect in the DOM, the setters for prop properties should trigger updates to the cached nodes.
Already handled in generateClassBodyCode:
The setters for each prop key not only update the prop object and the corresponding attribute but also rely on the cached nodes to reflect these changes in the DOM. Since the attributeChangedCallback updates the prop object when attributes change, and the setters update both the object and the attributes, reactive updates are ensured.
5. Final Compiled Component Example
With these changes, compiling the tester.comp.html would produce a class similar to the following:
class ItemComp extends HTMLElement {
static get observedAttributes() {
return ['prop-name', 'prop-uid'];
}
constructor() {
super();
this.prop = {};
this.prop.name = this.getAttribute('prop-name') || "Beaer";
this.prop.uid = this.getAttribute('prop-uid') || 1;
}
attributeChangedCallback(name, oldValue, newValue) {
if (name.startsWith('prop-')) {
const propName = name.slice(5);
this.prop[propName] = newValue;
}
}
_buildDOM() {
const fragment = document.createDocumentFragment();
const itemcomp1 = document.createElement('item-comp');
fragment.appendChild(itemcomp1);
const h11 = document.createElement('h1');
h11.textContent = this.prop.name;
itemcomp1.appendChild(h11);
const h21 = document.createElement('h2');
h21.textContent = this.prop.uid;
itemcomp1.appendChild(h21);
const p1 = document.createElement('p');
p1.textContent = this.description;
fragment.appendChild(p1);
this._fragment = fragment;
}
connectedCallback() {
this._buildDOM();
this.appendChild(this._fragment);
}
disconnectedCallback() {}
get description() { return this._description; }
set description(value) {
if (this._description !== value) {
this._description = value;
// Update cached nodes if any
this.p1.textContent = this.description;
}
}
}
customElements.define('item-comp', ItemComp);
Key Points in the Compiled Class:
- Observed Attributes:
prop-name and prop-uid are observed for changes.
- Constructor: Initializes the
prop object with values from attributes or default values.
- Attribute Changed Callback: Updates the
prop object when prop-name or prop-uid attributes change.
- DOM Building:
{prop.name} and {prop.uid} bindings are correctly referenced as this.prop.name and this.prop.uid.
- Property Setters: Changing
prop properties will update the respective DOM nodes.
6. Testing the Feature
Given your app.page.html and tester.comp.html, compiling them with the updated compiler will produce components that correctly bind prop attributes to properties within the component classes. Here's how the process works:
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>
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>
Compiled Component (ItemComp)
As shown earlier, the compiled ItemComp class correctly initializes and binds the prop object, reflecting changes in the DOM when prop-name or prop-uid attributes change.
7. Additional Enhancements
To further refine the data binding mechanism, consider the following enhancements:
-
Type Conversion:
- Convert attribute values to appropriate types (e.g., numbers, booleans) based on predefined property types or naming conventions.
-
Default Values:
- Allow components to define default values for
prop properties when attributes are not provided.
-
Two-Way Binding:
- Implement two-way binding where changes in the
prop object reflect back to the attributes and vice versa.
-
Attribute Reflection:
- Ensure that setting properties programmatically updates the corresponding attributes, maintaining synchronization.
-
Error Handling:
- Add error handling for missing
prop attributes or invalid binding expressions to aid developers during development.
8. Conclusion
By extending the compiler to parse prop-{key} attributes and generate a corresponding prop object within component classes, you've enabled a powerful and isolated data binding mechanism. This approach leverages native Web Components APIs, ensuring efficient updates and seamless integration within your application.
The modifications ensure that:
- Attributes are Bound to Properties:
prop-{key} attributes are automatically linked to prop properties, enabling dynamic data binding.
- Reactive Updates: Changes to
prop properties or corresponding attributes reflect immediately in the DOM.
- Clean Separation: The
prop object provides an isolated namespace for property bindings, avoiding conflicts and enhancing maintainability.
Implementing these changes will significantly enhance your component architecture, providing a robust foundation for building dynamic and interactive web applications.