Cat.js is a lightweight, state-of-the-art engine designed to build powerful UIs, prioritizing the highest performance and efficiency, and based exclusively on modern native browser APIs, primarily Web Components.
Practices and things to avoid for Cat.js
No Virtual DOMs or similar practices.
No Webpack, bundlers, polyfills, etc.
Write HTML or CSS code into a JS file, function or similar.
Render methods for components, or logics that trigger unnecessary reflows and repainting.
Requirements for Cat.js
Our engine it's attach through a script:src tag on the top of the head tag.
Written on vanilla low level JavaScript that fits perfectly the browser runtime.
Beautiful and ease Syntax and Project tree
CSC - Client Side Compiler before loading the DOM.
So far this is the state of Cat.js
code
Assistant
// cat.js
// Immediately Invoked Function Expression (IIFE) to encapsulate the engine
(function() {
'use strict';
/**
* Internal module for tracking loaded files and components.
*/
const Registry = (function() {
const loadedFiles = new Set();
const registeredComponents = new Set();
return {
isFileLoaded: (path) => loadedFiles.has(path),
markFileAsLoaded: (path) => loadedFiles.add(path),
isComponentRegistered: (name) => registeredComponents.has(name),
registerComponent: (name) => registeredComponents.add(name),
};
})();
/**
* Internal module for handling component registration.
*/
const ComponentManager = (function() {
const templateCache = new Map();
function registerComponent(name, templateContent) {
if (Registry.isComponentRegistered(name)) {
console.warn(`Component already registered: ${name}`);
return;
}
// Cache the template content
templateCache.set(name, templateContent);
class CustomElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = templateCache.get(name);
}
}
customElements.define(name, CustomElement);
Registry.registerComponent(name);
console.log(`Component registered: ${name}`);
}
return {
registerComponent,
};
})();
/**
* Internal module for loading and parsing HTML files.
*/
const Loader = (function() {
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;
}
}
function parseHTML(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return doc;
}
return {
loadFile,
parseHTML,
};
})();
/**
* Internal module for handling script execution and nested loading.
*/
const ScriptProcessor = (function() {
async function processScripts(doc) {
const scripts = doc.querySelectorAll('script');
for (const script of scripts) {
const scriptContent = script.textContent;
// Find load calls and execute them sequentially
const loadCalls = [...scriptContent.matchAll(/load\(\s*['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?\s*\)/g)];
for (const match of loadCalls) {
const componentPath = match[1];
const targetSelector = match[2];
await window.load(componentPath, targetSelector);
}
// Execute the script content
if (scriptContent.trim()) {
try {
new Function(scriptContent)();
} catch (error) {
console.error(`Error executing script in ${componentPath}: ${error.message}`);
}
}
}
}
return {
processScripts,
};
})();
/**
* Internal module for inserting content into the DOM.
*/
const DOMHandler = (function() {
function insertContent(doc, targetSelector) {
const insert = () => {
const targetElement = document.querySelector(targetSelector);
if (targetElement) {
const fragment = document.createDocumentFragment();
const bodyContent = doc.body;
while (bodyContent.firstChild) {
fragment.appendChild(bodyContent.firstChild);
}
targetElement.appendChild(fragment);
} else {
console.error(`Target element not found: ${targetSelector}`);
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', insert);
} else {
insert();
}
}
return {
insertContent,
};
})();
/**
* Global load function.
* @param {string} path - The path to the HTML file (without .html extension).
* @param {string} [targetSelector] - Optional CSS selector of the target element to insert content into.
* @returns {Promise<void>}
*/
window.load = async function(path, targetSelector) {
console.log(`Loading: ${path}`);
if (Registry.isFileLoaded(path)) {
console.log(`Already loaded: ${path}`);
return;
}
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
Registry.markFileAsLoaded(path);
// Process components
const templates = doc.querySelectorAll('template[name]');
for (const template of templates) {
const componentName = template.getAttribute('name');
const templateContent = template.innerHTML;
ComponentManager.registerComponent(componentName, templateContent);
}
// Process scripts and nested loads
await ScriptProcessor.processScripts(doc);
// Insert content into the target element if specified
if (targetSelector) {
DOMHandler.insertContent(doc, targetSelector);
}
} catch (error) {
// Error has already been logged in Loader; no need to throw
}
};
})();
Your first task involves the method load, which is intended solely for loading and registering a component for use. Currently, we've had to modify the engine to manage an additional parameter, tag-selector, to retrieve raw HTML, primarily for building views or pages. For instance, it’s utilized to set up the root view in index.html with load('app', 'app'). However, this solution lacks robustness and violates the single-purpose principle of the load method (loading and registering a component for use).
I don’t want the engine to handle everything as a component. Therefore, it’s your responsibility to discover the most optimal solution that embraces our principles: ease of use, clarity, efficient browser runtime, and the best performance with memory usage. You should explore multiple approaches, test them against potential edge cases, and determine the most effective one.
To address the concerns you've raised about the load method in Cat.js, we'll aim to separate responsibilities clearly between component registration and view rendering. This separation adheres to the Single Responsibility Principle, enhancing the engine's robustness, maintainability, and clarity.
Current Issue Overview
Overloaded load Method: The load method currently handles both:
Component Loading and Registration: Parsing <template name="..."> and defining custom elements.
View Rendering: Inserting raw HTML into a specified target element.
Consequences:
Violates Single Responsibility: Mixing component logic with view rendering.
Reduced Clarity: Developers must understand dual roles of load.
Potential for Errors: Misuse or unintended side-effects when using load for different purposes.
Proposed Solution: Separate loadComponent and loadView Methods
By dividing the load method into two distinct methods—loadComponent and loadView—we can ensure each function has a clear, singular purpose. This enhances usability, clarity, and maintainability.
1. loadComponent Method
Purpose: Load and register web components.
Usage: window.loadComponent('componentPath')
2. loadView Method
Purpose: Load raw HTML and insert it into a specified target element in the DOM.
Suppose you have a view defined in views/home.html:
html
<div>
<h1>Welcome to the Home Page</h1>
<custom-button>Start</custom-button>
</div>
<script>
// Any view-specific script
console.log('Home view loaded');
</script>
Component Management vs. View Rendering are handled independently.
Enhanced Readability and Maintainability:
Developers can quickly understand the purpose of each method.
Easier to debug and extend functionalities.
Adherence to Cat.js Principles:
Ease of Use: Distinct methods simplify usage patterns.
Clarity: Responsibilities are unambiguous.
Efficient Browser Runtime: Avoids unnecessary processing by isolating tasks.
Best Performance with Memory Usage: Minimizes overhead by preventing method overloading.
Flexibility for Future Enhancements:
Additional functionalities (like loadService, loadMiddleware, etc.) can be introduced following the same pattern.
Potential Edge Cases and Handling
Loading Non-existent Files:
Handled By: Loader throws and logs errors if fetch fails.
developer's responsibility: Ensure paths are correct.
Duplicate Component or View Loading:
Handled By: Registry prevents reloading via isFileLoaded checks.
Scripts with Mixed loadComponent and loadView Calls:
Handled By: ScriptProcessor sequentially processes all calls ensuring dependencies are loaded in order.
Circular Dependencies:
Mitigation: Using the Registry to track loaded files can help prevent infinite loops, but it's advisable to manage dependencies carefully during development.
Conclusion
By separating the load method into loadComponent and loadView, Cat.js becomes more robust, maintainable, and aligned with best practices. This refactoring enhances the engine's clarity and efficiency without compromising performance or memory usage. Developers can now more intuitively manage components and views, leading to a smoother development experience.
If you have further requirements or need additional features, this modular approach will facilitate seamless integrations and extensions.
Not yet included in a published release.
// cat.js
// Immediately Invoked Function Expression (IIFE) to encapsulate the engine
(function() {
'use strict';
/**
* Internal module for tracking loaded files and components.
*/
const Registry = (function() {
const loadedFiles = new Set();
const registeredComponents = new Set();
return {
isFileLoaded: (path) => loadedFiles.has(path),
markFileAsLoaded: (path) => loadedFiles.add(path),
isComponentRegistered: (name) => registeredComponents.has(name),
registerComponent: (name) => registeredComponents.add(name),
};
})();
/**
* Internal module for handling component registration.
*/
const ComponentManager = (function() {
const templateCache = new Map();
function registerComponent(name, templateContent) {
if (Registry.isComponentRegistered(name)) {
console.warn(`Component already registered: ${name}`);
return;
}
// Cache the template content
templateCache.set(name, templateContent);
class CustomElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = templateCache.get(name);
}
}
customElements.define(name, CustomElement);
Registry.registerComponent(name);
console.log(`Component registered: ${name}`);
}
return {
registerComponent,
};
})();
/**
* Internal module for loading and parsing HTML files.
*/
const Loader = (function() {
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;
}
}
function parseHTML(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
return doc;
}
return {
loadFile,
parseHTML,
};
})();
/**
* Internal module for handling script execution and nested loading.
*/
const ScriptProcessor = (function() {
async function processScripts(doc, currentPath) {
const scripts = doc.querySelectorAll('script');
for (const script of scripts) {
const scriptContent = script.textContent;
// Find loadComponent and loadView calls and execute them sequentially
const loadComponentCalls = [...scriptContent.matchAll(/loadComponent\(\s*['"]([^'"]+)['"]\s*\)/g)];
for (const match of loadComponentCalls) {
const componentPath = match[1];
await window.loadComponent(componentPath);
}
const loadViewCalls = [...scriptContent.matchAll(/loadView\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g)];
for (const match of loadViewCalls) {
const viewPath = match[1];
const targetSelector = match[2];
await window.loadView(viewPath, targetSelector);
}
// Execute the remaining script content
const remainingScript = scriptContent.replace(/loadComponent\(\s*['"][^'"]+['"]\s*\)/g, '')
.replace(/loadView\(\s*['"][^'"]+['"]\s*,\s*['"][^'"]+['"]\s*\)/g, '');
if (remainingScript.trim()) {
try {
new Function(remainingScript)();
} catch (error) {
console.error(`Error executing script in ${currentPath}: ${error.message}`);
}
}
}
}
return {
processScripts,
};
})();
/**
* Internal module for inserting content into the DOM.
*/
const DOMHandler = (function() {
function insertContent(doc, targetSelector) {
const insert = () => {
const targetElement = document.querySelector(targetSelector);
if (targetElement) {
const fragment = document.createDocumentFragment();
const bodyContent = doc.body;
while (bodyContent.firstChild) {
fragment.appendChild(bodyContent.firstChild);
}
targetElement.appendChild(fragment);
} else {
console.error(`Target element not found: ${targetSelector}`);
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', insert);
} else {
insert();
}
}
return {
insertContent,
};
})();
/**
* Function to load and register a component.
* @param {string} path - The path to the component HTML file (without .html extension).
* @returns {Promise<void>}
*/
window.loadComponent = async function(path) {
console.log(`Loading component: ${path}`);
if (Registry.isFileLoaded(path)) {
console.log(`Component already loaded: ${path}`);
return;
}
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
Registry.markFileAsLoaded(path);
// Process components
const templates = doc.querySelectorAll('template[name]');
for (const template of templates) {
const componentName = template.getAttribute('name');
const templateContent = template.innerHTML;
ComponentManager.registerComponent(componentName, templateContent);
}
// Process scripts and nested loads
await ScriptProcessor.processScripts(doc, path);
} catch (error) {
// Error has already been logged in Loader; no need to throw
}
};
/**
* Function to load and render a view into a target selector.
* @param {string} path - The path to the view HTML file (without .html extension).
* @param {string} targetSelector - CSS selector of the target element to insert content into.
* @returns {Promise<void>}
*/
window.loadView = async function(path, targetSelector) {
console.log(`Loading view: ${path} into ${targetSelector}`);
if (Registry.isFileLoaded(path)) {
console.log(`View already loaded: ${path}`);
return;
}
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
Registry.markFileAsLoaded(path);
// Process components within the view
const templates = doc.querySelectorAll('template[name]');
for (const template of templates) {
const componentName = template.getAttribute('name');
const templateContent = template.innerHTML;
ComponentManager.registerComponent(componentName, templateContent);
}
// Process scripts and nested loads
await ScriptProcessor.processScripts(doc, path);
// Insert content into the target element
DOMHandler.insertContent(doc, targetSelector);
} catch (error) {
// Error has already been logged in Loader; no need to throw
}
};
})();