To integrate isolated attribute data binding into our compiler, we'll enhance the existing component.js and scripter.js files. This feature will allow developers to bind component attributes to a prop object within the component's class, enabling reactive data handling using native Web Components APIs.
Below are the detailed steps and the fully updated files to achieve this functionality.
Overview of Changes
-
Detection of prop Bindings:
- Parsing HTML: During the parsing of
.comp.html files, the compiler will scan for {prop.<key>} expressions within the HTML content.
- Attribute Mapping: For each detected
{prop.<key>}, the compiler will look for a corresponding prop-<key> attribute on the component's root element.
-
Generation of prop Object in Class:
- Constructor Initialization: The compiler will generate a
this.prop object within the component's constructor. Each key in this object corresponds to a prop-<key> attribute, retrieving its value using the native getAttribute method.
-
Future Enhancements:
- Getters and Setters: While this initial integration focuses on setting up the
prop object, further enhancements will introduce getters and setters to make the prop properties reactive.
1. Updated component.js
Enhancements in component.js involve detecting prop bindings and generating the corresponding prop object within the component's class.
// cat/src/component.js
const fs = require('fs-extra');
const path = require('path');
const {
parseScript,
generateDOMCode,
generateClassBodyCode,
} = require('./scripter');
/**
* Parses the HTML content to find all {prop.key} bindings.
* @param {string} html - The HTML content of the component.
* @returns {Set<string>} - A set of prop keys used in the HTML.
*/
function collectPropKeys(html) {
const propRegex = /\{prop\.([a-zA-Z0-9_$]+)\}/g;
const props = new Set();
let match;
while ((match = propRegex.exec(html)) !== null) {
props.add(match[1]);
}
return props;
}
/**
* Parse a component file to extract tagName, HTML, script, and style sections.
* Additionally, detect prop bindings and map them to component attributes.
* @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];
let innerContent = componentMatch[2];
// 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();
// Collect prop keys used in the HTML
const propKeys = collectPropKeys(innerContent);
return {
tagName,
html: innerContent,
script: scriptContent,
style: styleContent,
props: Array.from(propKeys),
};
}
/**
* Convert a kebab-case or other tag name to PascalCase for class naming.
* @param {string} tagName - The custom element tag name.
* @returns {string} - PascalCase string.
*/
function toPascalCase(tagName) {
return tagName
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Generate the class code for the component, including the prop object.
* @param {object} component - Component details.
* @returns {string} - The compiled class code.
*/
function generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
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 the prop keys for further processing
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
module.exports = {
parseComponent,
generateComponentClassCode,
toPascalCase,
};
Key Additions:
-
collectPropKeys Function:
- Scans the HTML content for
{prop.<key>} expressions.
- Returns a set of unique prop keys found.
-
Enhanced parseComponent Function:
- Now returns an additional
props property containing an array of prop keys used in the component's HTML.
-
Modified generateComponentClassCode:
- Accepts the
props array and passes it to generateClassBodyCode for inclusion in the class constructor.
2. Updated scripter.js
Enhancements in scripter.js involve generating the prop object within the component's class based on detected prop bindings.
// cat/src/scripter.js
const acorn = require('acorn'); // Import Acorn for JavaScript parsing
const { parseDocument } = require('htmlparser2');
/**
* Parse the script content to extract properties and methods.
* @param {string} script - The script content.
* @returns {{ properties: Array, methods: Array }} - Parsed properties and methods.
*/
function parseScript(script) {
const properties = [];
const methods = [];
try {
// Parse the script content into an AST
const ast = acorn.parse(script, { ecmaVersion: 2020, locations: true });
ast.body.forEach(node => {
if (node.type === 'VariableDeclaration') {
node.declarations.forEach(declarator => {
if (declarator.id.type === 'Identifier') {
const varName = declarator.id.name;
const varValue = script.substring(declarator.init.start, declarator.init.end);
properties.push({ name: varName, value: varValue });
}
});
} else if (node.type === 'FunctionDeclaration') {
const funcName = node.id.name;
const params = node.params.map(param => script.substring(param.start, param.end)).join(', ');
const body = script.substring(node.body.start, node.body.end);
methods.push({ name: funcName, params, body });
}
});
} catch (error) {
console.error(`Error parsing script: ${error.message}`);
}
return { properties, methods };
}
/**
* Transform method body to replace variable references with 'this.' prefix.
* @param {string} body - The method body.
* @param {Array<string>} 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;
}
/**
* Sanitize a string to be a valid JavaScript variable name.
* @param {string} name - The original name.
* @returns {string} - The sanitized name.
*/
function sanitizeVarName(name) {
// Replace invalid characters with underscores
return name.replace(/[^a-zA-Z0-9_$]/g, '_');
}
/**
* 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 === '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;
}
// Additionally, check for prop bindings
const hasPropBinding = Object.values(node.attribs).some(value => /\{prop\.[\w$]+\}/.test(value));
if (hasPropBinding) {
return true;
}
}
if (node.children && node.children.some(child => child.type === 'text' && /\{prop\.[\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) {
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)));
}
segments.push(`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 };
}
/**
* 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 }) {
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 any props are detected
if (props && props.length > 0) {
classBody += ` this.prop = {
${props.map(key => `${key}: this.getAttribute('prop-${key}')`).join(',\n ')}
};
`;
}
classBody += `
this._buildDOM();
`;
classBody += ` }
_buildDOM() {
const fragment = document.createDocumentFragment();
${domCode}
${isComponent ? ` this.appendChild(fragment);` : ` this.rootElement = fragment;`}
}
`;
// connectedCallback
classBody += `
connectedCallback() {
`;
if (isComponent) {
classBody += ` this._buildDOM();
`;
}
// 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
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 methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classBody += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
return classBody;
}
module.exports = {
parseScript,
transformMethodBody,
generateDOMCode,
generateClassBodyCode,
};
Key Additions:
-
Propagation of props:
- The
generateClassBodyCode function now accepts a props parameter, which is an array of prop keys detected in the component's HTML.
-
Initialization of this.prop Object:
- Within the constructor, the
prop object is initialized with keys corresponding to the detected prop bindings. Each key retrieves its value using this.getAttribute('prop-<key>').
-
Enhanced needsReference Function:
- Ensures that elements with
prop bindings are assigned to this.<varName> to maintain proper references for reactive updates.
3. No Changes Required in page.js and compiler.js for This Feature
The current scope focuses on integrating the prop object within components. As such, modifications are confined to component.js and scripter.js. Neither page.js nor compiler.js requires changes for this specific feature.
4. Example Integration
Given the following component and page definitions:
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>
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>
Compiled ItemComp Component
After running the compiler with the updated logic, the ItemComp component will be compiled as follows:
class ItemComp extends HTMLElement {
constructor() {
super();
this.prop = {
name: this.getAttribute('prop-name'),
uid: this.getAttribute('prop-uid')
};
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
this.itemComp = document.createElement('item-comp');
fragment.appendChild(this.itemComp);
const textNode1 = document.createTextNode(this._description);
fragment.appendChild(textNode1);
this.appendChild(fragment);
}
connectedCallback() {
this._buildDOM();
}
disconnectedCallback() {
}
get name() { return this._name; }
set name(value) {
if (this._name !== value) {
this._name = value;
this.itemComp.setAttribute('name', this._name);
}
}
get uid() { return this._uid; }
set uid(value) {
if (this._uid !== value) {
this._uid = value;
this.itemComp.setAttribute('uid', this._uid);
}
}
get description() { return this._description; }
set description(value) {
if (this._description !== value) {
this._description = value;
this.textNode1.textContent = this._description;
}
}
}
customElements.define('item-comp', ItemComp);
Explanation of the Compiled Code:
-
Constructor:
- Initializes the
prop object with name and uid, retrieving their values from the corresponding prop-name and prop-uid attributes.
-
DOM Construction:
- Builds the DOM by creating the necessary elements and text nodes.
- Reactive bindings are set up for
{prop.name}, {prop.uid}, and {description}.
-
Getters and Setters:
- Provides getters and setters for
name, uid, and description.
- The setters ensure that when these properties are updated, the corresponding DOM elements are updated automatically.
5. Testing the Feature
To ensure that the new prop binding feature works as expected, follow these steps:
-
Define a Component with prop Bindings:
- Use
{prop.key} in your component's HTML to bind to properties.
-
Pass Attributes Corresponding to Props:
- When using the component, provide
prop-<key> attributes to pass data.
-
Compile the Project:
- Run the compiler to generate the custom element classes with the
prop object initialized.
-
Verify Reactive Behavior:
- Update the
prop attributes dynamically and observe the changes in the DOM, ensuring that the bindings update correctly.
Conclusion
By enhancing the component.js and scripter.js files, we've successfully integrated isolated attribute data binding into our compiler. This allows for a more structured and reactive approach to managing component properties, leveraging native Web Components APIs without external dependencies. Future developments can expand on this foundation by introducing reactive getters and setters, event dispatching for property changes, and more advanced binding capabilities.