Project Overview
Cat.js is a lightweight, state-of-the-art engine designed to build powerful User Interfaces (UIs). It prioritizes the highest performance and efficiency, based exclusively on modern native browser APIs, primarily Web Components.
Version: 0.1.0 (as of October 1, 2024)
Core Concepts and Principles
Utilizes modern native browser APIs, especially Web Components
Focuses on maximum performance and efficiency
Promotes a lightweight approach to UI development
Emphasizes simplicity and ease of use
Technical Details
Key Features
Client-Side Compiler (CSC) before loading the DOM
Attachment through a script:src tag in the head of HTML documents
Written in vanilla, low-level JavaScript optimized for browser runtime and memory usage
Beautiful and easy-to-use syntax
Efficient project tree structure
Compiles everything on the loading stage, Ahead Of Time (AOT).
Everything that was compiled it's "0-dependency", neither of cat.js.
Implementation Details
No Virtual DOM or similar abstractions
Avoids use of bundlers, Webpack, polyfills, etc.
Discourages writing HTML or CSS code within JavaScript files
Eliminates render methods for components and logic that trigger unnecessary reflows and repainting
Avoid treat Cat.js as a runtime at any cost.
Code
code
Assistant
// Updated cat.js with style tag inclusion fix
(function() {
'use strict';
/**
* Internal module for tracking loaded files.
*/
const Registry = (function() {
const loadedFiles = new Set();
return {
isFileLoaded: (path) => loadedFiles.has(path),
markFileAsLoaded: (path) => loadedFiles.add(path),
};
})();
/**
* Compiler module for generating optimized component classes.
*/
const Compiler = (function() {
/**
* Compiles the component's template and script into an optimized component class definition.
* @param {string} name - The name of the component (e.g., 'my-component').
* @param {string} templateContent - The inner HTML of the component's <template>.
* @param {string} scriptContent - The content of the component's <script>.
*/
function compileComponent(name, templateContent, scriptContent) {
// Helper functions
function componentNameToClassName(name) {
return name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
}
function extractDynamicExpressions(text) {
const regex = /\{([^}]+)\}/g;
let match;
const expressions = [];
while ((match = regex.exec(text)) !== null) {
expressions.push(match[1].trim());
}
return expressions;
}
function replaceExpressions(text) {
return text.replace(/\{([^}]+)\}/g, '${this.$1}');
}
const className = componentNameToClassName(name);
// Create a template element and set its innerHTML to the templateContent
const templateElement = document.createElement('template');
templateElement.innerHTML = templateContent;
const templateContentFragment = templateElement.content;
// Initialize code snippets
let elementCode = '';
let propertyInitializations = '';
let getterSetterCode = '';
const dynamicProperties = new Set();
const propertyToUpdateCode = {};
const initialProperties = {};
const propertiesHandled = new Set();
let nodeCounter = 1;
function processNode(node, parentVarName) {
if (node.nodeType === Node.ELEMENT_NODE) {
const nodeName = node.tagName.toLowerCase();
if (nodeName === 'style') {
// Create code to create and append style element
const styleContent = node.textContent;
if (styleContent.trim()) {
elementCode += `const style = document.createElement('style');\n`;
elementCode += `style.textContent = ${JSON.stringify(styleContent)};\n`;
elementCode += `${parentVarName}.appendChild(style);\n`;
}
return;
}
// Assign instance variable name
let nodeVarName;
if (node.id) {
nodeVarName = `this.$${node.id}`;
} else if (nodeName === 'button' || nodeName === 'input' || nodeName === 'div' || nodeName === 'span') {
nodeVarName = `this._${nodeName}${nodeCounter++}`;
} else {
nodeVarName = `node${nodeCounter++}`;
}
// Create node
if (nodeVarName.startsWith('this.')) {
// Assign to this property without 'const'
elementCode += `${nodeVarName} = document.createElement('${nodeName}');\n`;
} else {
// Local variable with 'const'
elementCode += `const ${nodeVarName} = document.createElement('${nodeName}');\n`;
}
// Process attributes
for (let attr of node.attributes) {
const attrName = attr.name;
const attrValue = attr.value;
const dynamicExprs = extractDynamicExpressions(attrValue);
if (dynamicExprs.length > 0) {
dynamicExprs.forEach(expr => {
dynamicProperties.add(expr);
if (!propertyToUpdateCode[expr]) {
propertyToUpdateCode[expr] = new Set();
}
const updateCode = `${nodeVarName}.setAttribute('${attrName}', \`${replaceExpressions(attrValue)}\`);`;
propertyToUpdateCode[expr].add(updateCode);
});
// Initialize attribute with current property values
elementCode += `${nodeVarName}.setAttribute('${attrName}', \`${replaceExpressions(attrValue)}\`);\n`;
} else {
// Static attribute
elementCode += `${nodeVarName}.setAttribute('${attrName}', ${JSON.stringify(attrValue)});\n`;
}
}
// Process child nodes
if (node.childNodes.length > 0) {
for (let child of node.childNodes) {
processNode(child, nodeVarName);
}
}
// Append to parent
elementCode += `${parentVarName}.appendChild(${nodeVarName});\n`;
} else if (node.nodeType === Node.TEXT_NODE) {
// Handle text nodes directly under parentVarName
const textContent = node.nodeValue;
if (textContent.trim() !== '') {
const dynamicExprs = extractDynamicExpressions(textContent);
if (dynamicExprs.length > 0) {
const textNodeVar = `this._textNode${nodeCounter++}`;
if (!propertiesHandled.has(textNodeVar)) {
propertiesHandled.add(textNodeVar);
if (textNodeVar.startsWith('this.')) {
elementCode += `${textNodeVar} = document.createTextNode(\`${replaceExpressions(textContent)}\`);\n`;
} else {
elementCode += `const ${textNodeVar} = document.createTextNode(\`${replaceExpressions(textContent)}\`);\n`;
}
}
elementCode += `${parentVarName}.appendChild(${textNodeVar});\n`;
dynamicExprs.forEach(expr => {
dynamicProperties.add(expr);
if (!propertyToUpdateCode[expr]) {
propertyToUpdateCode[expr] = new Set();
}
const updateCode = `${textNodeVar}.textContent = \`${replaceExpressions(textContent)}\`;`;
propertyToUpdateCode[expr].add(updateCode);
});
} else {
const textNodeVar = `document.createTextNode(${JSON.stringify(textContent)})`;
elementCode += `${parentVarName}.appendChild(${textNodeVar});\n`;
}
}
}
}
// Start processing from templateContentFragment
elementCode += `const shadowRoot = this.attachShadow({ mode: 'open' });\n`;
// Process child nodes of the template content
const rootVarName = 'shadowRoot';
for (let child of templateContentFragment.childNodes) {
processNode(child, rootVarName);
}
// Now process scriptContent to find initial property assignments
const propertyInitRegex = /this\.(\w+)\s*=\s*(.+?);/g;
let match;
while ((match = propertyInitRegex.exec(scriptContent)) !== null) {
const propName = match[1];
const propValue = match[2];
initialProperties[propName] = propValue;
}
// For properties not initialized, set default to null
dynamicProperties.forEach(prop => {
if (!initialProperties.hasOwnProperty(prop)) {
initialProperties[prop] = 'null';
}
});
// Build property initializations
for (let [prop, value] of Object.entries(initialProperties)) {
propertyInitializations += `this._${prop} = ${value};\n`;
}
// Build getters and setters with update code
for (let prop of dynamicProperties) {
let updateCode = '';
if (propertyToUpdateCode[prop]) {
updateCode = Array.from(propertyToUpdateCode[prop]).join('\n');
}
getterSetterCode += `
get ${prop}() {
return this._${prop};
}
set ${prop}(value) {
this._${prop} = value;
${updateCode}
}
`;
}
// Generate the full class code
const classCode = `
class ${className} extends HTMLElement {
constructor() {
super();
${elementCode}
${propertyInitializations}
${scriptContent}
}
${getterSetterCode}
}
customElements.define('${name}', ${className});
`;
// Output the compiled class code
console.log(`Compiled component class for ${name}:\n${classCode}`);
// Evaluate the class code
try {
eval(classCode);
} catch (error) {
console.error(`Error compiling component ${name}: ${error.message}`);
console.error(error);
console.log(classCode);
}
}
return {
compileComponent,
};
})();
/**
* Internal module for loading and parsing HTML files.
*/
const Loader = (function() {
/**
* Loads an HTML file from the given path.
* @param {string} path - The path to the HTML file (without .html extension).
* @returns {Promise<string>} - A promise that resolves to the content of the HTML file.
*/
async function loadFile(path) {
const fullPath = `${path}.html`;
try {
const response = await fetch(fullPath);
if (!response.ok) {
throw new Error(`Failed to load: ${fullPath} (Status: ${response.status})`);
}
const content = await response.text();
return content;
} catch (error) {
console.error(error.message);
throw error;
}
}
/**
* Parses an HTML string into a Document object.
* @param {string} htmlString - The HTML string to parse.
* @returns {Document} - The parsed Document object.
*/
function parseHTML(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return doc;
}
return {
loadFile,
parseHTML,
};
})();
/**
* Global load function.
* @param {string} path - The path to the HTML file (without .html extension).
*/
window.load = function(path) {
console.log(`Loading: ${path}`);
if (Registry.isFileLoaded(path)) {
console.log(`Already loading or loaded: ${path}`);
return;
}
// Mark the file as loaded immediately to prevent race conditions
Registry.markFileAsLoaded(path);
(async function() {
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
// Extract the <template> with the 'name' attribute
const template = doc.querySelector('template[name]');
if (!template) {
console.error(`No <template name="..."> found in ${path}.html`);
return;
}
const componentName = template.getAttribute('name');
const templateContent = template.innerHTML;
// Extract the <script> content
const script = doc.querySelector('script');
const scriptContent = script ? script.textContent : '';
// Use compiler to generate and define the component
Compiler.compileComponent(componentName, templateContent, scriptContent);
console.log(`Component registered: ${componentName}`);
} catch (error) {
console.error(`Error loading component from ${path}: ${error.message}`);
// Optionally, you can remove the path from the Registry to allow retries
// Registry.removeFile(path);
}
})();
};
})();
Sample component:
code
<!-- app/comp/counter.html -->
<template name="my-counter">
<style>
.on {
background-color: blue;
}
.off {
background-color: aliceblue;
}
.btn {
padding: 20px;
}
</style>
<button class="{status} btn">Count: {count}</button>
</template>
<script>
this.count = 0;
this.status = 'on';
const button = this.shadowRoot.querySelector('button');
const span = button.querySelector('span');
const component = this; // To maintain correct context inside functions
function updateCount() {
component.count++;
component.status = component.status === 'on' ? 'off' : 'on';
// The reactive system will automatically update the DOM elements where {count} and {status} are used
}
button.addEventListener('click', updateCount);
</script>
Your goal it's update the compiler for avoid duplicating logics and data, allowing a non linear or neither exponential growth of resources and computation when are defined multiple instances of the same component. Reusing everything that can be reused, sharing a single prototype by component when is registered, with all its methods.
Invest all the time you need finding the most optimal approach, once finished output cat.js with the implementation and report of updates.
Here is the updated cat.js with the optimizations implemented:
javascript
// Updated cat.js with optimizations to avoid duplicating logic and data
(function() {
'use strict';
/**
* Internal module for tracking loaded files.
*/
const Registry = (function() {
const loadedFiles = new Set();
return {
isFileLoaded: (path) => loadedFiles.has(path),
markFileAsLoaded: (path) => loadedFiles.add(path),
};
})();
/**
* Compiler module for generating optimized component classes.
*/
const Compiler = (function() {
/**
* Compiles the component's template and script into an optimized component class definition.
* @param {string} name - The name of the component (e.g., 'my-component').
* @param {string} templateContent - The inner HTML of the component's <template>.
* @param {string} scriptContent - The content of the component's <script>.
*/
function compileComponent(name, templateContent, scriptContent) {
// Helper functions
function componentNameToClassName(name) {
return name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
}
function extractDynamicExpressions(text) {
const regex = /\{([^}]+)\}/g;
let match;
const expressions = [];
while ((match = regex.exec(text)) !== null) {
expressions.push(match[1].trim());
}
return expressions;
}
function replaceExpressions(text) {
return text.replace(/\{([^}]+)\}/g, '${this.$1}');
}
const className = componentNameToClassName(name);
// Create a template element and set its innerHTML to the templateContent
const templateElement = document.createElement('template');
templateElement.innerHTML = templateContent;
// Initialize code snippets
let methodCode = ''; // methods to be defined on the class prototype
let initCode = ''; // code to be in the init method
let propertyInitializations = '';
let getterSetterCode = '';
const dynamicProperties = new Set();
const propertyUpdateStatements = {};
const elementReferences = [];
let nodeCounter = 1;
function processNode(node, parentVarName, path) {
if (node.nodeType === Node.ELEMENT_NODE) {
const nodeName = node.tagName.toLowerCase();
// Skip 'style' tags, they can remain in the template
if (nodeName === 'style') {
return;
}
// Assign instance variable name
let nodeVarName;
if (node.id) {
nodeVarName = `this.$${node.id}`;
} else {
nodeVarName = `this._node${nodeCounter++}`;
}
// Add to elementReferences
elementReferences.push({
varName: nodeVarName,
selector: path
});
// Process attributes
for (let attr of node.attributes) {
const attrName = attr.name;
const attrValue = attr.value;
const dynamicExprs = extractDynamicExpressions(attrValue);
if (dynamicExprs.length > 0) {
dynamicExprs.forEach(expr => {
dynamicProperties.add(expr);
if (!propertyUpdateStatements[expr]) {
propertyUpdateStatements[expr] = [];
}
const updateCode = `${nodeVarName}.setAttribute('${attrName}', \`${replaceExpressions(attrValue)}\`);`;
propertyUpdateStatements[expr].push(updateCode);
});
}
}
// Process child nodes
if (node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
const childPath = `${path}.childNodes[${i}]`;
processNode(child, nodeVarName, childPath);
}
}
} else if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.nodeValue;
if (textContent.trim() !== '') {
const dynamicExprs = extractDynamicExpressions(textContent);
if (dynamicExprs.length > 0) {
const nodeVarName = `this._textNode${nodeCounter++}`;
elementReferences.push({
varName: nodeVarName,
selector: path
});
dynamicExprs.forEach(expr => {
dynamicProperties.add(expr);
if (!propertyUpdateStatements[expr]) {
propertyUpdateStatements[expr] = [];
}
const updateCode = `${nodeVarName}.nodeValue = \`${replaceExpressions(textContent)}\`;`;
propertyUpdateStatements[expr].push(updateCode);
});
}
}
}
}
// Start processing from the template content
processNode(templateElement.content, 'shadowRoot', 'this.shadowRoot');
// Build the 'init' method code, which will set up element references
for(let ref of elementReferences) {
initCode += `${ref.varName} = ${ref.selector};\n`;
}
// Now process scriptContent to separate functions and initial properties
const functionRegex = /function\s+([a-zA-Z_$][0-9a-zA-Z_$]*)\s*\(([^)]*)\)\s*\{([\s\S]*?)\}\s*/g;
let functionMatch;
while ((functionMatch = functionRegex.exec(scriptContent)) !== null) {
const functionName = functionMatch[1];
const functionArgs = functionMatch[2];
const functionBody = functionMatch[3];
methodCode += `
${functionName}(${functionArgs}) {
${functionBody}
}
`;
}
// Remove functions from scriptContent
scriptContent = scriptContent.replace(functionRegex, '');
// Any other code in scriptContent goes into initCode
initCode += scriptContent;
// Build getters and setters
for (let prop of dynamicProperties) {
let updateCode = '';
if (propertyUpdateStatements[prop]) {
updateCode = propertyUpdateStatements[prop].join('\n');
}
getterSetterCode += `
get ${prop}() {
return this._${prop};
}
set ${prop}(value) {
this._${prop} = value;
${updateCode}
}
`;
}
// Build the class code
const classCode = `
class ${className} extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' }).appendChild(${className}.templateElement.content.cloneNode(true));
${propertyInitializations}
this.init();
}
init() {
${initCode}
}
${methodCode}
${getterSetterCode}
}
${className}.templateElement = document.createElement('template');
${className}.templateElement.innerHTML = \`${templateContent}\`;
customElements.define('${name}', ${className});
`;
// Output the compiled class code
// console.log(`Compiled component class for ${name}:\n${classCode}`);
// Evaluate the class code
try {
eval(classCode);
} catch (error) {
console.error(`Error compiling component ${name}: ${error.message}`);
console.error(error);
console.log(classCode);
}
}
return {
compileComponent,
};
})();
/**
* Internal module for loading and parsing HTML files.
*/
const Loader = (function() {
/**
* Loads an HTML file from the given path.
* @param {string} path - The path to the HTML file (without .html extension).
* @returns {Promise<string>} - A promise that resolves to the content of the HTML file.
*/
async function loadFile(path) {
const fullPath = `${path}.html`;
try {
const response = await fetch(fullPath);
if (!response.ok) {
throw new Error(`Failed to load: ${fullPath} (Status: ${response.status})`);
}
const content = await response.text();
return content;
} catch (error) {
console.error(error.message);
throw error;
}
}
/**
* Parses an HTML string into a Document object.
* @param {string} htmlString - The HTML string to parse.
* @returns {Document} - The parsed Document object.
*/
function parseHTML(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return doc;
}
return {
loadFile,
parseHTML,
};
})();
/**
* Global load function.
* @param {string} path - The path to the HTML file (without .html extension).
*/
window.load = function(path) {
console.log(`Loading: ${path}`);
if (Registry.isFileLoaded(path)) {
console.log(`Already loading or loaded: ${path}`);
return;
}
// Mark the file as loaded immediately to prevent race conditions
Registry.markFileAsLoaded(path);
(async function() {
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
// Extract the <template> with the 'name' attribute
const template = doc.querySelector('template[name]');
if (!template) {
console.error(`No <template name="..."> found in ${path}.html`);
return;
}
const componentName = template.getAttribute('name');
const templateContent = template.innerHTML;
// Extract the <script> content
const script = doc.querySelector('script');
const scriptContent = script ? script.textContent : '';
// Use compiler to generate and define the component
Compiler.compileComponent(componentName, templateContent, scriptContent);
console.log(`Component registered: ${componentName}`);
} catch (error) {
console.error(`Error loading component from ${path}: ${error.message}`);
// Optionally, you can remove the path from the Registry to allow retries
// Registry.removeFile(path);
}
})();
};
})();
Report of Updates
In this updated version of cat.js, we've optimized the compiler to avoid duplicating logic and data, ensuring that resource usage and computation grow linearly with the number of component instances. Here's a summary of the changes:
Shared Component Template
Before: Each instance of a component procedurally built its DOM structure during construction, leading to duplicated code and resource consumption.
After: We introduced a shared templateElement for each component class. This template is compiled once and stored as a static property on the component's class. In the constructor, we clone this template and append it to the shadow DOM. This ensures that the DOM structure is built once and reused across all instances.
Before: Functions defined in the component's <script> were placed inside the constructor, leading to function redefinitions for every instance.
After: We parse the scriptContent to extract function declarations. These functions are converted into methods and defined on the component's prototype. This means that all instances share the same methods, reducing memory usage and avoiding redundant computations.
javascript
// Extract functions and define them on the prototype
methodCode += `
${functionName}(${functionArgs}) {
${functionBody}
}
`;
Per-Instance Initialization
Before: All property initializations and function definitions were inside the constructor, causing data duplication.
After: We introduced an init method that contains per-instance initializations. The constructor now only performs minimal setup—attaching the shadow DOM and calling this.init(). This approach separates shared logic from instance-specific data.
Memory Efficiency: By sharing templates and methods across instances, we significantly reduce memory consumption.
Performance Improvement: Avoiding redundant computations and function creations enhances performance, especially when many instances are present.
Maintainability: Separating per-instance initialization from shared logic makes the codebase easier to understand and maintain.
Scalability: The resource usage now grows linearly with the number of instances, ensuring that the application remains responsive even as the number of components increases.
Conclusion
These optimizations align with best practices in JavaScript and web component development, ensuring that cat.js remains lightweight, efficient, and suitable for building high-performance user interfaces.
Optimized Getters and Setters
Before: Getters and setters for reactive properties were potentially redefined per instance.
After: We define getters and setters on the class prototype. These accessors update the DOM elements when properties change. Since they are on the prototype, all instances share the same getter/setter logic.
javascript
${getterSetterCode}
Element References
We process the component's template to identify elements and text nodes that have dynamic expressions (e.g., {count}, {status}). In the init method, we set up references to these elements using selectors based on the DOM structure. This allows us to update the DOM efficiently when properties change.
javascript
// In the init method
${ref.varName} = ${ref.selector};
Dynamic Property Tracking
We maintain a set of dynamic properties (dynamicProperties) that are used in the template. For each property, we generate update statements that modify the appropriate parts of the DOM when the property's value changes.
javascript
// In getters and setters
set ${prop}(value) {
this._${prop} = value;
${updateCode}
}