@stacksjs/stx
Version:
A Bun plugin that allows for using Laravel Blade-like syntax.
36 lines (28 loc) • 1.19 kB
TypeScript
declare type IslandHandlers = Record<string, () => Promise<any>>
type IslandHydrationFn = (element: any, props: any) => void | Promise<void>
const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
async function hydrateIsland(
element: any,
name: string,
handler: () => Promise<any>,
): Promise<void> {
if (!isBrowser) return
try {
const id = element.getAttribute('data-island-id')
const propsScript = document.querySelector(`script[data-island-props="${id}"]`)
const props = propsScript ? JSON.parse(propsScript.textContent || '{}') : {}
const module = await handler()
const hydrateFn: IslandHydrationFn = module.default || module.hydrate
if (typeof hydrateFn !== 'function') {
console.error(`Island handler for "${name}" does not export a valid hydration function`)
return
}
await hydrateFn(element, props)
element.setAttribute('data-hydrated', 'true')
}
catch (error) {
console.error(`Failed to hydrate island "${name}":`, error)
}
}
export declare function hydrateIslands(handlers: IslandHandlers): void;
export declare function preloadIslandHandlers(handlers: IslandHandlers): void;