To integrate a new isolated logic for reactive properties that allows users to pass data to components using the prop-{name} attribute convention, you'll need to modify several parts of your compiler system. This includes updating your scripter.js, component.js, and potentially compiler.js files to handle the new prop object within your components.
Below is a comprehensive guide detailing the necessary changes, complete with updated code snippets and explanations.
Overview
-
Detection of prop- Attributes:
- Modify the DOM generation process to identify attributes prefixed with
prop-.
- Extract these attributes and bundle them into a
prop object within the component's class.
-
Reactive prop Object:
- Implement getters and setters for each property within the
prop object to ensure reactivity.
- Update the template bindings to reference
prop properties accordingly.
-
Handling in Templates:
- Ensure that the component's template can seamlessly use
{prop.name}, {prop.uid}, etc., reflecting the values passed via attributes.
-
Compiler Integration:
- Ensure that the compiler correctly injects the necessary scripts and styles to support the new reactive
prop logic.
Step 1: Update scripter.js to Handle prop- Attributes
The scripter.js module is responsible for parsing scripts and generating DOM manipulation code. We'll enhance it to detect prop- prefixed attributes and assign them to a prop object within the component's class.
Changes in scripter.js
-
Detect and Extract prop- Attributes:
- When traversing attributes of a component, identify those that start with
prop-.
- Extract the property name and value, handling both static values and dynamic expressions.
-
Assign to prop Object:
- Instead of setting these as standard attributes, assign them to a
this.prop object within the component's class.
- Ensure that
this.prop is initialized and reactive.
-
Update Template Bindings:
- Ensure that template expressions like
{prop.name} reference the prop object correctly.
Here's the updated scripter.js:
// 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.prop.propName = value;'
const assignRegex = new RegExp(`([^\\.\\w$])${propName}\\s*=`, 'g');
transformedBody = transformedBody.replace(assignRegex, `$1this.prop.${propName} =`);
// Replace variable references with 'this.prop.propName'
const varRegex = new RegExp(`([^\\.\\w$])${propName}([^\\w$])`, 'g');
transformedBody = transformedBody.replace(varRegex, `$1this.prop.${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 = [];
const propAttributes = {}; // Collect prop- attributes
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- attributes
const propName = attrName.slice(5); // Remove 'prop-' prefix
const { expression, propNames } = generateAttributeExpression(attrValue);
// Initialize prop object if not already
if (!propAttributes[propName]) {
propAttributes[propName] = expression;
code += ` this.prop = this.prop || {};
this.prop.${propName} = ${expression};
`;
// Register as a reactive property
cachedNodes[propName] = [];
}
} 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: `this.prop.${propName}`,
});
});
} 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.${propName}`,
});
});
}
}
}
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.prop.${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.prop.${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, propAttributes };
}
/**
* 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 }) {
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
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 += ` }
`;
// Generate getters and setters for 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 += ` }
}
`;
});
// Add prop object getters and setters for reactivity
classBody += `
get prop() { return this._prop; }
set prop(newProps) {
this._prop = Object.assign({}, this._prop, newProps);
for (const [key, value] of Object.entries(newProps)) {
if (this.hasOwnProperty(\`_\${key}\`)) {
this[\`_\${key}\`] = value;
}
// Update any cached nodes bound to this prop
if (this.cachedNodes && this.cachedNodes[key]) {
this.cachedNodes[key].forEach(node => {
if (node.type === 'text') {
this[node.varName].textContent = value;
} else if (node.type === 'attribute') {
this[node.elementVarName].setAttribute(node.attrName, value);
}
});
}
}
}
`;
// 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,
};
Explanation of Changes
-
Prop Attribute Detection:
- Added a
propAttributes object to collect all prop- prefixed attributes.
- In the
traverse function, when an attribute starts with prop-, it's extracted and assigned to this.prop.<propName>.
-
Reactive prop Object:
- Initialized
this.prop in the constructor.
- Updated the
generateTextExpression and generateAttributeExpression functions to reference this.prop.<propertyName> instead of this.<propertyName>.
-
Class Body Enhancements:
- Added getters and setters for the
prop object to ensure that any updates to prop properties are reactive.
- In the setter for
prop, merged new properties and updated the DOM accordingly.
-
Ensure Reactivity in DOM Bindings:
- Cached nodes are now also updated when
prop properties change, ensuring that the DOM reflects the latest prop values.
Step 2: Update component.js to Integrate prop Object
With scripter.js handling the extraction and assignment of prop- attributes, we'll ensure that the generateComponentClassCode function correctly incorporates the reactive prop object within the component's class.
Changes in component.js
// cat/src/component.js
const fs = require('fs-extra');
const path = require('path');
const {
parseScript,
generateDOMCode,
generateClassBodyCode,
} = require('./scripter');
/**
* 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.
* @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, propAttributes } = generateDOMCode(html);
// Generate class body
const classBody = generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
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;
}
module.exports = {
parseComponent,
generateComponentClassCode,
toPascalCase,
};
Explanation of Changes
-
Handling prop Attributes:
- The
generateComponentClassCode function now receives propAttributes from generateDOMCode.
- These
prop attributes are incorporated into the prop object within the component's class.
-
Reactivity:
- The
prop object is designed to be reactive. Any updates to its properties will automatically reflect in the component's DOM bindings.
Step 3: Update compiler.js if Necessary
While the primary changes are within scripter.js and component.js, ensure that compiler.js correctly integrates these modifications. Specifically, ensure that when generating the registration scripts, the prop object is recognized and handled appropriately.
Changes in compiler.js
Review the compiler.js to ensure that the generated scripts support the reactive prop object. If you've used the component.js and scripter.js modifications as above, compiler.js should already correctly handle the prop object. However, ensure that any further integration points don't disrupt the new reactive logic.
If necessary, update the generateRegistrationScript or other relevant functions to accommodate the prop object. However, based on the provided compiler.js code, no immediate changes are required.
Step 4: Example Usage
Let's demonstrate how the updated compiler handles the new prop logic with the provided syntax samples.
Example: 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>
Example: 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>
Compiled item-comp
After running the compiler, the item-comp will have a class similar to the following:
class ItemComp extends HTMLElement {
constructor() {
super();
this._description = 'This is a product target A';
this.prop = {};
}
_buildDOM() {
const fragment = document.createDocumentFragment();
this.itemComp1 = document.createElement('item-comp');
this.itemComp1.innerHTML = '<h1>' + this.prop.name + '</h1>' +
'<h2>' + this.prop.uid + '</h2>' +
'<p>' + this.description + '</p>';
fragment.appendChild(this.itemComp1);
this._fragment = fragment;
}
connectedCallback() {
this._buildDOM();
this.appendChild(this._fragment);
}
disconnectedCallback() {
// Cleanup if necessary
}
get description() { return this._description; }
set description(value) {
if (this._description !== value) {
this._description = value;
this.itemComp1.querySelector('p').textContent = value;
}
}
get prop() { return this._prop; }
set prop(newProps) {
this._prop = Object.assign({}, this._prop, newProps);
for (const [key, value] of Object.entries(newProps)) {
if (this.hasOwnProperty(`_${key}`)) {
this[`_${key}`] = value;
}
// Update any cached nodes bound to this prop
if (this.cachedNodes && this.cachedNodes[key]) {
this.cachedNodes[key].forEach(node => {
if (node.type === 'text') {
this[node.varName].textContent = value;
} else if (node.type === 'attribute') {
this[node.elementVarName].setAttribute(node.attrName, value);
}
});
}
}
}
// Additional methods if any
}
customElements.define('item-comp', ItemComp);
Behavior Explanation
-
Initialization:
- The
prop object is initialized in the constructor.
- Any
prop- attributes passed to the component (e.g., prop-uid="{index}" and prop-name="Beaer") are assigned to this.prop.uid and this.prop.name respectively.
-
Reactivity:
- When the
prop object is updated (e.g., when index changes in the parent component), the setter ensures that the DOM elements bound to these properties are updated automatically.
- For instance, changing
prop.uid will update the content of <h2> dynamically.
-
Template Bindings:
- The component's template references
prop properties using {prop.name} and {prop.uid}, ensuring that any changes to these properties reflect in the DOM.
-
Parent Component Interaction:
- In
app.page.html, when the increment function changes the index value, this change propagates to the item-comp via the prop-uid attribute, triggering the reactive update.
Conclusion
By following the above steps, you've successfully integrated an isolated logic for reactive properties using the prop-{name} attribute convention. This enhancement allows components to receive data dynamically and ensures that any changes to these properties are reactive, seamlessly updating the DOM as needed.
Recap of Changes
-
scripter.js:
- Enhanced to detect
prop- attributes.
- Assigned these attributes to a reactive
prop object within the component's class.
-
component.js:
- Updated to incorporate the
prop object logic within component class generation.
-
compiler.js:
- Reviewed to ensure seamless integration (no immediate changes required based on the provided code).
-
Templates & Usage:
- Demonstrated with
tester.comp.html and app.page.html how to utilize the new prop logic effectively.
This modular and reactive approach enhances the flexibility and interactivity of your components, aligning with modern web development practices.