Certainly! Below is a JavaScript implementation that fulfills your requirements. The code performs the following steps:
- Fetch and parse the HTML content.
- Extract variables from the
<script> tag.
- Compile the HTML by replacing
{expressions} with their corresponding values.
- Collect references to the nodes that contain the expressions for future updates.
- Create a custom element that includes the compiled HTML and exposes methods to update the nodes directly without modifying the DOM structure by adding extra elements or attributes.
Let's proceed step by step.
<!-- sample.html -->
<h1> Hello {who} </h1>
<script> let who = 'world'; </script>
// compiler.js
// Function to fetch and compile the HTML
async function fetchAndCompileHTML(url) {
const response = await fetch(url);
const htmlText = await response.text();
// Parse the HTML text into a DOM
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
// Extract variables from the script tag
const scriptContent = doc.querySelector('script')?.textContent || '';
const variables = extractVariablesFromScript(scriptContent);
// Find text nodes with expressions and compile them
const nodeReferences = [];
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT, null, false);
let node;
while ((node = walker.nextNode())) {
const expressions = node.textContent.match(/{([^}]+)}/g);
if (expressions) {
expressions.forEach((expression) => {
const expr = expression.slice(1, -1).trim();
if (variables.hasOwnProperty(expr)) {
// Replace the expression with the variable value
node.textContent = node.textContent.replace(expression, variables[expr]);
// Store the reference to this node
nodeReferences.push({
node: node,
expression: expr,
});
}
});
}
}
return {
compiledHTML: doc.body.innerHTML,
nodeReferences: nodeReferences,
};
}
// Function to extract variables from script content
function extractVariablesFromScript(scriptContent) {
const variables = {};
// Use Function constructor to create a function that returns the variables
const variableExtractor = new Function(
'const vars = {};' +
scriptContent +
'; for (let prop in this) { if (this.hasOwnProperty(prop)) vars[prop] = this[prop]; } return vars;'
);
Object.assign(variables, variableExtractor.call({}));
return variables;
}
// Custom Element definition
class CompiledElement extends HTMLElement {
constructor(compiledHTML, nodeReferences) {
super();
// Attach a shadow root
const shadow = this.attachShadow({ mode: 'open' });
// Set the compiled HTML content
shadow.innerHTML = compiledHTML;
// Store node references
this.nodeReferences = nodeReferences.map((ref) => {
// Update the node references to point to nodes in the shadow DOM
const path = getNodePath(ref.node);
return {
node: shadow.querySelector(path),
expression: ref.expression,
};
});
}
// Method to update variables
updateVariable(variableName, value) {
this.nodeReferences.forEach((ref) => {
if (ref.expression === variableName) {
ref.node.textContent = ref.node.textContent.replace(
this.variables[variableName],
value
);
this.variables[variableName] = value;
}
});
}
}
// Helper function to get a CSS selector path to a node
function getNodePath(node) {
if (node.nodeType === Node.TEXT_NODE) {
return getNodePath(node.parentNode);
}
if (node.id) {
return `#${node.id}`;
}
if (node.tagName.toLowerCase() === 'body') {
return 'body';
}
const siblings = Array.from(node.parentNode.children);
const index = siblings.indexOf(node) + 1;
return `${getNodePath(node.parentNode)} > ${node.tagName.toLowerCase()}:nth-child(${index})`;
}
// Usage example
(async () => {
const result = await fetchAndCompileHTML('sample.html');
// Log the compiled HTML
console.log('Compiled HTML:');
console.log(result.compiledHTML);
// Log the node references
console.log('Node References:');
console.log(result.nodeReferences);
// Define the custom element
customElements.define(
'compiled-element',
class extends CompiledElement {
constructor() {
super(result.compiledHTML, result.nodeReferences);
// Initialize variables
this.variables = extractVariablesFromScript(
document.querySelector('script')?.textContent || ''
);
}
}
);
// Create an instance of the custom element and add it to the document
const compiledElement = document.createElement('compiled-element');
document.body.appendChild(compiledElement);
// Update the variable after 2 seconds
setTimeout(() => {
compiledElement.updateVariable('who', 'universe');
}, 2000);
})();
Explanation:
Notes:
Output:
After running the code, the initial output in the console will be:
Compiled HTML:
<h1> Hello world </h1>
Node References:
[ { node: TextNode, expression: 'who' } ]
The document will display:
Hello world
After 2 seconds, it will update to:
Hello universe
Feel free to integrate this code into your project and adjust it according to your specific needs. Let me know if you have any questions or need further assistance!