nyxxworks / ui /src /lib /layer.ts
Kazzze's picture
Update to current version
e94c49d verified
Raw History Blame Contribute Delete
1.57 kB
import { useStore } from '@/store'
/** Whether the page is shown as a layer over the host's own page. The host loads it as
* /nyxxworks/ui?in=host; nothing else is taken as a sign of it. */
export const inLayer = new URLSearchParams(window.location.search).get('in') === 'host'
/** Tell the host page something. Only in the layer, and only to a page of the same origin. */
function post(message: { type: string; [key: string]: unknown }) {
if (inLayer && window.parent !== window) window.parent.postMessage(message, window.location.origin)
}
/** Hide the layer: the host keeps the page as it is, so nothing is asked and nothing is lost.
* What has the focus lets it go first, so that the page's keys stop with it. */
export function hideLayer() {
const focused = document.activeElement
if (focused instanceof HTMLElement) focused.blur()
post({ type: 'NYXX_HIDE' })
}
/** In the layer, tell the host whether a tool holds work that was not kept, and whether a job
* is running: once now, then each time either of them changes. */
let reporting = false
export function reportToHost() {
if (!inLayer || reporting) return
reporting = true
let last = ''
const tell = () => {
const { unkept, jobs } = useStore.getState()
const state = { unkept: unkept !== '', busy: jobs.some((job) => job.state === 'waiting' || job.state === 'running') }
const key = JSON.stringify(state)
if (key === last) return
last = key
post({ type: 'NYXX_STATE', ...state })
}
tell()
useStore.subscribe(tell)
}