To enable your engine to compile all components (including nested ones) into a single blob when CatConfig.bundleAll is set to true, we'll need to implement a mechanism that tracks the loading state of components. This ensures that even deeply nested components are included in the final bundle.
Here's a comprehensive approach to achieve this:
-
Load Tracking with Promises:
- Introduce a counter to keep track of ongoing load operations.
- Ensure that each
load invocation increments the counter and decrements it upon completion.
- Finalize the bundle only when the counter reaches zero, indicating that all components have been loaded.
-
Handling Nested Loads:
- Since components can load other components, ensure that the load tracker accounts for these nested loads.
- Use asynchronous functions to manage the flow and guarantee that all components are accounted for before bundling.
-
Optimizing the Compiler:
- Accumulate all component codes into an array when bundling is enabled.
- Once all components are loaded, concatenate the accumulated codes into a single blob and inject it into the DOM.
Below is the updated cat.js implementing the above logic:
(function() {
'use strict';
/**
* Global configuration object for Cat.js
* Developers can set CatConfig.bundleAll before loading components.
*/
window.CatConfig = window.CatConfig || {
bundleAll: false // Default: Per-Component Blob Files
};
/**
* Internal module for tracking loaded files.
*/
const Registry = (function() {
const loadedFiles = new Set();
return {
/**
* Checks if a file has already been loaded.
* @param {string} path - The path to the file.
* @returns {boolean} - True if the file is loaded, else false.
*/
isFileLoaded: (path) => loadedFiles.has(path),
/**
* Marks a file as loaded to prevent redundant loading.
* @param {string} path - The path to the file.
*/
markFileAsLoaded: (path) => loadedFiles.add(path),
};
})();
/**
* Compiler module for generating and registering component classes using Blob URLs.
*/
const Compiler = (function() {
// Array to store compiled component codes in bundling mode
let bundledCode = '';
// Flag to indicate if bundling script has been injected
let bundleScriptInjected = false;
// Array to store compiled component codes in bundling mode
let compiledComponents = [];
// Load tracking
let pendingLoads = 0;
let bundleFinalized = false;
/**
* Compiles a single component's template and script into a 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>.
* @returns {string} - The compiled class code as a string.
*/
function compileComponentCode(name, templateContent, scriptContent) {
// [Compilation logic remains unchanged...]
// For brevity, assume the compileComponentCode function is as defined in your original code.
// It compiles the component and returns the class code as a string.
// ...
// Example placeholder (replace with your actual compilation logic)
const classCode = `
class ${componentNameToClassName(name)} extends HTMLElement {
constructor() {
super();
// Initialization code...
}
// Getters, setters, methods...
}
customElements.define('${name}', ${componentNameToClassName(name)});
`;
return classCode;
}
/**
* Compiles and registers multiple components in bundling mode.
*/
function compileAndRegisterBundle() {
if (bundleScriptInjected || compiledComponents.length === 0) return;
bundleScriptInjected = true;
// Combine all component codes into one string
bundledCode = compiledComponents.join('\n');
// Create a Blob from the bundled code
const blob = new Blob([bundledCode], { type: 'application/javascript' });
const blobURL = URL.createObjectURL(blob);
// Create a script element
const script = document.createElement('script');
script.src = blobURL;
script.type = 'module'; // Use module type for modern JavaScript features
script.onload = () => {
console.log(`All components loaded and registered as a bundle.`);
// Revoke the Blob URL after the script has been loaded to free memory
URL.revokeObjectURL(blobURL);
};
script.onerror = (error) => {
console.error(`Error loading component bundle:`, error);
// Revoke the Blob URL on error to free memory
URL.revokeObjectURL(blobURL);
};
// Append the script to the document head
document.head.appendChild(script);
}
/**
* Compiles and registers a single component or accumulates for bundling based on configuration.
* @param {string} name - The name of the component.
* @param {string} templateContent - The template content.
* @param {string} scriptContent - The script content.
*/
function compileAndRegister(name, templateContent, scriptContent) {
const classCode = compileComponentCode(name, templateContent, scriptContent);
if (window.CatConfig.bundleAll) {
// Bundling mode: accumulate component codes
compiledComponents.push(classCode);
} else {
// Per-Component mode: compile and register immediately
compileAndRegisterComponent(name, classCode);
}
}
/**
* Finalizes the bundling process by injecting the bundled script.
*/
function finalizeBundle() {
if (window.CatConfig.bundleAll && !bundleFinalized) {
compileAndRegisterBundle();
bundleFinalized = true; // Ensure bundle is only injected once
}
}
/**
* Compiles and registers the component using Blob URLs.
* @param {string} name - The name of the component.
* @param {string} code - The compiled JavaScript class code.
*/
function compileAndRegisterComponent(name, code) {
// Create a Blob from the code
const blob = new Blob([code], { type: 'application/javascript' });
const blobURL = URL.createObjectURL(blob);
// Create a script element
const script = document.createElement('script');
script.src = blobURL;
script.type = 'module'; // Use module type for modern JavaScript features
script.onload = () => {
console.log(`Component ${name} loaded and registered.`);
// Revoke the Blob URL after the script has been loaded to free memory
URL.revokeObjectURL(blobURL);
};
script.onerror = (error) => {
console.error(`Error loading component ${name}:`, error);
// Revoke the Blob URL on error to free memory
URL.revokeObjectURL(blobURL);
};
// Append the script to the document head
document.head.appendChild(script);
}
return {
/**
* Compiles and registers a component based on bundling configuration.
* @param {string} name - The name of the component.
* @param {string} templateContent - The template content.
* @param {string} scriptContent - The script content.
*/
compileComponent: compileAndRegister,
/**
* Finalizes the bundling process by injecting the bundled script.
* Should be called when all components have been loaded.
*/
finalizeBundle: finalizeBundle,
/**
* Increment the pending load counter.
*/
incrementLoad: function() {
pendingLoads++;
},
/**
* Decrement the pending load counter and finalize if no more loads are pending.
*/
decrementLoad: function() {
pendingLoads--;
if (pendingLoads === 0) {
Compiler.finalizeBundle();
}
}
};
})();
/**
* 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);
// Increment the pending load counter
if (window.CatConfig.bundleAll) {
Compiler.incrementLoad();
}
(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 prepared for registration: ${componentName}`);
} catch (error) {
console.error(`Error loading component from ${path}: ${error.message}`);
} finally {
// Decrement the pending load counter and finalize if needed
if (window.CatConfig.bundleAll) {
Compiler.decrementLoad();
}
}
})();
};
})();
Explanation of the Changes:
-
Load Tracking in Compiler:
pendingLoads: A counter to keep track of how many components are currently being loaded.
bundleFinalized: A flag to ensure that the bundle is only injected once.
incrementLoad & decrementLoad: Methods to manage the pendingLoads counter.
-
Modified window.load Function:
- When
bundleAll is enabled, each load call increments the pendingLoads before initiating the load.
- Upon completion (whether successful or failed), it decrements the
pendingLoads.
- If
pendingLoads reaches zero, it implies that all components (including nested ones) have been loaded, and the bundle can be finalized.
-
Finalizing the Bundle:
finalizeBundle in the Compiler checks if bundling is enabled and ensures the bundle isn't already injected.
- It then concatenates all accumulated component codes and injects them as a single script blob.
- This method is called automatically when all loads are complete.
-
Handling Nested Loads:
- Since nested
load calls will also go through the same window.load function, each nested load will correctly increment and decrement the pendingLoads counter.
- This ensures that the system waits for all nested components to be loaded before finalizing the bundle.
Usage Instructions:
-
Enable Bundling:
Before loading any components, set the CatConfig.bundleAll to true:
<script>
window.CatConfig = {
bundleAll: true
};
</script>
<script src="path/to/cat.js"></script>
<script>
// Start loading components
load('component-a');
load('component-b');
// ... load other top-level components
</script>
-
Loading Components:
Use the load function to load your components. If a component loads other components, ensure that those load calls are made within their respective scripts. The tracking mechanism will handle nested loads automatically.
-
Finalization:
The bundle is automatically finalized and injected once all components (including nested ones) have been loaded. There's no need for manual intervention.
Benefits of This Approach:
- Scalability: Handles any depth of nested component loads without manual tracking.
- Efficiency: Only injects the bundled script once all components are ready, reducing network requests.
- Maintainability: Centralized load tracking ensures easier debugging and future enhancements.
Additional Considerations:
- Error Handling: Ensure that components handle their own errors gracefully. The bundling process logs errors encountered during component loading.
- Performance: While bundling reduces the number of network requests, ensure that the final bundle size is optimized to prevent long load times.
- Caching: Consider implementing caching strategies for the bundled script to enhance performance in subsequent loads.
By implementing these changes, your engine will robustly handle the bundling of all components, regardless of their nesting depth, ensuring efficient and maintainable component management.