import { getHostElements, mount, RootFragment, renderIsland } from './lib' import { render, ComponentType } from 'preact' export type InitialProps = { [x: string]: any } export type Island
= {
/**
* A WeakMap that yields the mutation observers associated with a particular root. Used for cleaning up observers
* on destroy.
*/
_rootsToObservers: WeakMap
/**
* A valid selector to a script tag located in the HTML document with a type of either `text/props` or `application/json`
* containing props to pass into the component. If there are multiple scripts found with the selector, all props are merged with
* the last script found taking priority.
*/
propsSelector?: string
/**
* Passed in if using for web components
*/
elementName?: string
}) => void
/**
* Contains the current props used to render the island.
*/
props: P
/**
* Triggers a rerenders of the island with the new props given.
*/
rerender: (props: P) => void
/**
* Destroys all instances of the island on the page and disconnects any associated observers.
*/
destroy: () => void
}
export const createIsland = (
widget: ComponentType ,
) => {
const island: Island = {
_rootsToObservers: new WeakMap(),
_roots: [],
_executedScript: document.currentScript,
// @ts-ignore
props: {},
render: ({
selector,
clean = false,
replace = false,
inline = false,
initialProps = {},
propsSelector,
elementName,
}) => {
let rendered = false
const load = () => {
/**
* We listen for multiple events to render so soon as we do it once
* successfully we break early for others.
*/
if (rendered === true) return
const hostElements = getHostElements({
selector,
inline,
elementName,
})
// Do nothing if no host elements returned
if (hostElements.length === 0) return
const { rootFragments } = mount ({
island,
widget,
clean,
hostElements,
replace,
// @ts-ignore Not sure how to fix this error
initialProps,
propsSelector,
})
island._roots = island._roots.concat(rootFragments)
rendered = true
}
load()
document.addEventListener('DOMContentLoaded', load)
document.addEventListener('load', load)
},
rerender: (newProps) => {
island._roots.forEach((rootFragment) => {
renderIsland({
island,
widget,
rootFragment,
props: { ...island.props, ...newProps },
})
})
},
destroy: () => {
island._roots.forEach((rootFragment) => {
island._rootsToObservers.get(rootFragment)?.disconnect()
render(null, rootFragment)
})
},
}
return island
}