You have a new contract: conceptualize, design, and create a lightweight JavaScript UI engine that efficiently manages components, data structures, and state. Use only pure low-level JavaScript, Web Components, and modern Web APIs the highest performance.
Introduction to Cat.js blueprint.
Our engine, named by the name of the animal for its known lightness, flexibility and accuracy, looks to outperform current solutions, like Svelte.
Unlike React, Svelte, Angular, and similar frameworks, our engine operates in a vanilla environment without the need for bundles, polyfills, or Webpack. It avoids inefficient practices associated with virtual DOMs, as well as unnecessary reflows and repaints, such as rebuilding or re-rendering an entire component just to update a single element.
Our engine needs to be lightweight, user-friendly, and highly optimized, leveraging raw, low-level JavaScript knowledge tailored to modern browser runtimes. It is designed specifically for creating robust and efficient user interfaces for Tauri-based applications, without the need for bundlers.
Our primary reference it's Svelte, I like how they manage the concept of "Reactivity". But, our engine instead of Svelte, which is a framework, it's going to specialize and focus only on UI, components and data management.
Technical expectative:
Pure raw JavaScript for the motor of the engine.
An architecture thought carefully to fit the browser JS runtime.
SOTA Memory usage.
Ease to use API and Syntax
SOTA Reactive engine.
Design a new ease way to import components into the DOM.
Our importing logic must compile and inject the code into our DOM before loads.
Avoid:
Think as "Reactivity" in the way React does it.
No Rendering methods or state management for rebuild and repaint component.
Syntax expectative:
note.html
<template name="cat-note" id="Note">
<div>
<textarea @input="update" id="content">{content}</textarea>
</div>
</template>
<script>
let serial = 00832;
let content = serial + text;
update(newText) {
text = newText;
}
</script>
index.html
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The code above it's a matter of desired reference, a vision I'd like to try to achieve, but as the expert and on charge of the development of this engine, you must base your decisions and actions on factual data about our context, environment and desired performance and simplicity goals.
Invest all the time needed thinking and designing such engine, and output an initial version, functional and robust.
Cat.js - Initial Version
Design Overview
Cat.js is a lightweight, efficient JavaScript UI engine designed to create reactive web applications without the overhead of traditional frameworks. It leverages pure low-level JavaScript, Web Components, and modern Web APIs to provide a performant and user-friendly development experience. Cat.js focuses on UI components and data management, drawing inspiration from Svelte's reactivity while avoiding virtual DOMs and unnecessary reflows or repaints.
Key Features
Pure JavaScript Implementation: Built entirely with raw JavaScript, eliminating the need for bundlers or polyfills.
Web Components: Utilizes custom elements to encapsulate component logic and styling.
Reactive Data Binding: Implements a reactive system that updates only the necessary parts of the DOM.
No Virtual DOM: Directly manipulates the DOM for optimal performance.
Easy Component Importing: Simplifies the process of importing and using components.
Engine Architecture
1. Component Loader (load Function)
The load function is responsible for fetching component files, parsing them, and defining custom elements.
2. Template and Script Parsing
Components are defined in HTML files containing a <template> and a <script> section. The engine parses these sections to extract the template HTML and the associated JavaScript code.
3. Custom Element Definition
Using the information from the parsing step, the engine defines a new custom element. It uses the name attribute from the template to determine the tag name.
4. Reactivity System
Data properties are wrapped in JavaScript Proxy objects to observe changes and update the DOM accordingly. This allows the engine to reactively update only the parts of the UI that are affected by data changes.
5. Event Handling
Event listeners are set up by parsing event directives in the template (e.g., @input="update"). These directives are connected to methods defined in the script section.
Implementation Details
cat.js
Below is the initial implementation of cat.js:
javascript
// cat.js
function load(url) {
fetch(url)
.then(response => response.text())
.then(text => {
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'text/html');
const templateElem = doc.querySelector('template');
const scriptElem = doc.querySelector('script');
if (!templateElem || !scriptElem) {
console.error('Template or script not found in component');
return;
}
const componentName = templateElem.getAttribute('name');
if (!componentName) {
console.error('Component name not specified in template');
return;
}
const componentTemplate = templateElem.innerHTML.trim();
const componentScript = scriptElem.innerHTML.trim();
customElements.define(
componentName,
class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
// Initialize data object
const data = {};
// Execute component script with 'data' as 'this'
const scriptFunc = new Function(componentScript);
scriptFunc.call(data);
// Separate methods from data properties
this.methods = {};
for (let key in data) {
if (typeof data[key] === 'function') {
this.methods[key] = data[key].bind(data);
}
}
// Create reactive data proxy
const self = this;
this.data = new Proxy(data, {
set(target, property, value) {
target[property] = value;
self.update();
return true;
},
});
// Parse and clone the template
const templateWrapper = document.createElement('template');
templateWrapper.innerHTML = componentTemplate;
this.shadowRoot.appendChild(templateWrapper.content.cloneNode(true));
// Bind events
this.bindEvents();
// Initial render
this.update();
}
update() {
const content = this.shadowRoot;
// Replace {placeholders} with data values
const walker = document.createTreeWalker(
content,
NodeFilter.SHOW_TEXT,
null,
false
);
let node;
while ((node = walker.nextNode())) {
node.textContent = node.textContent.replace(/\{(.*?)\}/g, (match, p1) => {
const key = p1.trim();
return this.data.hasOwnProperty(key) ? this.data[key] : '';
});
}
// Update elements with 'id' attributes matching data properties
content.querySelectorAll('[id]').forEach((elem) => {
const id = elem.getAttribute('id');
if (this.data.hasOwnProperty(id)) {
if (elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA') {
elem.value = this.data[id];
} else {
elem.textContent = this.data[id];
}
}
});
}
bindEvents() {
const self = this;
this.shadowRoot.querySelectorAll('*').forEach((elem) => {
[...elem.attributes].forEach((attr) => {
if (attr.name.startsWith('@')) {
const eventName = attr.name.substring(1);
const methodName = attr.value;
if (self.methods[methodName]) {
elem.addEventListener(eventName, function (event) {
self.methods[methodName].call(self.data, event);
});
}
}
});
});
}
}
);
})
.catch((err) => {
console.error('Error loading component:', err);
});
}
Component Definition (note.html)
Here's how you can define a component using the expected syntax:
Loading the Component: When load('note.html') is called, the engine fetches note.html, parses the <template> and <script> sections, and defines a new custom element <cat-note>.
Component Initialization:
The engine executes the script section, binding the this context to the component's data object.
Data properties (serial, text, content) and methods (update) are initialized.
Reactivity Setup:
The data object is wrapped in a Proxy to observe changes.
Any updates to data properties trigger the update() method, which refreshes the DOM where necessary.
Rendering the Template:
The engine clones the template content into the component's shadow DOM.
Placeholders in the template (e.g., {content}) are replaced with the current data values.
Event Binding:
Event directives in the template (e.g., @input="update") are parsed.
Event listeners are attached to call the corresponding methods when events occur.
User Interaction:
When the user types into the <textarea>, the update method updates the text and content properties.
The reactivity system detects the changes and updates the DOM, reflecting the new content.
Considerations and Next Steps
Security
Script Execution: Using new Function carries security risks if loading components from untrusted sources.
Mitigation: Ensure all component files are from trusted origins or sanitize the script content before execution.
Performance
Optimization: The initial version is suitable for small to medium applications.
Future Work: Optimize the reactivity system to batch updates and reduce unnecessary DOM manipulations.
Features to Add
Lifecycle Methods: Implement hooks like connectedCallback and disconnectedCallback for custom initialization and cleanup.
Nested Components: Allow components to include and interact with other custom elements.
Styling Options: Support scoped styles within components.
Advanced Data Binding: Enhance the template parser to handle conditionals and loops.
Usage Guide
Define Components: Create HTML files with <template> and <script> sections to define your components.
Use the name attribute in <template> to specify the custom element's tag name.
Initialize data and methods in the <script> section using this.
Import Components: In your main HTML file, include cat.js and call the load function with the path to your component files.
Use Components: Simply use your custom elements in the HTML body as you would with any standard HTML tags.
Conclusion
The initial version of Cat.js achieves the goal of creating a lightweight, efficient UI engine that leverages modern browser capabilities. By focusing on pure JavaScript and Web Components, it provides a foundation for building reactive applications without the need for heavy frameworks or tooling. Future enhancements can expand its capabilities, improve performance, and provide additional developer conveniences.
Footnote
This initial version serves as a starting point. As you continue developing Cat.js, consider the following:
Testing: Rigorously test components to ensure reactivity and event handling work as expected.
Error Handling: Improve error messages and handling to aid in development.
Documentation: Create comprehensive documentation for users of the engine.
By focusing on these areas, Cat.js can evolve into a robust tool for modern web development, particularly suited for Tauri-based applications where lightweight and efficiency are paramount.