Spaces:
Paused
Paused
File size: 8,496 Bytes
8d1819a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | // Import a component into a target element
// Import a component and recursively load its nested components
// Returns the parsed document for additional processing
// cache object to store loaded components
const componentCache = {};
// Lock map to prevent multiple simultaneous imports of the same component
const importLocks = new Map();
export async function importComponent(path, targetElement) {
// Create a unique key for this import based on the target element
const lockKey = targetElement.id || targetElement.getAttribute('data-component-id') || targetElement;
// If this component is already being loaded, return early
if (importLocks.get(lockKey)) {
console.log(`Component ${path} is already being loaded for target`, targetElement);
return;
}
// Set the lock
importLocks.set(lockKey, true);
try {
if (!targetElement) {
throw new Error("Target element is required");
}
// Show loading indicator
targetElement.innerHTML = '<div class="loading"></div>';
// full component url
const trimmedPath = path.replace(/^\/+/, "");
const componentUrl = trimmedPath.startsWith("components/") ? trimmedPath : "components/" + trimmedPath;
// get html from cache or fetch it
let html;
if (componentCache[componentUrl]) {
html = componentCache[componentUrl];
} else {
const response = await fetch(componentUrl);
if (!response.ok) {
throw new Error(
`Error loading component ${path}: ${response.statusText}`
);
}
html = await response.text();
// store in cache
componentCache[componentUrl] = html;
}
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const allNodes = [
...doc.querySelectorAll("style"),
...doc.querySelectorAll("script"),
...doc.body.childNodes,
];
const loadPromises = [];
let blobCounter = 0;
for (const node of allNodes) {
if (node.nodeName === "SCRIPT") {
const isModule =
node.type === "module" || node.getAttribute("type") === "module";
if (isModule) {
if (node.src) {
// For <script type="module" src="..." use dynamic import
const resolvedUrl = new URL(
node.src,
globalThis.location.origin
).toString();
// Check if module is already in cache
if (!componentCache[resolvedUrl]) {
const modulePromise = import(resolvedUrl);
componentCache[resolvedUrl] = modulePromise;
loadPromises.push(modulePromise);
}
} else {
const virtualUrl = `${componentUrl.replaceAll(
"/",
"_"
)}.${++blobCounter}.js`;
// For inline module scripts, use cache or create blob
if (!componentCache[virtualUrl]) {
// Transform relative import paths to absolute URLs
let content = node.textContent.replace(
/import\s+([^'"]+)\s+from\s+["']([^"']+)["']/g,
(match, bindings, importPath) => {
// Convert relative OR root-based (e.g. /src/...) to absolute URLs
if (!/^https?:\/\//.test(importPath)) {
const absoluteUrl = new URL(
importPath,
globalThis.location.origin
).href;
return `import ${bindings} from "${absoluteUrl}"`;
}
return match;
}
);
// Add sourceURL to the content
content += `\n//# sourceURL=${virtualUrl}`;
// Create a Blob from the rewritten content
const blob = new Blob([content], {
type: "text/javascript",
});
const blobUrl = URL.createObjectURL(blob);
const modulePromise = import(blobUrl)
.catch((err) => {
console.error("Failed to load inline module", err);
throw err;
})
.finally(() => URL.revokeObjectURL(blobUrl));
componentCache[virtualUrl] = modulePromise;
loadPromises.push(modulePromise);
}
}
} else {
// Non-module script
const script = document.createElement("script");
Array.from(node.attributes || []).forEach((attr) => {
script.setAttribute(attr.name, attr.value);
});
script.textContent = node.textContent;
if (script.src) {
const promise = new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = reject;
});
loadPromises.push(promise);
}
targetElement.appendChild(script);
}
} else if (
node.nodeName === "STYLE" ||
(node.nodeName === "LINK" && node.rel === "stylesheet")
) {
const clone = node.cloneNode(true);
if (clone.tagName === "LINK" && clone.rel === "stylesheet") {
const promise = new Promise((resolve, reject) => {
clone.onload = resolve;
clone.onerror = reject;
});
loadPromises.push(promise);
}
targetElement.appendChild(clone);
} else {
const clone = node.cloneNode(true);
targetElement.appendChild(clone);
}
}
// Wait for all tracked external scripts/styles to finish loading
await Promise.all(loadPromises);
// Remove loading indicator
const loadingEl = targetElement.querySelector(':scope > .loading');
if (loadingEl) {
targetElement.removeChild(loadingEl);
}
// // Load any nested components
// await loadComponents([targetElement]);
// Return parsed document
return doc;
} catch (error) {
console.error("Error importing component:", error);
throw error;
} finally {
// Release the lock when done, regardless of success or failure
importLocks.delete(lockKey);
}
}
// Load all x-component tags starting from root elements
export async function loadComponents(roots = [document.documentElement]) {
try {
// Convert single root to array if needed
const rootElements = Array.isArray(roots) ? roots : [roots];
// Find all top-level components and load them in parallel
const components = rootElements.flatMap((root) =>
Array.from(root.querySelectorAll("x-component"))
);
if (components.length === 0) return;
await Promise.all(
components.map(async (component) => {
const path = component.getAttribute("path");
if (!path) {
console.error("x-component missing path attribute:", component);
return;
}
await importComponent(path, component);
})
);
} catch (error) {
console.error("Error loading components:", error);
}
}
// Function to traverse parents and collect x-component attributes
export function getParentAttributes(el) {
let element = el;
let attrs = {};
while (element) {
if (element.tagName.toLowerCase() === 'x-component') {
// Get all attributes
for (let attr of element.attributes) {
try {
// Try to parse as JSON first
attrs[attr.name] = JSON.parse(attr.value);
} catch(_e) {
// If not JSON, use raw value
attrs[attr.name] = attr.value;
}
}
}
element = element.parentElement;
}
return attrs;
}
// expose as global for x-components in Alpine
globalThis.xAttrs = getParentAttributes;
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => loadComponents());
} else {
loadComponents();
}
// Watch for DOM changes to dynamically load x-components
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === 1) {
// ELEMENT_NODE
// Check if this node or its descendants contain x-component(s)
if (node.matches?.("x-component")) {
importComponent(node.getAttribute("path"), node);
} else if (node.querySelectorAll) {
loadComponents([node]);
}
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
|