Integration Proposal Report
Overview of the Existing Compiler
The current compiler system is designed to process HTML-based components and pages, converting them into custom elements with associated JavaScript class definitions. The system comprises several modules:
-
compiler.js: Orchestrates the compilation process, handling file I/O, detecting used components, accumulating styles, generating registration and router scripts, and injecting these into the index.html file.
-
component.js: Parses .comp.html files to extract component details (tag name, HTML, script, style) and generates the corresponding JavaScript class code that extends HTMLElement.
-
page.js: Similar to component.js, but tailored for .page.html files, which also include routing information. It generates JavaScript classes for pages as custom elements.
-
scripter.js: Handles script parsing within components and pages. It utilizes the Acorn parser to extract properties and methods from <script> sections, transforms template expressions (e.g., {this._propName}), and generates DOM manipulation code based on the component's HTML structure.
-
Dependency Libraries: The compiler leverages libraries like fs-extra for file operations, glob for file pattern matching, and htmlparser2 for HTML parsing.
Current Workflow
-
File Discovery: The compiler scans the project directory for .comp.html and .page.html files, excluding directories like node_modules and internal cat directories to prevent recursion.
-
Parsing Components and Pages: Each component and page file is parsed to extract its tag name, HTML content, scripts, and styles. These are then transformed into JavaScript class definitions using component.js and page.js.
-
Script Generation: scripter.js processes the extracted scripts to identify properties and methods, transforming template expressions into JavaScript code that dynamically updates the DOM based on property changes.
-
Usage Detection: The compiler analyzes all .html files to identify which components and pages are actually used, ensuring that only relevant code is included in the final build.
-
Registration and Routing: Generated scripts for component registration and client-side routing are injected into the index.html file, along with accumulated styles.
Proposed Feature: Passing Properties via Attributes to Components
Feature Description
Introduce the capability to pass properties to components through HTML attributes, allowing components to access these properties via a prop object within their class definitions. This enables dynamic and flexible data binding between parent elements and child components.
Example Syntax:
<!-- app.page.html -->
<app route="/">
<counter-logic uid="10"></counter-logic>
</app>
<!-- tester.comp.html -->
<item-comp>
<h1>{prop.uid}</h1>
</item-comp>
In this example:
- The
<counter-logic> component is instantiated with an attribute uid="10".
- Inside the
<item-comp> component, {prop.uid} accesses the passed uid property.
Integration Requirements
-
Non-Intrusive Integration: The new feature must integrate seamlessly without altering or disrupting existing compiler functionalities.
-
Build-Time Processing: The creation and assignment of the prop object must occur during the build process, ensuring that runtime performance remains unaffected.
-
Support for Static Attributes: The initial implementation will focus on static attribute values, as indicated by the example.
Integration Strategy
To integrate the new feature effectively while adhering to the requirements, the following strategy is proposed:
1. Enhance Component Usage Detection
Objective: Identify components instantiated with attributes to map these attributes to the prop object within the component.
Implementation Steps:
Code Snippet Example:
function detectUsedComponents(htmlContents, availableComponents) {
const usedComponents = new Map();
const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b([^>]*)>/g;
htmlContents.forEach((content) => {
let match;
while ((match = tagRegex.exec(content)) !== null) {
let tag = match[1];
if (availableComponents.has(tag)) {
const attrsString = match[2];
const attrsRegex = /([a-zA-Z][a-zA-Z0-9-]*)=["']([^"']+)["']/g;
let attrMatch;
const attrs = {};
while ((attrMatch = attrsRegex.exec(attrsString)) !== null) {
attrs[attrMatch[1]] = attrMatch[2];
}
usedComponents.set(tag, attrs);
}
}
});
return usedComponents;
}
2. Pass Collected Attributes to Component Class Generation
Objective: Ensure that attributes passed during component instantiation are available within the component's class via the prop object.
Implementation Steps:
Code Snippet Example:
// In compiler.js
usedComponents.forEach((attrs, tagName) => {
// Pass attrs to generateComponentClassCode
const classCode = generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
props: attrs, // New parameter
});
componentMap.set(tagName, classCode);
});
// In component.js
function generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
props, // New parameter
}) {
const className = toPascalCase(tagName);
// DOM and other code generation remains unchanged...
// Assemble the full class code with prop initialization
let classCode = `class ${className} extends HTMLElement {
constructor() {
super();
this.prop = ${JSON.stringify(props)};
${/* Existing initialization code */ ''}
}
connectedCallback() {
${/* Existing connectedCallback code */ ''}
}
${/* Existing getters, setters, and methods */ ''}
}
customElements.define('${tagName}', ${className});
`;
return classCode;
}
3. Update Template Expression Handling
Objective: Allow components to access passed properties via the prop object within their templates (e.g., {prop.uid}).
Implementation Steps:
Code Snippet Example:
function generateDOMCode(html) {
// Existing implementation...
function generateTextExpression(textContent) {
const exprRegex = /\{([\w$.]+)\}/g; // Updated regex to allow dots for prop access
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]}`);
const propAccess = match[1].split('.'); // Handle nested properties
if (propAccess.length > 1 && propAccess[0] === 'prop') {
propNames.push(propAccess[1]);
} else {
propNames.push(match[1]);
}
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(JSON.stringify(textContent.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
// Existing implementation...
}
4. Ensure Reactive Updates (Optional Enhancement)
Objective: While not explicitly required, enabling reactivity for prop changes can enhance component interactivity.
Implementation Steps:
5. Maintain Existing Compiler Features
Objective: Ensure that the integration of the new prop feature does not interfere with or alter existing compiler functionalities.
Implementation Steps:
-
Conditional Processing:
- Only process and generate
prop objects for components that are instantiated with attributes.
- Components without attributes remain unaffected, maintaining their current behavior.
-
Testing and Validation:
- Conduct thorough testing to verify that existing components and pages function as intended post-integration.
- Implement automated tests to cover scenarios with and without the new
prop feature.
Detailed Implementation Steps
Below is a comprehensive step-by-step guide to implementing the proposed integration, ensuring adherence to the specified requirements.
Step 1: Enhance Component Usage Detection
-
Objective: Detect components instantiated with attributes and capture the attributes' names and values.
-
Modification in compiler.js:
/**
* Detect used components in the provided HTML contents by parsing the HTML tags.
* @param {Array<string>} htmlContents - Array of HTML file contents.
* @param {Set<string>} availableComponents - Set of all available component tag names.
* @returns {Map<string, Object>} - Map of used component tag names to their attributes.
*/
function detectUsedComponents(htmlContents, availableComponents) {
const usedComponents = new Map();
// Regex to match all tags in the HTML with attributes
const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b([^>]*)>/g;
htmlContents.forEach((content) => {
let match;
while ((match = tagRegex.exec(content)) !== null) {
let tag = match[1];
if (availableComponents.has(tag)) {
const attrsString = match[2];
const attrsRegex = /([a-zA-Z][a-zA-Z0-9-]*)=["']([^"']+)["']/g;
let attrMatch;
const attrs = {};
while ((attrMatch = attrsRegex.exec(attrsString)) !== null) {
attrs[attrMatch[1]] = attrMatch[2];
}
usedComponents.set(tag, attrs);
}
}
});
return usedComponents;
}
Step 2: Pass Attributes to Component Class Generation
-
Modification in compiler.js:
// After collecting usedComponents as a Map<tagName, attrs>
usedComponents.forEach((attrs, tagName) => {
// Retrieve HTML, style, script as before
const componentData = /* existing retrieval logic */;
const classCode = generateComponentClassCode({
tagName,
html: componentData.html,
style: componentData.style,
properties: componentData.properties,
methods: componentData.methods,
props: attrs, // Pass extracted attributes
});
componentMap.set(tagName, classCode);
});
-
Modification in component.js:
/**
* Generate the class code for the component, including props.
* @param {object} component - Component details.
* @returns {string} - The compiled class code.
*/
function generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
props, // New parameter
}) {
const className = toPascalCase(tagName);
// Generate DOM code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
// Generate class body, including prop initialization
const classBody = generateClassBodyCode({
properties,
methods,
domCode,
cachedNodes,
eventListeners,
isComponent: true,
parentClass: 'HTMLElement',
props, // Pass props for inclusion in class code
});
// Assemble the full class code
let classCode = `class ${className} extends HTMLElement {
${classBody}
}
customElements.define('tagName′,{className});
`;
return classCode;
}
- **Modification in `scripter.js`**:
```javascript
/**
* 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() {
super();
`;
// Initialize prop object if props are provided
if (props && Object.keys(props).length > 0) {
classBody += ` this.prop = ${JSON.stringify(props)};
`;
} else {
classBody += ` this.prop = {};
`;
}
// Initialize properties
properties.forEach(prop => {
classBody += ` this._${prop.name} = ${prop.value};
`;
});
// Continue with DOM building
if (!isComponent) {
classBody += `
this._buildDOM();
`;
}
classBody += ` }
_buildDOM() {
const fragment = document.createDocumentFragment();
${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 based on cachedNodes
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;
}
Step 3: Update Template Expression Handling
-
Modification in scripter.js:
Update the generateTextExpression and generateAttributeExpression functions to recognize and correctly handle expressions like {prop.uid}.
function generateTextExpression(textContent) {
const exprRegex = /\{([\w$.]+)\}/g; // Allow dots for prop access
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]}`); // e.g., this.prop.uid
const propAccess = match[1].split('.');
if (propAccess.length > 1 && propAccess[0] === 'prop') {
propNames.push(propAccess[1]);
} else {
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; // Allow dots for prop access
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]}`); // e.g., this.prop.uid
const propAccess = match[1].split('.');
if (propAccess.length > 1 && propAccess[0] === 'prop') {
propNames.push(propAccess[1]);
} else {
propNames.push(match[1]);
}
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
Step 4: Ensure Backward Compatibility
Step 5: Inject Generated Code
-
Modification in compiler.js:
Ensure that the generated component class code with the prop object is correctly injected into the final script.
// After generating registrationScript and routerScript
const fullScript = `
registrationScript{routerScript}
`;
// Inject the script as before
### **Key Considerations**
1. **Immutable Existing Features**: The integration is designed to be additive. Existing component and page functionalities remain unchanged unless attributes are explicitly passed during instantiation.
2. **Build-Time Processing**: All mappings from HTML attributes to the `prop` object occur during the compilation phase, ensuring runtime performance is unaffected.
3. **Scalability**: The approach supports any number of attributes passed to components, making it scalable for complex applications.
4. **Error Handling**: Implement robust error handling to notify developers of missing routes or invalid component structures, as already partially handled in the existing compiler.
5. **Documentation and Developer Guidance**: Update compiler documentation to guide developers on using the new `prop` feature, including syntax examples and best practices.
### **Conclusion**
The proposed integration approach effectively introduces the capability to pass properties to components via attributes and access them through a `prop` object within the component classes. By enhancing component usage detection, modifying class generation, and updating template expression handling, the feature is seamlessly integrated without disrupting existing compiler functionalities. Adhering to build-time processing ensures that the `prop` object is efficiently generated, maintaining optimal runtime performance.
This strategic integration not only meets the specified requirements but also lays the groundwork for future enhancements, such as dynamic property bindings and reactivity, thereby augmenting the compiler's robustness and developer flexibility.