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 it's adding the method, insert("path", "selector");
Context, we are going to allow the user to import content through two specialized methods:
load("path") -> Load and register components to be used on the view.
Components are defined within the template tag with a name attribute.
insert("paht", "selector") -> Insert RAW html into a view or component.
<!-- name.html -->
<template name="user-name">
<div>
My name is O1
</div>
</template>
You must find the most optimal logic and mechanism for adding the method insert, following the criteria:
It's always defined at the top
Can integrate raw html into views and components
Can manage nested loading or insertion.
And for the load method, you just need to make it capable to load a component within a component.
Find the most optimal logic and mechanism that embraces to our principles, explore all the edge-cases and build a robust implementation, that works perfectly. Invest all the time needed.
To achieve your requirements, we'll modify the existing code to add the insert method and adjust the load method to support nested component loading within components. Here's the complete updated cat.js code:
javascript
// 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);
}
async connectedCallback() {
// Process scripts in the shadow root
await ScriptProcessor.processScripts(this.shadowRoot);
}
}
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(rootNode) {
const scripts = rootNode.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);
}
// Find insert calls and execute them sequentially
const insertCalls = [...scriptContent.matchAll(/insert\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g)];
for (const match of insertCalls) {
const insertPath = match[1];
const targetSelector = match[2];
await window.insert(insertPath, targetSelector, rootNode);
}
// Execute the script content
if (scriptContent.trim()) {
try {
new Function(scriptContent)();
} catch (error) {
console.error(`Error executing script: ${error.message}`);
}
}
}
}
return {
processScripts,
};
})();
/**
* Internal module for inserting content into the DOM.
*/
const DOMHandler = (function() {
function insertContent(doc, targetSelector, contextRoot = document) {
const insert = () => {
const targetElement = contextRoot.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 (contextRoot !== document || document.readyState !== 'loading') {
insert();
} else {
document.addEventListener('DOMContentLoaded', 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
}
};
/**
* Global insert function.
* @param {string} path - The path to the HTML file (without .html extension).
* @param {string} targetSelector - CSS selector of the target element to insert content into.
* @param {Node} [contextRoot] - The root node to operate within (defaults to document).
* @returns {Promise<void>}
*/
window.insert = async function(path, targetSelector, contextRoot = document) {
console.log(`Inserting: ${path} into ${targetSelector}`);
try {
const responseText = await Loader.loadFile(path);
const doc = Loader.parseHTML(responseText);
// Process any scripts and nested inserts/loads
await ScriptProcessor.processScripts(doc);
// Insert content into the target element within the contextRoot
DOMHandler.insertContent(doc, targetSelector, contextRoot);
} catch (error) {
console.error(`Error in insert: ${error.message}`);
}
};
})();
Explanation:
Insert Method Implementation (window.insert):
We've added a new global insert function that takes a path, a targetSelector, and an optional contextRoot (defaults to document).
It loads the specified HTML file, parses it, processes any nested scripts (handling nested load and insert calls), and then inserts the content into the target element within the contextRoot.
This allows raw HTML to be integrated into views and components.
Context-Aware Script Processing:
The ScriptProcessor.processScripts function now accepts a rootNode parameter. It processes scripts within the given rootNode, allowing scripts within components to be executed in the correct context.
It handles both load and insert calls, ensuring that nested loading or insertion is managed properly.
Component Scripts Execution in connectedCallback:
In the ComponentManager, when defining a custom element, we override the connectedCallback method.
When a component is added to the DOM, connectedCallback is called, and we process any scripts within the component's shadow DOM (this.shadowRoot).
This ensures that any insert or load calls within a component's template are executed after the component is connected, allowing for correct element availability.
DOMHandler Adjustments:
The insertContent function in DOMHandler now accepts an optional contextRoot. It uses this root for querying the target element and performing the insertion.
If the contextRoot is not the main document, it immediately performs the insertion without waiting for DOMContentLoaded.
Load Method Supports Nested Components:
The window.load function remains largely the same but, coupled with the adjusted ScriptProcessor, it now supports loading components within components.
When a component is loaded, any load calls within its scripts are processed, ensuring that all nested components are registered before they are needed.
The load('name') call ensures that the user-name component is registered before it's used within the hello-world template.
Edge Cases and Robustness:
Component Registration: The Registry module prevents components from being registered multiple times.
Contextual Insertions: By passing the contextRoot, we ensure that insertions happen within the correct DOM context, whether it's the main document or a component's shadow DOM.
Nested Loading/Inserting: The script processor handles nested load and insert calls by processing scripts recursively within the loaded documents.
Error Handling: Errors during loading, parsing, or script execution are caught and logged without stopping the entire process.
Conclusion:
This implementation provides a robust solution that adheres to your principles and requirements. The insert method allows for integrating raw HTML into views and components, manages nested operations, and ensures clean and efficient script execution within the appropriate contexts.