import type { Attachment } from 'svelte/attachments'; /** * Keeps a popover inside the box it must not leave: moved back across, in CSS * pixels (the canvas and a window's zoom scale it), and capped to the vertical * room inside its clipping container (`.window > .body`, `dialog`, its window, * or the viewport) on the side it opens to (`up` or down; a tooltip leaves `up` * out and is only moved). */ export function fit(pop: HTMLElement, up?: boolean) { const style = pop.style; style.transform = style.maxWidth = ''; const clip = pop.closest('.window > .body, dialog'); const rect = pop.getBoundingClientRect(); const win = pop.closest('.window:not(.auto-height)'); const wide = !win || rect.width > win.getBoundingClientRect().width - 16; const box = ( clip ?? (wide ? pop.closest('main') : win) ?? document.documentElement ).getBoundingClientRect(); const scale = rect.width / pop.offsetWidth || 1; const maxBoxW = Math.min(box.width, document.documentElement.clientWidth) - 16; const width = clip ? Math.min(rect.width, maxBoxW) : rect.width; const right = rect.left + width; const rightEdge = Math.min(box.right, document.documentElement.clientWidth) - 8; const leftEdge = Math.max(box.left, 0) + 8; const past = right > rightEdge ? rightEdge - right : rect.left < leftEdge ? leftEdge - rect.left : 0; if (past) style.transform = `translateX(${Math.round(past / scale)}px)`; if (up === undefined) return; const topEdge = Math.max(box.top, 0) + 8; const bottomEdge = Math.min(box.bottom, document.documentElement.clientHeight) - 8; const room = Math.max( 72, (up ? rect.bottom - topEdge : bottomEdge - rect.top) / scale, ); style.maxWidth = `${Math.floor(width / scale)}px`; style.maxHeight = style.overflowY = ''; style.removeProperty('--selector-height'); const computed = getComputedStyle(pop); const cssMax = parseFloat(computed.maxHeight) || Infinity; const maxH = Math.floor(Math.min(room, cssMax)); style.maxHeight = `${maxH}px`; if (maxH < 320) style.setProperty('--selector-height', `${maxH}px`); if (computed.display !== 'flex') style.overflowY = 'auto'; } /** `fit` once the popover is on the page and whenever its layout box resizes. */ export const fitted = (up: boolean): Attachment => (pop) => { const update = () => pop.isConnected && fit(pop, up); queueMicrotask(update); window.addEventListener('resize', update); return () => window.removeEventListener('resize', update); }; /** Closes a popover on a press outside it (`keep` says what counts as inside) or on Escape, taken so the chat under it keeps its own state. Returns the cleanup, for an $effect. */ export function dismissal( keep: (target: Element) => boolean, close: () => void, ): () => void { const away = (event: PointerEvent) => event.target instanceof Element && !keep(event.target) && close(); const escape = (event: KeyboardEvent) => event.key === 'Escape' && (event.preventDefault(), close()); document.addEventListener('pointerdown', away, true); document.addEventListener('keydown', escape); return () => { document.removeEventListener('pointerdown', away, true); document.removeEventListener('keydown', escape); }; } /** * Remembers what has the focus now and returns a function that gives it back, * once whatever took it is gone and left it on the page: a popover closed by * Esc, a pick or its own button leaves the keyboard where it was. */ export function keepFocus(): () => void { const before = document.activeElement; return () => queueMicrotask(() => { const now = document.activeElement; if ( before instanceof HTMLElement && before.isConnected && (!now || now === document.body) ) before.focus({ preventScroll: true }); }); } /** * Runs `step` on animation frames while it reports changes, settling after * a few unchanged frames and waking again when `target` or its ancestors move. */ export function followFrames( target: Element | null | undefined, step: () => boolean, observed: Element[] = [], ): () => void { const SETTLE = 3; let frame = 0; let still = 0; const run = () => { frame = 0; still = step() ? 0 : still + 1; if (still < SETTLE) frame = requestAnimationFrame(run); }; const wake = () => { still = 0; frame ||= requestAnimationFrame(run); }; const move = (event: PointerEvent) => { if (event.buttons) wake(); }; const observer = new ResizeObserver(wake); if (target) observer.observe(target); for (const element of observed) observer.observe(element); const mutations = new MutationObserver(wake); for ( let node: Element | null = target ?? null; node; node = node.parentElement ) mutations.observe(node, { attributes: true, attributeFilter: ['style', 'class'], }); const wakers = ['scroll', 'wheel', 'transitionstart', 'animationstart']; for (const name of wakers) document.addEventListener(name, wake, { capture: true, passive: true }); document.addEventListener('pointermove', move, { capture: true, passive: true, }); window.addEventListener('resize', wake); wake(); return () => { cancelAnimationFrame(frame); observer.disconnect(); mutations.disconnect(); for (const name of wakers) document.removeEventListener(name, wake, { capture: true }); document.removeEventListener('pointermove', move, { capture: true }); window.removeEventListener('resize', wake); }; } /** A word's menu escapes clipping windows but stays attached to that word. * On a phone its CSS supplies the bottom-sheet position instead. */ export const floating = (anchor: HTMLElement | undefined): Attachment => (pop) => { pop.showPopover(); const update = () => { if (!anchor || !pop.isConnected) return; if (matchMedia('(max-width: 760px)').matches) { pop.style.left = pop.style.top = ''; return; } const button = anchor.getBoundingClientRect(); const menu = pop.getBoundingClientRect(); const scale = menu.width / pop.offsetWidth || 1; const left = Math.max( 8, Math.min(button.right - menu.width, innerWidth - menu.width - 8), ); const above = button.top - menu.height - 4; pop.style.left = `${left / scale}px`; pop.style.top = `${Math.max(8, above >= 8 ? above : button.bottom + 4) / scale}px`; }; let previousBounds = ''; const stop = followFrames(anchor, () => { const bounds = anchor?.getBoundingClientRect(); const key = bounds ? `${bounds.x},${bounds.y},${bounds.width},${bounds.height}` : ''; if (key === previousBounds) return false; previousBounds = key; update(); return true; }, [pop]); queueMicrotask(update); return stop; };