To implement the new prop feature for passing data through attributes in components, we've made updates to the scripter.js and component.js files. These updates include:
-
Collecting prop.key Usages: The compiler now scans both the script sections and the HTML templates within components to identify usages of prop.key. This ensures that any data passed through attributes is correctly recognized and handled.
-
Injecting Console Logs: For debugging purposes, the compiler injects a console.log statement within each component's constructor to log the collected prop keys and their corresponding values.
Below are the fully updated files with the necessary changes highlighted and explained.
cat\src\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, methods, and prop keys.
* @param {string} script - The script content.
* @returns {{ properties: Array, methods: Array, propKeys: Set }} - Parsed properties, methods, and prop keys.
*/
function parseScript(script) {
const properties = [];
const methods = [];
const propKeys = new Set(); // Initialize a Set to store unique prop keys
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 });
}
// **New Feature: Collect prop.key usages in scripts**
else if (node.type === 'MemberExpression' && node.object.name === 'prop') {
if (node.property && node.property.type === 'Identifier') {
propKeys.add(node.property.name);
}
}
});
} catch (error) {
console.error(`Error parsing script: ${error.message}`);
}
return { properties, methods, propKeys };
}
/**
* 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, event listeners, and prop keys.
*/
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 propKeys = new Set(); // Initialize a Set to store unique prop keys
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 => {
propKeys.add(propName); // **Collect prop.key from attributes**
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 => {
propKeys.add(propName); // **Collect prop.key from text nodes**
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.prop.${match[1]}`); // **Update to use this.prop**
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]}`); // **Update to use this.prop**
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, propKeys }; // **Return propKeys**
}
/**
* Generate the class body code for components and pages.
* @param {object} options - Options for class body generation.
* @param {Set<string>} options.propKeys - Set of prop keys to include.
* @returns {string} - The class body code.
*/
function generateClassBodyCode({ properties, methods, domCode, cachedNodes, eventListeners, isComponent, parentClass, propKeys }) {
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};
`;
});
// **New Feature: Initialize this.prop with attribute values**
if (propKeys && propKeys.size > 0) {
classBody += `
this.prop = {
${Array.from(propKeys).map(key => ` ${key}: this.getAttribute('${key}'),`).join('\n')}
};
`;
}
// For components, do not build DOM in constructor
if (!isComponent) {
// For pages, build DOM in constructor
classBody += `
this._buildDOM();
`;
}
// **New Feature: Inject console.log for prop keys**
if (propKeys && propKeys.size > 0) {
classBody += `
console.log('Props:', this.prop);
`;
}
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
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,
};
Changes Summary in scripter.js:
-
Prop Key Collection in Scripts: Modified the parseScript function to identify and collect all usages of prop.KEY within the script sections of components.
-
Prop Key Collection in HTML: Updated the generateDOMCode function to detect prop.KEY patterns within the HTML templates and collect these keys.
-
Class Body Generation: Enhanced the generateClassBodyCode function to initialize a this.prop object in the constructor using the collected prop keys and inject a console.log statement to output these props for debugging.
cat\src\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('');
}
/**
* Parse a component file to extract tagName, HTML, script, style, and prop keys.
* @param {string} filePath - Path to the .comp.html file.
* @returns {Promise<{ tagName: string, html: string, script: string, style: string, propKeys: Set }>} - 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();
// **New Feature: Parse script and DOM to collect prop keys**
const { properties, methods, propKeys: scriptPropKeys } = parseScript(scriptContent);
const { code: domCode, cachedNodes, eventListeners, propKeys: domPropKeys } = generateDOMCode(innerContent);
// Combine prop keys from script and DOM
const combinedPropKeys = new Set([...scriptPropKeys, ...domPropKeys]);
return {
tagName,
html: innerContent,
script: scriptContent,
style: styleContent,
propKeys: combinedPropKeys, // **Include propKeys in the returned object**
};
}
/**
* 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,
propKeys, // **Receive propKeys**
}) {
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
propKeys, // **Pass propKeys to generateClassBodyCode**
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
module.exports = {
parseComponent,
generateComponentClassCode,
toPascalCase,
};
Changes Summary in component.js:
-
Prop Key Parsing: Updated the parseComponent function to utilize the enhanced parseScript and generateDOMCode functions from scripter.js, which now return a set of propKeys. These keys are essential for binding attribute values to the component's internal prop object.
-
Class Body Generation with Prop Keys: Modified the generateComponentClassCode function to pass the collected propKeys to the generateClassBodyCode function. This allows the compiler to generate the necessary code within the component's constructor to initialize the prop object and log the props for debugging.
With these updates, your framework now supports passing data through attributes to components using the reserved prop method. The compiler will correctly parse and handle prop.key usages both within scripts and HTML templates, ensuring seamless data binding and enhanced debugging capabilities.