import { ComponentType, h, render } from 'preact' import { InitialProps, Island } from './island' type HostElement = HTMLElement | ShadowRoot export const isInShadow = (node: HostElement | HTMLOrSVGScriptElement) => { return node.getRootNode() instanceof ShadowRoot } export const isShadowRoot = (x: unknown): x is ShadowRoot => { return x instanceof ShadowRoot } export const formatProp = (str: string) => { return `${str.charAt(0).toLowerCase()}${str.slice(1)}` } export const getPropsFromElement = ( element: HostElement | HTMLOrSVGScriptElement, ) => { // In a shadow dom we replace the host element because it's within the shadow root. However, // we want the props of the autonomous custom element. const targetElement = isInShadow(element) ? (element.getRootNode() as any).host : element const { dataset } = targetElement const props: { [x: string]: any } = {} for (var d in dataset) { // We don't pull props for inherited attributes if (dataset.hasOwnProperty(d) === false) return // data-prop or data-props works! const propName = formatProp(d.split(/(props?)/).pop() || '') if (propName) { props[propName] = dataset[d] } } return props } export const isValidPropsScript = (element: Element) => { return ( // element.tagName.toLowerCase() === 'script' && ['text/props', 'application/json'].includes( element.getAttribute('type') || '', ) ) } export const getInteriorPropsScriptsForElement = (element: HostElement) => { // getElementsByTagName does not exist on shadow roots and within a shadow root // the caller can't place in props scripts if (isShadowRoot(element)) return [] return Array.from(element.getElementsByTagName('script')).filter( isValidPropsScript, ) } export const getPropsScriptsBySelector = (selector: string) => { return Array.from(document.querySelectorAll(selector)).filter( isValidPropsScript, // Checked by filter call ) as HTMLOrSVGScriptElement[] } export const getPropsFromScripts = (scripts: HTMLOrSVGScriptElement[]) => { let interiorScriptProps: any = {} scripts.forEach((script) => { // Swallow any potential errors so we don't throw on someone else's page try { interiorScriptProps = { ...interiorScriptProps, ...JSON.parse(script.innerHTML), } } catch (e: any) {} }) return interiorScriptProps } /** * Get the props from a host element's data attributes * @param {Element} The host element * @return {Object} props object to be passed to the component */ export const generateHostElementProps =
( island: Island
,
element: HostElement,
initialProps = {},
propsSelector: string | undefined | null,
): P => {
const elementProps = getPropsFromElement(element)
const currentScriptProps = island._executedScript
? getPropsFromElement(island._executedScript)
: {}
const interiorScriptProps = getPropsFromScripts(
getInteriorPropsScriptsForElement(element),
)
const propsSelectorProps = propsSelector
? getPropsFromScripts(getPropsScriptsBySelector(propsSelector))
: {}
return {
...initialProps,
...elementProps,
...currentScriptProps,
...propsSelectorProps,
...interiorScriptProps,
}
}
export const getHostElements = ({
selector,
inline,
elementName,
}: {
selector?: string
inline: boolean
/**
* Passed if targeting web components so that mount in can create web components inside of the host elements
*/
elementName?: string
}): HostElement[] => {
const currentScript = document.currentScript
if (inline && currentScript?.parentNode) {
// @ts-ignore Not sure on this one
return [currentScript.parentNode]
}
// Next, try to get the selector from the current script
const maybeSelector = currentScript?.dataset.mountIn
if (maybeSelector) {
return Array.from(
document.querySelectorAll ({
island,
hostElement,
initialProps,
onNewProps,
propsSelector,
}: {
island: Island
hostElement: HostElement
initialProps: any
onNewProps: (props: P) => void
propsSelector: string | undefined | null
}) => {
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function () {
onNewProps(
generateHostElementProps(
island,
hostElement,
initialProps,
propsSelector,
),
)
})
})
const config = { attributes: true, childList: true, characterData: true }
if (island._executedScript) {
observer.observe(island._executedScript, config)
}
getInteriorPropsScriptsForElement(hostElement).forEach((script) => {
observer.observe(script, { ...config, subtree: true })
})
if (propsSelector) {
getPropsScriptsBySelector(propsSelector).forEach((script) => {
observer.observe(script, { ...config, subtree: true })
})
}
/**
* If the host element is a shadow root we want to observe on the host of it.
*
* Example:
* ({
island,
widget,
rootFragment,
props,
}: {
island: Island
widget: ComponentType
rootFragment: RootFragment
props: P
}) => {
island.props = props
render(h(widget, props), rootFragment)
}
export const mount = ({
island,
widget,
hostElements,
clean,
replace,
initialProps,
propsSelector,
}: {
island: Island
widget: ComponentType
hostElements: Array (
island,
hostElement,
initialProps,
propsSelector,
)
if (clean) {
hostElement.replaceChildren()
}
let rootFragment: any
if (replace) {
rootFragment = createRootFragment(
hostElement.parentElement || document.body,
hostElement,
)
} else {
const renderNode = document.createElement('div')
hostElement.appendChild(renderNode)
rootFragment = createRootFragment(hostElement, renderNode)
}
rootFragments.push(rootFragment)
renderIsland({ island, widget, rootFragment, props })
const observer = watchForPropChanges ({
island,
hostElement,
initialProps,
onNewProps: (newProps) => {
renderIsland({ island, widget, rootFragment, props: newProps })
},
propsSelector,
})
island._rootsToObservers.set(rootFragment, observer)
})
return { rootFragments }
}