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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// 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>
Our compiler works perfect, your task it's integrate a new feature, which is sharing the get, set, and custom functions within the class body, not on the constructor. In this way, the component's logic is defined once.
Please, invest all the time you need for finding the most optimal approach, that fits our principles, and browser runtime and memory usage.
Sure! To integrate the new feature where getters, setters, and custom functions are shared within the class body (instead of being redefined in each instance's constructor), we need to modify the compileComponent function in your compiler.
The goal is to:
Extract custom function definitions from the scriptContent and move them into the class body as methods.
Ensure that these methods reference this correctly (replacing any references to component with this if necessary).
Adjust the constructor code so that any references to these functions are appropriately bound and accessible.
Keep property initializations and instance-specific code within the constructor.
Below is the updated compileComponent function with detailed comments explaining each step:
javascript
/**
* 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 (['button', 'input', 'div', 'span', 'p', 'a'].includes(nodeName)) {
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 and function definitions
// Extract function definitions and remaining code from scriptContent
function extractFunctionDefinitions(scriptContent) {
const functionDefinitions = [];
const nonFunctionLines = [];
let lines = scriptContent.split('\n');
let insideFunction = false;
let currentFunctionLines = [];
let braceLevel = 0;
for (let line of lines) {
// Include the line in the function or non-function code
if (!insideFunction) {
if (line.trim().startsWith('function ')) {
insideFunction = true;
braceLevel = (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
currentFunctionLines.push(line);
} else {
// Collect initial property assignments
const propInitMatch = line.trim().match(/^this\.(\w+)\s*=\s*(.*);$/);
if (propInitMatch) {
const propName = propInitMatch[1];
const propValue = propInitMatch[2];
initialProperties[propName] = propValue;
} else {
nonFunctionLines.push(line);
}
}
} else {
currentFunctionLines.push(line);
braceLevel += (line.match(/\{/g) || []).length;
braceLevel -= (line.match(/\}/g) || []).length;
if (braceLevel === 0) {
insideFunction = false;
functionDefinitions.push(currentFunctionLines.join('\n'));
currentFunctionLines = [];
}
}
}
return {
functionDefinitions,
remainingCode: nonFunctionLines.join('\n')
};
}
const { functionDefinitions, remainingCode } = extractFunctionDefinitions(scriptContent);
// Collect function names
const functionNames = [];
let classMethodsCode = '';
// Process each function definition
for (let funcDef of functionDefinitions) {
// Extract function name, parameters, body
const funcMatch = /^function\s+(\w+)\s*\(([^)]*)\)\s*\{([\s\S]*?)\}\s*$/m.exec(funcDef.trim());
if (funcMatch) {
const funcName = funcMatch[1];
const funcParams = funcMatch[2];
let funcBody = funcMatch[3];
// Replace 'component.' with 'this.'
funcBody = funcBody.replace(/\bcomponent\./g, 'this.');
// Add to class methods
classMethodsCode += `
${funcName}(${funcParams}) {
${funcBody}
}
`;
// Collect function names
functionNames.push(funcName);
}
}
// Initialize properties not assigned in scriptContent
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}
}
`;
}
// Adjust constructor code to bind methods
let constructorCode = remainingCode;
// Prepend 'const functionName = this.functionName.bind(this);'
let bindingCode = '';
for (let funcName of functionNames) {
bindingCode += `const ${funcName} = this.${funcName}.bind(this);\n`;
}
// Prepend binding code to constructor code
constructorCode = bindingCode + constructorCode;
// Generate the full class code
const classCode = `
class ${className} extends HTMLElement {
constructor() {
super();
${elementCode}
${propertyInitializations}
${constructorCode}
}
${getterSetterCode}
${classMethodsCode}
}
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);
}
}
Explanation of Changes:
Extraction of Function Definitions:
We added the extractFunctionDefinitions function to parse the scriptContent. This function separates function definitions from the rest of the code.
Function definitions are stored in an array functionDefinitions, while the remaining code (property initializations and other instance-specific code) is stored in remainingCode.
Processing Function Definitions:
For each function definition, we extract the function name, parameters, and body.
We replace any occurrences of component. with this. in the function body to ensure the correct this context.
We then reconstruct these functions as class methods and append them to classMethodsCode.
Function names are collected in functionNames for later use.
Property Initializations:
We continue to collect property initializations from the scriptContent as before.
Properties are initialized in the constructor with this._propertyName = value;.
Binding Methods in Constructor:
In the constructor, we need to ensure that any references to these methods are bound correctly.
We prepend const methodName = this.methodName.bind(this); for each function name at the beginning of the constructor code. This ensures that the methods have the correct this context when used (e.g., in event listeners).
Updating Constructor Code:
The remaining code after extracting function definitions (remainingCode) is considered the constructor code.
We combine the binding code and constructor code, which will be executed per instance.
Defining Getters and Setters:
Getters and setters remain defined within the class body, ensuring they are shared across instances.
Building the Class Code:
We compile the final class code by inserting elementCode, propertyInitializations, constructorCode, getterSetterCode, and classMethodsCode into their appropriate places.
Sample Output with the Provided Component:
Using your sample component, the compiled class code would look something like this (simplified for brevity):
javascript
class MyCounter extends HTMLElement {
constructor() {
super();
// Element creation and initializations
const shadowRoot = this.attachShadow({ mode: 'open' });
// ... (other element code)
// Property initializations
this._count = 0;
this._status = 'on';
// Binding methods
const updateCount = this.updateCount.bind(this);
// Constructor code
const button = this.shadowRoot.querySelector('button');
const span = button.querySelector('span');
const component = this;
button.addEventListener('click', updateCount);
}
// Getters and Setters
get count() {
return this._count;
}
set count(value) {
this._count = value;
// Update code for count
}
get status() {
return this._status;
}
set status(value) {
this._status = value;
// Update code for status
}
// Class methods (shared across instances)
updateCount() {
this.count++;
this.status = this.status === 'on' ? 'off' : 'on';
// ... (additional logic)
}
}
customElements.define('my-counter', MyCounter);
Benefits of This Approach:
Memory Efficiency: By moving methods to the class body, we avoid redefining them for every instance, reducing memory usage.
Consistency: The component's logic is defined once, adhering to object-oriented principles.
Performance: Sharing methods improves performance, especially when many instances of a component are created.
Simplicity: Users can write their scripts naturally, and the compiler handles the optimization.
Additional Considerations:
Context (this vs. component): We replace component with this in function bodies to ensure the correct context. Users should be aware that within methods, this refers to the component instance.
Event Listeners: When adding event listeners in the constructor, we bind methods to this to ensure they have the correct context when called.
Variable Scope: Variables declared in the constructor are instance-specific, while methods are shared across instances.
Conclusion:
By modifying the compileComponent function as shown, we've integrated the new feature that ensures getters, setters, and custom functions are shared within the class body, not redefined in each instance's constructor. This satisfies the requirements of sharing logic, improving performance, and adhering to the principles of Cat.js that prioritize efficiency and simplicity.
Feel free to integrate this updated function into your Cat.js compiler and test it with your components!