@michaelyagi/shoji 0.1.0-beta.13 → 0.1.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/shoji-core.css +43 -0
- package/dist/core/shoji-core.min.css +1 -1
- package/dist/esm/core/iconSwap.d.ts +21 -0
- package/dist/esm/iconSwap-BAXTLihx.js +21 -0
- package/dist/esm/iconSwap-BAXTLihx.js.map +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index2.css +43 -0
- package/dist/esm/plugins/autoplay/index.js +4 -2
- package/dist/esm/plugins/autoplay/index.js.map +1 -1
- package/dist/esm/plugins/fullscreen/index.js +4 -2
- package/dist/esm/plugins/fullscreen/index.js.map +1 -1
- package/dist/esm/plugins/zoom/icons.d.ts +14 -1
- package/dist/esm/plugins/zoom/index.js +18 -2
- package/dist/esm/plugins/zoom/index.js.map +1 -1
- package/dist/plugins/autoplay.js +20 -2
- package/dist/plugins/autoplay.js.map +1 -1
- package/dist/plugins/autoplay.min.js +1 -1
- package/dist/plugins/autoplay.min.js.map +1 -1
- package/dist/plugins/fullscreen.js +20 -2
- package/dist/plugins/fullscreen.js.map +1 -1
- package/dist/plugins/fullscreen.min.js +1 -1
- package/dist/plugins/fullscreen.min.js.map +1 -1
- package/dist/plugins/zoom.js +34 -2
- package/dist/plugins/zoom.js.map +1 -1
- package/dist/plugins/zoom.min.js +1 -1
- package/dist/plugins/zoom.min.js.map +1 -1
- package/dist/shoji.css +43 -0
- package/dist/shoji.js +41 -7
- package/dist/shoji.js.map +1 -1
- package/dist/shoji.min.css +1 -1
- package/dist/shoji.min.js +1 -1
- package/dist/shoji.min.js.map +1 -1
- package/package.json +1 -1
package/dist/shoji.min.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shoji.min.js","sources":["../src/core/bodyScrollLock.ts","../src/core/EventBus.ts","../src/core/icons.ts","../src/core/dom.ts","../src/core/FocusTrap.ts","../src/gestures/GestureEngine.ts","../src/core/zoomTransition.ts","../src/core/GestureController.ts","../src/core/LiveRegion.ts","../src/core/scan.ts","../src/core/SlideManager.ts","../src/transitions/presets.ts","../src/transitions/SlideTransition.ts","../src/core/Gallery.ts","../src/plugins/activeThumbnail/index.ts","../src/plugins/autoplay/icons.ts","../src/plugins/autoplay/index.ts","../src/plugins/fullscreen/icons.ts","../src/plugins/fullscreen/index.ts","../src/plugins/layout/masonry.ts","../src/plugins/layout/justified.ts","../src/plugins/layout/index.ts","../src/core/rotateFlipNormalize.ts","../src/plugins/rotateFlip/icons.ts","../src/plugins/rotateFlip/index.ts","../src/plugins/video/vimeo.ts","../src/plugins/video/youtube.ts","../src/plugins/video/index.ts","../src/plugins/zoom/icons.ts","../src/plugins/zoom/zoomMath.ts","../src/plugins/zoom/index.ts","../src/index.ts"],"sourcesContent":["/** DESIGN.md §2.6a — reference-counted page scroll lock. */\nlet lockCount = 0;\nlet savedHtmlOverflow = '';\nlet savedHtmlPaddingRight = '';\nlet savedHtmlPaddingLeft = '';\nlet savedScrollX = 0;\nlet savedScrollY = 0;\nlet styleObserver: MutationObserver | null = null;\n// Set by markIntentionalScroll() (ActiveThumbnail's own scrollIntoView while\n// locked, DESIGN.md §2.6a/§4.2) — a real bug/regression: unlockBodyScroll()\n// unconditionally restoring savedScrollX/Y (below) was meant to undo\n// *unrelated* code hijacking scroll during the lock (a router, a stray\n// \"scroll to top\" button), but it just as unconditionally undid Shoji's own\n// legitimate background-page scrolling too, making ActiveThumbnail's\n// scrollIntoView a complete no-op the instant the lightbox that triggers it\n// is also what's holding the lock — every navigation while open, always.\n// Once anything marks an intentional scroll during this lock session, skip\n// the restore entirely rather than try to track a smooth-scroll animation's\n// eventual resting position (no reliable completion signal across browsers)\n// — same \"leave it where legitimate code put it\" reasoning, just without\n// pinpointing the exact pixel.\nlet intentionalScrollOccurred = false;\n\nconst LIGHTBOX_SELECTOR = '.shoji-outer';\n\n/** Call after intentionally scrolling something on the host page while the lock is active (e.g. ActiveThumbnail's own `scrollIntoView`) — tells `unlockBodyScroll()` not to undo it. */\nexport function markIntentionalScroll(): void {\n intentionalScrollOccurred = true;\n}\n\nfunction isRtl(): boolean {\n return getComputedStyle(document.documentElement).direction === 'rtl';\n}\n\n/**\n * Walks up from `node` looking for a real scrollable container — lets\n * `onTouchMove` below allow touch-scrolling through to something like a\n * host-app modal/sidebar opened on top of the lightbox, instead of\n * blocking it just because it's outside `.shoji-outer`. Stops at\n * `document.documentElement` deliberately — that's the exact background\n * scroll this lock exists to block, not a container to exempt from it.\n */\nfunction hasScrollableAncestor(node: Node | null): boolean {\n let el = node instanceof Element ? node : (node?.parentElement ?? null);\n while (el && el !== document.documentElement) {\n const style = getComputedStyle(el);\n if (\n (style.overflowY === 'auto' || style.overflowY === 'scroll') &&\n el.scrollHeight > el.clientHeight\n ) {\n return true;\n }\n el = el.parentElement;\n }\n return false;\n}\n\n// Computed once per gesture, in onTouchStart below, not recomputed on every\n// onTouchMove — a touch's `event.target` stays fixed to the original\n// touchstart target for the whole gesture regardless of where the finger\n// moves (Touch Events spec), so re-walking the ancestor chain and calling\n// getComputedStyle again on every move would just repeat the same, not-free\n// answer for no benefit (CLAUDE.md: no forced synchronous layout in hot\n// paths like gestures/scroll).\nlet touchAllowsScrollThrough = false;\n\nfunction onTouchStart(event: TouchEvent): void {\n const target = event.target;\n const insideLightbox = target instanceof Element && target.closest(LIGHTBOX_SELECTOR) !== null;\n touchAllowsScrollThrough = !insideLightbox && hasScrollableAncestor(target as Node | null);\n}\n\n/**\n * A real gap: `overflow: hidden` on `<html>` doesn't reliably block iOS\n * Safari's own touch-driven rubber-band/bounce scroll in every case — a\n * well-known limitation of this technique across the ecosystem. The common\n * workaround (flipping `body` to `position: fixed` while locked) has its\n * own real tradeoffs: a full reflow, plus manual scroll-position capture/\n * restore that's a frequent source of bugs in other libraries (the exact\n * class of bug this whole lock has already had twice — see the other real\n * bugs in this file's history). Lighter alternative: block the browser's\n * default only for a touchmove that didn't start inside a lightbox,\n * leaving Shoji's own in-dialog gesture handling (which already manages\n * its own `preventDefault`, see `GestureEngine.ts`) completely untouched.\n * Not a passive listener — `preventDefault` is genuinely required here to\n * suppress the browser's native scroll, not just observe it.\n *\n * Also untouched: a touch that started on a genuinely scrollable ancestor\n * outside the lightbox (`touchAllowsScrollThrough`, set in `onTouchStart`\n * above) — a real bug, reported from real usage: this used to block\n * touch-scrolling in *any* host-app UI outside `.shoji-outer`, including\n * something like a Bootstrap modal or sidebar opened on top of the\n * lightbox, not just the page body behind it.\n */\nfunction onTouchMove(event: TouchEvent): void {\n const target = event.target;\n const insideLightbox = target instanceof Element && target.closest(LIGHTBOX_SELECTOR) !== null;\n if (!insideLightbox && !touchAllowsScrollThrough) event.preventDefault();\n}\n\n/**\n * A real gap: this lock is reference-counted against other `Gallery`\n * instances, but has no way to know about unrelated code on the host page\n * — another modal/dropdown library that also sets\n * `document.documentElement.style.overflow`, then clears it back to `''`\n * on its own close, would silently undo this lock mid-lightbox with\n * neither library aware of the other. Watching the one attribute this\n * lock itself owns is the only way to detect and correct that reactively.\n * `takeRecords()` discards the mutation record our own corrective write\n * below just queued — otherwise the observer would fire again for a\n * change it caused itself, forever.\n */\nfunction onStyleMutation(): void {\n if (lockCount === 0) return;\n const html = document.documentElement;\n if (getComputedStyle(html).overflow !== 'hidden') {\n html.style.overflow = 'hidden';\n styleObserver?.takeRecords();\n }\n}\n\nexport function lockBodyScroll(): void {\n if (lockCount === 0) {\n // A real gap: `overflow: hidden` blocks wheel/touch/keyboard-driven\n // scrolling, but not a programmatic `window.scrollTo()`/`scrollTop`\n // write — confirmed directly. If the host's own code scrolls the\n // window while the lightbox is open (a router restoring scroll\n // position, an unrelated \"scroll to top\" button), the page ends up\n // somewhere different than where the viewer left it once the lock\n // releases. Restored unconditionally on unlock below — a scroll\n // *lock* implies the background stays frozen in place for the whole\n // time the lightbox is open, not just protected from direct input.\n savedScrollX = window.scrollX;\n savedScrollY = window.scrollY;\n intentionalScrollOccurred = false;\n\n // A real bug: hiding overflow below reclaims the scrollbar's own\n // gutter, widening <html>'s content box by however many px the\n // scrollbar was — on a host page whose content spans the full viewport\n // width, that reflow is visible as a shift right when the lightbox\n // opens/closes (and reverses on close). Measured *before* overflow is\n // hidden (clientWidth only grows once the gutter is actually reclaimed,\n // so measuring after would always read 0) and only compensated for when\n // a real scrollbar was actually there — a page that never had one gets\n // no padding at all, nothing to compensate for.\n //\n // Two rejected approaches, both real bugs of their own: padding-right\n // on `document.body` compensates the wrong element — a page whose body\n // is narrower than the viewport (a centered, `max-width`-capped layout,\n // this docs site included) never touches the scrollbar's gutter in the\n // first place, so padding body just shrinks its own content box by an\n // *extra* scrollbar-width's worth, a new, self-inflicted reflow.\n // `scrollbar-gutter: stable` compensates the right element (`<html>`,\n // the same one the width is measured on) but paints its own visible,\n // if non-interactive, scrollbar-track styling for as long as the lock\n // is active — trading a brief shift for a permanent scrollbar-shaped\n // strip sitting over the page the whole time the lightbox is open,\n // which reads as more wrong, not less. Padding is genuinely invisible\n // — the same blank space a wider margin would be — and, applied to\n // `<html>` (not `body`), compensates the actual element the scrollbar's\n // gutter belongs to either way.\n const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n const rtl = isRtl();\n savedHtmlPaddingRight = document.documentElement.style.paddingRight;\n savedHtmlPaddingLeft = document.documentElement.style.paddingLeft;\n if (scrollbarWidth > 0) {\n // A real gap: a classic scrollbar renders on the *left* on a\n // `direction: rtl` page, not the right — compensating the wrong\n // side would reintroduce the exact reflow this exists to prevent,\n // just mirrored. Checked at lock time, not baked in as a fixed\n // assumption.\n if (rtl) {\n const currentPaddingLeft =\n parseFloat(getComputedStyle(document.documentElement).paddingLeft) || 0;\n document.documentElement.style.paddingLeft = `${currentPaddingLeft + scrollbarWidth}px`;\n } else {\n const currentPaddingRight =\n parseFloat(getComputedStyle(document.documentElement).paddingRight) || 0;\n document.documentElement.style.paddingRight = `${currentPaddingRight + scrollbarWidth}px`;\n }\n }\n\n // A real bug: `document.body.style.overflow = 'hidden'` (this function's\n // original, and until now only, scroll-blocking mechanism) was still\n // set here alongside <html>'s own below — redundant, and not harmless:\n // any value of `overflow` other than `visible` makes an element\n // establish a new block-formatting context, which blocks top-margin\n // collapsing between it and its first child. Confirmed directly via\n // real-browser instrumentation: with body's overflow locked, an h1\n // immediately inside it rendered `bodyMarginTop + h1's own default\n // margin-top` below the viewport top (its margin no longer collapsing\n // into body's own); the instant `unlockBodyScroll()` restored body's\n // overflow, collapsing resumed and the h1 snapped back up by its own\n // margin's worth — reading as the page shifting upward right as the\n // lightbox closes, on *any* page where the first child's margin would\n // otherwise collapse with body's (essentially any page without padding/\n // border on body itself — not a corner case). <html>'s own overflow:\n // hidden below is sufficient on its own to block user-driven scrolling\n // (wheel/touch/keyboard) — confirmed directly — since it's the real\n // scrolling element in standards mode; body's lock was never adding\n // independent protection, only this side effect.\n //\n // <html>'s own overflow, not just body's — mobile viewport-widening\n // bug, see DESIGN.md §2.6a. Both axes, not just overflow-x: setting\n // only one non-'visible' axis forces the browser to silently promote\n // the other from 'visible' to 'auto' (mixing hidden+visible isn't\n // allowed per spec), which revealed a real scrollbar that wasn't\n // there before.\n savedHtmlOverflow = document.documentElement.style.overflow;\n document.documentElement.style.overflow = 'hidden';\n\n // passive: true — onTouchStart only ever reads/caches, never calls\n // preventDefault(), unlike onTouchMove below.\n document.addEventListener('touchstart', onTouchStart, { passive: true });\n document.addEventListener('touchmove', onTouchMove, { passive: false });\n\n // Starts observing only after the writes above have already landed, so\n // it never reacts to its own initial setup — only to a later, external\n // change.\n styleObserver = new MutationObserver(onStyleMutation);\n styleObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['style'],\n });\n }\n lockCount++;\n}\n\nexport function unlockBodyScroll(): void {\n lockCount = Math.max(0, lockCount - 1);\n if (lockCount === 0) {\n styleObserver?.disconnect();\n styleObserver = null;\n document.removeEventListener('touchstart', onTouchStart);\n document.removeEventListener('touchmove', onTouchMove);\n\n document.documentElement.style.overflow = savedHtmlOverflow;\n document.documentElement.style.paddingRight = savedHtmlPaddingRight;\n document.documentElement.style.paddingLeft = savedHtmlPaddingLeft;\n\n if (!intentionalScrollOccurred) {\n window.scrollTo({ left: savedScrollX, top: savedScrollY, behavior: 'instant' });\n }\n }\n}\n","export type EventMap = Record<string, unknown>;\n\nexport type Unsubscribe = () => void;\n\ntype Listener<T> = (detail: T) => void;\n\n/**\n * Typed pub/sub used by Gallery and every plugin (`ctx.on`). Plugin\n * subscriptions are unsubscribed automatically on destroy by the caller\n * that owns the PluginContext, not by this class.\n */\nexport class EventBus<Events extends EventMap> {\n private listeners = new Map<keyof Events, Set<Listener<unknown>>>();\n\n on<K extends keyof Events>(event: K, fn: Listener<Events[K]>): Unsubscribe {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(fn as Listener<unknown>);\n return () => this.off(event, fn);\n }\n\n off<K extends keyof Events>(event: K, fn: Listener<Events[K]>): void {\n this.listeners.get(event)?.delete(fn as Listener<unknown>);\n }\n\n emit<K extends keyof Events>(event: K, detail: Events[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const fn of set) (fn as Listener<Events[K]>)(detail);\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, overridable per-button. */\n\nexport const CLOSE_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg>';\n\nexport const PREV_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 6l-6 6 6 6\"/></svg>';\n\nexport const NEXT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 6l6 6-6 6\"/></svg>';\n\nexport const CAPTION_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><path d=\"M7 10h10M7 14h6\"/></svg>';\n\nexport const CARET_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"20\" height=\"20\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M6 9l6 6 6-6\"/></svg>';\n","import { CAPTION_ICON, CARET_ICON, CLOSE_ICON, NEXT_ICON, PREV_ICON } from './icons';\n\nlet idCounter = 0;\n\nexport interface LightboxLabels {\n close: string;\n previous: string;\n next: string;\n showCaption: string;\n hideCaption: string;\n fullCaption: string; // DESIGN.md §2.3a — aria-label for the caption modal's own dialog role\n moreControls: string; // DESIGN.md §3.1a — the toolbar overflow popover's own toggle/dialog label\n}\n\nexport interface LightboxDom {\n outer: HTMLElement;\n backdrop: HTMLElement;\n dialog: HTMLElement;\n counter: HTMLElement;\n caption: HTMLElement;\n closeButton: HTMLButtonElement;\n prevButton: HTMLButtonElement;\n nextButton: HTMLButtonElement;\n captionToggleButton: HTMLButtonElement; // DESIGN.md §2.3a\n /** DESIGN.md §2.3a — a truncated caption's click/Enter/Space target opens this, showing the full text scrollable, so a long caption never has to cover the nav arrows to be readable. Hidden (`[hidden]`) whenever not open. */\n captionModal: HTMLElement;\n captionModalPanel: HTMLElement;\n captionModalContent: HTMLElement;\n captionModalCloseButton: HTMLButtonElement;\n /** The whole toolbar bar — DESIGN.md §2.3a's toolbar-height measurement observes this, not any one slot, since it's what actually wraps to multiple rows. */\n toolbar: HTMLElement;\n /** DESIGN.md §3 — `ctx.ui.toolbar(slot, ...)` inserts into these; close lives in `right`. */\n toolbarLeft: HTMLElement;\n toolbarCenter: HTMLElement;\n toolbarRight: HTMLElement;\n /** DESIGN.md §3.1a — hidden unless the toolbar actually overflows; toggles `toolbarOverflowPanel`. Lives in `toolbarRight`, just before `closeButton`. */\n toolbarOverflowButton: HTMLButtonElement;\n /** DESIGN.md §3.1a — the floating popover collapsed plugin buttons relocate into once they don't fit. */\n toolbarOverflowPanel: HTMLElement;\n}\n\nfunction iconButton(className: string, icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = className;\n button.ariaLabel = button.title = label;\n button.innerHTML = icon;\n return button;\n}\n\n/**\n * DESIGN.md §2.6 — `.shoji-outer` is the exact element `ctx.ui.outer()` (§3)\n * will return to plugins once the real plugin loader exists. Close/prev/next\n * are core-owned baseline controls, not routed through any plugin API.\n */\nexport function buildLightboxDom(slides: HTMLElement, labels: LightboxLabels): LightboxDom {\n const labelId = `shoji-counter-${++idCounter}`;\n\n const outer = document.createElement('div');\n outer.className = 'shoji-outer';\n\n const backdrop = document.createElement('div');\n backdrop.className = 'shoji-backdrop';\n outer.appendChild(backdrop);\n\n const dialog = document.createElement('div');\n dialog.className = 'shoji-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.setAttribute('aria-labelledby', labelId);\n dialog.tabIndex = -1;\n\n const toolbar = document.createElement('div');\n toolbar.className = 'shoji-toolbar';\n const toolbarLeft = document.createElement('div');\n toolbarLeft.className = 'shoji-toolbar-slot shoji-toolbar-left';\n const toolbarCenter = document.createElement('div');\n toolbarCenter.className = 'shoji-toolbar-slot shoji-toolbar-center';\n const toolbarRight = document.createElement('div');\n toolbarRight.className = 'shoji-toolbar-slot shoji-toolbar-right';\n const closeButton = iconButton('shoji-close', CLOSE_ICON, labels.close);\n // Ahead of close so plugin buttons (always inserted right before close) land between the two.\n const captionToggleButton = iconButton(\n 'shoji-toolbar-button shoji-caption-toggle',\n CAPTION_ICON,\n labels.showCaption,\n );\n captionToggleButton.setAttribute('aria-pressed', 'false');\n captionToggleButton.hidden = true;\n // DESIGN.md §3.1a — requested directly: close stays the absolute\n // rightmost control, with the (usually hidden) overflow caret just to its\n // left — `pluginToolbar()` inserts new buttons immediately before the\n // caret now, not before close, so they still land to the left of both\n // fixed controls.\n const toolbarOverflowButton = iconButton(\n 'shoji-toolbar-button shoji-toolbar-overflow',\n CARET_ICON,\n labels.moreControls,\n );\n toolbarOverflowButton.setAttribute('aria-haspopup', 'true');\n toolbarOverflowButton.setAttribute('aria-expanded', 'false');\n toolbarOverflowButton.hidden = true;\n toolbarRight.append(captionToggleButton, toolbarOverflowButton, closeButton);\n\n const toolbarOverflowPanel = document.createElement('div');\n toolbarOverflowPanel.className = 'shoji-toolbar-overflow-panel';\n toolbarOverflowPanel.setAttribute('role', 'dialog');\n toolbarOverflowPanel.setAttribute('aria-label', labels.moreControls);\n toolbarOverflowPanel.tabIndex = -1;\n toolbarOverflowPanel.hidden = true;\n\n // The counter lives in the toolbar's own left slot (flex flow, not\n // independent absolute positioning) specifically so a plugin button\n // sharing that slot (e.g. autoplay's play/pause, ctx.ui.toolbar('left', ...))\n // sits next to it instead of the two overlapping and fighting over clicks.\n const counter = document.createElement('div');\n counter.className = 'shoji-counter';\n counter.id = labelId;\n toolbarLeft.appendChild(counter);\n\n toolbar.append(toolbarLeft, toolbarCenter, toolbarRight);\n dialog.appendChild(toolbar);\n // Appended to `dialog` directly, not nested in `.shoji-toolbar` — the\n // toolbar's own `pointer-events: none` base rule (re-enabled per-slot,\n // not per-descendant) would otherwise need remembering to re-enable here\n // too; sidestepped entirely by living outside it, same placement pattern\n // `.shoji-caption-modal` already uses below.\n dialog.appendChild(toolbarOverflowPanel);\n\n const prevButton = iconButton('shoji-nav shoji-nav-prev', PREV_ICON, labels.previous);\n const nextButton = iconButton('shoji-nav shoji-nav-next', NEXT_ICON, labels.next);\n dialog.appendChild(prevButton);\n dialog.appendChild(nextButton);\n\n dialog.appendChild(slides);\n\n const caption = document.createElement('div');\n caption.className = 'shoji-caption';\n dialog.appendChild(caption);\n\n const captionModal = document.createElement('div');\n captionModal.className = 'shoji-caption-modal';\n captionModal.hidden = true;\n const captionModalPanel = document.createElement('div');\n captionModalPanel.className = 'shoji-caption-modal-panel';\n captionModalPanel.setAttribute('role', 'dialog');\n captionModalPanel.setAttribute('aria-modal', 'true');\n captionModalPanel.setAttribute('aria-label', labels.fullCaption);\n captionModalPanel.tabIndex = -1;\n const captionModalCloseButton = iconButton('shoji-caption-modal-close', CLOSE_ICON, labels.close);\n const captionModalContent = document.createElement('div');\n captionModalContent.className = 'shoji-caption-modal-content';\n captionModalPanel.append(captionModalCloseButton, captionModalContent);\n captionModal.appendChild(captionModalPanel);\n dialog.appendChild(captionModal);\n\n outer.appendChild(dialog);\n\n return {\n outer,\n backdrop,\n dialog,\n counter,\n caption,\n captionModal,\n captionModalPanel,\n captionModalContent,\n captionModalCloseButton,\n closeButton,\n prevButton,\n nextButton,\n captionToggleButton,\n toolbar,\n toolbarLeft,\n toolbarCenter,\n toolbarRight,\n toolbarOverflowButton,\n toolbarOverflowPanel,\n };\n}\n","const FOCUSABLE_SELECTOR =\n 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), video[controls], [tabindex]:not([tabindex=\"-1\"])';\n\n/** DESIGN.md §2.6 — focus trap on open, focus restore on close, Tab cycles within the dialog. */\nexport class FocusTrap {\n private container: HTMLElement | null = null;\n private previouslyFocused: HTMLElement | null = null;\n\n private readonly onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== 'Tab' || !this.container) return;\n\n const focusable = this.getFocusable();\n if (focusable.length === 0) {\n event.preventDefault();\n this.container.focus();\n return;\n }\n\n const first = focusable[0]!;\n const last = focusable[focusable.length - 1]!;\n const active = document.activeElement;\n const activeIsInside = active instanceof HTMLElement && focusable.includes(active);\n\n if (event.shiftKey) {\n if (!activeIsInside || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else if (!activeIsInside || active === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n private getFocusable(): HTMLElement[] {\n if (!this.container) return [];\n return Array.from(this.container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n }\n\n activate(container: HTMLElement): void {\n this.previouslyFocused = document.activeElement as HTMLElement | null;\n this.container = container;\n document.addEventListener('keydown', this.onKeydown, true);\n container.focus();\n }\n\n /**\n * DESIGN.md §2.3a — narrows (or widens back) which subtree Tab cycles\n * within, without touching `previouslyFocused`/the listener registration\n * — a caption modal nested inside the already-trapped dialog needs Tab\n * confined to just itself while open, then back to the whole dialog on\n * close, but must NOT trigger `activate()`'s own focus-capture (that's\n * reserved for the real open/close boundary; re-running it mid-session\n * would capture the wrong \"previously focused\" element and restore focus\n * to it too early). `getFocusable()` reads `this.container` fresh on\n * every keydown, so simply reassigning it is enough — no need for a\n * second, independent `FocusTrap` instance, which would double-handle\n * every Tab keypress (two capture-phase `document` listeners, each\n * computing its own overlapping focusable list).\n */\n retarget(container: HTMLElement): void {\n this.container = container;\n container.focus();\n }\n\n deactivate(): void {\n document.removeEventListener('keydown', this.onKeydown, true);\n this.container = null;\n // preventScroll: true — a bare focus() call auto-scrolls the target\n // into view within any scrollable ancestor by default. A real bug:\n // previouslyFocused is captured once at activate() time and never\n // updated afterward (nothing re-focuses the current thumbnail as the\n // viewer navigates), so restoring it on close can drag a host's own\n // scrollable thumbnail strip all the way back to wherever the gallery\n // was originally opened from, discarding whatever it had scrolled to\n // since — e.g. ActiveThumbnail's auto-scroll, entirely undone by a\n // focus restoration that has nothing to do with it.\n this.previouslyFocused?.focus({ preventScroll: true });\n this.previouslyFocused = null;\n }\n}\n","/**\n * DESIGN.md §2.4 — one Pointer-Events-based engine feeding all consumers:\n * core drag-to-navigate, core vertical-swipe-to-close, and (via `onPinch`/\n * `onDoubleTap`/`onWheelZoom`) a future zoom plugin that doesn't exist yet.\n * Pointer Events (not separate mouse/touch listeners) give mouse-drag and\n * touch-swipe parity for free — one code path, one set of thresholds.\n *\n * State machine: `idle → pending → dragging(h|v) → idle`. `pending` is the\n * window before `lockThreshold` is crossed, where it's still ambiguous\n * whether this is a tap, a horizontal drag, or a vertical drag; `dragging`\n * is entered once one axis's delta exceeds the threshold first, and the\n * *other* axis is ignored for the rest of that gesture (an axis lock, not\n * a snapped direction — diagonal drags don't fight the engine). There's no\n * literal blocking `settling` state after release: `onDragEnd` reports the\n * outcome synchronously and the caller owns however long its own\n * snap-back/completion animation takes; a new `pointerdown` before that\n * finishes is allowed to interrupt it (matches real touch-carousel UX —\n * grabbing a still-settling slide feels responsive, not broken).\n *\n * Pinch tracking is a separate concern layered on top of the same pointer\n * map: a second simultaneous pointer suspends whatever single-pointer drag\n * state was in progress (real pinches start from a single touch already\n * down) and switches to distance-ratio tracking until back down to one\n * pointer or zero.\n */\n\nexport type GestureDirection = 'horizontal' | 'vertical';\n\nexport interface GestureEngineOptions {\n /** px of movement before a direction locks in. DESIGN.md §2.4 default: 10. */\n lockThreshold: number;\n /** px of movement past which a released drag counts as \"swiped\" (completes), independent of velocity. DESIGN.md §2.4 default: 50. */\n swipeThreshold: number;\n /** px/ms release velocity past which a drag completes even under swipeThreshold — a fast flick counts. DESIGN.md §2.4 default: 0.3. */\n swipeVelocity: number;\n}\n\nexport interface GestureEngineCallbacks {\n /** Direction has just locked in for this gesture — the first move past lockThreshold. */\n onDragStart?(direction: GestureDirection, event: PointerEvent): void;\n /** delta: signed px moved along the locked axis so far (this move's cumulative total, not a per-frame diff). */\n onDragMove?(direction: GestureDirection, delta: number, event: PointerEvent): void;\n /** Pointer released (or cancelled) after a drag was in progress. velocity is signed px/ms over the whole gesture; completed reflects swipeThreshold/swipeVelocity. cancelled is true for pointercancel (e.g. an OS gesture took over) — always treated as not-completed regardless of delta/velocity. */\n onDragEnd?(\n direction: GestureDirection,\n delta: number,\n velocity: number,\n completed: boolean,\n cancelled: boolean,\n ): void;\n /** A pointerdown that never crossed lockThreshold before release — not a drag. Used to detect double-tap (the engine tracks tap timing/position itself and calls onDoubleTap instead when two land close enough together) as well as being a simple tap signal on its own. */\n onTap?(x: number, y: number, event: PointerEvent): void;\n onDoubleTap?(x: number, y: number, event: PointerEvent): void;\n /** scale is relative to the pinch's own start distance (1 = unchanged), not a cumulative multiplier across multiple pinch gestures. */\n onPinchStart?(centerX: number, centerY: number): void;\n onPinchMove?(scale: number, centerX: number, centerY: number): void;\n onPinchEnd?(): void;\n /** Ctrl+wheel (trackpad pinch reports this way in every major browser) or a genuine ctrl+scroll-wheel. deltaScale is a small increment (positive = zoom in), not an absolute scale — the caller accumulates it. */\n onWheelZoom?(deltaScale: number, x: number, y: number, event: WheelEvent): void;\n /** Only consulted on pointerdown — returning true means this pointer is ignored for the rest of its lifetime (a click on a real button/control shouldn't also start a drag). */\n ignore?(event: PointerEvent): boolean;\n /** Consulted right before capturing a locked drag's pointer — `false` skips capture for this gesture entirely (not just its drag effect). Default `true` if omitted. See onPointerMove's capture branch for why this needs to be a real skip, not just a suppressed effect. */\n shouldCapture?(): boolean;\n}\n\nconst DOUBLE_TAP_MAX_DELAY_MS = 300;\nconst DOUBLE_TAP_MAX_DISTANCE = 30;\nconst TAP_MAX_DELAY_MS = 500; // a pointerdown→up this slow isn't a \"tap\" even if it never crossed lockThreshold\n\ninterface PointerState {\n startX: number;\n startY: number;\n startTime: number;\n lastX: number;\n lastY: number;\n lastTime: number;\n}\n\nexport class GestureEngine {\n private readonly target: HTMLElement;\n private readonly options: GestureEngineOptions;\n private readonly callbacks: GestureEngineCallbacks;\n\n private readonly pointers = new Map<number, PointerState>();\n private primaryPointerId: number | null = null;\n private direction: GestureDirection | null = null;\n private dragStartDistance = 0; // along the locked axis, at the moment direction locked — subtracted so onDragStart's delta is 0\n\n private pinching = false;\n private pinchStartDistance = 0;\n\n /** True once `setPointerCapture` has actually been called for the gesture currently in progress — see `suppressRetargetedClick`'s own doc comment for why this needs tracking separately from `direction`. */\n private capturedThisGesture = false;\n\n // -Infinity, not 0: `event.timeStamp` is time-since-navigation-start, so a\n // real first tap is always some large positive number and 0 would seem\n // like a safe \"no previous tap\" sentinel in practice — but not always: a\n // tap in the first 300ms of the page's life, near the viewport's top-left\n // corner, would satisfy registerTap's isDouble check against this\n // sentinel and get wrongly reported as a double-tap on nothing. -Infinity\n // can never be within DOUBLE_TAP_MAX_DELAY_MS of any real timestamp.\n private lastTapTime = -Infinity;\n private lastTapX = 0;\n private lastTapY = 0;\n\n constructor(\n target: HTMLElement,\n callbacks: GestureEngineCallbacks,\n options?: Partial<GestureEngineOptions>,\n ) {\n this.target = target;\n this.callbacks = callbacks;\n this.options = {\n lockThreshold: options?.lockThreshold ?? 10,\n swipeThreshold: options?.swipeThreshold ?? 50,\n swipeVelocity: options?.swipeVelocity ?? 0.3,\n };\n\n this.target.addEventListener('pointerdown', this.onPointerDown);\n // Not passive: once a horizontal/vertical drag direction has locked in,\n // preventDefault() on move is required so the browser's own\n // scroll/back-navigation gesture doesn't fight the drag — see\n // onPointerMove. Before that lock, moves don't preventDefault, so\n // ordinary page scroll/tap behavior is unaffected until a real drag is\n // actually recognized.\n this.target.addEventListener('pointermove', this.onPointerMove);\n this.target.addEventListener('pointerup', this.onPointerUp);\n this.target.addEventListener('pointercancel', this.onPointerCancel);\n // ctrl+wheel must preventDefault (documented, not passive) — otherwise\n // the browser zooms the whole page instead of this becoming a gesture\n // the caller can hand to a zoom plugin.\n this.target.addEventListener('wheel', this.onWheel, { passive: false });\n }\n\n destroy(): void {\n this.target.removeEventListener('pointerdown', this.onPointerDown);\n this.target.removeEventListener('pointermove', this.onPointerMove);\n this.target.removeEventListener('pointerup', this.onPointerUp);\n this.target.removeEventListener('pointercancel', this.onPointerCancel);\n this.target.removeEventListener('wheel', this.onWheel);\n this.pointers.clear();\n }\n\n private readonly onPointerDown = (event: PointerEvent): void => {\n if (event.isPrimary === false && this.pointers.size === 0) return; // stray non-primary with no primary tracked yet — ignore\n if (this.pointers.size === 0 && this.callbacks.ignore?.(event)) return;\n\n this.pointers.set(event.pointerId, {\n startX: event.clientX,\n startY: event.clientY,\n startTime: event.timeStamp,\n lastX: event.clientX,\n lastY: event.clientY,\n lastTime: event.timeStamp,\n });\n\n if (this.pointers.size === 1) {\n this.primaryPointerId = event.pointerId;\n this.direction = null;\n this.capturedThisGesture = false;\n // Deliberately NOT captured here — see onPointerMove's direction-lock\n // branch for why.\n } else if (this.pointers.size === 2) {\n // A second pointer arriving mid-drag suspends the single-pointer\n // gesture (real pinches start from an already-down single touch) and\n // starts pinch tracking instead.\n this.direction = null;\n this.pinching = true;\n const [a, b] = [...this.pointers.values()];\n this.pinchStartDistance = distanceBetween(a!, b!);\n const center = centerOf(a!, b!);\n this.callbacks.onPinchStart?.(center.x, center.y);\n }\n };\n\n private readonly onPointerMove = (event: PointerEvent): void => {\n const state = this.pointers.get(event.pointerId);\n if (!state) return;\n state.lastX = event.clientX;\n state.lastY = event.clientY;\n state.lastTime = event.timeStamp;\n\n if (this.pinching) {\n if (this.pointers.size < 2) return;\n const [a, b] = [...this.pointers.values()];\n const distance = distanceBetween(a!, b!);\n const scale = this.pinchStartDistance > 0 ? distance / this.pinchStartDistance : 1;\n const center = centerOf(a!, b!);\n this.callbacks.onPinchMove?.(scale, center.x, center.y);\n return;\n }\n\n if (event.pointerId !== this.primaryPointerId) return;\n\n const dx = event.clientX - state.startX;\n const dy = event.clientY - state.startY;\n\n if (this.direction === null) {\n const absX = Math.abs(dx);\n const absY = Math.abs(dy);\n if (Math.max(absX, absY) < this.options.lockThreshold) return; // still pending — too small to call yet\n this.direction = absX > absY ? 'horizontal' : 'vertical';\n this.dragStartDistance = this.direction === 'horizontal' ? dx : dy;\n // Captured only once a real drag is confirmed (direction locked), not\n // on every pointerdown — capturing eagerly retargets the browser's\n // synthesized mousedown/click to the capturing element, breaking any\n // click-target-based logic downstream on an ordinary tap. Deferring\n // capture to here fixes that — but a *confirmed* drag still captures,\n // and a captured pointer's release still fires a real click\n // afterward, still retargeted to `target`. See\n // `suppressRetargetedClick` below for that other half of the fix.\n if (this.callbacks.shouldCapture?.() ?? true) {\n this.target.setPointerCapture(event.pointerId);\n this.capturedThisGesture = true;\n }\n this.callbacks.onDragStart?.(this.direction, event);\n }\n\n if (this.direction === 'horizontal') event.preventDefault(); // stop page/back-gesture scroll from fighting the drag\n\n const delta = (this.direction === 'horizontal' ? dx : dy) - this.dragStartDistance;\n this.callbacks.onDragMove?.(this.direction, delta, event);\n };\n\n private readonly onPointerUp = (event: PointerEvent): void => {\n this.finishPointer(event, false);\n };\n\n private readonly onPointerCancel = (event: PointerEvent): void => {\n this.finishPointer(event, true);\n };\n\n private finishPointer(event: PointerEvent, cancelled: boolean): void {\n const state = this.pointers.get(event.pointerId);\n if (!state) return;\n // pointerup/pointercancel carry their own release coordinates — these\n // don't necessarily match the last pointermove (coalesced/throttled\n // move events, or a release with no intervening move at all), so total\n // delta/velocity/tap-position must be computed from *this* event's\n // position, not whatever onPointerMove last recorded.\n state.lastX = event.clientX;\n state.lastY = event.clientY;\n state.lastTime = event.timeStamp;\n this.pointers.delete(event.pointerId);\n\n if (this.pinching) {\n if (this.pointers.size < 2) {\n this.pinching = false;\n this.callbacks.onPinchEnd?.();\n }\n // Still >= 2 pointers (a third was down) — stay in pinch mode; not\n // handled further here, an unusual case not worth extra state for.\n return;\n }\n\n if (event.pointerId !== this.primaryPointerId) return;\n\n if (this.direction === null) {\n // Never crossed lockThreshold — a tap, not a drag (unless it was\n // cancelled, or took too long to plausibly be an intentional tap).\n if (!cancelled && event.timeStamp - state.startTime <= TAP_MAX_DELAY_MS) {\n this.registerTap(state.lastX, state.lastY, event);\n }\n } else {\n const elapsed = Math.max(1, state.lastTime - state.startTime); // avoid divide-by-zero on a same-tick move\n const totalDelta =\n (this.direction === 'horizontal'\n ? state.lastX - state.startX\n : state.lastY - state.startY) - this.dragStartDistance;\n const velocity = totalDelta / elapsed;\n const completed =\n !cancelled &&\n (Math.abs(totalDelta) >= this.options.swipeThreshold ||\n Math.abs(velocity) >= this.options.swipeVelocity);\n this.callbacks.onDragEnd?.(this.direction, totalDelta, velocity, completed, cancelled);\n if (this.capturedThisGesture) this.suppressRetargetedClick();\n }\n\n this.primaryPointerId = null;\n this.direction = null;\n this.capturedThisGesture = false;\n }\n\n /**\n * A captured pointer's release still fires a real `click`, retargeted to\n * `target` regardless of where the pointer visually ends up — misread by\n * Gallery's click-outside-to-close as landing nowhere recognizable.\n * Consumes exactly one `click` on `target` in the capture phase, then\n * removes itself; a fallback timeout also removes it in case no `click`\n * ever comes, so it can't swallow a later, unrelated one.\n */\n private suppressRetargetedClick(): void {\n let done = false;\n const cleanup = (event?: MouseEvent): void => {\n if (done) return;\n done = true;\n event?.stopPropagation();\n this.target.removeEventListener('click', cleanup, { capture: true });\n };\n this.target.addEventListener('click', cleanup, { capture: true });\n setTimeout(cleanup, 500);\n }\n\n private registerTap(x: number, y: number, event: PointerEvent): void {\n const now = event.timeStamp;\n const isDouble =\n now - this.lastTapTime <= DOUBLE_TAP_MAX_DELAY_MS &&\n Math.hypot(x - this.lastTapX, y - this.lastTapY) <= DOUBLE_TAP_MAX_DISTANCE;\n if (isDouble) {\n this.callbacks.onDoubleTap?.(x, y, event);\n this.lastTapTime = 0; // consumed — a third tap starts fresh, isn't a triple-double\n } else {\n this.callbacks.onTap?.(x, y, event);\n this.lastTapTime = now;\n this.lastTapX = x;\n this.lastTapY = y;\n }\n }\n\n private readonly onWheel = (event: WheelEvent): void => {\n if (!event.ctrlKey) return;\n event.preventDefault();\n // Browsers report trackpad pinch as ctrl+wheel with deltaY roughly\n // proportional to pinch speed; negate so pinching out (deltaY < 0,\n // conventionally) reads as zooming in (positive deltaScale).\n const deltaScale = -event.deltaY * 0.01;\n this.callbacks.onWheelZoom?.(deltaScale, event.clientX, event.clientY, event);\n };\n}\n\nfunction distanceBetween(\n a: { lastX: number; lastY: number },\n b: { lastX: number; lastY: number },\n): number {\n return Math.hypot(a.lastX - b.lastX, a.lastY - b.lastY);\n}\n\nfunction centerOf(\n a: { lastX: number; lastY: number },\n b: { lastX: number; lastY: number },\n): { x: number; y: number } {\n return { x: (a.lastX + b.lastX) / 2, y: (a.lastY + b.lastY) / 2 };\n}\n","/** The drag's exact on-screen appearance at the moment it completed a close — `translateY(px)`/`scale`/`opacity`, all as last shown live (translateY clamped, see `GestureController.takeFrozenDragTransform`). `zoomOut()` jumps `target` here instantly (after measuring its natural box — see `ZoomTransitionTarget.dragStart`) before transitioning away from it, so the close continues in one motion from exactly where the drag left off. */\nexport interface FrozenDragTransform {\n translateY: number;\n scale: number;\n opacity: number;\n}\n\nexport interface ZoomTransitionTarget {\n /** The thumbnail element to animate to/from. */\n origin: HTMLElement;\n /** The `.shoji-slide-media` element being animated — not `.shoji-slide` itself, whose transform is already owned by pool-offset positioning. */\n target: HTMLElement;\n /** `item.width / item.height`, when known, else the origin thumbnail's own `naturalWidth`/`naturalHeight` ratio — just a *shape* guess; see `effectiveTargetBox`. */\n aspectRatio?: number;\n /** The real photo's true pixel size — `item.width`/`item.height` only, never the thumbnail's own natural size (would under-cap a large photo). Caps `containedBox` below at native resolution, mirroring `.shoji-slide-img`'s own `max-width/max-height: 100%`, instead of always growing toward filling the dialog. */\n naturalSize?: { width: number; height: number };\n /**\n * A completed drag-close's own last appearance (`GestureController.\n * takeFrozenDragTransform`) — `zoomOut()` (the only consumer) jumps\n * `target` here instantly, *after* measuring its natural box for the\n * landing math, then transitions away from it. Order matters: applying\n * this before measuring would make `effectiveTargetBox()` read the\n * child `<img>`'s rect *already* shrunk by this scale, double-counting\n * it once `zoomOut()`'s own transform (computed from that shrunk\n * measurement) then wholesale replaces — not composes with — it.\n */\n dragStart?: FrozenDragTransform;\n /**\n * The zoomed `<img>`'s own real on-screen rect (`getBoundingClientRect()`)\n * at the moment a button-close (or any non-drag close) starts, if it's\n * currently zoomed in — captured by `Gallery.beginClose()` from\n * `registerZoomStartProvider()` *before* the Zoom plugin's own\n * `beforeClose` handler resets it back to neutral (so `zoomOut()`'s own\n * measurement below stays correct — same ordering requirement `dragStart`\n * has, and the same reason).\n *\n * A rect, not the Zoom plugin's raw scale/pan numbers — an earlier version\n * passed those through directly and re-applied them to `target`\n * (`.shoji-slide-media`) the same way `dragStart` reapplies its own\n * translateY/scale. That doesn't work here: Zoom's own pan math is\n * relative to the `<img>` itself with `transform-origin: 0 0`\n * (`zoom/index.ts`), a *different* element with a *different* origin than\n * `target`'s `transform-origin: center` below — reapplying the same\n * numbers onto the wrong element/origin pair visibly shifted the image\n * toward its top-left corner the instant close started, worse the more\n * zoomed in it was. A rect sidesteps this entirely: `zoomOut()` computes\n * the jump the same center-to-center way it computes everything else\n * (`transformBetween`), from `target`'s own freshly-measured natural box\n * to this rect — origin-and-coordinate-system-agnostic, so it doesn't\n * matter what internal convention produced the rect.\n *\n * `zoomOut()` jumps `target` here instantly, then transitions away from\n * it, so closing while zoomed continues in one motion from the zoomed-in\n * view instead of snapping back to neutral first and only then shrinking\n * to the thumbnail. Mutually exclusive with `dragStart` in practice — you\n * can't complete a vertical drag-close while the zoom plugin is also\n * mid-pan, since `GestureController` suspends its own drag handling\n * entirely while zoomed (`isZoomed()`, DESIGN.md §4.6).\n */\n zoomStart?: Box;\n}\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/** `\"300ms\"` / `\"0.3s\"` → milliseconds. Reads the *actual* computed value, not an assumed default, so a host overriding `--shoji-duration` still gets a correct fallback timeout below. */\nfunction parseCssTime(value: string): number {\n const first = value.split(',')[0]?.trim() ?? '';\n if (first.endsWith('ms')) return parseFloat(first);\n if (first.endsWith('s')) return parseFloat(first) * 1000;\n return 0;\n}\n\nexport interface Box {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\n/** The `object-fit: contain` box for `aspectRatio` within `container`, computed analytically since the real image may not be loaded yet. `naturalSize` caps the result at the photo's own true pixel size, never stretching past native resolution. Exported — `SlideManager.ts`'s open-transition placeholder (§2.3) reuses this same math. */\nexport function containedBox(\n container: Box,\n aspectRatio: number,\n naturalSize?: { width: number; height: number },\n): Box {\n const containerRatio = container.width / container.height;\n let width = aspectRatio > containerRatio ? container.width : container.height * aspectRatio;\n let height = aspectRatio > containerRatio ? container.width / aspectRatio : container.height;\n if (naturalSize && naturalSize.width > 0 && naturalSize.height > 0) {\n const cap = Math.min(1, naturalSize.width / width, naturalSize.height / height);\n width *= cap;\n height *= cap;\n }\n return {\n left: container.left + (container.width - width) / 2,\n top: container.top + (container.height - height) / 2,\n width,\n height,\n };\n}\n\n/**\n * `target`'s effective visual box, not necessarily its own\n * `getBoundingClientRect()`. `target` is always its full flex-box size; the\n * photo inside is usually *smaller*, letterboxed to its own aspect ratio —\n * a real bug used the container's full rect, making the animation scale\n * from/to a box far bigger than the photo ever renders at, visibly\n * shrinking it to something much smaller than the thumbnail whenever the\n * aspect ratios didn't match (the common case). Preferred sources: the real\n * rendered media child, if attached; else an analytical contain-box from\n * `aspectRatio`; else the container's own rect as a last resort.\n *\n * A real bug this guards against: on a fresh open with nothing decoded yet,\n * `target`'s only child at this point is the loading spinner (§2.3) — a\n * fixed ~40px circle, not the photo. Trusting its rect as \"the real\n * rendered media child\" made the FLIP transition scale toward/from a box\n * far smaller than the actual photo, so the scale factor came out inverted\n * (>1 instead of <1) and the spinner rendered wildly oversized for the\n * transition's first frames before shrinking back down — never the actual\n * photo, which hadn't swapped in yet either way.\n *\n * Same reasoning excludes `.shoji-slide-open-placeholder` (§2.3's low-res\n * open() stand-in): it's a real, non-spinner `<img>`, but its own rendered\n * rect reflects *its* crop/aspect ratio, not the real photo's — trusting it\n * would scale toward the placeholder's shape instead of the real photo's,\n * only to visibly jump again once the real photo swaps in and this\n * transition (already run) no longer applies. Excluding it falls through to\n * the analytical `aspectRatio`-based box below, sized for the real photo\n * regardless of what shape the placeholder happens to be.\n */\nfunction effectiveTargetBox(\n target: HTMLElement,\n aspectRatio?: number,\n naturalSize?: { width: number; height: number },\n): Box {\n const child = target.firstElementChild;\n const isPlaceholder =\n child instanceof HTMLElement &&\n (child.classList.contains('shoji-slide-spinner') ||\n child.classList.contains('shoji-slide-open-placeholder'));\n if (child instanceof HTMLElement && !isPlaceholder) {\n const rect = child.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return rect;\n }\n const containerRect = target.getBoundingClientRect();\n if (aspectRatio && containerRect.width > 0 && containerRect.height > 0) {\n return containedBox(containerRect, aspectRatio, naturalSize);\n }\n return containerRect;\n}\n\n/**\n * Center-to-center translate + a single uniform scale that lands `target`'s\n * effective box (`effectiveTargetBox` above) *within* `origin`'s box,\n * without distorting it. `null` if either has no real size — nothing sane\n * to animate. One scale factor, not independent scaleX/scaleY: origin and\n * the photo essentially never share an exact aspect ratio, and scaling each\n * axis independently to force a rect match visibly squeezes/stretches the\n * image. `Math.min` keeps the box fully contained within origin's rect\n * (same tradeoff `object-fit: contain` makes); center always lands exactly\n * on origin's center, only the unconstrained axis's edges fall short.\n */\n/**\n * The actual translate3d/scale3d math `computeTransform` below needs —\n * pulled out on its own so `zoomOut`'s `zoomStart` jump (a *second* use of\n * the exact same center-to-center box-fitting math, landing on a captured\n * live rect instead of `origin`'s) can reuse it directly, rather than\n * re-deriving Zoom's own transform-origin/coordinate conventions on a\n * different element — see `ZoomTransitionTarget.zoomStart`'s own doc\n * comment for why that direct-replication approach doesn't work.\n */\nfunction transformBetween(from: Box, to: Box): string {\n const scale = Math.min(to.width / from.width, to.height / from.height);\n const translateX = to.left + to.width / 2 - (from.left + from.width / 2);\n const translateY = to.top + to.height / 2 - (from.top + from.height / 2);\n // translate3d/scale3d, not translate()/scale() — forces the GPU\n // compositing path instead of a main-thread-painted 2D transform, the\n // same fix already validated for the Zoom plugin's own scale animation\n // (DESIGN.md §4.6): this is the identical technique (a large photo\n // scaled via `transform`) on the same element, just driven by open/close\n // instead of pinch/toolbar zoom.\n return `translate3d(${translateX}px, ${translateY}px, 0) scale3d(${scale}, ${scale}, 1)`;\n}\n\n/**\n * `origin`'s effective visual box, not necessarily its own\n * `getBoundingClientRect()`. In selector/DOM-markup mode without Layout,\n * `origin` is typically a plain `<a>` wrapping a `<img>` — an inline element\n * by default, whose own box is sized to a text-line-height sliver (its\n * `font-size`/`line-height`), not the image it visually contains, even\n * though the image itself paints at full size. A real bug: the zoom\n * open/close transform used that sliver directly as the FLIP target,\n * landing the animation at a tiny, essentially-random offset instead of the\n * real thumbnail's visible position and size. Layout tiles aren't affected\n * (`display: block`, sized to match their child image exactly) — preferring\n * the child's rect there returns the same box either way.\n *\n * `querySelector('img')`, not `firstElementChild` — matches `scan.ts`'s own\n * `scanImage()` convention for locating a thumbnail inside arbitrary host\n * markup, where the `<img>` isn't necessarily the first child (a badge or\n * caption element placed before it in the DOM would otherwise get measured\n * instead, no more correct than the wrapper's own sliver).\n */\nfunction effectiveOriginBox(origin: HTMLElement): Box {\n const img = origin.querySelector('img');\n if (img) {\n const rect = img.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return rect;\n }\n return origin.getBoundingClientRect();\n}\n\nfunction computeTransform(\n origin: HTMLElement,\n target: HTMLElement,\n aspectRatio?: number,\n naturalSize?: { width: number; height: number },\n): string | null {\n const originRect = effectiveOriginBox(origin);\n const targetRect = effectiveTargetBox(target, aspectRatio, naturalSize);\n if (\n targetRect.width === 0 ||\n targetRect.height === 0 ||\n originRect.width === 0 ||\n originRect.height === 0\n ) {\n return null;\n }\n return transformBetween(targetRect, originRect);\n}\n\n/**\n * Waits for `target`'s own transition (on `property`, default `'transform'`)\n * to end (with a safety-net timeout in case transitionend never fires — an\n * interrupted/removed element, a browser quirk, or `--shoji-duration: 0ms`\n * under `prefers-reduced-motion`, which some browsers never fire a real\n * transitionend for at all) then calls `cb` exactly once. Exported: the\n * gesture-driven drag-to-navigate/drag-to-close settle animations (§2.4,\n * `Gallery.ts`) reuse this same wait-with-fallback logic rather than\n * duplicating it — same instant-jump-then-transition FLIP family of moves\n * as the zoom transition, just on a different element/property pairing.\n * `close()`'s own controls-fade-before-zoom-out sequencing (§2.6a) reuses it\n * a second way, waiting on `opacity` instead.\n */\nexport function waitForTransitionEnd(\n target: HTMLElement,\n cb: () => void,\n property = 'transform',\n): void {\n const durationMs = parseCssTime(getComputedStyle(target).transitionDuration);\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n target.removeEventListener('transitionend', onEnd);\n cb();\n };\n const onEnd = (event: Event): void => {\n if (event.target === target && (event as TransitionEvent).propertyName === property) finish();\n };\n target.addEventListener('transitionend', onEnd);\n setTimeout(finish, durationMs + 100);\n}\n\n/**\n * A real bug: unconditionally clearing `transform` here could wipe out a\n * value another plugin (rotateFlip) legitimately set on the *same* element\n * in the time between this animation starting and its cleanup callback\n * firing (transitionend, or the fallback timeout — either can land well\n * after a quick click elsewhere). Only clears `transform` if it still\n * matches what this animation itself last wrote — nothing else has touched\n * it since — otherwise leaves it alone. `transition`/`transformOrigin`\n * are always safe to clear; nothing else in this codebase sets them.\n *\n * A second real bug, found via reopening the lightbox: `expectedTransform`\n * must be the value *read back* from `target.style.transform` right after\n * assigning it, not the raw string `computeTransform()` produced. Setting\n * `element.style.transform` to a string containing an arbitrary JS float\n * (e.g. `scale(0.10416666666666667)`, `computeTransform`'s un-rounded\n * `Math.min(...)` result) and reading it back gives a *differently\n * formatted* string — the browser's CSSOM serializer rounds/reformats\n * numeric values on its own (observed in Chromium: `scale(0.104167)`).\n * Comparing the raw JS string against that reformatted one here always\n * failed for any scale factor without a short, clean decimal, silently\n * skipping the clear — permanently leaving `zoomOut`'s shrink transform\n * applied to `.shoji-slide-media` after the lightbox closed. The next\n * `open()`'s `computeTransform` then measured that *already-shrunk*\n * element's `getBoundingClientRect()` as if it were the natural size,\n * computing a near-1 (barely visible) scale instead of a real zoom-in —\n * reads as \"doesn't zoom, just appears,\" and compounds on every further\n * open/close cycle since the stuck transform is never cleared either way.\n * `zoomIn`'s own `'none'` literal never hit this — a fixed string round-trips\n * through the CSSOM unchanged, unlike an arbitrary computed float.\n *\n * `opacity` is cleared unconditionally, same as `transition`/\n * `transformOrigin` — a completed drag-close (`Gallery.beginClose`) bakes\n * the drag's own dim onto `target` before this animation starts; nothing\n * else in this codebase sets `.shoji-slide-media`'s opacity, so there's\n * nothing else's value this could ever clobber.\n */\nfunction clearInlineTransform(target: HTMLElement, expectedTransform: string): void {\n target.style.transition = '';\n target.style.transformOrigin = '';\n target.style.willChange = '';\n target.style.opacity = '';\n if (target.style.transform === expectedTransform) target.style.transform = '';\n}\n\n/**\n * FLIP-style open: `target` starts visually at `origin`'s position/size (an\n * instant, untransitioned jump), then transitions to its natural layout —\n * reads as \"growing out of the thumbnail.\" Fire-and-forget: cleans up its\n * own inline styles once the transition ends, nothing to await.\n */\nexport function zoomIn({ origin, target, aspectRatio, naturalSize }: ZoomTransitionTarget): void {\n if (prefersReducedMotion()) return;\n const transform = computeTransform(origin, target, aspectRatio, naturalSize);\n if (!transform) return;\n\n target.style.transition = 'none';\n // computeTransform's translateX/Y is center-to-center math — must pair with\n // a center transform-origin (the CSS default), not 'top left', or the\n // scaled box ends up offset from origin by however far origin's center\n // sits from its own top-left corner.\n target.style.transformOrigin = 'center';\n // Promotes target onto its own compositing layer before the animated\n // transform starts, not mid-animation — same GPU-seam mitigation as the\n // Zoom plugin (DESIGN.md §4.6). Cleared in clearInlineTransform once the\n // transition ends, not left on permanently: this is the offset-0 pool\n // slot, alive for the gallery's whole lifetime, not a class scoped to\n // only-while-zoomed.\n target.style.willChange = 'transform';\n target.style.transform = transform;\n void target.offsetHeight; // force the instant jump to commit before transitioning away from it\n target.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n target.style.transform = 'none';\n\n waitForTransitionEnd(target, () => clearInlineTransform(target, 'none'));\n}\n\n/**\n * Reverse of `zoomIn`: `target` transitions from its natural position down\n * to `origin`'s rect — \"shrinking back into the thumbnail.\" `onComplete`\n * always fires exactly once, synchronously if there's nothing to animate\n * (reduced motion, or no valid rect), otherwise once the transition ends —\n * callers use this to know when it's safe to actually hide/finalize.\n */\nexport function zoomOut(\n { origin, target, aspectRatio, naturalSize, dragStart, zoomStart }: ZoomTransitionTarget,\n onComplete: () => void,\n): void {\n if (prefersReducedMotion()) {\n onComplete();\n return;\n }\n // Measured before dragStart/zoomStart is ever applied to `target` — see\n // ZoomTransitionTarget.dragStart's doc comment for why the order matters.\n const transform = computeTransform(origin, target, aspectRatio, naturalSize);\n if (!transform) {\n onComplete();\n return;\n }\n\n // computeTransform's translateX/Y is center-to-center math — must pair with\n // a center transform-origin (the CSS default), not 'top left', or the\n // scaled box ends up offset from origin by however far origin's center\n // sits from its own top-left corner.\n target.style.transformOrigin = 'center';\n target.style.willChange = 'transform'; // see zoomIn's doc comment on this line\n if (dragStart) {\n // Instant jump to exactly where the drag left off — same FLIP\n // technique `zoomIn()` uses to jump onto origin's box before\n // transitioning away from it, just jumping to wherever the drag left\n // off instead of a fixed point. translate3d/scale3d (not the 2D forms),\n // matching the landing transform's own function list below — mismatched\n // function types between the transition's start/end values force the\n // browser into matrix-decomposition interpolation instead of simple\n // per-parameter interpolation, and lose the GPU-compositing path this\n // codebase otherwise always uses for this element (DESIGN.md §2.3b).\n target.style.transition = 'none';\n target.style.transform = `translate3d(0px, ${dragStart.translateY}px, 0px) scale3d(${dragStart.scale}, ${dragStart.scale}, 1)`;\n target.style.opacity = String(dragStart.opacity);\n void target.offsetHeight; // commit the jump before transitioning away from it\n } else if (zoomStart) {\n // Same FLIP jump as dragStart above, computed the same center-to-center\n // way as `transform` above (not dragStart's raw translate/scale reuse\n // — see ZoomTransitionTarget.zoomStart's doc comment for why that\n // doesn't work here). `target`'s own effective box, re-measured fresh:\n // cheap, and guaranteed unchanged since the read inside\n // computeTransform() above — nothing's touched `target` in between.\n // Still correct even if `target` is currently rotated/flipped (the\n // RotateFlip plugin, applied directly to this same element, unlike\n // Zoom's own scale/pan — see below): both this measurement and\n // `zoomStart` itself were captured at the same rotation, so the\n // scale/translate between their two (equally rotated) bounding boxes\n // still isolates the zoom-only delta correctly.\n const targetRect = effectiveTargetBox(target, aspectRatio, naturalSize);\n if (targetRect.width > 0 && targetRect.height > 0) {\n // Composed onto whatever's already there, never replacing it outright\n // — a real bug, reported from real usage: closing while both rotated/\n // flipped *and* zoomed wholesale-overwrote RotateFlip's own\n // scaleX/scaleY/rotate() with this jump's plain translate/scale,\n // un-rotating *instantly* right here, before the real transition\n // below even starts — a snap to neutral rotation, then a separate\n // zoom-out, instead of the smooth combined un-rotate-while-shrinking\n // motion closing while rotated (without zoomStart at all) already\n // gets for free: transitioning target's transform from *whatever it\n // currently is* to the final plain shrink value is what makes that\n // work, and it needs target's rotation to still be sitting there\n // when the transition starts, not already erased by this jump.\n const existing = target.style.transform;\n const jump = transformBetween(targetRect, zoomStart);\n target.style.transition = 'none';\n target.style.transform = existing && existing !== 'none' ? `${existing} ${jump}` : jump;\n void target.offsetHeight;\n }\n }\n target.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n void target.offsetHeight;\n target.style.transform = transform;\n // Read back what the browser actually stored, not the raw string just\n // assigned — see clearInlineTransform's own doc comment for why the two\n // can differ (CSSOM float reformatting) and why that difference matters.\n const appliedTransform = target.style.transform;\n\n waitForTransitionEnd(target, () => {\n clearInlineTransform(target, appliedTransform);\n onComplete();\n });\n}\n","import {\n GestureEngine,\n type GestureDirection,\n type GestureEngineOptions,\n} from '../gestures/GestureEngine';\nimport type { SlideManager } from './SlideManager';\nimport { waitForTransitionEnd, type FrozenDragTransform } from './zoomTransition';\n\n/** DESIGN.md §2.4 — the drag-released settle easing, distinct from `--shoji-easing`'s open/close/zoom curve. */\nconst DRAG_SETTLE_TRANSITION = 'transform var(--shoji-duration) var(--shoji-momentum-easing)';\nconst DRAG_FEEDBACK_TRANSITION =\n 'transform var(--shoji-duration) var(--shoji-momentum-easing), opacity var(--shoji-duration) var(--shoji-momentum-easing)';\n/** px of vertical drag at which live close-feedback maxes out — independent of `swipeThreshold`, which decides actual completion. */\nconst VERTICAL_FEEDBACK_DISTANCE = 160;\n\n/**\n * A real interactive control, plus `.shoji-caption` — a click/drag starting\n * there should select/scroll its text natively, not get captured as a\n * gesture. Also used by `Gallery.ts`'s `isBackdropClick`, which used to have\n * its own narrower list (missing select/input/textarea/a[href]) — a\n * plugin-mounted non-button control got misread as a backdrop click and\n * closed the gallery. One shared selector so that can't recur.\n *\n * `.shoji-caption-modal` (DESIGN.md §2.3a) — a real bug, reported from real\n * usage: `GestureEngine`'s own tap recognition (`ignore` gates it before\n * any pointer tracking starts, `GestureEngine.ts`) runs entirely on\n * pointer events, independent of whatever a click listener's own\n * `stopPropagation()` does — a tap anywhere inside the caption modal\n * (its content area specifically; the close button was already covered as\n * a real `<button>`) still read as a legitimate tap on the dialog and fired\n * the `tap` bus event, which the Autoplay plugin listens to for its own\n * tap-to-toggle-play/pause. Excluding the whole modal here is what\n * actually stops that, not anything at the click-event layer.\n */\nexport const INTERACTIVE_CONTROL_SELECTOR =\n 'button, video, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption, .shoji-caption-modal, .shoji-toolbar-overflow-panel';\n\n/**\n * `INTERACTIVE_CONTROL_SELECTOR` minus `video` — everything else there still\n * needs a real click/drag to behave natively (select/scroll caption text,\n * a plugin's own control, etc.), same reasoning as that selector's own doc\n * comment. `video` is carved out separately, below: unlike those, a native\n * `<video controls>`'s own interactive surface (tap-to-toggle, the\n * scrub-bar drag) isn't the *whole* element — DESIGN.md §2.4/§4.3's\n * swipe-to-navigate-video-slides feature needs gestures to reach the rest\n * of it, not be blocked outright the way the shared selector above still\n * blocks it for backdrop-click/caption-selection purposes.\n */\nconst GESTURE_IGNORE_SELECTOR =\n 'button, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption, .shoji-caption-modal, .shoji-toolbar-overflow-panel';\n\n/**\n * A native `<video controls>`'s own scrub-bar/tap-to-toggle chrome is\n * browser-rendered, not real DOM Shoji can measure — there's no element to\n * exclude by selector the way `GESTURE_IGNORE_SELECTOR` excludes a real\n * `<button>`. Approximated instead as a fixed bottom margin\n * (`--shoji-video-gesture-margin`, shoji.css), reserved for the browser's\n * own touch handling; a touch starting above it is fair game for Shoji's\n * own gestures, same as anywhere on a photo slide.\n */\nfunction isInVideoControlsMargin(event: PointerEvent, video: HTMLVideoElement): boolean {\n const rect = video.getBoundingClientRect();\n const margin = parseFloat(\n getComputedStyle(video).getPropertyValue('--shoji-video-gesture-margin'),\n );\n return event.clientY >= rect.bottom - (Number.isFinite(margin) ? margin : 0);\n}\n\n/**\n * A real bug, found auditing this feature end to end with a real browser\n * (not caught by any jsdom unit test — real `click`-after-drag retargeting\n * only happens in a real browser, same gap `GestureEngine`'s own\n * `suppressRetargetedClick` doc comment describes): a drag starting inside\n * a video's reserved bottom margin is correctly never tracked as a Shoji\n * gesture (see `isInVideoControlsMargin` above) — left alone for the\n * browser's own scrub-bar handling. But the pointer is free to move\n * anywhere before release, the same way a real scrub-bar drag routinely\n * does, and an un-captured pointer's trailing `click` lands wherever it\n * actually ends up — often well past the video's own rendered bounds, in\n * `.shoji-slide-media`'s empty letterbox padding around it. That's not a\n * real interactive control (`INTERACTIVE_CONTROL_SELECTOR`), so `Gallery.ts`'s\n * `isBackdropClick` read it as a genuine backdrop click and closed the\n * gallery — defeating \"left alone for the browser's own controls\" the\n * moment a real scrub-bar interaction moved vertically at all. Confirmed\n * directly: a drag starting 5px above a video's bottom edge, moving 200px\n * down, closed the gallery even though `isInVideoControlsMargin` correctly\n * ignored the pointerdown. Same fix as a captured drag's own retargeted\n * click — swallow exactly one trailing click, capture phase, so it never\n * reaches `isBackdropClick` at all. A fallback timeout also removes the\n * listener in case no `click` ever comes, so it can't swallow a later,\n * unrelated one.\n */\nfunction suppressNextClick(dialog: HTMLElement): void {\n let done = false;\n const cleanup = (event?: MouseEvent): void => {\n if (done) return;\n done = true;\n event?.stopPropagation();\n dialog.removeEventListener('click', cleanup, { capture: true });\n };\n dialog.addEventListener('click', cleanup, { capture: true });\n setTimeout(cleanup, 500);\n}\n\n/**\n * `.shoji-caption--video` (shoji.css, DESIGN.md §2.3a/§4-video) sets\n * `pointer-events: none` on a video slide's caption, letting a click reach\n * the video/provider controls underneath it — which also means it never\n * appears in `event.composedPath()` there at all, so\n * `GESTURE_IGNORE_SELECTOR`'s selector-based check can't see it, the same\n * gap `Gallery.ts`'s `isBackdropClick()` already solves the same way:\n * checked by coordinates instead, the one place this function has to be.\n * A real bug this fixes: swipe-to-navigate/drag-to-close over a provider\n * video's own letterboxed margins (below) would otherwise engage right\n * through the caption sitting over them.\n */\nfunction isOverVideoCaption(event: PointerEvent, caption: HTMLElement): boolean {\n if (caption.hidden || !caption.classList.contains('shoji-caption--video')) return false;\n const rect = caption.getBoundingClientRect();\n return (\n event.clientX >= rect.left &&\n event.clientX <= rect.right &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom\n );\n}\n\n/** A click/drag starting on a real control (or, on a video slide, its click-through caption — see `isOverVideoCaption`) shouldn't also be captured as a gesture — see `GESTURE_IGNORE_SELECTOR`/`isInVideoControlsMargin`. Ignoring specifically for the video-margin reason also arms `suppressNextClick` — see its own doc comment. */\nfunction shouldIgnoreGesture(\n event: PointerEvent,\n caption: HTMLElement,\n dialog: HTMLElement,\n): boolean {\n if (isOverVideoCaption(event, caption)) return true;\n const path = event.composedPath();\n const video = path.find((node): node is HTMLVideoElement => node instanceof HTMLVideoElement);\n if (video) {\n if (!isInVideoControlsMargin(event, video)) return false;\n suppressNextClick(dialog);\n return true;\n }\n return path.some((node) => node instanceof Element && node.matches(GESTURE_IGNORE_SELECTOR));\n}\n\n/** What `GestureController` needs from `Gallery` — narrow on purpose, so this module never reaches into Gallery internals beyond this contract. */\nexport interface GestureControllerHost {\n dialog: HTMLElement;\n /** Read live, not snapshotted — `shouldIgnoreGesture()` needs its current bounding box/visibility on every gesture start, not whatever it was when `GestureController` was constructed. See `isOverVideoCaption`. */\n caption: HTMLElement;\n slides: SlideManager;\n canGoNext(): boolean;\n canGoPrev(): boolean;\n next(): void;\n prev(): void;\n close(): void;\n /** Same effect as `close()`, but for a completed vertical swipe — skips the separate controls-fade pause in front of the zoom-out (see `finishVerticalDrag`). */\n closeFromSwipe(frozenDrag: FrozenDragTransform): void;\n /** Live, reversible — crossing the close threshold mid-drag hides the toolbar/nav/counter/caption (a \"let go now and this closes\" cue); dragging back under it before release reveals them again. See `applyVerticalDragFeedback`. */\n setControlsHiddenForDrag(hidden: boolean): void;\n /** `closable: false` (GalleryOptions) — false suspends vertical drag-to-close entirely: no live feedback, release never calls `close()`. */\n canClose(): boolean;\n onActivity(): void;\n /** DESIGN.md §4-zoom — true while zoomed; suspends drag-to-navigate/close. */\n isZoomed(): boolean;\n}\n\n/** Relays for gestures core has no built-in behavior for — DESIGN.md §2.4; the zoom plugin (§4-zoom) consumes these via the gallery event bus. */\nexport interface GestureRelayCallbacks {\n onTap(x: number, y: number): void;\n onDoubleTap(x: number, y: number): void;\n onPinchStart(centerX: number, centerY: number): void;\n onPinchMove(scale: number, centerX: number, centerY: number): void;\n onPinchEnd(): void;\n onWheelZoom(deltaScale: number, x: number, y: number): void;\n}\n\n/**\n * DESIGN.md §2.4 — owns the gesture-driven side of the lightbox: horizontal\n * drag-to-navigate and vertical drag-to-close, built on `GestureEngine`\n * (`src/gestures/`) plus the live-feedback/settle-animation mechanics\n * specific to this lightbox's DOM. Split out of `Gallery.ts` (CLAUDE.md:\n * files ≤ ~400 lines) — `Gallery` only constructs this, forwards the host\n * callbacks it needs, and relays no-built-in-effect gestures onto its bus.\n */\nexport class GestureController {\n private readonly engine: GestureEngine;\n /** Same distance `GestureEngine` itself uses to decide a release would complete the close — reused here so the live controls-hide cue in `applyVerticalDragFeedback` actually means what it visually claims. */\n private readonly controlsHideThreshold: number;\n private controlsHiddenForDrag = false;\n private lastDragDelta = 0;\n\n constructor(\n private readonly host: GestureControllerHost,\n relay: GestureRelayCallbacks,\n options?: Partial<GestureEngineOptions>,\n ) {\n this.controlsHideThreshold = options?.swipeThreshold ?? 50;\n this.engine = new GestureEngine(\n host.dialog,\n {\n ignore: (event) => shouldIgnoreGesture(event, host.caption, host.dialog),\n shouldCapture: () => !host.isZoomed(),\n onDragStart: () => host.onActivity(),\n onDragMove: this.onDragMove,\n onDragEnd: this.onDragEnd,\n onTap: (x, y) => relay.onTap(x, y),\n onDoubleTap: (x, y) => relay.onDoubleTap(x, y),\n onPinchStart: (centerX, centerY) => relay.onPinchStart(centerX, centerY),\n onPinchMove: (scale, centerX, centerY) => relay.onPinchMove(scale, centerX, centerY),\n onPinchEnd: () => relay.onPinchEnd(),\n onWheelZoom: (deltaScale, x, y) => relay.onWheelZoom(deltaScale, x, y),\n },\n options,\n );\n }\n\n destroy(): void {\n this.engine.destroy();\n }\n\n /** Horizontal follows the finger 1:1; vertical drives close-feedback instead. Axis-locked, one branch per drag. */\n private readonly onDragMove = (direction: GestureDirection, delta: number): void => {\n if (this.host.isZoomed()) return; // the zoom plugin owns pan while zoomed\n if (direction === 'horizontal') {\n this.host.slides.setDragOffset(delta, null);\n } else if (this.host.canClose()) {\n this.applyVerticalDragFeedback(delta);\n }\n };\n\n private readonly onDragEnd = (\n direction: GestureDirection,\n delta: number,\n _velocity: number,\n completed: boolean,\n ): void => {\n if (this.host.isZoomed()) return;\n if (direction === 'horizontal') {\n this.finishHorizontalDrag(delta, completed);\n } else {\n this.finishVerticalDrag(completed);\n }\n };\n\n /** `completed` decides intent; `canGoNext`/`canGoPrev` guard whether that's actually possible (`loop: false` at an end item). */\n private finishHorizontalDrag(delta: number, completed: boolean): void {\n const goingNext = delta < 0;\n const canMove = goingNext ? this.host.canGoNext() : this.host.canGoPrev();\n\n if (!completed || delta === 0 || !canMove) {\n this.settleDragOffset(0, () => {});\n return;\n }\n\n const width = this.host.dialog.getBoundingClientRect().width || 1;\n const target = goingNext ? -width : width;\n this.settleDragOffset(target, () => {\n // Instant, untransitioned reset in the same synchronous tick as the\n // index change — same FLIP-family trick as zoomTransition.ts's\n // instant-jump: the slot that just animated into the center position\n // is about to receive that exact same \"new current\" item's content\n // (its structural offset already matches, since preload keeps it\n // rendered), so resetting to offset 0 while simultaneously swapping\n // content is visually seamless, not a jump.\n this.host.slides.setDragOffset(0, null);\n if (goingNext) this.host.next();\n else this.host.prev();\n });\n }\n\n private settleDragOffset(targetPx: number, onSettled: () => void): void {\n const settleEl = this.host.slides.getSlotRoot(0);\n this.host.slides.setDragOffset(targetPx, DRAG_SETTLE_TRANSITION);\n if (!settleEl) {\n onSettled();\n return;\n }\n waitForTransitionEnd(settleEl, onSettled);\n }\n\n /**\n * Purely presentational — scales/fades the *image* as it's dragged away,\n * without closing until release decides. Applied to `host.slides.element`,\n * not `host.dialog` — requested directly: toolbar/nav/counter/caption are\n * siblings, not descendants, so they stay anchored, not moving with it.\n */\n private applyVerticalDragFeedback(delta: number): void {\n const progress = Math.min(Math.abs(delta) / VERTICAL_FEEDBACK_DISTANCE, 1);\n const slides = this.host.slides.element;\n this.lastDragDelta = delta;\n slides.style.transition = '';\n slides.style.transform = `translateY(${delta}px) scale(${1 - progress * 0.15})`;\n slides.style.opacity = String(1 - progress * 0.6);\n\n // Requested directly: past the same distance a release would close,\n // controls disappear — a \"let go now\" cue, distinct from the image's own\n // dim above (capped at 0.4, never fully hides). Reversible: retreating\n // under it before release reveals them. Only on a crossing, not every move.\n const pastThreshold = Math.abs(delta) >= this.controlsHideThreshold;\n if (pastThreshold !== this.controlsHiddenForDrag) {\n this.controlsHiddenForDrag = pastThreshold;\n this.host.setControlsHiddenForDrag(pastThreshold);\n }\n }\n\n private clearVerticalDragFeedback(animate: boolean): void {\n const slides = this.host.slides.element;\n slides.style.transition = animate ? DRAG_FEEDBACK_TRANSITION : '';\n slides.style.transform = '';\n slides.style.opacity = '';\n }\n\n private finishVerticalDrag(completed: boolean): void {\n const wasHiddenForDrag = this.controlsHiddenForDrag;\n this.controlsHiddenForDrag = false;\n if (completed && this.host.canClose()) {\n this.host.closeFromSwipe(this.takeFrozenDragTransform());\n } else {\n // Not completed, or closable: false suspended the drag entirely (no\n // feedback was ever applied by onDragMove) — either way, a clean\n // reset (harmless no-op in the suspended case, nothing to clear).\n this.clearVerticalDragFeedback(true);\n // Not closing — controls must come back if the cue above left them\n // hidden, regardless of exactly where release landed (e.g.\n // swipeVelocity deciding \"not completed\" past this threshold).\n if (wasHiddenForDrag) this.host.setControlsHiddenForDrag(false);\n }\n }\n\n /**\n * Reads the drag's last live appearance, instantly resets `.shoji-slides`\n * back to neutral (nothing left on it to visibly snap — `Gallery` bakes\n * these same values onto the photo itself in the same synchronous tick,\n * so the rendered result is unchanged, just re-homed), and returns them\n * for that hand-off. Translate is the raw, unclamped drag distance —\n * requested directly: the close animation must continue from exactly\n * where the drag left off, full stop, not recenter first. (A previous\n * version clamped this to the same 160px the dim/scale feedback ramps\n * over, to bound how far away the close animation could start — but\n * clamping is itself an instant correction: for any drag past that\n * distance, release visibly snapped the photo from wherever it actually\n * was back to the clamped point, before the real shrink-to-thumbnail\n * motion continued from there. That snap — not the shrink itself — is\n * what reads as \"jumps to a small image in the middle of the screen.\"\n * Reported from real usage, confirmed on video: released past the clamp,\n * the photo visibly jumped from off-screen back to near-center in a\n * single frame.)\n */\n private takeFrozenDragTransform(): FrozenDragTransform {\n const progress = Math.min(Math.abs(this.lastDragDelta) / VERTICAL_FEEDBACK_DISTANCE, 1);\n const frozen: FrozenDragTransform = {\n translateY: this.lastDragDelta,\n scale: 1 - progress * 0.15,\n opacity: 1 - progress * 0.6,\n };\n this.clearVerticalDragFeedback(false);\n return frozen;\n }\n}\n","/** DESIGN.md §2.6 — visually-hidden `aria-live` region announcing slide changes. */\nexport class LiveRegion {\n readonly element: HTMLElement;\n\n constructor() {\n this.element = document.createElement('div');\n this.element.className = 'shoji-live-region';\n this.element.setAttribute('role', 'status');\n this.element.setAttribute('aria-live', 'polite');\n }\n\n announce(text: string): void {\n // Clear-then-set (with a forced reflow between) so repeated identical\n // announcements still fire in real assistive tech, which otherwise\n // ignores a text node set to the same value it already held.\n this.element.textContent = '';\n void this.element.offsetWidth;\n this.element.textContent = text;\n }\n}\n","import type { GalleryItem, GalleryItemInput, MediaSource, VideoDescriptor } from './types';\n\n/** DESIGN.md §2.1 zero-config quickstart. */\nexport const DEFAULT_SELECTOR =\n ':scope > a, :scope > [data-shoji-src], :scope > [data-shoji-video]';\n\nexport interface ScannedItem {\n element: HTMLElement;\n item: GalleryItem;\n}\n\nexport function scanContainer(\n container: HTMLElement,\n selector: string = DEFAULT_SELECTOR,\n): ScannedItem[] {\n const elements = Array.from(container.querySelectorAll<HTMLElement>(selector));\n const scanned: ScannedItem[] = [];\n for (const element of elements) {\n const item = scanVideo(element) ?? scanImage(element);\n if (item) scanned.push({ element, item });\n }\n return scanned;\n}\n\nfunction attr(el: Element, name: string): string | undefined {\n return el.getAttribute(name) ?? undefined;\n}\n\nfunction numAttr(el: Element, name: string): number | undefined {\n const raw = el.getAttribute(name);\n if (raw === null) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) ? n : undefined;\n}\n\n/**\n * `caption`/`id` first, then any other `data-shoji-*` attribute with no\n * matching `GalleryItem` field lands in `item.data`, keyed verbatim (not\n * camelCased) — DESIGN.md §2.1. By this point every named field above is\n * already set, so `key in item` alone tells known suffixes (src/thumb/\n * alt/.../poster) apart from custom ones — except attributes that fold into\n * a *nested* field (`video-id`/`video-provider` → `item.video.id`/\n * `.provider`, both already applied in `scanVideo` by the time this runs)\n * or have no field of their own at all (`no-drag`, GestureController's\n * drag-opt-out); `key in item` can't see either case, so both are excluded\n * by name instead.\n */\nconst NO_OWN_DATA_FIELD = new Set(['no-drag', 'video-id', 'video-provider']);\n\nfunction applyCommon(element: HTMLElement, item: GalleryItem, src: string): void {\n const caption = attr(element, 'data-shoji-caption');\n if (caption) item.caption = caption;\n item.id = attr(element, 'data-shoji-id') ?? src;\n\n let data: Record<string, string> | undefined;\n for (const a of element.attributes) {\n if (!a.name.startsWith('data-shoji-')) continue;\n const key = a.name.slice(11);\n if (!NO_OWN_DATA_FIELD.has(key) && !(key in item)) (data ??= {})[key] = a.value;\n }\n if (data) item.data = data;\n}\n\nfunction scanImage(element: HTMLElement): GalleryItem | undefined {\n const src = attr(element, 'href') ?? attr(element, 'data-shoji-src');\n if (!src) return undefined;\n\n const item: GalleryItem = { src };\n const img = element.querySelector('img');\n const thumb = img?.getAttribute('src') ?? attr(element, 'data-shoji-thumb');\n if (thumb) item.thumb = thumb;\n const alt = img?.getAttribute('alt') ?? attr(element, 'data-shoji-alt');\n if (alt) item.alt = alt;\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n // On the wrapping element, not the inner <img> (that's the thumb; `src`\n // above is the full-resolution image, so it needs its own attribute).\n const srcset = attr(element, 'data-shoji-srcset');\n if (srcset) item.srcset = srcset;\n const sizes = attr(element, 'data-shoji-sizes');\n if (sizes) item.sizes = sizes;\n applyCommon(element, item, src);\n return item;\n}\n\n/**\n * DESIGN.md §2.1 — a nested `<video>` is always html5; `data-shoji-video`\n * checks known provider hosts first. `data-shoji-video-id`/\n * `data-shoji-video-provider` (both optional) can override what would\n * otherwise be parsed out of that URL — see `resolveExplicitVideo`.\n */\nfunction scanVideo(element: HTMLElement): GalleryItem | undefined {\n const videoIdAttr = attr(element, 'data-shoji-video-id');\n const videoEl = element.querySelector('video');\n if (videoEl) {\n if (videoIdAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${videoIdAttr}\" ignored — no effect on a nested <video> (always html5).`,\n );\n }\n const sources: MediaSource[] = Array.from(videoEl.querySelectorAll('source'))\n .map((s) => ({ src: s.getAttribute('src') ?? '', type: s.getAttribute('type') ?? '' }))\n .filter((s) => s.src);\n const src = videoEl.getAttribute('src') ?? sources[0]?.src;\n if (!src) return undefined;\n\n const item: GalleryItem = { src, video: { provider: 'html5' } };\n if (sources.length) item.sources = sources;\n const poster = videoEl.getAttribute('poster');\n if (poster) item.poster = poster;\n // Same bug as the data-shoji-video branch below: without this, these\n // fall through into item.data.width/height as strings instead.\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n applyCommon(element, item, src);\n return item;\n }\n\n const videoUrl = attr(element, 'data-shoji-video');\n if (videoUrl) {\n const providerAttr = attr(element, 'data-shoji-video-provider');\n const resolved = resolveExplicitVideo(videoUrl, providerAttr, videoIdAttr);\n const item: GalleryItem = { src: videoUrl, video: resolved.video };\n if (resolved.sources) item.sources = resolved.sources;\n const poster = attr(element, 'data-shoji-poster');\n if (poster) item.poster = poster;\n // A real bug: unlike `scanImage`, this never read these — they fell\n // through into `item.data.width`/`item.data.height` as strings instead\n // of `item.width`/`item.height`, silently losing `applyAspect()`'s\n // aspect-ratio and the open-placeholder's explicit natural-size box for\n // every DOM-mode (`data-shoji-*`) provider-video item.\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n applyCommon(element, item, videoUrl);\n return item;\n }\n\n if (videoIdAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${videoIdAttr}\" ignored — requires a data-shoji-video URL.`,\n );\n }\n return undefined;\n}\n\nconst KNOWN_VIDEO_PROVIDERS = new Set(['youtube', 'vimeo', 'html5']);\n\nfunction html5Fallback(url: string): { video: VideoDescriptor; sources: MediaSource[] } {\n return { video: { provider: 'html5' }, sources: [{ src: url, type: guessVideoType(url) }] };\n}\n\n/**\n * `data-shoji-video-provider` declares the provider outright — trusts an id\n * even off a non-YouTube/non-Vimeo host (e.g. an internal proxy URL).\n * Mirrors dynamic mode's `video: { provider: '...' }`.\n */\nfunction resolveExplicitVideo(\n url: string,\n providerAttr: string | undefined,\n idAttr: string | undefined,\n): { video: VideoDescriptor; sources?: MediaSource[] } {\n if (providerAttr && !KNOWN_VIDEO_PROVIDERS.has(providerAttr)) {\n console.warn(`Shoji: data-shoji-video-provider=\"${providerAttr}\" isn't recognized — ignored.`);\n providerAttr = undefined;\n }\n\n if (providerAttr === 'html5') {\n if (idAttr)\n console.warn(`Shoji: data-shoji-video-id=\"${idAttr}\" ignored — provider html5 has no id.`);\n return html5Fallback(url);\n }\n\n const youtube = resolveDetectedProvider(\n 'youtube',\n url,\n providerAttr,\n idAttr,\n isYouTubeUrl,\n detectYouTubeId,\n );\n if (youtube) return youtube;\n const vimeo = resolveDetectedProvider(\n 'vimeo',\n url,\n providerAttr,\n idAttr,\n isVimeoUrl,\n detectVimeoId,\n );\n if (vimeo) return vimeo;\n\n if (idAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${idAttr}\" ignored — data-shoji-video=\"${url}\" isn't a recognized YouTube/Vimeo URL; falling back to html5.`,\n );\n }\n return html5Fallback(url);\n}\n\n/** Shared logic for youtube/vimeo, the only two providers with URL-based host detection. `undefined` means \"not this provider, try the next one\"; anything else is final, explicit trusting `idAttr` off any host, unset falling back to html5 quietly. */\nfunction resolveDetectedProvider(\n provider: 'youtube' | 'vimeo',\n url: string,\n providerAttr: string | undefined,\n idAttr: string | undefined,\n isHost: (url: string) => boolean,\n detectId: (url: string) => string | undefined,\n): { video: VideoDescriptor; sources?: MediaSource[] } | undefined {\n const explicit = providerAttr === provider;\n if (!explicit && !isHost(url)) return undefined;\n const id = idAttr ?? detectId(url);\n if (!id) {\n if (!explicit) return html5Fallback(url);\n console.warn(\n `Shoji: data-shoji-video-provider=\"${provider}\" but no id could be parsed from \"${url}\".`,\n );\n }\n return { video: { provider, id, url } };\n}\n\nconst YOUTUBE_HOSTS = new Set(['youtu.be', 'youtube.com', 'youtube-nocookie.com']);\nconst VIMEO_HOSTS = new Set(['vimeo.com', 'player.vimeo.com']);\n\n/** Strips the `www.`/`m.`/`music.` subdomain YouTube/Vimeo serve the same content under either way. */\nfunction normalizeVideoHost(hostname: string): string {\n return hostname.replace(/^(www|m|music)\\./, '');\n}\n\n/** Host-only, weaker than `detectYouTubeId` on purpose — tells \"wrong site\" (a real misconfig with an explicit id set) apart from \"right site, unparsed path\" (what an explicit id is for). */\nfunction isYouTubeUrl(url: string): boolean {\n try {\n return YOUTUBE_HOSTS.has(normalizeVideoHost(new URL(url, window.location.href).hostname));\n } catch {\n return false;\n }\n}\n\n/** Same reasoning as `isYouTubeUrl`, for Vimeo's two hosts (`vimeo.com` for an ordinary page link, `player.vimeo.com` for an already-embed-shaped URL). */\nfunction isVimeoUrl(url: string): boolean {\n try {\n return VIMEO_HOSTS.has(normalizeVideoHost(new URL(url, window.location.href).hostname));\n } catch {\n return false;\n }\n}\n\n/**\n * `youtu.be/{id}`, `watch?v=`, `/embed/`, `/shorts/`, `/live/` (streams/\n * premieres), `/v/` (legacy), on `youtube.com` or `youtube-nocookie.com`\n * (the privacy-enhanced embed domain) — `www.`/`m.`/`music.` subdomains all\n * normalize the same way. `undefined` otherwise.\n */\nfunction detectYouTubeId(url: string): string | undefined {\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n const host = normalizeVideoHost(parsed.hostname);\n if (host === 'youtu.be') return parsed.pathname.slice(1).split('/')[0] || undefined;\n if (!YOUTUBE_HOSTS.has(host)) return undefined;\n if (parsed.pathname === '/watch') return parsed.searchParams.get('v') ?? undefined;\n const match = parsed.pathname.match(/^\\/(?:embed|shorts|live|v)\\/([^/?]+)/);\n return match?.[1];\n}\n\n/** First numeric path segment on a recognized Vimeo host — covers `vimeo.com/{id}`, `vimeo.com/{id}/{hash}` (unlisted-video privacy hash, kept in `url` not the id), `player.vimeo.com/video/{id}`, and an id buried deeper (`vimeo.com/channels/x/{id}`). `undefined` on an unrecognized host too. */\nfunction detectVimeoId(url: string): string | undefined {\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n if (!VIMEO_HOSTS.has(normalizeVideoHost(parsed.hostname))) return undefined;\n return parsed.pathname.match(/\\/(\\d+)(?:\\/|$)/)?.[1];\n}\n\n/** youtube/vimeo, in host-detection preference order — same pair `resolveDetectedProvider` covers for selector mode. */\nconst DETECTABLE_PROVIDERS = [\n { provider: 'youtube' as const, isHost: isYouTubeUrl, detectId: detectYouTubeId },\n { provider: 'vimeo' as const, isHost: isVimeoUrl, detectId: detectVimeoId },\n];\n\n/**\n * Dynamic mode skips `scanContainer()` entirely, so it never gets the same\n * src-based detection `data-shoji-video`/`data-shoji-video-id` have.\n * Mirrors it here: `video: true` infers the whole descriptor from `src`\n * (youtube or vimeo if the host matches, else html5); `{provider:'youtube'|\n * 'vimeo'}` with no `id` fills in just the id. An explicit `id` always\n * wins. Warns (doesn't throw) when a detectable-provider item ends up with\n * no id — the renderer guards this at render time too, showing a\n * placeholder instead of a broken embed.\n */\nexport function resolveDynamicVideoItems(items: GalleryItemInput[]): GalleryItem[] {\n return items.map((item): GalleryItem => {\n if (item.video === true) {\n const detected = DETECTABLE_PROVIDERS.find((p) => p.isHost(item.src));\n const video: VideoDescriptor = detected\n ? { provider: detected.provider, id: detected.detectId(item.src) }\n : { provider: 'html5' };\n if ((video.provider === 'youtube' || video.provider === 'vimeo') && !video.id) {\n console.warn(\n `Shoji: item \"${item.id ?? item.src}\" has video: true, but no id could be parsed from src (\"${item.src}\") — the embed won't load. Use an explicit video.id instead.`,\n );\n }\n return { ...item, video };\n }\n // TS narrows `item.video` past this point, but not `item`'s own type —\n // hence the cast (the map's `: GalleryItem` annotation is what actually\n // catches a mistake here).\n const resolved = item as GalleryItem;\n const provider = resolved.video?.provider;\n if (provider !== 'youtube' && provider !== 'vimeo') return resolved;\n if (resolved.video && 'id' in resolved.video && resolved.video.id) return resolved;\n const id = DETECTABLE_PROVIDERS.find((p) => p.provider === provider)!.detectId(resolved.src);\n if (!id) {\n console.warn(\n `Shoji: item \"${resolved.id ?? resolved.src}\" has video.provider: '${provider}' with no id, and src (\"${resolved.src}\") isn't a recognized ${provider === 'youtube' ? 'YouTube' : 'Vimeo'} URL — the embed won't load. Set video.id explicitly.`,\n );\n return resolved;\n }\n return { ...resolved, video: { provider, id, url: resolved.video?.url } };\n });\n}\n\nfunction guessVideoType(url: string): string {\n const clean = url.split(/[?#]/)[0] ?? url;\n const ext = clean.slice(clean.lastIndexOf('.') + 1).toLowerCase();\n if (ext === 'webm') return 'video/webm';\n if (ext === 'ogg' || ext === 'ogv') return 'video/ogg';\n return 'video/mp4';\n}\n","import type { VideoProviderRenderer } from './plugin';\nimport type { GalleryItem } from './types';\nimport { containedBox } from './zoomTransition';\n\ninterface Slot {\n root: HTMLElement;\n media: HTMLElement;\n /** Which pool position (`-preload…+preload`) this slot represents — reassigned by `render()`, not fixed at construction (see the class comment below). */\n offset: number;\n /** The index this slot currently wants to show, whether or not content has arrived — also how a later-resolving decode (`pending` below) finds the right slot. */\n assignedIndex: number | null;\n /** False from the moment a slot is (re)assigned a new index until that index's content has actually swapped in — see `isActiveReady()`. */\n ready: boolean;\n}\n\n/** A fully-built, ready-to-display node for a given item index — survives slot reassignment (see `cache` below), unlike `Slot.ready`, which resets the moment its slot moves on to a different index. */\ninterface CacheEntry {\n node: HTMLElement;\n item: GalleryItem;\n}\n\nexport interface SlideManagerOptions {\n preload: number;\n videoProviders: Map<string, VideoProviderRenderer>;\n}\n\n/**\n * DESIGN.md §2.3 — only `currentIndex ± preload` exist in the DOM. Content\n * already resident and ready is never moved between slots — the slot that\n * already holds it just gets its own `offset` relabeled to its new pool\n * position; only content resident nowhere yet gets built fresh into\n * whatever's left over. O(preload) re-render cost either way, but never a\n * DOM reparent — which matters for a provider video's `<iframe>` (§4.3):\n * most browsers reload an iframe moved to a new parent, so a live embed can\n * only safely change position by relabeling, never by being moved.\n */\nexport class SlideManager {\n readonly element: HTMLElement;\n private readonly slots: Slot[];\n private readonly preload: number;\n private readonly videoProviders: Map<string, VideoProviderRenderer>;\n private dragOffsetPx = 0;\n\n /** Ready nodes keyed by item index — trimmed to `centerIndex ± preload` each `render()`, same window the slots cover, so an evicted entry's video/iframe resources get released even if no slot ever reclaims it. */\n private readonly cache = new Map<number, CacheEntry>();\n\n /**\n * Image decodes in flight, keyed by item index, not by whichever slot\n * started them — a real bug this fixes: navigating before a preload\n * decode resolved used to reassign that slot, abandoning the decode and\n * starting a duplicate elsewhere, so a slow preload could never finish,\n * only restart. `reveal()` looks up which slot currently wants this\n * index at resolve time, so a reshuffled pool still lands it correctly.\n */\n private readonly pending = new Map<number, HTMLImageElement>();\n\n constructor(options: SlideManagerOptions) {\n this.element = document.createElement('div');\n this.element.className = 'shoji-slides';\n this.preload = options.preload;\n this.videoProviders = options.videoProviders;\n\n const count = options.preload * 2 + 1;\n this.slots = Array.from({ length: count }, (_, i) => {\n const offset = i - options.preload;\n const root = document.createElement('div');\n root.className = 'shoji-slide';\n\n const media = document.createElement('div');\n media.className = 'shoji-slide-media';\n root.appendChild(media);\n\n this.element.appendChild(root);\n return { root, media, offset, assignedIndex: null, ready: false };\n });\n this.applyTransforms(null);\n }\n\n /** The active slot's `.shoji-slide-media` — not `.shoji-slide`, whose transform is owned by pool-offset positioning. */\n getActiveMedia(): HTMLElement | null {\n return this.slots.find((slot) => slot.offset === 0)?.media ?? null;\n }\n\n /** False while the active slot's content is still decoding — Gallery.ts uses this right after `render()` to show the loading state immediately, without waiting for `onLoad`. */\n isActiveReady(): boolean {\n return this.slots.find((slot) => slot.offset === 0)?.ready ?? false;\n }\n\n /**\n * DESIGN.md §2.4 — live drag-to-navigate feedback: every slot's\n * structural `offset * 100%` position gets this same `px` added on top,\n * so dragging left/right visually slides the whole pool together (the\n * adjacent preloaded slot already exists at `±100%`) — no new DOM, no\n * content re-render mid-drag. `transition`: `null` during the live drag\n * (1:1 with the pointer); a real value only for the post-release settle\n * animation, reset back to `null` once that transition ends.\n */\n setDragOffset(px: number, transition: string | null): void {\n this.dragOffsetPx = px;\n this.applyTransforms(transition);\n }\n\n /** The pool slot's `.shoji-slide` root at a structural offset — what the drag settle animation (§2.4) waits for `transitionend` on. */\n getSlotRoot(offset: number): HTMLElement | null {\n return this.slots.find((slot) => slot.offset === offset)?.root ?? null;\n }\n\n private applyTransforms(transition: string | null): void {\n for (const slot of this.slots) {\n slot.root.style.transition = transition ?? '';\n slot.root.style.transform = `translateX(calc(${slot.offset * 100}% + ${this.dragOffsetPx}px))`;\n }\n }\n\n /** Re-renders whichever slots need a different item; `onLoad` fires per index once its media settles. `openPlaceholderSrc` (only from `Gallery.open()`) swaps the centerIndex slot's spinner for a low-res placeholder once it decodes, if not already ready. `loop` matches `Gallery.ts`'s own `nextIndex()`/`prevIndex()` wrap-around — without it, the pool slot just past the last (or before the first) item has no item to preload at all, so a boundary drag reveals nothing even though the completed navigation itself already wraps correctly. */\n render(\n items: readonly GalleryItem[],\n centerIndex: number,\n onLoad: (index: number) => void,\n openPlaceholderSrc?: string,\n loop = false,\n ): void {\n // A real bug found wiring this up, in two parts:\n // 1. Wrapping is only safe from an *index-collision* standpoint when\n // there are enough real items to fill the whole pool without\n // revisiting one twice. `items.length === this.slots.length`\n // (`2*preload + 1`) looks like exactly enough — but that's the\n // degenerate case where the pool *is* the whole gallery: the \"prev\"\n // slot at the first item and the \"next\" slot at the last item both\n // wrap to the *other* end, making the first and last items adjacent\n // in the pool even though nothing actually collides on one index.\n // Confirmed directly, reproduced in CI: a real fixture built\n // specifically to keep two provider-video items apart (never within\n // `preload` of each other, so at most one `.shoji-slide-provider-\n // video` is ever resident) broke exactly this way once its\n // `demo/assets/`-dependent photo tiles were empty (gitignored, so a\n // fresh CI checkout has none) — collapsing it down to precisely\n // `items.length === this.slots.length`, wrapping the two video items\n // into each other's pool despite the fixture's own spacer tile still\n // sitting between them in the array. Requiring *strictly* more items\n // than pool slots (`>`, not `>=`) is what actually guarantees the\n // first and last items are never both in the wrapped pool at once.\n // 2. Below that threshold, an out-of-range offset just shows nothing at\n // that edge, same as `loop: false` — correct for a gallery too small\n // to usefully \"loop\" through anyway.\n const canWrap = loop && items.length > this.slots.length;\n const targets = this.slots.map((_, i) => {\n const offset = i - this.preload;\n const rawIndex = centerIndex + offset;\n const index = canWrap ? ((rawIndex % items.length) + items.length) % items.length : rawIndex;\n const item = index >= 0 && index < items.length ? items[index] : undefined;\n return { offset, index, item };\n });\n\n // Trim the cache to the same window the slots above now cover — the\n // *wrapped* set of indices, not a raw numeric range, matching `loop`;\n // a raw-range check would otherwise immediately evict a just-cached\n // wrapped entry (e.g. index 0, preloaded one slot past the last item)\n // since it falls far outside `centerIndex ± preload` as plain numbers.\n // Releases a dropped video here rather than just letting the reference\n // disappear (which would leave it paused-in-place, never released).\n const windowIndices = new Set(targets.map((t) => t.index));\n for (const [index, entry] of this.cache) {\n if (!windowIndices.has(index)) {\n releaseVideoNode(entry.node);\n this.cache.delete(index);\n }\n }\n\n // Phase 1 — claim in place, before anything gets destructively\n // released. A target already resident and ready in *some* slot (not\n // necessarily the one whose own offset happens to match) stays exactly\n // where it is — only that slot's `offset` moves (see the class comment\n // above). Still mid-decode elsewhere isn't claimed here (no `ready`\n // slot yet) — falls through to phase 2, where `ensureImageDecoding`'s\n // in-flight guard reconciles it once the one real decode resolves.\n const claimedIndices = new Set<number>();\n const claimedSlots = new Set<Slot>();\n for (const target of targets) {\n if (!target.item) continue;\n const owner = this.slots.find((s) => s.assignedIndex === target.index && s.ready);\n if (!owner) continue;\n claimedIndices.add(target.index);\n claimedSlots.add(owner);\n if (owner.offset === target.offset) continue; // already exactly right, nothing to do\n owner.offset = target.offset;\n onLoad(target.index);\n }\n\n // Phase 2 — whatever's left: slots phase 1 didn't claim are free to\n // clear (out-of-range target) or take on fresh content (a genuinely\n // new index, or one already mid-decode elsewhere).\n const freeSlots = this.slots.filter((s) => !claimedSlots.has(s));\n const freeTargets = targets.filter((t) => !t.item || !claimedIndices.has(t.index));\n\n freeTargets.forEach((target, i) => {\n const slot = freeSlots[i]!;\n slot.offset = target.offset;\n const { index, item } = target;\n\n if (!item) {\n slot.assignedIndex = null;\n slot.ready = false;\n releaseVideo(slot.media);\n slot.media.replaceChildren();\n return;\n }\n if (slot.assignedIndex === index) return; // unchanged — a decode already in flight here\n\n slot.assignedIndex = index;\n slot.ready = false;\n releaseVideo(slot.media);\n slot.media.replaceChildren(createSpinner());\n // Early, not just from swapIn/moveIn/onReady below — a provider\n // video's poster (shown synchronously, well before onReady) needs\n // --shoji-provider-video-aspect (shoji.css) set before it ever\n // paints, or it always letterboxes to the 16:9 fallback regardless of\n // the item's own declared shape.\n this.applyAspect(slot, item);\n if (index === centerIndex && openPlaceholderSrc) {\n const naturalSize =\n item.width && item.height ? { width: item.width, height: item.height } : undefined;\n this.revealOpenPlaceholder(openPlaceholderSrc, slot, index, naturalSize);\n }\n\n if (item.video?.provider === 'html5') {\n this.renderVideo(item, slot, index, onLoad);\n } else if (item.video) {\n this.renderProviderVideo(item, slot, index, onLoad);\n } else {\n this.ensureImageDecoding(item, index, onLoad); // no-ops if index is already being decoded elsewhere\n }\n });\n\n // Reflect any relabeling above immediately, never animated — masked\n // either by SlideTransition's own ghost-clone crossfade, or by landing\n // exactly on a completed drag's already-settled position (§2.4);\n // animating this too would fight both.\n this.applyTransforms(null);\n }\n\n private applyAspect(slot: Slot, item: GalleryItem): void {\n if (item.width && item.height) {\n slot.media.style.aspectRatio = `${item.width} / ${item.height}`;\n } else {\n slot.media.style.removeProperty('aspect-ratio');\n }\n // A provider video's real shape (YouTube/Vimeo iframe, via\n // shoji.css's cqw/cqh sizing) — kept separate from the aspect-ratio\n // above since that alone can't shape a non-replaced element like an\n // iframe/div (see shoji.css's own comment on this). Only set for a\n // video item: harmless either way, but meaningless for a photo, whose\n // own object-fit: contain already uses its real decoded dimensions\n // directly.\n if (item.video && item.width && item.height) {\n slot.media.style.setProperty(\n '--shoji-provider-video-aspect',\n `calc(${item.width} / ${item.height})`,\n );\n } else {\n slot.media.style.removeProperty('--shoji-provider-video-aspect');\n }\n }\n\n /** Releases the slot's old content and swaps the new node in, caching it. `ensureImageDecoding` goes through `moveIn` instead. */\n private swapIn(slot: Slot, node: HTMLElement, item: GalleryItem, index: number): void {\n releaseVideo(slot.media);\n this.applyAspect(slot, item);\n slot.media.replaceChildren(node);\n slot.ready = true;\n this.cache.set(index, { node, item });\n }\n\n /**\n * Inserts a just-decoded node into the slot waiting on it — skips\n * `releaseVideo`, unlike `swapIn`: this is its first insertion anywhere,\n * nothing outgoing to release. `render()`'s claim pass (Phase 1) never\n * calls this — it reuses `ready` content in place, no DOM touch at all.\n */\n private moveIn(slot: Slot, entry: CacheEntry, index: number): void {\n this.applyAspect(slot, entry.item);\n slot.media.replaceChildren(entry.node);\n slot.ready = true;\n this.cache.set(index, entry);\n }\n\n /** Starts decoding `item` for `index`, only if nothing already is (see `pending`). Resolves by looking up whichever slot currently wants this index, not the one active when the decode started. */\n private ensureImageDecoding(\n item: GalleryItem,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n if (this.pending.has(index)) return;\n\n const img = document.createElement('img');\n img.className = 'shoji-slide-img';\n img.alt = item.alt ?? '';\n // A real bug: <img> is natively draggable by default in every browser\n // (drag-to-save-elsewhere). Left on, a real drag gesture — navigate,\n // vertical-close, or the zoom plugin's own pan — can lose the race to\n // the browser's own \"start a native image drag\" recognition, which\n // fires pointercancel and hands the interaction off to dragstart/drag\n // instead: the gesture appears to move once, then stop dead, since\n // every pointer event after the cancel is simply never dispatched here\n // again. Disabling native drag makes Pointer Events own the gesture\n // unconditionally.\n img.draggable = false;\n // The one image the viewer is actually waiting on — hint the browser to\n // schedule it ahead of any lower-priority background fetches contending\n // for the same connection pool.\n if ('fetchPriority' in img) img.fetchPriority = 'high';\n if (item.srcset) img.srcset = item.srcset;\n if (item.sizes) img.sizes = item.sizes;\n img.src = item.src;\n this.pending.set(index, img);\n\n const reveal = (): void => {\n this.pending.delete(index);\n const entry: CacheEntry = { node: img, item };\n this.cache.set(index, entry);\n const slot = this.slots.find((s) => s.assignedIndex === index);\n if (!slot) return; // nobody currently wants it anymore\n this.moveIn(slot, entry, index);\n onLoad(index);\n };\n\n if (typeof img.decode === 'function') {\n img.decode().then(reveal, reveal);\n } else {\n img.addEventListener('load', reveal, { once: true });\n img.addEventListener('error', reveal, { once: true });\n }\n }\n\n /**\n * DESIGN.md §2.3 — swaps the spinner for the placeholder once *it*\n * decodes, not immediately: `item.thumb` is often just `item.src` again,\n * so an undecoded placeholder can leave as long a blank gap as the\n * spinner it replaces.\n *\n * A real bug: `.shoji-slide-open-placeholder`'s CSS unconditionally\n * force-fills the frame (deliberate default: a real photo is usually\n * bigger than the dialog). Wrong for a genuinely small photo with known\n * `item.width`/`item.height` — same \"grows too big, snaps down once real\"\n * symptom the zoom-in transition itself had (§2.3b), but that fix only\n * governs the animated *transform*, not this placeholder's own CSS box\n * once it settles. When `naturalSize` is known, sizes the placeholder\n * explicitly instead, reusing `containedBox` (`zoomTransition.ts`) —\n * unknown-size items keep the original force-fill guess.\n *\n * A second real bug in that same fix: measured `slot.media`'s own rect as\n * \"the container\" — but `slot.media` is the exact element the zoom-in\n * transition (§2.3b) animates a `scale()` transform on. `getBoundingClientRect()`\n * reflects whatever transform is *currently* applied, and the placeholder's\n * own decode typically resolves before that ~300ms animation settles — so\n * this measured a still-small, mid-animation rect (often the origin\n * thumbnail's own tiny size) instead of the real dialog size. `slot.root`\n * (`.shoji-slide`) fixes it: same box, only ever `translateX`'d for\n * pool-offset positioning, never scaled — a stable read regardless of\n * what its child is mid-animation through.\n */\n private revealOpenPlaceholder(\n src: string,\n slot: Slot,\n index: number,\n naturalSize?: { width: number; height: number },\n ): void {\n const img = createOpenPlaceholder(src);\n const reveal = (): void => {\n if (slot.assignedIndex !== index || slot.ready) return; // stale, or the real content already won the race\n // Only loading indicators, not slot.media wholesale — a provider video\n // may have already appended its own (still-hidden) container alongside\n // it. A real bug: this only ever cleared the spinner, not a\n // `.shoji-slide-provider-poster` a provider video's `item.poster`\n // (`showProviderPoster`, below) may have *already* synchronously\n // inserted by the time this async decode resolves — leaving both\n // visible at once, the poster at its own small natural size next to\n // this placeholder's explicitly-computed large box.\n slot.media\n .querySelectorAll('.shoji-slide-spinner, .shoji-slide-provider-poster')\n .forEach((el) => el.remove());\n slot.media.appendChild(img);\n if (naturalSize) {\n const containerRect = slot.root.getBoundingClientRect();\n const box = containedBox(\n { left: 0, top: 0, width: containerRect.width, height: containerRect.height },\n naturalSize.width / naturalSize.height,\n naturalSize,\n );\n img.style.width = `${box.width}px`;\n img.style.height = `${box.height}px`;\n }\n };\n if (typeof img.decode === 'function') {\n img.decode().then(reveal, reveal);\n } else {\n img.addEventListener('load', reveal, { once: true });\n img.addEventListener('error', reveal, { once: true });\n }\n }\n\n /** Native `<video controls>` — real playback, not just a poster. Not autoplayed/muted: a deliberate click-to-play, not a background loop. */\n private renderVideo(\n item: GalleryItem,\n slot: Slot,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n const hasSource = Boolean(item.src) || Boolean(item.sources && item.sources.length > 0);\n if (!hasSource) {\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n this.swapIn(slot, placeholder, item, index);\n onLoad(index);\n return;\n }\n\n const video = document.createElement('video');\n video.className = 'shoji-slide-video';\n video.controls = true;\n video.playsInline = true;\n // Same real bug as the image path's own `img.draggable = false` above\n // (`ensureImageDecoding()`), never fixed here since no e2e test\n // previously drove a real mouse drag over an actual native\n // `<video controls>` element to catch it: a `<video>` is natively\n // draggable by default too (drag-to-save-elsewhere), and left on, a\n // real drag gesture (navigate, vertical-close) can lose the race to the\n // browser's own \"start a native media drag\" recognition — it fires\n // `pointercancel` and hands the interaction to `dragstart`/`drag`\n // instead, so the gesture appears to move once, then stop dead, since\n // every pointer event after the cancel is simply never dispatched here\n // again. Confirmed directly: reproduced consistently (every browser\n // project) for a horizontal drag specifically, though the same\n // mechanism can affect vertical too. Disabling native drag makes\n // Pointer Events own the gesture unconditionally, same as for photos.\n video.draggable = false;\n if (item.poster) video.poster = item.poster;\n // Before `loadedmetadata`, a <video> has no real intrinsic size to\n // contain itself against (object-fit: contain, above) — the UA default\n // (300x150) until then, visibly jumping to the real shape once it\n // loads. item.width/item.height (already known up front, unlike a\n // photo's real dimensions) sidesteps that: same shape from the first\n // frame the poster shows, no jump once metadata actually arrives.\n if (item.width && item.height) {\n video.style.aspectRatio = `${item.width} / ${item.height}`;\n }\n\n if (item.sources && item.sources.length > 0) {\n for (const s of item.sources) {\n const source = document.createElement('source');\n source.src = s.src;\n source.type = s.type;\n video.appendChild(source);\n }\n } else {\n video.src = item.src;\n }\n\n // Inserted immediately (unlike the image path above) — the native\n // `poster` attribute already shows something meaningful without\n // waiting on `loadedmetadata`, so there's no decode-style gap to close\n // here; deferring would only make video slides slower to show anything.\n this.swapIn(slot, video, item, index);\n const reveal = (): void => onLoad(index);\n video.addEventListener('loadedmetadata', reveal, { once: true });\n video.addEventListener('error', reveal, { once: true });\n }\n\n /** DESIGN.md §4-video. Unregistered provider → same placeholder as no-source video. */\n private renderProviderVideo(\n item: GalleryItem,\n slot: Slot,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n const video = item.video!;\n const renderFn =\n video.provider === 'custom' ? video.render : this.videoProviders.get(video.provider);\n\n if (!renderFn) {\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n this.swapIn(slot, placeholder, item, index);\n onLoad(index);\n return;\n }\n\n // DESIGN.md §4.3 — shows item.poster immediately, in place of the\n // generic spinner Phase 2 already put in slot.media, if the host\n // supplied one; same idea as native <video poster>, just applied to a\n // provider embed instead. A renderer without a host-supplied poster can\n // still resolve a fallback of its own via the setPoster callback below.\n if (item.poster) showProviderPoster(slot, item.poster);\n\n const container = document.createElement('div');\n container.className = 'shoji-slide-provider-video';\n container.hidden = true;\n const controller = new AbortController();\n providerAbortControllers.set(container, controller);\n\n // Unlike an <img> decode, an iframe embed only actually loads once\n // attached to the live document — attach now, hidden behind the\n // still-visible spinner (or poster, above), instead of deferring\n // attachment until ready.\n slot.media.appendChild(container);\n\n let revealed = false;\n const onReady = (): void => {\n if (revealed || controller.signal.aborted) return;\n revealed = true;\n container.hidden = false;\n // Whichever loading indicator(s) — Phase 2's spinner, a poster, an\n // open placeholder — are still sitting behind the now-visible embed,\n // never the embed itself. A real bug: a host-supplied `item.poster`\n // (`showProviderPoster`, above) and `Gallery.open()`'s own low-res\n // placeholder (`revealOpenPlaceholder`, below) are added independently\n // of each other and neither replaces the other, so *both* can be\n // sitting in `slot.media` at once by the time this runs.\n // `querySelector(...).remove()` only ever removed the first match in\n // DOM order, permanently leaking whichever indicator lost that\n // race — visible as the leaked one's image bleeding through the\n // transparent letterboxing gaps around a provider embed that isn't\n // exactly the container's own aspect ratio.\n slot.media\n .querySelectorAll(\n '.shoji-slide-spinner, .shoji-slide-open-placeholder, .shoji-slide-provider-poster',\n )\n .forEach((el) => el.remove());\n this.applyAspect(slot, item);\n slot.ready = true;\n this.cache.set(index, { node: container, item });\n onLoad(index);\n };\n const setPoster = (url: string): void => {\n // A host-supplied poster (above) always wins over a renderer's own\n // fallback — and once the real embed is showing, or this slide's\n // moved on, a fallback resolving late (e.g. an async fetch) must\n // never replace or paint over it.\n if (item.poster || revealed || controller.signal.aborted) return;\n showProviderPoster(slot, url);\n };\n renderFn(container, item, onReady, controller.signal, setPoster);\n }\n\n destroy(): void {\n for (const slot of this.slots) {\n releaseVideo(slot.media);\n slot.media.replaceChildren();\n slot.assignedIndex = null; // any decode still in `pending` correctly finds no slot wanting it once it resolves\n slot.ready = false;\n }\n this.cache.clear();\n this.pending.clear();\n this.element.remove();\n }\n}\n\n/** DESIGN.md §4.3 — a provider video's loading placeholder, host-supplied (`item.poster`) or a renderer's own fallback (`setPoster`) — replaces whichever generic indicator (spinner, or an earlier poster call) is currently in `slot.media`, same \"only one loading indicator at a time\" rule `createOpenPlaceholder`'s own callers already follow. Reuses `.shoji-slide-img`'s sizing, same reasoning as that function. */\nfunction showProviderPoster(slot: Slot, url: string): void {\n // A real bug: this only ever cleared the spinner/a previous poster, never\n // an already-shown `.shoji-slide-open-placeholder` (`revealOpenPlaceholder`,\n // above) — that placeholder's async image decode can resolve *before*\n // this (e.g. `setPoster`'s fallback, resolved later than the initial\n // synchronous poster call), leaving both visible at once.\n slot.media\n .querySelectorAll(\n '.shoji-slide-spinner, .shoji-slide-open-placeholder, .shoji-slide-provider-poster',\n )\n .forEach((el) => el.remove());\n const img = document.createElement('img');\n img.className = 'shoji-slide-img shoji-slide-provider-poster';\n img.alt = '';\n img.draggable = false;\n img.src = url;\n slot.media.appendChild(img);\n}\n\n/** DESIGN.md §2.3 — low-res open() placeholder; reuses .shoji-slide-img's sizing so the zoom-in FLIP measures it like real content (zoomTransition.ts's effectiveTargetBox only special-cases the spinner as non-content). */\nfunction createOpenPlaceholder(src: string): HTMLImageElement {\n const img = document.createElement('img');\n img.className = 'shoji-slide-img shoji-slide-open-placeholder';\n img.alt = '';\n img.draggable = false;\n img.src = src;\n return img;\n}\n\n/** DESIGN.md §2.3 — shown in a slot while its content is still decoding/loading, replacing whatever a stale \"keep the old image visible\" approach would have left there (a previous version of this did that; it read as broken, not helpful, since the old image no longer matches the caption/counter/URL that already moved on). Purely CSS-animated (a rotating ring via `border`), no JS-driven layout. */\nfunction createSpinner(): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = 'shoji-slide-spinner';\n spinner.setAttribute('aria-hidden', 'true');\n return spinner;\n}\n\nconst providerAbortControllers = new WeakMap<HTMLElement, AbortController>();\n\n/** Pause/release a slot's previous <video> or provider content, if any. */\nfunction releaseVideo(media: HTMLElement): void {\n const video = media.querySelector('video');\n if (video) releaseVideoNode(video);\n const provider = media.querySelector<HTMLElement>('.shoji-slide-provider-video');\n if (provider) releaseProviderNode(provider);\n}\n\n/**\n * Pauses whatever's playing in `media` — native `<video>`, or a provider\n * embed wired via `wirePlayableContract` (§4-video) — without\n * releasing/destroying it, unlike `releaseVideo` above. `Gallery` calls\n * this on `close()` and before every navigation, on the outgoing slide.\n */\nexport function pauseMedia(media: HTMLElement | null): void {\n const video = media?.querySelector('video');\n if (video) {\n video.pause();\n return;\n }\n const provider = media?.querySelector<HTMLElement & { pause?: () => void }>(\n '.shoji-slide-provider-video',\n );\n if (provider && typeof provider.pause === 'function') provider.pause();\n}\n\n/** Cache-eviction counterpart — the node itself might *be* the content. */\nfunction releaseVideoNode(node: HTMLElement): void {\n if (node.tagName !== 'VIDEO') {\n releaseProviderNode(node);\n return;\n }\n const video = node as HTMLVideoElement;\n video.pause();\n video.removeAttribute('src');\n video.load();\n}\n\nfunction releaseProviderNode(node: HTMLElement): void {\n const controller = providerAbortControllers.get(node);\n if (!controller) return;\n providerAbortControllers.delete(node);\n controller.abort();\n}\n","/**\n * DESIGN.md §2.5 — built-in presets, generated from a small config→transform\n * DSL rather than ~20 hand-written keyframe functions. `enter(direction)` is\n * where the incoming slide starts (then transitions to natural: `transform:\n * none; opacity: 1`); `leave(direction)` is where the outgoing clone (see\n * `SlideTransition.ts`) ends up (starts at natural, transitions to this).\n * `direction` is `1` for next()-style, `-1` for prev()-style — presets that\n * don't care (fade, zoom, flipX, deck, drop...) never read it. transform/\n * opacity only, per CLAUDE.md's hardware-accelerated-CSS3 constraint.\n */\n\nexport interface TransitionState {\n transform: string;\n opacity: number;\n}\n\nexport interface TransitionPreset {\n name: string;\n enter(direction: 1 | -1): TransitionState;\n leave(direction: 1 | -1): TransitionState;\n}\n\n/** One end of one preset. `directional: true` multiplies translateX/Y/rotateZ/Y by nav direction (mirror-image next vs prev — the \"slide\" family); omitted means the same fixed transform either way (the \"fade\" family — fadeUp always rises). */\ninterface AxisConfig {\n directional?: boolean;\n translateX?: number; // %\n translateY?: number; // %\n scale?: number;\n rotateX?: number; // deg, never direction-multiplied\n rotateY?: number; // deg\n rotateZ?: number; // deg\n perspective?: number; // px, needed alongside rotateX/Y for real 3D depth\n opacity?: number; // default 1\n}\n\nfunction resolveAxis(config: AxisConfig, direction: 1 | -1): TransitionState {\n const sign = config.directional ? direction : 1;\n const parts: string[] = [];\n if (config.perspective) parts.push(`perspective(${config.perspective}px)`);\n const tx = config.translateX !== undefined ? config.translateX * sign : 0;\n const ty = config.translateY ?? 0;\n if (tx !== 0 || ty !== 0) parts.push(`translate(${tx}%, ${ty}%)`);\n if (config.rotateY !== undefined) parts.push(`rotateY(${config.rotateY * sign}deg)`);\n if (config.rotateX !== undefined) parts.push(`rotateX(${config.rotateX}deg)`);\n if (config.rotateZ !== undefined) parts.push(`rotateZ(${config.rotateZ * sign}deg)`);\n if (config.scale !== undefined) parts.push(`scale(${config.scale})`);\n return { transform: parts.length > 0 ? parts.join(' ') : 'none', opacity: config.opacity ?? 1 };\n}\n\ninterface PresetSpec {\n name: string;\n enter: AxisConfig;\n leave: AxisConfig;\n}\n\nfunction preset(spec: PresetSpec): TransitionPreset {\n return {\n name: spec.name,\n enter: (direction) => resolveAxis(spec.enter, direction),\n leave: (direction) => resolveAxis(spec.leave, direction),\n };\n}\n\nconst PRESET_LIST: TransitionPreset[] = [\n // The four DESIGN.md calls out by name: default mode, plus fade/zoom/deck.\n preset({\n name: 'slide',\n enter: { directional: true, translateX: 100 },\n leave: { directional: true, translateX: -100 },\n }),\n preset({\n name: 'fade',\n enter: { opacity: 0 },\n leave: { opacity: 0 },\n }),\n preset({\n name: 'zoom',\n enter: { scale: 0.6, opacity: 0 },\n leave: { scale: 1.4, opacity: 0 },\n }),\n preset({\n // \"lg-style deck\": the incoming slide drops into place from slightly\n // above/small while the outgoing one recedes back and fades, like a\n // card being placed on top of a deck — not direction-dependent, a deck\n // doesn't care whether the card came from the left or right.\n name: 'deck',\n enter: { translateY: 6, scale: 0.85, opacity: 0 },\n leave: { translateY: -4, scale: 0.92, opacity: 0 },\n }),\n\n // Positional siblings of `slide`.\n preset({\n name: 'slideVertical',\n enter: { directional: true, translateY: 100 },\n leave: { directional: true, translateY: -100 },\n }),\n preset({\n name: 'push',\n // Same geometry as `slide` but travels further (120% vs 100%) and with\n // no cross-fade at all — a harder, snappier \"shove it off\" feel.\n enter: { directional: true, translateX: 120 },\n leave: { directional: true, translateX: -120 },\n }),\n\n // Fixed-direction fades (not nav-direction-aware — a named entrance style).\n preset({\n name: 'fadeUp',\n enter: { translateY: 12, opacity: 0 },\n leave: { translateY: -12, opacity: 0 },\n }),\n preset({\n name: 'fadeDown',\n enter: { translateY: -12, opacity: 0 },\n leave: { translateY: 12, opacity: 0 },\n }),\n preset({\n name: 'fadeLeft',\n enter: { translateX: -12, opacity: 0 },\n leave: { translateX: 12, opacity: 0 },\n }),\n preset({\n name: 'fadeRight',\n enter: { translateX: 12, opacity: 0 },\n leave: { translateX: -12, opacity: 0 },\n }),\n\n // Zoom family.\n preset({ name: 'zoomOut', enter: { scale: 1.4, opacity: 0 }, leave: { scale: 0.6, opacity: 0 } }),\n preset({ name: 'scaleUp', enter: { scale: 0.7 }, leave: { scale: 1.3 } }),\n preset({ name: 'scaleDown', enter: { scale: 1.3 }, leave: { scale: 0.7 } }),\n\n // Rotation family — `rotate` is fixed-direction; `rotateLeft`/`rotateRight`\n // tie their spin to nav direction instead.\n preset({\n name: 'rotate',\n enter: { rotateZ: 15, opacity: 0 },\n leave: { rotateZ: -15, opacity: 0 },\n }),\n preset({\n name: 'rotateLeft',\n enter: { directional: true, rotateZ: -25, opacity: 0 },\n leave: { directional: true, rotateZ: 25, opacity: 0 },\n }),\n preset({\n name: 'rotateRight',\n enter: { directional: true, rotateZ: 25, opacity: 0 },\n leave: { directional: true, rotateZ: -25, opacity: 0 },\n }),\n\n // 3D family — needs `perspective()` in the same transform for real depth.\n preset({\n name: 'flipX',\n enter: { rotateX: 90, perspective: 1200, opacity: 0 },\n leave: { rotateX: -90, perspective: 1200, opacity: 0 },\n }),\n preset({\n name: 'flipY',\n enter: { directional: true, rotateY: 90, perspective: 1200, opacity: 0 },\n leave: { directional: true, rotateY: -90, perspective: 1200, opacity: 0 },\n }),\n preset({\n name: 'cube',\n enter: { directional: true, rotateY: 70, translateX: 40, perspective: 1600, opacity: 1 },\n leave: { directional: true, rotateY: -70, translateX: -40, perspective: 1600, opacity: 1 },\n }),\n preset({\n name: 'coverflow',\n enter: {\n directional: true,\n rotateY: 35,\n translateX: 60,\n scale: 0.8,\n perspective: 1400,\n opacity: 0,\n },\n leave: {\n directional: true,\n rotateY: -35,\n translateX: -60,\n scale: 0.8,\n perspective: 1400,\n opacity: 0,\n },\n }),\n\n // Fixed-direction drop.\n preset({\n name: 'drop',\n enter: { translateY: -30, opacity: 0 },\n leave: { translateY: 20, opacity: 0 },\n }),\n];\n\n/** Keyed by name for `Gallery`'s `mode` lookup — an unrecognized string is treated as a custom CSS-class-pair mode instead (see `SlideTransition.animateCustom`), not an error. */\nexport const TRANSITION_PRESETS: Readonly<Record<string, TransitionPreset>> = Object.fromEntries(\n PRESET_LIST.map((p) => [p.name, p]),\n);\n","import type { SlideManager } from '../core/SlideManager';\nimport type { TransitionPreset } from './presets';\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/** `\"300ms\"` / `\"0.3s\"` → milliseconds — same parser as `zoomTransition.ts`, duplicated rather than shared: two independent transition subsystems that happen to share a timing format. */\nfunction parseCssTime(value: string): number {\n const first = value.split(',')[0]?.trim() ?? '';\n if (first.endsWith('ms')) return parseFloat(first);\n if (first.endsWith('s')) return parseFloat(first) * 1000;\n return 0;\n}\n\n/** Waits for `transitionend` *or* `animationend` (with a timeout fallback) then calls `cb` once — the custom CSS-class-pair path (§2.5) may use either, since \"no JS needed\" for the host means Shoji can't assume which. */\nfunction waitForEnd(el: HTMLElement, cb: () => void): void {\n const style = getComputedStyle(el);\n const durationMs = Math.max(\n parseCssTime(style.transitionDuration),\n parseCssTime(style.animationDuration),\n );\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n el.removeEventListener('transitionend', onEnd);\n el.removeEventListener('animationend', onEnd);\n cb();\n };\n const onEnd = (event: Event): void => {\n if (event.target === el) finish();\n };\n el.addEventListener('transitionend', onEnd);\n el.addEventListener('animationend', onEnd);\n setTimeout(finish, durationMs + 100);\n}\n\n/** Incoming slide: instant jump to `(transform, opacity)` (same FLIP trick as `zoomTransition.ts`'s `zoomIn`), then transitions to natural. */\nfunction applyEnter(el: HTMLElement, transform: string, opacity: number): void {\n el.style.transition = 'none';\n el.style.transformOrigin = 'center';\n el.style.transform = transform;\n el.style.opacity = String(opacity);\n void el.offsetHeight; // force the instant jump to commit before transitioning away from it\n el.style.transition =\n 'transform var(--shoji-duration) var(--shoji-easing), opacity var(--shoji-duration) var(--shoji-easing)';\n el.style.transform = 'none';\n el.style.opacity = '1';\n}\n\n/** Outgoing ghost: already sits at natural (a fresh clone has no inline transform yet), so it transitions the other way — natural → `(transform, opacity)`, mirroring `zoomOut`'s shape. */\nfunction applyLeave(el: HTMLElement, transform: string, opacity: number): void {\n el.style.transformOrigin = 'center';\n el.style.transition =\n 'transform var(--shoji-duration) var(--shoji-easing), opacity var(--shoji-duration) var(--shoji-easing)';\n void el.offsetHeight;\n el.style.transform = transform;\n el.style.opacity = String(opacity);\n}\n\nfunction clearInlineTransform(el: HTMLElement): void {\n el.style.transition = '';\n el.style.transform = '';\n el.style.opacity = '';\n el.style.transformOrigin = '';\n}\n\n/**\n * DESIGN.md §2.5 — animates a slide-to-slide navigation via a temporary\n * \"ghost\": a clone of the outgoing `.shoji-slide-media`, positioned over\n * the real slot, playing the preset's `leave` keyframe while `swapContent`\n * (the real `SlideManager.render()` reassignment) runs invisibly underneath\n * it. The newly-swapped-in real active media then plays `enter`. Both\n * animate concurrently.\n *\n * Deliberately separate from the gesture engine's own live-drag/settle\n * animation (`GestureController.ts`, §2.4): `mode` is a discrete \"jump\" for\n * programmatic navigation, not layered onto a continuous drag — a completed\n * swipe always uses its own pool-shift regardless of `mode`. See\n * `Gallery.navigate()`'s `animate` flag.\n */\nexport class SlideTransition {\n constructor(\n private readonly slides: SlideManager,\n private readonly decorateLeave: (clonedMedia: HTMLElement) => () => void = () => () => {},\n ) {}\n\n /** A recognized built-in preset (`TRANSITION_PRESETS`). */\n animate(preset: TransitionPreset, direction: 1 | -1, swapContent: () => void): void {\n this.run(swapContent, (ghost, incoming) => {\n const leave = preset.leave(direction);\n applyLeave(ghost, leave.transform, leave.opacity);\n const enter = preset.enter(direction);\n applyEnter(incoming, enter.transform, enter.opacity);\n });\n }\n\n /** An unrecognized `mode` string: a host-supplied CSS class pair (`shoji-transition-<mode>-leave`/`-enter`), not an error — §2.5's \"custom animation = a CSS class pair, no JS needed.\" */\n animateCustom(mode: string, direction: 1 | -1, swapContent: () => void): void {\n const dirAttr = direction === 1 ? 'next' : 'prev';\n this.run(\n swapContent,\n (ghost, incoming) => {\n ghost.dataset.shojiDirection = dirAttr;\n ghost.classList.add(`shoji-transition-${mode}-leave`);\n incoming.dataset.shojiDirection = dirAttr;\n incoming.classList.add(`shoji-transition-${mode}-enter`);\n },\n (incoming) => {\n incoming.classList.remove(`shoji-transition-${mode}-enter`);\n delete incoming.dataset.shojiDirection;\n },\n );\n }\n\n private run(\n swapContent: () => void,\n kickOff: (ghost: HTMLElement, incoming: HTMLElement) => void,\n cleanupIncoming: (incoming: HTMLElement) => void = clearInlineTransform,\n ): void {\n if (prefersReducedMotion()) {\n swapContent();\n return;\n }\n const outgoing = this.slides.getActiveMedia();\n if (!outgoing) {\n swapContent();\n return;\n }\n\n const ghost = document.createElement('div');\n ghost.className = 'shoji-slide-ghost';\n const clonedMedia = ghost.appendChild(outgoing.cloneNode(true) as HTMLElement);\n this.slides.element.appendChild(ghost);\n // DESIGN.md §2.5/§4.5 — plugins with a per-slide visual override (e.g.\n // RotateFlip's rotate/flip, Zoom's scale/pan) freeze it onto the clone\n // here, before the reflow below commits it as the leave animation's\n // start — the real node was already reset by now, so the clone alone\n // wouldn't otherwise carry it. `settleLeave` (called after `kickOff`\n // below) is what starts each one transitioning back to neutral.\n const settleLeave = this.decorateLeave(clonedMedia);\n void ghost.offsetHeight; // commit the ghost's (and clone's) starting appearance before anything changes it\n\n swapContent();\n\n const incoming = this.slides.getActiveMedia();\n if (!incoming) {\n ghost.remove();\n return;\n }\n\n kickOff(ghost, incoming);\n settleLeave();\n waitForEnd(ghost, () => ghost.remove());\n waitForEnd(incoming, () => cleanupIncoming(incoming));\n }\n}\n","import {\n lockBodyScroll,\n unlockBodyScroll,\n markIntentionalScroll as markIntentionalScrollInternal,\n} from './bodyScrollLock';\nimport { EventBus, type Unsubscribe } from './EventBus';\nimport { buildLightboxDom, type LightboxDom } from './dom';\nimport { FocusTrap } from './FocusTrap';\nimport { GestureController, INTERACTIVE_CONTROL_SELECTOR } from './GestureController';\nimport { LiveRegion } from './LiveRegion';\nimport type { ButtonSpec, PluginContext, ShojiPlugin, VideoProviderRenderer } from './plugin';\nimport { DEFAULT_SELECTOR, resolveDynamicVideoItems, scanContainer } from './scan';\nimport { pauseMedia, SlideManager } from './SlideManager';\nimport type {\n DangerousHtmlCaption,\n GalleryEvents,\n GalleryItem,\n GalleryItemInput,\n GalleryOptions,\n} from './types';\nimport { TRANSITION_PRESETS } from '../transitions/presets';\nimport { SlideTransition } from '../transitions/SlideTransition';\nimport { zoomIn, zoomOut, type Box, type FrozenDragTransform } from './zoomTransition';\n\nfunction itemKey(item: GalleryItem | GalleryItemInput): string {\n return item.id ?? item.src;\n}\n\nfunction resolveElement(target: HTMLElement | string): HTMLElement {\n if (typeof target !== 'string') return target;\n const el = document.querySelector<HTMLElement>(target);\n if (!el) throw new Error(`Shoji: no element matches selector \"${target}\"`);\n return el;\n}\n\n/**\n * DESIGN.md §2.7 — lets code that never held a closure reference to a\n * gallery (a callback resolving long after the call site is gone, a\n * separate `<script>`, devtools) reach the live instance anyway, via\n * `Gallery.getInstance()`/`Gallery.instances()`. Two structures kept in\n * lockstep rather than one: the `WeakMap` gives O(1) lookup-by-element\n * without leaking (an entry is only reachable through an element the host\n * still holds a reference to itself), but WeakMaps aren't iterable, so\n * `instances()` needs the parallel `Set` too. The constructor adds to\n * both; `destroy()` removes from both.\n */\nconst instanceRegistry = new WeakMap<HTMLElement, Gallery>();\nconst allInstances = new Set<Gallery>();\n\n/** CLAUDE.md — all user-visible strings go through `locale`; these are the fallback defaults. */\nconst DEFAULT_LOCALE = {\n close: 'Close',\n previous: 'Previous image',\n next: 'Next image',\n showCaption: 'Show caption',\n hideCaption: 'Hide caption',\n fullCaption: 'Full caption', // DESIGN.md §2.3a\n moreControls: 'More controls', // DESIGN.md §3.1a\n};\n\n/**\n * A click that isn't on the image, a button, a video, or an overlay\n * (counter/caption) counts as \"clicked outside the content.\" Walks\n * `event.composedPath()` (captured at dispatch time) rather than\n * `event.target.closest(...)` — a click handler earlier in the same bubble\n * phase can synchronously replace the clicked element's subtree (e.g. a\n * toolbar button swapping its own icon via `innerHTML` in its click\n * handler), which detaches the original target from the document before\n * this listener (attached higher up, on `.shoji-outer`) ever runs;\n * `.closest()` on a detached node finds no ancestors and would wrongly\n * read as \"clicked outside,\" closing the gallery. `composedPath()` isn't\n * affected by DOM mutations that happen after dispatch.\n *\n * Provider video (YouTube/Vimeo): exclude only the actual iframe/mount\n * element, not the entire `.shoji-slide-provider-video` container. This\n * allows clicks on the blank space around the embed (sides, padding-top\n * toolbar inset) to close the gallery, matching image and HTML5 video\n * behaviour. Clicks that land inside the cross-origin iframe never bubble\n * to the parent at all, so no special handling is needed there; `iframe`\n * covers the edge case where the frame hasn't yet captured focus and a\n * click registers on the element itself from the parent-page perspective.\n * `.shoji-video-mount` is the Vimeo SDK wrapper; YouTube uses a bare\n * `<iframe>` directly inside `.shoji-slide-provider-video`.\n *\n * `caption` — a real bug, reported from real usage: `.shoji-caption--video`\n * (DESIGN.md §2.3a) is `pointer-events: none` so a click on it reaches the\n * video's own native controls underneath, which works fine when the video\n * fills enough of the slide to actually BE underneath it. A letterboxed\n * video (narrower or shorter than the dialog, so the caption's own\n * bottom-left position sits over plain `.shoji-slide-media` background\n * instead) has nothing there to click through *to* — the click fell all\n * the way through to a genuine backdrop click, closing the gallery on what\n * was meant as an interaction with the caption/video area, not \"click\n * outside to close.\" `pointer-events: none` is exactly what removes the\n * caption from `composedPath()` in the first place, so this can't be fixed\n * by adding `.shoji-caption` to the selector above (already there — it\n * already protects a normal, non-click-through caption on a photo slide)\n * — checked by coordinates instead, the one place in this function that\n * has to be.\n */\nfunction isBackdropClick(event: MouseEvent, caption: HTMLElement | null): boolean {\n const hitsProtectedElement = event\n .composedPath()\n .some(\n (node) =>\n node instanceof Element &&\n node.matches(\n `.shoji-slide-img, .shoji-video-mount, iframe, .shoji-counter, ${INTERACTIVE_CONTROL_SELECTOR}`,\n ),\n );\n if (hitsProtectedElement) return false;\n\n if (caption && !caption.hidden && caption.classList.contains('shoji-caption--video')) {\n const rect = caption.getBoundingClientRect();\n const withinCaption =\n event.clientX >= rect.left &&\n event.clientX <= rect.right &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom;\n if (withinCaption) return false;\n }\n\n return true;\n}\n\nfunction isDangerousHtmlCaption(value: unknown): value is DangerousHtmlCaption {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as DangerousHtmlCaption).dangerouslySetInnerHTML === 'string'\n );\n}\n\n/**\n * Core lifecycle (DESIGN.md §2.2), item model / DOM scanning (§2.1), and the\n * lightbox itself: pooled slides (§2.3), dialog semantics/focus trap/live\n * region (§2.6, non-optional), gestures (§2.4, via `GestureController`) and\n * slide-to-slide transitions (§2.5, via `SlideTransition`).\n */\nexport class Gallery {\n /** DESIGN.md §2.7 — the live instance mounted on `el`, or `undefined` if none exists there (or it's since been destroyed). */\n static getInstance(el: HTMLElement): Gallery | undefined {\n return instanceRegistry.get(el);\n }\n\n /** DESIGN.md §2.7 — every live instance, e.g. for page-wide teardown or devtools inspection. */\n static instances(): IterableIterator<Gallery> {\n return allInstances.values();\n }\n\n /** Not `readonly` — `reinit()` (§2.7) reassigns this + every option-derived field below; initializers here just satisfy strict-init. */\n options: GalleryOptions = {};\n readonly element: HTMLElement;\n\n private readonly bus = new EventBus<GalleryEvents>();\n private selector: string = DEFAULT_SELECTOR;\n private isDynamicMode = false;\n private preload = 1;\n private locale: typeof DEFAULT_LOCALE = DEFAULT_LOCALE;\n private showCounter = true;\n private captionVisibleOnVideo = false; // DESIGN.md §2.3a\n // DESIGN.md §2.5 — true from the moment transitionCaption()/open()'s own\n // fade-in starts hiding the caption until the midpoint (or, for open(),\n // the end) where content is swapped and it's revealed again. The async\n // image-load callback in renderCurrentSlide() checks this too, not just\n // the synchronous call in the same function — decode() resolves on a\n // microtask, which can beat the caption's own self-timed reveal for an\n // already-preloaded slide, and updating caption content the instant it\n // fires would show the *new* slide's caption fading, not the outgoing\n // one — same content-swap-timing bug either call site could cause alone.\n private captionFadePending = false;\n private loop = true;\n private closable = true;\n private autoHideDelay: number | false = 5000;\n /** DESIGN.md §3.1a — GalleryOptions.maxPinnedToolbarButtons; see measureToolbarOverflow(). */\n private maxPinnedToolbarButtons = 2;\n private readonly focusTrap = new FocusTrap();\n private readonly liveRegion = new LiveRegion();\n private autoHideTimer: ReturnType<typeof setTimeout> | null = null;\n private autoHidden = false;\n /**\n * Every control `wireControlHover()` has ever wired — the full candidate\n * list `reconcileHover()` (below) checks `:hover` against, kept separate\n * from `hoveringElements` (elements *believed* to be hovered) so\n * reconciliation can also *add* one currently missing from that set, not\n * just remove a stale one.\n */\n private readonly hoverableElements = new Set<HTMLElement>();\n /**\n * The subset of `hoverableElements` the pointer is currently considered\n * to be over — a `Set`, not a plain incrementing counter, so\n * `onActivity()` (below) can reconcile it against the browser's own live\n * `:hover` ground truth on every real pointer movement, self-healing from\n * a `pointerenter`/`pointerleave` pair that never fired at all. Two real\n * bugs, both reported from real usage, both variations on the same\n * browser behavior already leveraged elsewhere in this file (`hidden`\n * doesn't fire `pointerleave` under a stationary cursor, §2.3a): (1) a\n * control that synchronously replaces its own children while the pointer\n * sits stationary over it (Autoplay's own play/pause icon swap) can\n * desync the browser's internal hover-chain tracking badly enough that\n * the *next* real pointer movement away from it never fires `pointerleave`\n * — a plain counter has no way to detect a leave that never reports\n * itself. (2) the mirror image: a control that *appears* under an\n * already-stationary cursor (the common case right after `open()` —\n * whatever the viewer clicked to get here is often right where a\n * toolbar/caption/nav control ends up) never gets a `pointerenter`\n * either, since browsers only recompute hover state on actual pointer\n * movement, not on an element materializing under one already sitting\n * still — so idle auto-hide could fire and hide a control the viewer's\n * cursor is, visibly, still resting directly on top of. Re-deriving \"is\n * this actually hovered\" fresh from the browser on every real pointer\n * move fixes both directions at once, since neither depends on any\n * event having fired correctly in the first place.\n */\n private readonly hoveringElements = new Set<HTMLElement>();\n private isClosing = false;\n /** True while a vertical drag has hidden controls past its own distance threshold (`setControlsHiddenForDrag`) — `onActivity()` defers to it, since the drag's own continuous pointermove stream would otherwise immediately re-reveal what it just hid on every single move. */\n private controlsHiddenByDrag = false;\n private itemList: GalleryItem[] = [];\n private scannedElements: HTMLElement[] = [];\n private activeIndex = 0;\n private opened = false;\n private destroyed = false;\n private slides: SlideManager | null = null;\n private dom: LightboxDom | null = null;\n private gesture: GestureController | null = null;\n private transition: SlideTransition | null = null;\n /** DESIGN.md §2.3a — measures `.shoji-toolbar`'s real rendered height (it can wrap to multiple rows on a narrow viewport with many toolbar buttons registered) so the caption's own height cap can reserve exactly that much space, not a fixed single-row guess. */\n private toolbarHeightObserver: ResizeObserver | null = null;\n private toolbarHeightFrame: number | null = null;\n private captionTruncationFrame: number | null = null;\n /** DESIGN.md §2.3a — a truncated caption's own click/Enter/Space target opens this; also gates `GestureController`'s `isZoomed` (alongside the real zoom gate) so a drag over the open modal can't also navigate/close the lightbox underneath it. */\n private captionModalOpen = false;\n private captionModalReturnFocus: HTMLElement | null = null;\n /**\n * DESIGN.md §2.3a — every real path into `openCaptionModal()` starts from\n * a click *or* a keydown on the caption, so `captionModalReturnFocus`\n * above is always the caption itself either way; this instead\n * distinguishes *how* it got there, so `closeCaptionModal()` only\n * actually calls `.focus()` for the keyboard path (a real Tab+Enter user,\n * where restoring focus continues their tab sequence correctly) and\n * leaves it alone for a mouse click (where the resulting focus was\n * purely incidental — nothing about clicking to read a caption means the\n * *next* keypress, e.g. a plugin's own Space shortcut, should still\n * silently target it).\n */\n private captionModalOpenedViaKeyboard = false;\n /**\n * DESIGN.md §3.1a — every `ctx.ui.toolbar()`-registered button, in\n * registration order, alongside the slot it was registered into (so a\n * collapsed one can be restored to the right place, not just anywhere).\n * Registration order is what decides overflow priority: up to\n * `maxPinnedToolbarButtons` stay pinned, the rest collapse into the\n * popover before them, latest-registered first — see\n * `measureToolbarOverflow()`.\n */\n private readonly pluginToolbarButtons: Array<{\n el: HTMLElement;\n slot: 'left' | 'center' | 'right';\n }> = [];\n private toolbarOverflowOpen = false;\n private toolbarOverflowReturnFocus: HTMLElement | null = null;\n private readonly shortcuts = new Map<string, (e: KeyboardEvent) => void>();\n private readonly pluginStorage = new Map<string, unknown>();\n /** Backs `getActivePlugins()`. */\n private readonly activePluginNames = new Set<string>();\n private readonly videoProviders = new Map<string, VideoProviderRenderer>();\n private zoomGate: (() => boolean) | null = null;\n /** DESIGN.md §2.6a/§4.6 — the zoomed `<img>`'s own real on-screen rect, read by `beginClose()` before `beforeClose` fires (see `registerZoomStartProvider()`), so a button-close continues the zoom-out from wherever the viewer was actually zoomed/panned to instead of snapping back to neutral first. */\n private zoomStartProvider: (() => Box | null) | null = null;\n /** DESIGN.md §2.5/§4.5 — plugins with a per-slide visual override (RotateFlip's rotate/flip, Zoom's scale/pan) that reset unanimated on `beforeSlide` (must clear before `SlideManager.render()` reparents the outgoing node). Multi-slot: more than one can be active on the same slide, each targeting a different part of the clone, so they don't conflict. See `registerSlideLeaveDecorator()`. */\n private readonly slideLeaveDecorators = new Set<\n (clonedMedia: HTMLElement) => (() => void) | void\n >();\n private pluginCleanups: Array<() => void> = [];\n\n private readonly onContainerClick = (event: MouseEvent): void => {\n let node = event.target as Node | null;\n while (node && node !== this.element) {\n if (node instanceof HTMLElement) {\n const index = this.scannedElements.indexOf(node);\n if (index !== -1) {\n event.preventDefault();\n this.open(index);\n return;\n }\n }\n node = node.parentNode;\n }\n };\n\n private readonly onOuterClick = (event: MouseEvent): void => {\n if (this.closable && isBackdropClick(event, this.dom?.caption ?? null)) this.close();\n };\n\n /**\n * DESIGN.md §2.8 — any interaction re-shows controls, restarts the idle\n * clock. `autoHideDelay: 0` = \"never show controls\" — a no-op here.\n * `autoHideDelay: false` = \"always visible\" — also a no-op: nothing to\n * reveal (already shown) or reschedule (no timer ever runs). Also a no-op\n * once `isClosing` — a real bug, reported from real usage: moving the\n * mouse during close()'s own controls-fade-then-zoom-out sequence (§2.6a)\n * re-showed the just-hidden controls mid-animation, since these listeners\n * stay wired for the whole close sequence. Same reasoning for\n * `controlsHiddenByDrag` (§2.4/§2.8): a vertical drag's own `pointermove`\n * stream would otherwise re-reveal what it just hid, every single frame.\n */\n private readonly onActivity = (): void => {\n this.reconcileHover();\n if (\n this.autoHideDelay === 0 ||\n this.autoHideDelay === false ||\n this.isClosing ||\n this.controlsHiddenByDrag ||\n // DESIGN.md §2.3a — requested directly: mouse movement/interaction\n // over the open caption modal shouldn't re-reveal controls already\n // hidden behind it — `dom.outer`'s own pointermove/pointerdown/etc.\n // listeners (below) still see it bubble through, same as any other\n // activity, so without this an idle-hidden toolbar would pop back\n // the instant the viewer so much as moved the mouse to read.\n this.captionModalOpen\n )\n return;\n this.showControls();\n this.scheduleAutoHide();\n };\n\n /** x */\n private controlsHiddenAtGestureStart = false;\n private readonly captureGestureStartState = (): void => {\n this.controlsHiddenAtGestureStart = this.autoHidden;\n };\n\n private readonly onKeydown = (event: KeyboardEvent): void => {\n // A focused <video>'s native controls own arrow/space/home/end for\n // seeking, volume, and play/pause — don't let slide navigation hijack\n // those while the viewer is actually interacting with the video. Escape\n // still closes the gallery regardless.\n if (document.activeElement instanceof HTMLVideoElement && event.key !== 'Escape') return;\n\n this.onActivity();\n switch (event.key) {\n case 'Escape':\n if (this.closable) this.close();\n break;\n case 'ArrowLeft':\n case 'a':\n case 'A':\n this.prev();\n break;\n case 'ArrowRight':\n case 'd':\n case 'D':\n this.next();\n break;\n case 'Home':\n this.goTo(0);\n break;\n case 'End':\n this.goTo(this.itemList.length - 1);\n break;\n default: {\n // DESIGN.md §3 — ctx.ui.registerShortcut(); unhandled keys still\n // fall through with no preventDefault, same as before plugins existed.\n const shortcut = this.shortcuts.get(event.key);\n if (!shortcut) return;\n shortcut(event);\n }\n }\n event.preventDefault();\n };\n\n /**\n * DESIGN.md §2.3a — capture phase, added only while the caption modal is\n * open (not from `open()` onward like `onKeydown`, which is bubble\n * phase): capture always finishes before bubble starts, so\n * `stopPropagation()` here reliably beats `onKeydown`'s own bubble-phase\n * handling regardless of where in the dialog focus happens to be. A real\n * bug, reported from real usage: an earlier version of this only special-\n * cased `Escape`, leaving every other key (`Space` — Autoplay's own\n * play/pause shortcut if that plugin's loaded, arrow keys, `w`/`s` for\n * Zoom, any plugin-registered shortcut) to fall straight through to\n * `onKeydown` while the modal sat open on screen. A modal dialog should\n * make the background fully inert to keyboard input while it's open, not\n * just for one key — so this now stops propagation for *every* key\n * unconditionally, closing the modal as the one piece of extra behavior\n * layered on top for `Escape` specifically. Deliberately no\n * `preventDefault()` here — the modal's own contents (the close button,\n * a scrollable panel) keep their normal native key behavior (Space\n * activating a focused button, arrow/Space scrolling), only the\n * *background* gallery is what this isolates it from.\n */\n private readonly onCaptionModalKeydown = (event: KeyboardEvent): void => {\n event.stopPropagation();\n if (event.key === 'Escape') this.closeCaptionModal();\n };\n\n constructor(target: HTMLElement | string, options: GalleryOptions = {}) {\n this.element = resolveElement(target);\n instanceRegistry.set(this.element, this);\n allInstances.add(this);\n this.applyOptions(options);\n }\n\n /** Everything the constructor does after `this.element` is resolved — shared with `reinit()` (§2.7). */\n private applyOptions(options: GalleryOptions): void {\n this.options = options;\n this.selector = options.selector ?? DEFAULT_SELECTOR;\n this.isDynamicMode = options.items !== undefined;\n this.preload = options.preload ?? 1;\n this.locale = { ...DEFAULT_LOCALE, ...options.locale };\n this.showCounter = options.counter ?? true;\n this.loop = options.loop ?? true;\n this.closable = options.closable ?? true;\n this.autoHideDelay = options.autoHideDelay ?? 5000;\n this.maxPinnedToolbarButtons = options.maxPinnedToolbarButtons ?? 2;\n // Reset explicitly — a reinit() call must not inherit these from before.\n this.activeIndex = 0;\n this.scannedElements = [];\n\n if (this.isDynamicMode) {\n this.itemList = resolveDynamicVideoItems(options.items ?? []);\n } else {\n const scanned = scanContainer(this.element, this.selector);\n this.itemList = scanned.map((s) => s.item);\n this.scannedElements = scanned.map((s) => s.element);\n this.element.addEventListener('click', this.onContainerClick);\n }\n\n // DESIGN.md §3.1 — plugins init here, at construction, not lazily on\n // first open(): a layout plugin needs to render the *inline* container\n // (this.element, always available) before open() is ever called — it's\n // what the viewer clicks to open in the first place. ensureLightbox()'s\n // `if (this.dom) return;` guard makes the later, harmless no-op call\n // from open() safe; building the (hidden, display:none until opened)\n // lightbox DOM this early costs one inert subtree per instance, which is\n // negligible next to the thumbnail images already loading regardless.\n this.ensureLightbox();\n // Set after ensureLightbox() (not inside it) so a reinit() with a\n // different `closable` value updates the already-built button too —\n // ensureLightbox() only builds the DOM once (`if (this.dom) return;`).\n this.dom!.closeButton.hidden = !this.closable;\n\n // Default is closed — the host clicks a thumbnail or calls open()\n // itself. openOnInit is the explicit, opt-in exception (deep-link-style\n // integrations); guarded on having at least one item so an empty\n // gallery can't \"open\" onto nothing.\n if (options.openOnInit && this.itemList.length > 0) {\n this.open(options.index ?? 0);\n }\n }\n\n get items(): readonly GalleryItem[] {\n return this.itemList;\n }\n\n get currentIndex(): number {\n return this.activeIndex;\n }\n\n /** True from the first `open()` until `close()`/`destroy()`. */\n get isOpen(): boolean {\n return this.opened;\n }\n\n /** True once `destroy()` has run. */\n get isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /** Whether auto-hide (§2.8) currently has controls faded. */\n get controlsHidden(): boolean {\n return this.autoHidden;\n }\n\n /** Names of plugins that actually initialized. */\n getActivePlugins(): string[] {\n return [...this.activePluginNames];\n }\n\n /** The active slide's `.shoji-slide-media` container. Empty before the first `open()`; `null` only after `destroy()`. */\n getActiveMedia(): HTMLElement | null {\n return this.slides?.getActiveMedia() ?? null;\n }\n\n /** DESIGN.md §4-zoom — suspends drag-to-navigate/close while zoomed. Single slot, not a multi-subscriber event. */\n registerZoomGate(isZoomed: () => boolean): () => void {\n this.zoomGate = isZoomed;\n return () => {\n if (this.zoomGate === isZoomed) this.zoomGate = null;\n };\n }\n\n /** DESIGN.md §2.6a/§4.6 — returns the zoomed image's current on-screen rect (`getBoundingClientRect()`), or `null` when not zoomed. Single slot, same pattern as `registerZoomGate` above. */\n registerZoomStartProvider(provider: () => Box | null): () => void {\n this.zoomStartProvider = provider;\n return () => {\n if (this.zoomStartProvider === provider) this.zoomStartProvider = null;\n };\n }\n\n /**\n * DESIGN.md §2.5/§4.5 — called once per navigation with the leave-\n * ghost's clone, right after `SlideTransition` creates it. Freeze\n * whatever per-slide visual state is about to be reset onto the clone\n * (or a descendant, e.g. Zoom's own `<img>`) and return a `() => void`\n * to trigger the transition back to neutral once committed — or return\n * nothing if there's nothing to animate away this time.\n */\n registerSlideLeaveDecorator(\n decorator: (clonedMedia: HTMLElement) => (() => void) | void,\n ): () => void {\n this.slideLeaveDecorators.add(decorator);\n return () => {\n this.slideLeaveDecorators.delete(decorator);\n };\n }\n\n on<K extends keyof GalleryEvents>(event: K, fn: (detail: GalleryEvents[K]) => void): Unsubscribe {\n return this.bus.on(event, fn);\n }\n\n private clampToRange(index: number): number {\n return Math.min(Math.max(index, 0), Math.max(this.itemList.length - 1, 0));\n }\n\n private ensureLightbox(): void {\n if (this.dom) return;\n this.slides = new SlideManager({\n preload: this.preload,\n videoProviders: this.videoProviders,\n });\n this.transition = new SlideTransition(this.slides, (clonedMedia) => {\n const settlers: Array<() => void> = [];\n for (const decorate of this.slideLeaveDecorators) {\n const settle = decorate(clonedMedia);\n if (settle) settlers.push(settle);\n }\n return () => {\n for (const settle of settlers) settle();\n };\n });\n const dom = buildLightboxDom(this.slides.element, this.locale);\n this.dom = dom;\n if (this.options.backdropOpacity != null) {\n const clamped = Math.min(Math.max(this.options.backdropOpacity, 0), 1);\n dom.outer.style.setProperty('--shoji-backdrop-opacity', String(clamped));\n }\n if (this.options.transitionDuration != null) {\n const clamped = Math.max(this.options.transitionDuration, 0);\n dom.outer.style.setProperty('--shoji-duration', `${clamped}ms`);\n }\n // DESIGN.md §2.8 — autoHideDelay: 0 means Shoji's own controls stay\n // permanently invisible (a host building fully custom chrome), not that\n // the whole gallery should behave like nothing is there — the mouse\n // cursor itself should still behave normally, not force-hidden along\n // with controls that were never meant to be seen in the first place.\n // Requested directly; `.shoji-cursor-visible` overrides the\n // `.shoji-controls-hidden` cursor:none rule via higher specificity.\n if (this.autoHideDelay === 0) dom.dialog.classList.add('shoji-cursor-visible');\n dom.outer.appendChild(this.liveRegion.element);\n dom.closeButton.addEventListener('click', () => this.close());\n dom.prevButton.addEventListener('click', () => this.prev());\n dom.nextButton.addEventListener('click', () => this.next());\n dom.captionToggleButton.addEventListener('click', () => {\n this.captionVisibleOnVideo = !this.captionVisibleOnVideo;\n this.updateCaptionVisibility();\n });\n dom.caption.addEventListener('click', this.onCaptionActivate);\n dom.caption.addEventListener('keydown', this.onCaptionActivate);\n dom.captionModalCloseButton.addEventListener('click', () => this.closeCaptionModal());\n // Closes on a genuine backdrop click (the modal element itself, not a\n // descendant) — always stops propagation regardless, since without it\n // *any* click anywhere inside the modal (the panel, its content, even\n // the close button) would keep bubbling up to onOuterClick below and\n // get misread as \"clicked outside the real content,\" closing the whole\n // lightbox out from under it.\n dom.captionModal.addEventListener('click', (event) => {\n event.stopPropagation();\n if (event.target === dom.captionModal) this.closeCaptionModal();\n });\n dom.toolbarOverflowButton.addEventListener('click', (event) => {\n event.stopPropagation();\n this.toggleToolbarOverflow();\n });\n // Closes on any click outside the panel and off the caret itself —\n // registered ahead of onOuterClick below (same-node listeners run in\n // registration order) so it can stop the click there too, the same\n // reasoning the caption modal's own backdrop-click listener above uses:\n // without it, a click that closes the popover would also keep bubbling\n // and get misread by onOuterClick as \"clicked outside the real\n // content,\" closing the whole lightbox in the same click.\n dom.outer.addEventListener('click', (event) => {\n if (!this.toolbarOverflowOpen) return;\n // event.composedPath(), not event.target — a real bug, found testing\n // this against Autoplay's own play/pause button (icon-swap-on-click,\n // same class of button CLAUDE.md/DESIGN.md §2.8 already documents):\n // if the click's own handler replaces the button's innerHTML\n // synchronously (as that pattern does), `event.target` can already be\n // a now-detached node by the time this bubble-phase listener runs —\n // `.contains(target)` then reads false even though the click\n // genuinely originated inside the panel, and the popover (wrongly)\n // closes out from under the very button that was just clicked.\n // composedPath() is captured at dispatch time, before any such\n // mutation, so it stays accurate regardless.\n const insidePanel = event\n .composedPath()\n .some((node) => node === dom.toolbarOverflowPanel || node === dom.toolbarOverflowButton);\n if (insidePanel) return;\n event.stopPropagation();\n this.closeToolbarOverflow();\n });\n dom.outer.addEventListener('click', this.onOuterClick);\n dom.outer.addEventListener('pointermove', this.onActivity, { passive: true });\n // Registered before onActivity's own pointerdown listener — order matters, see captureGestureStartState's doc comment.\n dom.outer.addEventListener('pointerdown', this.captureGestureStartState, { passive: true });\n dom.outer.addEventListener('pointerdown', this.onActivity, { passive: true });\n dom.outer.addEventListener('touchstart', this.onActivity, { passive: true });\n dom.outer.addEventListener('wheel', this.onActivity, { passive: true });\n dom.outer.addEventListener('focusin', this.onActivity);\n dom.outer.addEventListener('focusout', () => this.scheduleAutoHide());\n\n // Hovering pauses auto-hide (pointermove alone wouldn't catch a still\n // mouse) — every part of the overlay, not just individual buttons\n // (toolbarLeft/Center/Right cover the bar's own padding/gaps too, not\n // just the buttons already nested inside them). Plugin toolbar\n // buttons/overlays get this wiring at their own call sites.\n for (const el of [\n dom.closeButton,\n dom.prevButton,\n dom.nextButton,\n dom.captionToggleButton,\n dom.caption,\n dom.captionModalPanel,\n dom.counter,\n dom.toolbarLeft,\n dom.toolbarCenter,\n dom.toolbarRight,\n ]) {\n this.wireControlHover(el);\n }\n\n document.body.appendChild(dom.outer);\n\n // DESIGN.md §2.3a — a fixed single-row assumption undercounted a busy\n // toolbar (many plugins registering buttons) wrapping to multiple rows\n // on a narrow viewport, letting the caption's own height cap grow up\n // over the real controls instead of stopping below them. Measuring the\n // real rendered height instead of guessing is correct regardless of\n // plugin count or viewport width. rAF-batched, same pattern the Layout\n // plugin's own resize handling already uses (CLAUDE.md: batch DOM\n // writes that can thrash layout).\n this.toolbarHeightObserver = new ResizeObserver(() => this.scheduleToolbarOverflowMeasure());\n this.toolbarHeightObserver.observe(dom.toolbar);\n\n // DESIGN.md §2.4 — attached to the whole dialog (not just .shoji-slides)\n // so vertical swipe-to-close works from anywhere in it, not only over\n // the image; shouldIgnoreGesture() excludes real controls so their\n // native click/touch behavior is unaffected.\n this.gesture = new GestureController(\n {\n dialog: dom.dialog,\n caption: dom.caption,\n slides: this.slides,\n canGoNext: () => this.loop || this.activeIndex < this.itemList.length - 1,\n canGoPrev: () => this.loop || this.activeIndex > 0,\n // animate:false — a completed swipe already played its own\n // live-drag/settle animation (§2.4); running the §2.5 `mode`\n // transition on top would double-animate. See navigate()'s doc.\n next: () => this.navigate(this.nextIndex(), 1, false),\n prev: () => this.navigate(this.prevIndex(), -1, false),\n close: () => this.close(),\n closeFromSwipe: (frozenDrag) => this.closeFromSwipe(frozenDrag),\n setControlsHiddenForDrag: (hidden) => this.setControlsHiddenForDrag(hidden),\n canClose: () => this.closable,\n onActivity: () => this.onActivity(),\n // DESIGN.md §2.3a — also suspends drag-to-navigate/close while the\n // caption modal is open, same mechanism the Zoom plugin's own gate\n // already uses, so a drag starting over the modal can't also\n // navigate/close the lightbox underneath it.\n isZoomed: () =>\n (this.zoomGate?.() ?? false) || this.captionModalOpen || this.toolbarOverflowOpen,\n },\n {\n onTap: (x, y) =>\n this.bus.emit('tap', {\n x,\n y,\n controlsWereHidden: this.controlsHiddenAtGestureStart,\n }),\n onDoubleTap: (x, y) => this.bus.emit('doubleTap', { x, y }),\n onPinchStart: (centerX, centerY) => this.bus.emit('pinchStart', { centerX, centerY }),\n onPinchMove: (scale, centerX, centerY) =>\n this.bus.emit('pinchMove', { scale, centerX, centerY }),\n onPinchEnd: () => this.bus.emit('pinchEnd', {}),\n onWheelZoom: (deltaScale, x, y) => this.bus.emit('wheelZoom', { deltaScale, x, y }),\n },\n this.options.gestures,\n );\n\n this.initPlugins();\n }\n\n /**\n * DESIGN.md §3 — which of `declared`'s plugins will actually load,\n * resolved as a fixed point rather than a single pass: start with every\n * *structurally* valid entry (a real object with an `init` function),\n * then repeatedly drop any whose `requires` points at a name no longer\n * in the set, until a full pass drops nothing. That repetition is what\n * makes a chain cascade correctly — if a plugin gets dropped because\n * *its* own requirement failed, anything requiring that plugin drops on\n * the very next pass, the same as if the original problem were its own.\n * A genuine mutual requirement (A needs B, B needs A, both otherwise\n * fine) never gets caught in this — each still finds the other present\n * whenever it's checked, so both stay valid. That's correct, not a\n * missed case: this only ever decides *whether* something loads, never\n * *when* — nothing here reorders execution, so two plugins depending on\n * each other creates no actual ordering conflict to detect in the first\n * place.\n */\n private resolveValidPluginNames(declared: readonly ShojiPlugin[]): Set<string> {\n const validNames = new Set<string>();\n for (const plugin of declared) {\n if (plugin && typeof plugin.init === 'function') validNames.add(plugin.name);\n }\n let changed = true;\n while (changed) {\n changed = false;\n for (const plugin of declared) {\n if (!plugin || typeof plugin.init !== 'function' || !validNames.has(plugin.name)) continue;\n const unmet = (plugin.requires ?? []).some((name) => !validNames.has(name));\n if (unmet) {\n validNames.delete(plugin.name);\n changed = true;\n }\n }\n }\n return validNames;\n }\n\n /**\n * DESIGN.md §3 — plugins init here, not the constructor. `requires` is\n * resolved against the *whole* declared `plugins` list up front, not\n * registration order — a real friction point, reported directly: a host\n * with a `requires` chain had to carefully order the array by hand, with\n * no actual reason to (nothing about *execution* order needs to match\n * declaration order for a name-presence check). `resolveValidPluginNames()`\n * decides who's actually going to load, independent of position; this\n * loop still runs — and every `ctx.ui.toolbar()` registration still\n * lands — in exactly the array's own order regardless, so toolbar/\n * collapse-priority order (also array-order-driven, DESIGN.md §3.1a)\n * is completely unaffected by this. Cleared up front so a `reinit()`\n * doesn't inherit names from before.\n */\n private initPlugins(): void {\n this.activePluginNames.clear();\n this.videoProviders.clear();\n const declared = this.options.plugins ?? [];\n const validNames = this.resolveValidPluginNames(declared);\n\n for (const plugin of declared) {\n // Guards a real, easy-to-hit host mistake: `plugins: [Shoji.SomePlugin]`\n // silently becomes `plugins: [undefined]` if the referenced static\n // (e.g. Shoji.Autoplay) doesn't actually exist yet — a stale dist\n // build predating that plugin's addition is the most common cause.\n // One bad entry shouldn't crash plugin init for every entry after it.\n if (!plugin || typeof plugin.init !== 'function') {\n console.error(\n 'Shoji: skipping an invalid plugins[] entry (not a ShojiPlugin object):',\n plugin,\n );\n continue;\n }\n if (!validNames.has(plugin.name)) {\n const missing = (plugin.requires ?? []).filter((name) => !validNames.has(name));\n console.error(\n `Shoji: plugin \"${plugin.name}\" requires [${missing.join(', ')}], which failed to load (missing, invalid, or itself had an unmet requires) — skipping.`,\n );\n continue;\n }\n\n const pluginOptions: Record<string, unknown> = {\n ...plugin.defaults,\n ...(this.options[plugin.name] as Record<string, unknown> | undefined),\n };\n const ctx: PluginContext = {\n gallery: this,\n options: pluginOptions,\n on: this.on.bind(this),\n emit: (event, detail) => this.bus.emit(event, detail),\n ui: {\n toolbar: (slot, el) => this.pluginToolbar(slot, el),\n overlay: (el, layer) => this.pluginOverlay(el, layer),\n outer: () => this.dom!.outer,\n registerShortcut: (key, fn) => {\n this.shortcuts.set(key, fn);\n return () => this.shortcuts.delete(key);\n },\n registerVideoProvider: (name, render) => {\n this.videoProviders.set(name, render);\n return () => {\n if (this.videoProviders.get(name) === render) this.videoProviders.delete(name);\n };\n },\n },\n storage: {\n get: (key) => this.pluginStorage.get(key),\n set: (key, value) => {\n this.pluginStorage.set(key, value);\n },\n },\n };\n\n const cleanup = plugin.init(ctx);\n if (typeof cleanup === 'function') this.pluginCleanups.push(cleanup);\n this.activePluginNames.add(plugin.name);\n }\n }\n\n /**\n * DESIGN.md §3.1 — 'right' inserts immediately before the overflow caret\n * (DESIGN.md §3.1a — never after, and never after close either), so\n * close stays fixed absolute-rightmost, the caret sits just to its left,\n * and plugins cluster further left still, in registration order:\n * `plugins: [A, B, C]` reads A, B, C, caret, close. 'left'/'center' are\n * independent zones for a plugin that doesn't want to sit next to close.\n */\n private pluginToolbar(\n slot: 'left' | 'center' | 'right',\n el: HTMLElement | ButtonSpec,\n ): Unsubscribe {\n const dom = this.dom!;\n // buildToolbarButton() below already wires hover for ButtonSpec; a raw\n // element needs it here instead, once, not double-wired either way.\n const isRawElement = el instanceof HTMLElement;\n const node = isRawElement ? el : this.buildToolbarButton(el);\n const unhover = isRawElement ? this.wireControlHover(node) : null;\n if (slot === 'right') {\n dom.toolbarRight.insertBefore(node, dom.toolbarOverflowButton);\n } else {\n (slot === 'left' ? dom.toolbarLeft : dom.toolbarCenter).appendChild(node);\n }\n this.pluginToolbarButtons.push({ el: node, slot });\n this.scheduleToolbarOverflowMeasure();\n return () => {\n unhover?.();\n node.remove();\n const index = this.pluginToolbarButtons.findIndex((b) => b.el === node);\n if (index !== -1) this.pluginToolbarButtons.splice(index, 1);\n this.scheduleToolbarOverflowMeasure();\n };\n }\n\n private buildToolbarButton(spec: ButtonSpec): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n if (spec.icon) {\n button.ariaLabel = button.title = spec.label;\n button.innerHTML = spec.icon;\n } else {\n button.textContent = spec.label;\n }\n button.addEventListener('click', spec.onClick);\n this.wireControlHover(button);\n return button;\n }\n\n /**\n * DESIGN.md §3.1a — coalesces both toolbar-overflow measurement and the\n * pre-existing `--shoji-toolbar-height` update into one rAF-batched pass\n * (CLAUDE.md: batch DOM writes that can thrash layout), triggered by the\n * toolbar's own `ResizeObserver` (width *or* height changes — a busy\n * toolbar wrapping counts as both) and by `pluginToolbar()` registering\n * or unregistering a button. Order matters: overflow collapse has to run\n * *before* the height read, so the height custom property reflects the\n * settled (ideally single-row, post-collapse) toolbar, not a momentarily\n * wrapped one the caption's own height cap would otherwise over-reserve\n * space for.\n */\n private scheduleToolbarOverflowMeasure(): void {\n if (this.toolbarHeightFrame !== null) return;\n this.toolbarHeightFrame = requestAnimationFrame(() => {\n this.toolbarHeightFrame = null;\n if (!this.dom) return;\n this.measureToolbarOverflow();\n this.dom.dialog.style.setProperty(\n '--shoji-toolbar-height',\n `${this.dom.toolbar.getBoundingClientRect().height}px`,\n );\n });\n }\n\n /**\n * DESIGN.md §3.1a — collapses plugin toolbar buttons into\n * `toolbarOverflowPanel` once they don't fit in one row, instead of\n * letting the toolbar wrap to a second/third one. Always restores every\n * plugin button to its own original slot first and recomputes from that\n * clean slate, rather than incrementally adjusting whatever the previous\n * pass left behind — the *set* of buttons and the viewport width can\n * both have changed since then, and a fresh, deterministic pass is both\n * simpler and self-correcting than trying to reason about a delta.\n *\n * \"Fits in one row\" is measured, not assumed: each slot's own rendered\n * height is compared against `closeButton`'s (always exactly one row\n * tall, always present) — a slot has wrapped if it's taller than that,\n * regardless of *which* slot a plugin happened to register into (the\n * three slots wrap independently, DESIGN.md §3.1a's own CSS notes).\n *\n * Collapses latest-registered first (DESIGN.md §3's own registration-\n * order-is-priority convention — `plugins: [A, B, C]` keeps A pinned\n * before B/C). `maxPinnedToolbarButtons` (default 2, see\n * `GalleryOptions.maxPinnedToolbarButtons`) is a ceiling, not a\n * guarantee: collapsing always goes down to at most that many pinned,\n * but keeps going *below* it — down to zero if it must — whenever even\n * that many still leaves a slot wrapped. `closeButton` and the counter\n * (`toolbarLeft`) must never wrap onto their own line, and `fitsOneRow()`\n * already checks every slot's height, not just `toolbarRight`'s, so a\n * wide counter or other left-slot content competing for the same row\n * pushes the pinned count down too, not just the right slot's own\n * button count. `closeButton`/`toolbarOverflowButton` themselves are\n * never candidates for collapse — everything else relocates into the\n * popover, which renders directly below that row.\n */\n private measureToolbarOverflow(): void {\n if (!this.dom) return;\n const dom = this.dom;\n for (const { el, slot } of this.pluginToolbarButtons) {\n if (slot === 'right') dom.toolbarRight.insertBefore(el, dom.toolbarOverflowButton);\n else (slot === 'left' ? dom.toolbarLeft : dom.toolbarCenter).appendChild(el);\n }\n dom.toolbarOverflowPanel.replaceChildren();\n dom.toolbarOverflowButton.hidden = true;\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n\n const rowHeight = dom.closeButton.getBoundingClientRect().height;\n const fitsOneRow = (): boolean =>\n [dom.toolbarLeft, dom.toolbarCenter, dom.toolbarRight].every(\n (slotEl) => slotEl.getBoundingClientRect().height <= rowHeight + 1,\n );\n\n if (fitsOneRow()) return;\n\n const pinnedCeiling = Math.min(this.maxPinnedToolbarButtons, this.pluginToolbarButtons.length);\n dom.toolbarOverflowButton.hidden = false;\n for (let i = this.pluginToolbarButtons.length - 1; i >= 0; i--) {\n // Below the ceiling, stop as soon as it fits; at/above it, keep\n // collapsing regardless of fit — the ceiling is enforced first, then\n // fit is what decides whether to go further still.\n if (i < pinnedCeiling && fitsOneRow()) break;\n // Collapsed latest-registered first (the decision above), but\n // inserted at the *front* of the panel each time — the panel should\n // read in the same left-to-right registration order the toolbar row\n // itself would have shown, not reversed just because that's the order\n // they were evaluated in.\n dom.toolbarOverflowPanel.insertBefore(\n this.pluginToolbarButtons[i]!.el,\n dom.toolbarOverflowPanel.firstChild,\n );\n }\n }\n\n private readonly onToolbarOverflowKeydown = (event: KeyboardEvent): void => {\n event.stopPropagation();\n if (event.key === 'Escape') this.closeToolbarOverflow();\n };\n\n private toggleToolbarOverflow(): void {\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n else this.openToolbarOverflow();\n }\n\n private openToolbarOverflow(): void {\n if (!this.dom || this.toolbarOverflowOpen) return;\n this.toolbarOverflowReturnFocus = document.activeElement as HTMLElement | null;\n this.dom.toolbarOverflowPanel.hidden = false;\n this.positionToolbarOverflowPanel();\n this.dom.toolbarOverflowButton.setAttribute('aria-expanded', 'true');\n this.toolbarOverflowOpen = true;\n this.focusTrap.retarget(this.dom.toolbarOverflowPanel);\n document.addEventListener('keydown', this.onToolbarOverflowKeydown, true);\n }\n\n /**\n * DESIGN.md §3.1a — the panel's `right` offset is set here, per open,\n * rather than as a fixed CSS value: the caret's own x-position isn't\n * fixed, it shifts with how many buttons are pinned ahead of it\n * (`maxPinnedToolbarButtons` is host-configurable, and can itself be\n * reduced further at measure time, DESIGN.md §3.1a), so a static\n * `right: var(--shoji-spacing-md)` only happened to line up with the\n * caret at one particular pinned-button count and viewport width. It\n * otherwise anchored to the toolbar/dialog's own right edge — under\n * `closeButton`, which sits to the right of the caret, not under the\n * caret that actually opens it.\n *\n * Aligns the panel's own *content* edge (inside its padding), not just\n * its border box, with the caret's right edge — the panel's grid pitch\n * (44px columns, `--shoji-spacing-sm` gaps, `.shoji-toolbar-overflow-\n * panel` in shoji.css) already matches the toolbar row's own button\n * size/gap, so subtracting the panel's own right padding here is what\n * makes the popover's icon columns actually line up with the toolbar\n * row's icons above them, not just the panel block sitting roughly\n * nearby.\n *\n * Also sets the grid's own column count to match the toolbar row's own\n * column count right now: however many buttons are *actually* still\n * pinned on `toolbarRight`, *plus the caret itself* — requested directly:\n * the popover should read as the same row of columns continuing\n * downward, caret included, not a fixed 3 columns regardless of how many\n * ended up pinned. At the default `maxPinnedToolbarButtons` (2), that's 2\n * pinned + the caret = 3 columns. Collapsed buttons beyond that count\n * still wrap onto further rows within it, same as before.\n *\n * **A real bug: \"pinned\" is counted from `this.pluginToolbarButtons`\n * (registered via `ctx.ui.toolbar()`), never by querying `toolbarRight`'s\n * DOM children.** The old filter (`toolbarRight.children`, excluding\n * `closeButton`/`toolbarOverflowButton` by identity, `!el.hidden`) broke\n * once a host appended an unrelated element straight into `toolbarRight`\n * — not a documented extension point, but nothing stops it. Reported from\n * real usage: a plugin's own loading spinner, toggled via `style.display`\n * rather than the `hidden` attribute, passed `!el.hidden` and got\n * miscounted as a pinned button, turning a 3-column popover into 4.\n * Counting from the registry instead is immune to this regardless of how\n * such an element manages its own visibility. `closeButton`/\n * `toolbarOverflowButton` were never in `pluginToolbarButtons`, so\n * excluding them by identity is no longer needed either.\n */\n private positionToolbarOverflowPanel(): void {\n if (!this.dom) return;\n const {\n dialog,\n toolbarOverflowButton,\n toolbarOverflowPanel,\n toolbarRight,\n captionToggleButton,\n } = this.dom;\n const dialogRight = dialog.getBoundingClientRect().right;\n const caretRight = toolbarOverflowButton.getBoundingClientRect().right;\n const paddingRight = parseFloat(getComputedStyle(toolbarOverflowPanel).paddingRight) || 0;\n const right = dialogRight - caretRight - paddingRight;\n toolbarOverflowPanel.style.right = `${Math.max(0, right)}px`;\n\n // A second real bug, reported from real usage on a video slide: still\n // over/undercounts, even immune to the DOM-parentage issue above.\n // Undercounts by not knowing about `captionToggleButton` at all — a\n // real, space-consuming, never-collapsible button that only exists on\n // video slides, added directly in dom.ts rather than through\n // `ctx.ui.toolbar()`, so it was never in `pluginToolbarButtons` to\n // begin with. Overcounts separately, in the other direction: a\n // registered button hidden for its own content reasons (e.g. Zoom's\n // zoomIn/zoomOut/actualSize buttons hiding themselves on video slides,\n // §4.6) still passes the parentage check — hidden means zero layout\n // size, so `measureToolbarOverflow()`'s collapse loop never needed to\n // move it into the panel, leaving it sitting in `toolbarRight`,\n // invisible but still counted as if it occupied a column. Both fixed\n // by also checking `!b.el.hidden`, and adding one more for\n // `captionToggleButton` whenever it's currently shown.\n const pinnedCount =\n this.pluginToolbarButtons.filter(\n (b) => b.slot === 'right' && b.el.parentElement === toolbarRight && !b.el.hidden,\n ).length + (captionToggleButton.hidden ? 0 : 1);\n const columnCount = pinnedCount + 1; // + the caret itself\n toolbarOverflowPanel.style.gridTemplateColumns = `repeat(${columnCount}, 44px)`;\n }\n\n private closeToolbarOverflow(): void {\n if (!this.dom || !this.toolbarOverflowOpen) return;\n document.removeEventListener('keydown', this.onToolbarOverflowKeydown, true);\n this.dom.toolbarOverflowPanel.hidden = true;\n this.dom.toolbarOverflowButton.setAttribute('aria-expanded', 'false');\n this.toolbarOverflowOpen = false;\n this.focusTrap.retarget(this.dom.dialog);\n this.toolbarOverflowReturnFocus?.focus({ preventScroll: true });\n this.toolbarOverflowReturnFocus = null;\n }\n\n private pluginOverlay(el: HTMLElement, layer?: number): Unsubscribe {\n if (layer !== undefined) el.style.zIndex = String(layer);\n this.dom!.dialog.appendChild(el);\n const unhover = this.wireControlHover(el);\n return () => {\n unhover();\n el.remove();\n };\n }\n\n /** DESIGN.md §2.8/§3 — pauses auto-hide while genuinely hovered: controls, caption, and any plugin overlay (`ctx.ui.overlay()`). Unsubscribe also corrects the set if removed mid-hover — a real risk for overlay content a plugin can toggle while the gallery stays open, unlike static buttons. */\n private wireControlHover(el: HTMLElement): Unsubscribe {\n this.hoverableElements.add(el);\n const onEnter = (): void => {\n this.hoveringElements.add(el);\n this.onActivity();\n };\n const onLeave = (): void => {\n if (!this.hoveringElements.delete(el)) return;\n this.scheduleAutoHide();\n };\n el.addEventListener('pointerenter', onEnter);\n el.addEventListener('pointerleave', onLeave);\n return () => {\n el.removeEventListener('pointerenter', onEnter);\n el.removeEventListener('pointerleave', onLeave);\n this.hoverableElements.delete(el);\n if (this.hoveringElements.delete(el)) this.scheduleAutoHide();\n };\n }\n\n /**\n * DESIGN.md §2.8 — paused only by a real *hover*. Used to also treat a\n * *focused* control as active via `document.activeElement`, but a click\n * leaves a `<button>` focused indefinitely, permanently blocking\n * `hideControls()`. Focus still counts as activity (`focusin` →\n * `onActivity()`), it just no longer blocks the eventual hide.\n */\n private isControlActive(): boolean {\n return this.hoveringElements.size > 0;\n }\n\n /**\n * Syncs `hoveringElements` to the browser's own live `:hover` truth for\n * every registered control — both directions, not just dropping a stale\n * entry: also picks up one that's genuinely hovered but never got a\n * `pointerenter` of its own (see `hoveringElements`'s own doc comment for\n * why either direction can happen). Whichever ends up true here is what\n * `isControlActive()` reads immediately after, in the same `onActivity()`\n * call — no separate reveal step needed for a newly-added element; that\n * call already does it for any activity, hover included. Cheap in\n * practice: `hoverableElements` is normally single digits, and `:hover`\n * matching is a native, already-computed browser check, not a\n * layout-triggering one.\n */\n private reconcileHover(): void {\n for (const el of this.hoverableElements) {\n if (el.matches(':hover')) this.hoveringElements.add(el);\n else this.hoveringElements.delete(el);\n }\n }\n\n /**\n * The thumbnail for `index` — what the zoom transition animates to/from,\n * and what `activeThumbnail` marks/scrolls-to. `data-shoji-id` is an\n * explicit opt-in that works in any mode (needed for dynamic mode, which\n * has no scanned DOM); checked first so it can override selector mode's\n * default `scannedElements[index]` too, e.g. to target an inner element.\n */\n getOriginElement(index: number): HTMLElement | null {\n const item = this.itemList[index];\n if (item?.id && typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {\n const marked = document.querySelector<HTMLElement>(\n `[data-shoji-id=\"${CSS.escape(item.id)}\"]`,\n );\n if (marked) return marked;\n }\n return this.scannedElements[index] ?? null;\n }\n\n /** Lets a plugin's background-page `scrollIntoView()` survive `close()`'s scroll restore, routed through this shared instance rather than importing `bodyScrollLock` directly — required for the standalone core+plugins distribution, where a direct import would get its own disconnected module copy (DESIGN.md §4.2/§10). Same reasoning `getOriginElement`/`getActiveMedia` were made public for. */\n markIntentionalScroll(): void {\n markIntentionalScrollInternal();\n }\n\n private scheduleAutoHide(): void {\n if (this.autoHideTimer !== null) {\n clearTimeout(this.autoHideTimer);\n this.autoHideTimer = null;\n }\n if (!this.opened) return;\n if (this.autoHideDelay === false) return; // always visible — no timer to arm\n if (this.autoHideDelay === 0) {\n this.hideControls(); // 0 = hidden immediately, no reveal — see onActivity\n return;\n }\n this.autoHideTimer = setTimeout(() => this.hideControls(), this.autoHideDelay);\n }\n\n /**\n * Forces the same fade §2.8's idle timer would eventually trigger —\n * public so a plugin can hide controls on its own trigger. Same\n * `isControlActive()` guard as the timer. Also a no-op under\n * `autoHideDelay: false` — a real bug, reported from real usage: Autoplay's\n * tap-to-toggle-chrome behavior called this directly and ignored `false`\n * entirely, since only the idle timer checked it. `false` has to hold for\n * every caller, not just the timer. `forceHideControls()`/\n * `setControlsHiddenForDrag()` (close, drag-to-close) deliberately don't\n * check this — direct user actions with their own feedback, not auto-hide.\n */\n hideControls(): void {\n // A real bug, reported from real usage: an idle timer already ticking\n // down before the caption modal opened isn't cancelled by opening it\n // (DESIGN.md §2.3a) — `onActivity()`'s own `captionModalOpen` guard\n // only stops a *new* timer being armed while it's open, it doesn't stop\n // one already in flight from firing. Left unguarded here, that timer\n // could still call this mid-read, and `.shoji-controls-hidden`'s own\n // `cursor: none` (shoji.css) applies to the whole dialog including the\n // modal's own backdrop/panel — the cursor visibly vanishing over text\n // the viewer is actively reading, not idling on.\n //\n // A real bug, found testing this cross-browser: `hoveringElements` is\n // normally kept in sync by `reconcileHover()` running inside\n // `onActivity()`, on every real pointer event — but that only helps if\n // one actually fires *after* the pointer reaches wherever it's really\n // ending up. Confirmed directly: some browser pointer-simulation paths\n // (reproduced consistently under Firefox automation, though nothing\n // rules out a genuine — if rarer — real-hardware equivalent) fire their\n // last bubbling pointer event mid-transition, before the browser's own\n // `:hover` state has caught up to the pointer's actual final position —\n // reconciling *then* just recorded the wrong, stale answer, and with no\n // further pointer event ever arriving, nothing was left to correct it\n // before this timer fired. A plain counter would have the identical gap\n // (whatever event it's trusted to fire is the same one that didn't).\n // Fixed by re-reconciling right here too, immediately before the\n // decision that actually depends on the answer being fresh — this is\n // the one moment `hoveringElements` being even briefly stale actually\n // matters, so it's also the one moment worth an extra, authoritative\n // check instead of trusting whatever the last activity event happened\n // to leave behind.\n this.reconcileHover();\n if (\n !this.dom ||\n this.autoHidden ||\n this.isControlActive() ||\n this.autoHideDelay === false ||\n this.captionModalOpen ||\n // DESIGN.md §3.1a — same reasoning as `captionModalOpen` immediately\n // above: an idle timer already ticking down before the toolbar\n // overflow popover opened isn't cancelled by opening it, and the\n // popover is anchored to (visually part of) the toolbar this would\n // hide out from under it.\n this.toolbarOverflowOpen\n )\n return;\n this.autoHidden = true;\n this.dom.dialog.classList.add('shoji-controls-hidden');\n this.bus.emit('controls:hide', {});\n }\n\n private showControls(): void {\n if (!this.dom || !this.autoHidden) return;\n this.autoHidden = false;\n this.dom.dialog.classList.remove('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n this.bus.emit('controls:show', {});\n }\n\n /**\n * DESIGN.md §2.1 — `caption` is `string | HTMLElement | DangerousHtmlCaption`:\n * a plain string renders as text (`textContent`, auto-escaped, safe by\n * default); an `HTMLElement` is appended as real DOM (the host built it);\n * `{ dangerouslySetInnerHTML }` renders raw, unescaped HTML via `innerHTML`\n * — Shoji does not sanitize it, the host must, same contract as React's\n * identically-named escape hatch. Returns whether the caption element\n * should be hidden.\n */\n private renderCaption(\n el: HTMLElement,\n caption: string | HTMLElement | DangerousHtmlCaption | undefined,\n ): boolean {\n if (caption instanceof HTMLElement) {\n el.replaceChildren(caption);\n return false;\n }\n if (isDangerousHtmlCaption(caption)) {\n el.innerHTML = caption.dangerouslySetInnerHTML;\n return caption.dangerouslySetInnerHTML === '';\n }\n el.textContent = caption ?? '';\n return !caption;\n }\n\n /**\n * `.shoji-toolbar-button` only — never `.shoji-close`/`.shoji-nav`, which\n * are different classes entirely, so this can't accidentally block\n * closing or navigating away from a slow-loading slide. `tabIndex = -1`\n * (not just the CSS below) so a keyboard user tabbing through the\n * toolbar skips these entirely while disabled, not just visually dims\n * them — `pointer-events: none` alone wouldn't stop Enter/Space\n * activating an already-focused button.\n */\n private setSlideLoading(loading: boolean): void {\n if (!this.dom) return;\n this.dom.outer.classList.toggle('shoji-slide-loading', loading);\n for (const button of this.dom.outer.querySelectorAll<HTMLButtonElement>(\n '.shoji-toolbar-button',\n )) {\n button.ariaDisabled = loading ? 'true' : null;\n if (loading) button.tabIndex = -1;\n else button.removeAttribute('tabindex');\n }\n }\n\n /**\n * DESIGN.md §2.5 — the caption's disappear-then-reappear fits inside the\n * *same* `--shoji-duration` window the slide's own mode animation runs\n * in, not a separate one after it: fades out over the first half, swaps\n * content invisibly at the midpoint, fades back in over the second half\n * — timed to finish exactly when the mode animation does, not still\n * catching up a beat behind it. Self-timed off the resolved\n * `--shoji-duration` value rather than hooked to the mode animation's\n * own completion event: both are driven by the same duration either way,\n * and the fade-in's own completion is what has to line up, which a\n * \"start on completion, then animate\" hook can't give — by definition,\n * a fade started only once something else finishes hasn't finished\n * *with* it.\n */\n private transitionCaption(): void {\n const dom = this.dom;\n if (!dom) return;\n if (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n ) {\n return; // --shoji-duration is already 0ms; nothing to sequence\n }\n\n // .shoji-caption's own `transition: opacity var(--shoji-duration) ...`\n // rule transitions a single property, so the computed shorthand\n // resolves to exactly --shoji-duration's own value — same read as\n // `zoomTransition.ts`/`SlideTransition.ts` already use elsewhere,\n // rather than `getPropertyValue('--shoji-duration')` directly.\n const raw = getComputedStyle(dom.caption).transitionDuration.split(',')[0]?.trim() ?? '';\n const fullMs = raw.endsWith('ms')\n ? parseFloat(raw)\n : raw.endsWith('s')\n ? parseFloat(raw) * 1000\n : 0;\n const half = fullMs / 2;\n\n this.captionFadePending = true;\n dom.caption.style.transitionDuration = `${half}ms`;\n dom.caption.style.opacity = '0';\n\n setTimeout(() => {\n if (!this.dom) return;\n this.captionFadePending = false;\n this.updateCaptionVisibility();\n this.dom.caption.style.opacity = '';\n setTimeout(() => {\n // Only the temporary half-duration override — restores the\n // caption's normal full-duration transition (e.g. for idle\n // auto-hide) once this fade-in has actually finished with it.\n if (this.dom) this.dom.caption.style.transitionDuration = '';\n }, half);\n }, half);\n }\n\n /**\n * Content is always kept current (correct the instant loading finishes,\n * no text flash) — only `hidden` also gates on `isActiveReady()`, so a\n * caption for the *new* slide can't sit there readable while the\n * image/video it describes is still a spinner.\n */\n private updateCaptionVisibility(): void {\n if (!this.dom || !this.slides) return;\n const item = this.itemList[this.activeIndex];\n const noCaption = this.renderCaption(this.dom.caption, item?.caption);\n const isVideo = !!item?.video;\n this.dom.caption.classList.toggle('shoji-caption--video', isVideo);\n const hiddenByToggle = isVideo && !this.captionVisibleOnVideo;\n this.dom.caption.hidden = noCaption || !this.slides.isActiveReady() || hiddenByToggle;\n\n const btn = this.dom.captionToggleButton;\n btn.hidden = !isVideo || noCaption;\n if (!btn.hidden) {\n btn.setAttribute('aria-pressed', String(this.captionVisibleOnVideo));\n btn.ariaLabel = btn.title = this.captionVisibleOnVideo\n ? this.locale.hideCaption\n : this.locale.showCaption;\n }\n this.updateCaptionTruncation();\n // A real bug, reported from real usage: reopening an already-loaded\n // slide (e.g. clicking the same thumbnail twice) skips the async\n // image-decode path entirely — nothing re-runs this measurement once\n // the dialog actually finishes laying out, so the synchronous call\n // above can catch it mid-layout (still effectively 0×0 at that exact\n // point, even though `hidden` itself is already correctly false) and\n // wrongly conclude nothing overflows. A fresh *first* open happens to\n // dodge this because real image decode work is slow enough that by the\n // time it resolves, layout has already settled — not something a\n // reopen (cached, near-instant) can rely on. Re-checking one frame\n // later, after layout has actually been committed, catches the case the\n // synchronous read above can miss without regressing it (the sync call\n // already got it right whenever it can, so this is a rarely-needed\n // correction, not a routine double-measurement).\n if (this.captionTruncationFrame !== null) cancelAnimationFrame(this.captionTruncationFrame);\n this.captionTruncationFrame = requestAnimationFrame(() => {\n this.captionTruncationFrame = null;\n this.updateCaptionTruncation();\n });\n }\n\n /**\n * DESIGN.md §2.3a — the caption's own default height cap (above) already\n * keeps it clear of the toolbar, but says nothing about the vertically-\n * centered prev/next nav arrows sharing its same left edge; a long\n * enough caption could still grow up over one of those. `--shoji-*`\n * collapses it to roughly one line by default (shoji.css) regardless, so\n * this only ever needs to detect whether that collapse actually clipped\n * something — `scrollHeight > clientHeight` after layout, the same\n * technique already used elsewhere in this codebase (and its own tests)\n * to detect caption overflow. Marks it truncated/interactive only when\n * there's genuinely more to read; a caption that already fits shouldn't\n * look or behave clickable.\n *\n * A real bug, reported from real usage: the first version only capped\n * `max-height` + `overflow: hidden` — a plain pixel clip with no regard\n * for where a line of text actually ends, so the cutoff routinely sliced\n * straight through the middle of the last visible line instead of\n * stopping at a clean line boundary, reading as broken rather than\n * intentionally truncated.\n *\n * Two follow-up attempts, both also wrong, both worth recording so they\n * aren't retried: `-webkit-line-clamp` never cleanly stopped at a line\n * boundary here regardless of the line count fed into it. Replacing it\n * with `lines * lineHeight + paddingY` arithmetic (using\n * `getComputedStyle(el).lineHeight`) still left a sliver of the next\n * line visible in a real browser — confirmed by screenshot, not just\n * this sandbox. Root cause: a browser doesn't necessarily lay out N\n * stacked lines at exactly N times the CSS `line-height` value: text\n * layout does its own sub-pixel rounding per line, so arithmetic\n * multiplication drifts from the real rendered geometry by enough to\n * expose part of an extra line, and no fixed safety margin is correct\n * for every font/zoom/line-count combination.\n *\n * This version doesn't compute line boundaries at all — it reads them\n * straight from the browser's own layout via `Range.getClientRects()`,\n * which returns one rect per actual rendered line fragment (rich\n * captions with inline markup can put more than one rect on the same\n * visual row; each is handled independently below rather than grouped,\n * since only the topmost/bottommost edges per row matter here). The cap\n * is set to the bottom edge of the last line whose bottom still fits\n * inside the current (arbitrary, CSS-calc'd) height budget — a real\n * measured boundary, never an assumed one.\n *\n * A third real bug, caught after switching to this measured approach:\n * padding the box out by a full `padding-bottom` past that last line's\n * *measured* bottom still isn't safe, because line boxes butt up much\n * closer together than the padding value — the next (excluded) line's\n * own top can fall well inside that padding band, so its glyph\n * ascenders paint into what was supposed to be empty breathing room.\n * Fixed by also finding that next line's top and never letting the cap\n * reach it, regardless of how much of `padding-bottom` that leaves.\n */\n private updateCaptionTruncation(): void {\n if (!this.dom) return;\n const el = this.dom.caption;\n el.style.removeProperty('max-height');\n const truncated = !el.hidden && el.scrollHeight > el.clientHeight;\n if (truncated) {\n const paddingBottom = parseFloat(getComputedStyle(el).paddingBottom) || 0;\n const budget = el.clientHeight - paddingBottom;\n const elTop = el.getBoundingClientRect().top;\n const range = document.createRange();\n range.selectNodeContents(el);\n let lastFittingBottom = 0;\n let nextLineTop = Infinity;\n for (const rect of range.getClientRects()) {\n if (rect.height === 0) continue;\n const relTop = rect.top - elTop;\n const relBottom = rect.bottom - elTop;\n if (relBottom <= budget) {\n if (relBottom > lastFittingBottom) lastFittingBottom = relBottom;\n } else if (relTop < nextLineTop) {\n nextLineTop = relTop;\n }\n }\n const cutBottom = lastFittingBottom > 0 ? lastFittingBottom : budget;\n const desired = cutBottom + paddingBottom;\n const cap = Number.isFinite(nextLineTop) ? Math.min(desired, nextLineTop) : desired;\n el.style.maxHeight = `${Math.max(0, Math.floor(cap) - 1)}px`;\n }\n el.classList.toggle('shoji-caption--truncated', truncated);\n if (truncated) {\n el.tabIndex = 0;\n el.setAttribute('role', 'button');\n el.setAttribute('aria-haspopup', 'dialog');\n } else {\n el.removeAttribute('tabindex');\n el.removeAttribute('role');\n el.removeAttribute('aria-haspopup');\n if (this.captionModalOpen) this.closeCaptionModal();\n }\n }\n\n private readonly onCaptionActivate = (event: Event): void => {\n if (!this.dom?.caption.classList.contains('shoji-caption--truncated')) return;\n this.captionModalOpenedViaKeyboard = event instanceof KeyboardEvent;\n if (event instanceof KeyboardEvent) {\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n // A real bug, reported from real usage against Autoplay's\n // onCaptionExpand (§4.1 point 18): a *keyboard* activation here\n // (Tab+Enter/Space, the only path this branch actually runs for)\n // must not also bubble up to onKeydown's shortcut dispatch — this is\n // unambiguously \"activate this control,\" not also a global shortcut\n // key, same reasoning the caption modal's own keydown handler\n // already uses to isolate itself from onKeydown. This alone doesn't\n // cover the click path below reopening on a *later*, unrelated\n // keypress — see `captionModalOpenedViaKeyboard`'s own doc comment\n // for that half of the fix.\n event.stopPropagation();\n } else {\n // A mouse-drag that ended in a real text selection is not a click to\n // open — `.shoji-caption` is deliberately excluded from drag-to-\n // navigate (GestureController's INTERACTIVE_CONTROL_SELECTOR) so the\n // viewer can select/copy caption text; without this check, finishing\n // that selection would also toggle the modal open on every drag.\n const selection = window.getSelection();\n if (selection && !selection.isCollapsed) return;\n // A link/button inside a rich-HTML caption keeps its own click\n // behavior — this only opens the modal for a click on the caption\n // itself, not one that's actually aimed at interactive content\n // inside it.\n if (event.target instanceof Element && event.target.closest('a, button')) return;\n }\n this.openCaptionModal();\n };\n\n /**\n * DESIGN.md §2.3a — shows the full caption (re-rendered via the same\n * `renderCaption()` the truncated one already used, so a rich-HTML\n * caption's own links/formatting are identical in both places) in a\n * small nested dialog, scrollable if it's still taller than the\n * viewport allows. `FocusTrap.retarget()` narrows Tab-cycling to just\n * this modal without touching the outer trap's own focus-restore state\n * (see its own doc comment for why a second `FocusTrap` instance isn't\n * used instead). Requested directly: the modal *replaces* the truncated\n * caption rather than just visually sitting on top of it — hiding\n * `dom.caption` too, not only because the modal's own opaque backdrop\n * already covers it, but so it can't still be reached by a screen\n * reader's browse-mode cursor (unlike Tab, `FocusTrap`/`retarget()`\n * don't affect that) while a completely different dialog is the one\n * actually open.\n */\n private openCaptionModal(): void {\n if (!this.dom || this.captionModalOpen) return;\n const item = this.itemList[this.activeIndex];\n this.renderCaption(this.dom.captionModalContent, item?.caption);\n this.dom.captionModal.hidden = false;\n // Captured before hiding the caption below (a real bug, caught by e2e\n // regression: hiding the currently-focused caption blurs it immediately\n // — a hidden element can't hold focus — so reading `activeElement`\n // *after* that line ended up capturing wherever the browser's own\n // focus-loss fallback landed (the dialog), not the caption itself.\n // Escape/close-button/backdrop then \"restored\" focus to the dialog\n // instead of back to the caption that was actually focused when this\n // opened.\n this.captionModalReturnFocus = document.activeElement as HTMLElement | null;\n this.dom.caption.hidden = true;\n // A real bug, caught testing this: the click that opens the modal\n // typically leaves the pointer sitting right over the caption —\n // hiding it out from under a *stationary* cursor never fires the\n // `pointerleave` `wireControlHover()` needs to drop it from\n // `hoveringElements` (browsers only fire that on actual pointer\n // movement past an element's edge, not on the element disappearing).\n // `reconcileHover()` would eventually self-heal this on the next real\n // pointer move anyway, but nothing meaningful should still read as\n // \"hovered\" once the modal has taken over — clearing it immediately\n // here is more deterministic than waiting for that.\n this.hoveringElements.clear();\n this.captionModalOpen = true;\n this.focusTrap.retarget(this.dom.captionModalPanel);\n document.addEventListener('keydown', this.onCaptionModalKeydown, true);\n this.bus.emit('captionModalChange', { open: true });\n }\n\n /**\n * Requested directly: closing should leave the viewer looking at a fully\n * normal, fully visible gallery — not just the modal gone, but the\n * truncated caption back (via `updateCaptionVisibility()`, which\n * recomputes its real hidden state from scratch rather than blindly\n * flipping a flag back — the more robust \"recompute from source of\n * truth\" this codebase already prefers elsewhere) and any auto-hidden\n * toolbar/nav explicitly re-shown (`onActivity()`, same pairing every\n * other real interaction already uses) rather than left hidden until\n * the viewer happens to move the mouse.\n */\n private closeCaptionModal(): void {\n if (!this.dom || !this.captionModalOpen) return;\n document.removeEventListener('keydown', this.onCaptionModalKeydown, true);\n this.dom.captionModal.hidden = true;\n this.captionModalOpen = false;\n this.updateCaptionVisibility();\n this.focusTrap.retarget(this.dom.dialog);\n if (this.captionModalOpenedViaKeyboard) {\n this.captionModalReturnFocus?.focus({ preventScroll: true });\n }\n this.captionModalReturnFocus = null;\n this.captionModalOpenedViaKeyboard = false;\n this.onActivity();\n this.bus.emit('captionModalChange', { open: false });\n }\n\n private renderCurrentSlide(openPlaceholderSrc?: string): void {\n if (!this.slides || !this.dom) return;\n const dom = this.dom;\n this.slides.render(\n this.itemList,\n this.activeIndex,\n (loadedIndex) => {\n if (loadedIndex === this.activeIndex) {\n this.bus.emit('slideItemLoad', { index: loadedIndex });\n this.setSlideLoading(false);\n // captionFadePending: skip here too, not just the synchronous\n // call below — decode() resolves on a microtask, which can win\n // the race against the mode animation's own onComplete (the one\n // that's actually supposed to update it), especially for an\n // already-preloaded slide.\n if (!this.captionFadePending) this.updateCaptionVisibility();\n }\n },\n openPlaceholderSrc,\n this.loop,\n );\n this.setSlideLoading(!this.slides.isActiveReady());\n\n const item = this.itemList[this.activeIndex];\n const total = this.itemList.length;\n dom.counter.textContent = total > 0 ? `${this.activeIndex + 1} / ${total}` : '';\n dom.counter.hidden = !this.showCounter || total === 0;\n // navigate()'s animated path already faded the outgoing caption out\n // and updates content itself, once that fade (and the slide's own mode\n // transition) actually finishes — updating it here too, immediately,\n // would flash the new caption's text mid-fade instead of the outgoing\n // one.\n if (!this.captionFadePending) this.updateCaptionVisibility();\n const label = `Image ${this.activeIndex + 1} of ${total}${item?.alt ? `: ${item.alt}` : ''}`;\n this.liveRegion.announce(label);\n\n dom.prevButton.hidden = total <= 1;\n dom.nextButton.hidden = total <= 1;\n dom.prevButton.disabled = !this.loop && this.activeIndex <= 0;\n dom.nextButton.disabled = !this.loop && this.activeIndex >= total - 1;\n }\n\n open(index = this.options.index ?? 0): void {\n if (this.destroyed || this.opened) return;\n this.bus.emit('beforeOpen', { index });\n this.ensureLightbox();\n this.opened = true;\n this.activeIndex = index;\n this.captionVisibleOnVideo = !!this.options.showVideoCaption;\n lockBodyScroll();\n const origin = this.getOriginElement(index);\n // Both the open placeholder and the zoom-in animation below need a size\n // to show/grow toward before the real image has loaded — without\n // item.width/height, that size can only ever be guessed (\"probably\n // fills the dialog\"), which is exactly what visibly overshoots for a\n // genuinely small photo (§2.3/§2.3b's own real-bug history). Rather\n // than guess, skip both entirely when naturalSize is unknown: the\n // ordinary spinner shows, and the real image just appears once it's\n // ready — no animation of its own, deliberately (same \"no second,\n // disconnected transition\" reasoning the placeholder-to-real-image\n // handoff already uses elsewhere).\n const naturalSize = this.resolveNaturalSize(index);\n // The first slide's caption fades in alongside zoomIn() the same way a\n // navigated-to one fades in alongside the mode transition (§2.5) —\n // only when there's actually a zoom to sync with, same \"no second,\n // disconnected transition\" reasoning as the comment above: nothing\n // grows in from the thumbnail without known dimensions, so nothing\n // should fade in disconnected from that either.\n const fadeInOnOpen =\n !!(origin && naturalSize) &&\n !(\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n if (fadeInOnOpen && this.dom) {\n this.captionFadePending = true;\n this.dom.caption.style.opacity = '0';\n }\n // A real bug/inconsistency: a video item *does* have a known naturalSize\n // (its aspect ratio), but the low-res placeholder this unlocks is a\n // dead end — it's a static photo, immediately replaced by something\n // entirely different (an error state, or the real embed), not the same\n // image sharpening the way a photo's placeholder-to-full-res handoff\n // is. That made a fresh open() inconsistent with navigating back to an\n // already-cached video slide (no placeholder shown there at all, since\n // navigate() never passes one) — same \"no second, disconnected\n // transition\" reasoning as the naturalSize-unknown case above, just\n // triggered by content type instead of missing dimensions.\n this.renderCurrentSlide(\n naturalSize && !this.itemList[index]?.video\n ? this.resolveOpenPlaceholderSrc(this.itemList[index], origin)\n : undefined,\n );\n this.dom!.outer.classList.add('shoji-open');\n document.addEventListener('keydown', this.onKeydown);\n this.focusTrap.activate(this.dom!.dialog);\n this.scheduleAutoHide();\n\n const media = this.slides?.getActiveMedia();\n if (media && origin && naturalSize) {\n zoomIn({\n origin,\n target: media,\n aspectRatio: this.resolveAspectRatio(index, origin),\n naturalSize,\n });\n }\n if (fadeInOnOpen && this.dom) {\n // No half-duration split here, unlike transitionCaption() — there's\n // no outgoing caption to fade out first, just this one fading in\n // from nothing, over the same full --shoji-duration zoomIn() itself\n // runs on.\n this.captionFadePending = false;\n this.updateCaptionVisibility();\n this.dom.caption.style.opacity = '';\n }\n\n this.bus.emit('open', { index });\n this.bus.emit('afterOpen', { index });\n }\n\n /** DESIGN.md §2.3 — low-res open() placeholder source, checked in order: item.thumb, a live data-shoji-thumb on origin, else origin's own rendered <img>. */\n private resolveOpenPlaceholderSrc(\n item: GalleryItem | undefined,\n origin: HTMLElement | null,\n ): string | undefined {\n if (item?.thumb) return item.thumb;\n const dataThumb = origin?.getAttribute('data-shoji-thumb');\n if (dataThumb) return dataThumb;\n const img = origin?.querySelector('img');\n return img?.currentSrc || img?.src || undefined;\n }\n\n /**\n * DESIGN.md §2.2/§2.6 — navigates while open; always clamps an explicit\n * out-of-range index (this is a directed jump, not a step — `loop` only\n * affects `next()`/`prev()`, see below). No-op if not open. `animate`\n * (default `true`) runs the configured §2.5 transition; hosts that want\n * an instant jump — e.g. syncing to an external index without a visual\n * flourish — can pass `{ animate: false }`.\n */\n goTo(index: number, options?: { animate?: boolean }): void {\n if (this.destroyed || !this.opened || this.itemList.length === 0) return;\n const target = this.clampToRange(index);\n if (target === this.activeIndex) return;\n const direction: 1 | -1 = target > this.activeIndex ? 1 : -1;\n this.navigate(target, direction, options?.animate ?? true);\n }\n\n next(): void {\n this.navigate(this.nextIndex(), 1, true);\n }\n\n prev(): void {\n this.navigate(this.prevIndex(), -1, true);\n }\n\n private nextIndex(): number {\n const atEnd = this.activeIndex >= this.itemList.length - 1;\n return atEnd && this.loop ? 0 : this.activeIndex + 1;\n }\n\n private prevIndex(): number {\n const atStart = this.activeIndex <= 0;\n return atStart && this.loop ? this.itemList.length - 1 : this.activeIndex - 1;\n }\n\n /**\n * DESIGN.md §2.5 — the shared path behind `goTo()`/`next()`/`prev()`.\n * `animate` is `false` only for `GestureController`'s own host callbacks\n * (see `ensureLightbox()`): a gesture-completed swipe already played its\n * own live-drag/settle animation, so running a *second*, `mode`-based\n * transition on top of it would visibly double-animate. Every other\n * caller — buttons, keyboard, autoplay, a plugin calling `goTo()` — gets\n * the real, configured transition.\n */\n private navigate(target: number, direction: 1 | -1, animate: boolean): void {\n if (this.destroyed || !this.opened || this.itemList.length === 0) return;\n const clamped = this.clampToRange(target);\n if (clamped === this.activeIndex) return;\n // DESIGN.md §2.3a — the modal shows a specific slide's caption; leaving\n // it open across a navigation (arrow keys reach it even while the\n // gesture gate above suspends drag-navigate) would keep showing the\n // outgoing slide's text over the new slide.\n if (this.captionModalOpen) this.closeCaptionModal();\n // DESIGN.md §3.1a — the popover's own position depends on the current\n // toolbar height, which can change slide-to-slide (e.g. a video slide's\n // caption-toggle button appearing/disappearing); simplest to just close\n // it rather than reposition it mid-navigation.\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n const from = this.activeIndex;\n // beforeSlide fires first so a listener (e.g. Autoplay) can detach its\n // own 'pause' listener from the outgoing video before pauseMedia() below\n // triggers a native 'pause' event on it — otherwise that listener is\n // still attached and misreads this programmatic pause as the viewer\n // manually pausing the video, a real regression this caused once\n // (advancing past a stuck video called next(), which paused it here,\n // which the still-attached listener treated as a manual pause and\n // stopped the whole slideshow before the new slide's afterSlide handler\n // ever got a chance to run). activeIndex hasn't changed yet at this\n // point, so getActiveMedia() still resolves to the outgoing slide either\n // way — only the listener-detach ordering relative to pauseMedia matters.\n this.bus.emit('beforeSlide', { from, to: clamped });\n // A video started by the viewer keeps playing otherwise — this slide\n // stays cached (still within `preload`), and only pausing (not\n // releasing) lets it resume right where it left off if revisited.\n pauseMedia(this.slides?.getActiveMedia() ?? null);\n this.activeIndex = clamped;\n\n if (animate && this.transition) {\n // Not layered onto a gesture-completed swipe (the `else` branch) —\n // same scoping as the mode transition itself (§2.4/§2.5).\n this.transitionCaption();\n const swap = (): void => this.renderCurrentSlide();\n const modeName = this.resolveTransitionMode();\n const builtin = TRANSITION_PRESETS[modeName];\n if (builtin) {\n this.transition.animate(builtin, direction, swap);\n } else {\n this.transition.animateCustom(modeName, direction, swap);\n }\n } else {\n const swap = (): void => this.renderCurrentSlide();\n swap();\n }\n\n this.bus.emit('afterSlide', { from, to: clamped });\n }\n\n private resolveTransitionMode(): string {\n return this.options.mode ?? 'slide';\n }\n\n close(): void {\n this.beginClose();\n }\n\n /**\n * DESIGN.md §2.4/§2.6a — same effect as `close()`, from a completed\n * vertical swipe. `frozenDrag` is threaded through to `zoomOut()`'s own\n * `dragStart`, so the whole close continues as one motion from exactly\n * where the drag left off (see `GestureController.\n * takeFrozenDragTransform`).\n */\n private closeFromSwipe(frozenDrag: FrozenDragTransform): void {\n this.beginClose(frozenDrag);\n }\n\n /**\n * `frozenDrag` — see `closeFromSwipe()`'s doc comment; absent for a\n * button-close, which has no drag to continue from. Controls fade and the\n * zoom-out run concurrently, both starting the instant `forceHideControls()`\n * runs — not sequenced one after the other. (A previous version waited for\n * the controls' own fade to fully finish before starting the zoom-out, for\n * a button-close specifically — requested directly, to avoid stationary\n * chrome hovering over an already-shrinking photo. Reversed on later,\n * explicit feedback: waiting read as two distinct steps rather than one\n * motion; starting both together still avoids stationary chrome, since\n * the chrome is disappearing too, just without the pause.)\n */\n private beginClose(frozenDrag?: FrozenDragTransform): void {\n if (this.destroyed || !this.opened || this.isClosing) return;\n // DESIGN.md §2.3a — every close path (button, swipe, Escape, backdrop\n // click, destroy-while-open) funnels through here; the modal must not\n // linger past the lightbox itself closing, and its own document-level\n // keydown listener needs removing before that.\n if (this.captionModalOpen) this.closeCaptionModal();\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n // Read before beforeClose fires — the Zoom plugin's own beforeClose\n // handler resets its scale/pan back to neutral there (so zoomOut()'s\n // measurement below stays correct, same reasoning dragStart's own doc\n // comment explains), which would otherwise erase the very state this\n // is capturing.\n const zoomStart = this.zoomStartProvider?.() ?? undefined;\n this.bus.emit('beforeClose', {});\n\n // .shoji-outer must stay display:block for the zoom-out to be visible,\n // so the actual state flip (isOpen, focus restore, etc.) is deferred\n // until the animation finishes — see finishClose(). isClosing guards\n // against a second close() (e.g. a repeated Escape) re-triggering the\n // animation mid-flight while isOpen is still (deliberately) true.\n this.isClosing = true;\n\n const media = this.slides?.getActiveMedia();\n // close() never tears down the slide pool (reopening should be\n // instant), so nothing else stops a viewer-started video just because\n // the lightbox is now hidden.\n pauseMedia(media ?? null);\n\n const origin = this.getOriginElement(this.activeIndex);\n const naturalSize = this.resolveNaturalSize(this.activeIndex);\n // Real content already rendered doesn't need naturalSize at all —\n // effectiveTargetBox() (zoomTransition.ts) measures it directly, no\n // guessing involved. Only closing before it ever finished loading (no\n // real content, no naturalSize to fall back on either) would have\n // nothing but a guessed target to shrink toward — same \"don't guess\"\n // reasoning open() above already applies to its own animation.\n if (media && origin && (this.slides?.isActiveReady() || naturalSize)) {\n const aspectRatio = this.resolveAspectRatio(this.activeIndex, origin);\n this.forceHideControls();\n // Starts at the same instant as the zoom-out and the controls fade —\n // see the comment on .shoji-backdrop's own transition (shoji.css) for\n // why this can't just be left to the instant display:none cut at the\n // end of finishClose().\n if (this.dom) this.dom.backdrop.style.opacity = '0';\n zoomOut(\n { origin, target: media, aspectRatio, naturalSize, dragStart: frozenDrag, zoomStart },\n () => this.finishClose(),\n );\n } else {\n this.finishClose();\n }\n }\n\n /**\n * Forces the same fade §2.8's idle timer would eventually trigger, bypassing `hideControls()`'s own `isControlActive()` hover guard — the most common close path (clicking close) is hovering a control at this exact instant, and a deliberate close should hide regardless. No-op if already hidden.\n *\n * Also marks `.shoji-controls-hidden-for-close` alongside the ordinary\n * class — a real bug, reported from real usage: a plugin's own overlay\n * (Autoplay's progress bar, `autoplay.css`) was wired to fade on plain\n * `.shoji-controls-hidden`, the same class *ordinary idle auto-hide* also\n * applies — so it faded out and stayed gone through every idle period\n * too, not just the close animation the original request was actually\n * about. That went unnoticed for a while because until recently, tapping\n * the image toggled play/pause *and* revealed controls on the same tap,\n * papering over how often it was actually gone; once that tap-to-toggle\n * was removed (§4.1 point 15) as a separate, unrelated fix, an idle\n * slideshow now visibly loses its own progress indicator and never gets\n * it back without an unrelated interaction — surfacing this as a real\n * regression in practice, even though no code touching this class had\n * changed. This second class is the hook a plugin's CSS can key off\n * specifically for \"closing,\" without it ever matching ordinary idle-hide.\n */\n private forceHideControls(): void {\n if (!this.dom || this.autoHidden) return;\n this.autoHidden = true;\n this.dom.dialog.classList.add('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n this.bus.emit('controls:hide', {});\n }\n\n /**\n * DESIGN.md §2.4/§2.8 — `GestureController`'s live vertical-drag cue: hide\n * past the same distance a release would close, reveal again on retreat.\n * `hidden: false` only reveals if visible when *this* gesture started\n * (`controlsHiddenAtGestureStart`) — shouldn't resurrect controls already\n * separately hidden (idle, or `autoHideDelay: 0`) before the drag began.\n * `dragCloseThreshold` (bus event) fires on every crossing regardless of\n * that guard — Autoplay (§4-autoplay) needs to know about the crossing\n * itself, not just whether controls visibly moved.\n */\n private setControlsHiddenForDrag(hidden: boolean): void {\n this.controlsHiddenByDrag = hidden;\n if (hidden) this.forceHideControls();\n else if (!this.controlsHiddenAtGestureStart) this.showControls();\n // A real bug, reported from real usage: `.shoji-controls-hidden` also\n // hides the cursor (shoji.css) — fine for an idle/inactive hide, but\n // this hide happens *during* an active drag, so the cursor vanished\n // right when the viewer most needs to see it. This marker class scopes\n // a cursor override to specifically this case (see shoji.css).\n this.dom?.dialog.classList.toggle('shoji-controls-hidden-for-drag', hidden);\n this.bus.emit('dragCloseThreshold', { hidden });\n }\n\n /** `item.width`/`height`, else origin's `naturalWidth`/`naturalHeight` (accurate when `item.thumb` is unset). Feeds `computeTransform`'s letterbox-aware sizing. */\n private resolveAspectRatio(index: number, origin: HTMLElement | null): number | undefined {\n const item = this.itemList[index];\n if (item?.width && item.height) return item.width / item.height;\n const thumbImg = origin?.querySelector('img');\n if (thumbImg?.naturalWidth && thumbImg.naturalHeight) {\n return thumbImg.naturalWidth / thumbImg.naturalHeight;\n }\n return undefined;\n }\n\n /**\n * `item.width`/`height` only — deliberately never a thumbnail's own\n * `naturalWidth`/`naturalHeight` the way `resolveAspectRatio` above will:\n * that's a fine stand-in for *shape*, but using it as the real photo's\n * true pixel size would under-cap a genuinely large photo down to\n * thumbnail resolution. `undefined` here just means \"genuinely unknown,\"\n * not \"assume small\" — `zoomTransition.ts`'s `containedBox` already\n * treats it that way (no cap applied at all).\n */\n private resolveNaturalSize(index: number): { width: number; height: number } | undefined {\n const item = this.itemList[index];\n return item?.width && item.height ? { width: item.width, height: item.height } : undefined;\n }\n\n /**\n * Idempotent on purpose: a pending zoom-out's `transitionend`/fallback\n * timeout can still fire after `destroy()` has already force-finished the\n * close (§ destroy() below) — the `!this.opened` guard makes that a no-op\n * instead of a second `close`/`afterClose` emission on a torn-down gallery.\n */\n private finishClose(): void {\n if (!this.opened) return;\n this.isClosing = false;\n this.opened = false;\n unlockBodyScroll();\n document.removeEventListener('keydown', this.onKeydown);\n this.focusTrap.deactivate();\n this.dom?.outer.classList.remove('shoji-open');\n // Cleared, not left at '0' — a fresh open() must start fully opaque\n // again, not still faded out from the last close.\n if (this.dom) this.dom.backdrop.style.opacity = '';\n if (this.autoHideTimer !== null) {\n clearTimeout(this.autoHideTimer);\n this.autoHideTimer = null;\n }\n this.autoHidden = false;\n this.hoveringElements.clear();\n this.controlsHiddenByDrag = false;\n this.dom?.dialog.classList.remove('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n // A completed drag-close never calls setControlsHiddenForDrag(false)\n // (nothing left to un-hide for) — clean up the marker here instead, so\n // it can't linger into the next open().\n this.dom?.dialog.classList.remove('shoji-controls-hidden-for-drag');\n this.bus.emit('close', {});\n this.bus.emit('afterClose', {});\n }\n\n /** DESIGN.md §2.1 — diffs by id (fallback src), preserving the active slide. */\n updateSlides(items: GalleryItemInput[], currentIndex?: number): void {\n if (this.destroyed) return;\n\n const activeItem = this.itemList[this.activeIndex];\n const activeKey = activeItem ? itemKey(activeItem) : undefined;\n this.itemList = resolveDynamicVideoItems(items);\n\n let nextIndex = currentIndex;\n if (nextIndex === undefined && activeKey !== undefined) {\n const preserved = items.findIndex((item) => itemKey(item) === activeKey);\n if (preserved !== -1) nextIndex = preserved;\n }\n this.activeIndex = Math.min(\n Math.max(nextIndex ?? this.activeIndex, 0),\n Math.max(items.length - 1, 0),\n );\n\n if (this.opened) this.renderCurrentSlide();\n this.bus.emit('itemsUpdated', { items: this.itemList });\n }\n\n /**\n * Sugar over `updateSlides()` for the common \"insert some items\" case —\n * splices `items` into a copy of the current list at `atIndex` (default:\n * append at the end) and hands the result to `updateSlides()`, which\n * still does all the real work (active-item preservation, live re-render\n * if open, `itemsUpdated`). `atIndex` follows `Array.prototype.splice`'s\n * own semantics (negative counts from the end, out-of-range clamps) —\n * no extra validation on top of that.\n */\n addSlides(items: GalleryItemInput[], atIndex?: number): void {\n if (this.destroyed) return;\n const next: GalleryItemInput[] = [...this.itemList];\n next.splice(atIndex ?? next.length, 0, ...items);\n this.updateSlides(next);\n }\n\n /**\n * Sugar over `updateSlides()` for the common \"remove some items\" case.\n * Accepts a single id/index or an array mixing both: a `string` matches\n * the same `id ?? src` key `updateSlides()` already uses for active-item\n * preservation, a `number` matches that position in the *current*\n * `items` list (resolved against the list as it is now, before any\n * removal — passing `[0, 1]` removes the first two items, not \"index 0,\n * then whatever became index 1 after that\").\n */\n removeSlides(match: string | number | Array<string | number>): void {\n if (this.destroyed) return;\n const matches = Array.isArray(match) ? match : [match];\n const indices = new Set(matches.filter((m): m is number => typeof m === 'number'));\n const keys = new Set(matches.filter((m): m is string => typeof m === 'string'));\n const next = this.itemList.filter((item, i) => !indices.has(i) && !keys.has(itemKey(item)));\n this.updateSlides(next);\n }\n\n /** DESIGN.md §2.7 — selector-mode only; sugar over updateSlides() sourced from a DOM rescan. */\n refresh(): void {\n if (this.destroyed) return;\n if (this.isDynamicMode) {\n console.warn('Shoji: refresh() is a no-op in dynamic mode — call updateSlides() instead.');\n return;\n }\n const scanned = scanContainer(this.element, this.selector);\n this.scannedElements = scanned.map((s) => s.element);\n this.updateSlides(scanned.map((s) => s.item));\n }\n\n /** Shared by `destroy()`/`reinit()` (§2.7): force-close, run plugin cleanups, drop gesture/transition/slide/dialog. */\n private teardown(): void {\n if (this.opened) {\n // A real bug, caught by cross-test interference in the unit suite —\n // never reproduced as a simple direct assertion because the existing\n // \"destroy() while the modal is open\" test's `removeEventListener`\n // spy assertion was too loose to actually catch it (FocusTrap's own\n // unrelated document keydown listener removal satisfied the same\n // `expect.any(Function)` matcher). `beginClose()` closes the caption\n // modal first (DESIGN.md §2.3a) — `teardown()` calls `finishClose()`\n // directly instead, skipping `beginClose()` and its own close-path\n // entirely, so destroying a gallery while its caption modal was open\n // never removed that modal's document-level keydown listener. Left\n // unfixed, it leaks forever: a capture-phase listener bound to the\n // destroyed instance, `stopPropagation()`-ing every future keydown on\n // the page regardless of what it's for.\n if (this.captionModalOpen) this.closeCaptionModal();\n // Same gap, same fix, for the toolbar overflow popover (§3.1a) —\n // teardown() skips beginClose() entirely, so a destroy()/reinit()\n // while it happened to be open would leak its own document-level\n // keydown listener the same way.\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n if (!this.isClosing) this.bus.emit('beforeClose', {});\n this.finishClose();\n }\n for (const cleanup of this.pluginCleanups) cleanup();\n this.pluginCleanups = [];\n this.shortcuts.clear();\n this.pluginStorage.clear();\n this.activePluginNames.clear();\n this.videoProviders.clear();\n if (!this.isDynamicMode) {\n this.element.removeEventListener('click', this.onContainerClick);\n }\n this.gesture?.destroy();\n this.gesture = null;\n this.transition = null;\n this.toolbarHeightObserver?.disconnect();\n this.toolbarHeightObserver = null;\n if (this.toolbarHeightFrame !== null) cancelAnimationFrame(this.toolbarHeightFrame);\n this.toolbarHeightFrame = null;\n if (this.captionTruncationFrame !== null) cancelAnimationFrame(this.captionTruncationFrame);\n this.captionTruncationFrame = null;\n this.captionFadePending = false;\n this.slides?.destroy();\n this.dom?.outer.remove();\n this.slides = null;\n this.dom = null;\n // A real leak, caught by inspection: core's own `wireControlHover()`\n // calls in `ensureLightbox()` (closeButton, toolbar slots, caption,\n // counter, ...) never store/call the unsubscribe they return, since\n // there was never anywhere else that needed it before — those elements\n // were expected to just live and die with the rest of `dom` above.\n // `reinit()` routes through here too, though, and rebuilds a whole new\n // `dom` afterward (`ensureLightbox()` runs again) — without this,\n // `hoverableElements` would keep every previous reinit cycle's now-\n // detached elements forever, growing unbounded across repeated calls.\n this.hoverableElements.clear();\n this.hoveringElements.clear();\n // Same reasoning: a plugin's own `ctx.ui.toolbar()` unsubscribe not\n // being called for some reason must not leave stale, now-detached\n // elements in here across a `reinit()` cycle either.\n this.pluginToolbarButtons.length = 0;\n }\n\n destroy(): void {\n if (this.destroyed) return;\n // Guarded, not a plain delete(): if a second Gallery was constructed on\n // this same element without the first ever being destroyed, the\n // registry entry already points at that newer instance — an old,\n // stale `this` being destroyed later must not evict it.\n if (instanceRegistry.get(this.element) === this) instanceRegistry.delete(this.element);\n allInstances.delete(this);\n this.teardown();\n this.bus.emit('destroy', {});\n this.bus.clear();\n this.destroyed = true;\n }\n\n /**\n * DESIGN.md §2.7 — full teardown + reconstruction on `this`, not a new\n * object: `Shoji.getInstance(el)`/any held reference keeps working across\n * the call, unlike `destroy()` + `new Shoji(...)`. Omit `options` to\n * rebuild unchanged (a hard reset); pass options to reconfigure\n * structurally. `gallery.on(...)` listeners do NOT survive — the event\n * bus is fully cleared, same as `destroy()` — re-`on()` anything needed.\n */\n reinit(options: GalleryOptions = this.options): void {\n if (this.destroyed) return;\n this.teardown();\n this.bus.clear();\n this.applyOptions(options);\n }\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport './activeThumbnail.css';\n\nexport interface ActiveThumbnailOptions {\n /** CSS class applied to the origin thumbnail for whichever slide is currently active. Default `'shoji-thumb-active'` — Shoji ships no default styling for this class itself (the host's own thumbnail markup, or the layout plugin's tiles, define what \"active\" looks like); see `highlight` below for Shoji's own opt-in styling. */\n activeClass?: string;\n /** Scrolls the active thumbnail into view (`block: 'nearest'`) whenever it changes. Default `true`. */\n scrollIntoView?: boolean;\n /** Opt-in: also adds a second, fixed (non-renameable) class that Shoji ships real CSS for — a `borderColor` outline around the active thumbnail — instead of leaving 100% of the visual highlight to the host. Default `false`. */\n highlight?: boolean;\n /** Only visible when `highlight: true`. Sets `--shoji-active-thumbnail-border-color` on the active element. Default `'blue'`. */\n borderColor?: string;\n /** Only meaningful when `highlight: true`. Milliseconds after `close()` (i.e. after the highlight actually becomes visible, not from when the slide became active) to fade it out. Default `undefined` — persists indefinitely, moving only when a different slide becomes active. Does not touch `activeClass`, only the built-in `highlight` styling. */\n highlightDuration?: number;\n /** Only meaningful when `highlight: true` and `highlightDuration` is set — otherwise nothing ever fades, so this has no visible effect. How long the fade-to-transparent transition itself takes, in milliseconds, once `highlightDuration` elapses. Default `800`. Reported directly as \"fades too fast\" against the shared `--shoji-duration` (300ms, tuned for ordinary UI transitions, not a deliberately slow fade) this used to reuse. */\n highlightFadeDuration?: number;\n}\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/**\n * Opt-in: keeps the host's thumbnail grid in sync with whichever slide is\n * currently open — highlighting it and, by default, scrolling it into view —\n * as the viewer moves through the lightbox by any means (arrow keys,\n * prev/next buttons, a completed swipe, autoplay ticking forward, a plugin\n * calling `goTo()`). Not core: CLAUDE.md's \"everything that can be a plugin\n * is a plugin\" — a host whose thumbnail grid is short enough to always be\n * fully visible, or who doesn't want their page scrolling out from under\n * them mid-slideshow, should be able to leave this off entirely.\n *\n * Reuses `Gallery.getOriginElement()` (the same index → thumbnail lookup the\n * zoom transition already relies on, §2.3b) rather than re-deriving it, so\n * this plugin's coverage exactly matches whatever the zoom transition\n * already zooms to/from: `scannedElements[index]` in selector mode,\n * `data-shoji-id=\"<item.id>\"` markers elsewhere (including the layout\n * plugin's own tiles, which set that attribute automatically when\n * `item.id` is present).\n */\nexport const ActiveThumbnail: ShojiPlugin = {\n name: 'activeThumbnail',\n defaults: {\n activeClass: 'shoji-thumb-active',\n scrollIntoView: true,\n highlight: false,\n borderColor: 'blue',\n } satisfies ActiveThumbnailOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const activeClass = String(ctx.options.activeClass ?? 'shoji-thumb-active');\n const scrollIntoView = ctx.options.scrollIntoView !== false;\n const highlight = ctx.options.highlight === true;\n const borderColor = String(ctx.options.borderColor ?? 'blue');\n const highlightDuration =\n typeof ctx.options.highlightDuration === 'number' ? ctx.options.highlightDuration : null;\n const highlightFadeDuration =\n typeof ctx.options.highlightFadeDuration === 'number'\n ? ctx.options.highlightFadeDuration\n : 800;\n const HIGHLIGHT_CLASS = 'shoji-thumb-active--highlight';\n\n let current: HTMLElement | null = null;\n // The Layout plugin's own `groupBy` option always fully re-renders (its\n // own doc comment: \"grouped changes always fully re-render\") on any\n // `autoMeasure` correction, not just on real `updateSlides()` calls — a\n // real bug, found via a real integration combining `groupBy` with most\n // items missing `width`/`height` (so most tiles get an `autoMeasure`\n // correction as their real image loads): each correction rebuilt every\n // tile via `createTile()` from scratch, discarding the exact DOM element\n // `current` above pointed at along with whatever class was on it — the\n // highlight simply vanished, often while the lightbox was still open on\n // the very slide it was supposed to be marking. Tracking the *index*\n // (not just the resolved element) is what lets `onLayoutRender` below\n // re-resolve and re-mark the freshly-rebuilt tile — `getOriginElement()`\n // finds it again via the same `data-shoji-id`, which `createTile()` sets\n // on every rebuilt tile regardless.\n let currentIndex: number | null = null;\n let scrollTimer: ReturnType<typeof setTimeout> | null = null;\n let fadeTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPendingScroll(): void {\n if (scrollTimer !== null) {\n clearTimeout(scrollTimer);\n scrollTimer = null;\n }\n }\n\n /** Cancels a still-pending `highlightDuration` fade — called whenever the highlight moves or is re-applied (`applyClass`), so a stale countdown from a previous close never fires against a since-changed or since-reopened element. */\n function cancelFade(): void {\n if (fadeTimer !== null) {\n clearTimeout(fadeTimer);\n fadeTimer = null;\n }\n }\n\n /** Resolves and marks the origin element for `index` — no scrolling, so a DOM rebuild that didn't actually change which slide is active (`onLayoutRender` below) doesn't also re-trigger a scroll nothing about real navigation caused. */\n function applyClass(index: number): HTMLElement | null {\n cancelFade();\n const el = gallery.getOriginElement(index);\n if (current && current !== el) {\n current.classList.remove(activeClass);\n if (highlight) current.classList.remove(HIGHLIGHT_CLASS);\n }\n if (el) {\n el.classList.add(activeClass);\n if (highlight) {\n el.classList.add(HIGHLIGHT_CLASS);\n // Always the real color, not whatever a previous highlightDuration\n // fade may have left it at (transparent) — covers both a genuinely\n // new active element and this same element being re-marked (e.g.\n // reopening at the same index) after having already faded once.\n el.style.setProperty('--shoji-active-thumbnail-border-color', borderColor);\n el.style.setProperty(\n '--shoji-active-thumbnail-fade-duration',\n `${highlightFadeDuration}ms`,\n );\n }\n }\n current = el;\n return el;\n }\n\n /** Scrolling is best-effort — whatever goes wrong with it must never take the highlight down with it (already applied by `applyClass`). */\n function performScroll(el: HTMLElement): void {\n try {\n // The lightbox that's navigating (and so triggering this scroll)\n // is also what's holding the page scroll lock — without this,\n // closing it unconditionally snaps the page back to wherever it\n // was on open, undoing every scroll this call ever made.\n //\n // Through gallery.markIntentionalScroll(), not a direct import of\n // bodyScrollLock's own function — a real bug, confirmed directly:\n // in the standalone core+plugins distribution (DESIGN.md §10),\n // dist/plugins/activeThumbnail.js is bundled completely separately\n // from dist/core/shoji-core.js, so a direct import here would call\n // a totally independent copy of that module's state, invisible to\n // the actual unlockBodyScroll() running inside core. Routing\n // through the Gallery instance itself — always the same instance\n // regardless of bundle mode — reaches whichever bodyScrollLock\n // module *that* build of core is really using.\n gallery.markIntentionalScroll();\n el.scrollIntoView({\n block: 'nearest',\n inline: 'nearest',\n behavior: prefersReducedMotion() ? 'auto' : 'smooth',\n });\n } catch {\n // no-op — see comment above\n }\n }\n\n function apply(index: number): void {\n currentIndex = index;\n cancelPendingScroll();\n const el = applyClass(index);\n if (el && scrollIntoView) {\n // Debounced, not fired on every single navigation directly: a\n // real bug, reported from real usage and confirmed via direct\n // testing — navigating faster than a single smooth scroll can\n // finish (autoplay ticking, or just clicking quickly) leaves the\n // browser with an interrupted, not-yet-settled scroll animation,\n // which can visibly resolve later, at some unrelated later point\n // (e.g. exactly when the gallery closes) rather than simply being\n // superseded. Waiting a short beat before actually scrolling — and\n // restarting that wait on every subsequent navigation — means a\n // rapid burst only ever issues one real scrollIntoView call, for\n // wherever the viewer actually lands, instead of one *per step*\n // that can never keep up and pile up interrupted animations.\n // classList.add() above is unaffected either way — the highlight\n // itself is never debounced, only the scroll. `clear()` below\n // flushes this immediately instead of waiting out the rest of the\n // 80ms if close() happens first.\n scrollTimer = setTimeout(() => {\n scrollTimer = null;\n performScroll(el);\n }, 80);\n }\n }\n\n // NOT cleared on close — a real complaint, reported from real usage:\n // an earlier version removed the highlight the instant the lightbox\n // closed, which defeats the entire point of a *visible* \"you were just\n // looking at this one\" marker — it can only ever be seen once the\n // lightbox (and its backdrop) is gone, and clearing it right then meant\n // there was never a moment a host could actually see it. The highlight\n // now stays on whichever thumbnail was last active until a *different*\n // one becomes active (the next `open()`/`afterSlide`, whenever that is,\n // possibly a whole separate visit to the gallery later) — that's what\n // \"last viewed\" means. Only `onClose` below (the pending-scroll flush)\n // and real teardown (`destroy()`, returned below) still run on close;\n // the highlight itself is untouched by it.\n function onClose(): void {\n // Flushed, not dropped: a navigation immediately followed by close()\n // still means \"this is where I ended up\" — a real complaint, reported\n // from real usage, about an earlier version of this function that\n // called cancelPendingScroll() here instead, silently discarding that\n // final navigation's scroll if close() landed inside its 80ms window\n // (routine, at normal clicking speed) rather than running it. Flushing\n // immediately (not just letting the timer run out naturally after\n // close instead) avoids the *other* failure mode this guarded against\n // originally: the page visibly scrolling on its own some tens of ms\n // after the lightbox is already gone, rather than as part of closing it.\n const pending = scrollTimer !== null ? current : null;\n cancelPendingScroll();\n if (pending && scrollIntoView) performScroll(pending);\n\n // highlightDuration counts from here, not from whenever the slide\n // became active — the highlight is hidden behind the backdrop until\n // now, so a countdown that started earlier (while still open) would\n // burn down time nobody could actually see it for.\n if (highlight && highlightDuration !== null && current) {\n const el = current;\n fadeTimer = setTimeout(() => {\n fadeTimer = null;\n el.style.setProperty('--shoji-active-thumbnail-border-color', 'transparent');\n }, highlightDuration);\n }\n }\n\n /** Real teardown, run only when the plugin itself is going away (`destroy()`) — unlike `onClose()`, this does remove the highlight, since there's no plugin left afterward to manage or move it. */\n function teardown(): void {\n cancelPendingScroll();\n cancelFade();\n current?.classList.remove(activeClass);\n if (highlight) current?.classList.remove(HIGHLIGHT_CLASS);\n current = null;\n currentIndex = null;\n }\n\n const offOpen = ctx.on('afterOpen', ({ index }) => apply(index));\n const offSlide = ctx.on('afterSlide', ({ to }) => apply(to));\n // 'beforeClose', not 'close' — a real bug, reported from real usage and\n // confirmed by reading Gallery.ts directly: 'close' fires from inside\n // finishClose(), which only runs *after* the close (zoom-out) animation\n // completes — but unlockBodyScroll() (also in finishClose(), earlier in\n // the same function) has *already* run and already decided whether to\n // restore the pre-open scroll position, based on whatever\n // markIntentionalScroll() state existed *before* this handler ever got\n // a chance to flush a still-pending scroll. If the last navigation's\n // debounce hadn't fired yet, that decision was wrong: it snapped back\n // to the original position, and only *then* did this handler's flush\n // fire — starting a second, ~1s smooth scroll back to the correct\n // image, well after the lightbox was already gone. 'beforeClose' fires\n // synchronously before any of that — the animation, unlockBodyScroll(),\n // all of it — so flushing here guarantees markIntentionalScroll() has\n // already been called by the time the core makes its restore decision,\n // with no wrong snap-back and no visible second scroll to correct it.\n const offClose = ctx.on('beforeClose', onClose);\n // Re-marks (never re-scrolls, see applyClass's own doc comment) after\n // any render pass that may have rebuilt the DOM out from under `current`\n // — the layout plugin's own real bug, see the comment on `currentIndex`\n // above. Keeps working while closed too now, since `currentIndex` is no\n // longer reset to `null` on close — a layout rebuild between visits\n // still re-marks the right (still-persisted) tile.\n const offLayoutRender = ctx.on('layoutRender', () => {\n if (currentIndex !== null) applyClass(currentIndex);\n });\n\n return () => {\n offOpen();\n offSlide();\n offClose();\n offLayoutRender();\n teardown();\n };\n },\n};\n","/** DESIGN.md §9 — inline SVG, stroke/fill = currentColor, matches src/core/icons.ts's convention. */\n\nexport const PLAY_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"currentColor\"><path d=\"M8 5v14l11-7z\"/></svg>';\n\nexport const PAUSE_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"currentColor\"><path d=\"M7 5h4v14H7zM13 5h4v14h-4z\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { PAUSE_ICON, PLAY_ICON } from './icons';\nimport './autoplay.css';\n\n/**\n * A native `<video>` or a `.shoji-slide-provider-video` container a video\n * provider plugin (§4-video) has augmented with the same shape — Autoplay\n * never needs to know which. `play()`'s return type is technically a lie\n * for the provider case (that `.play` is a synchronous fire-and-forget, no\n * `HTMLVideoElement.play()`-style promise) — harmless, `enterSlide()`'s own\n * `typeof playResult.catch === 'function'` guard already treats a\n * non-promise `play()` result as \"nothing to await,\" same as `undefined`.\n */\ntype PlayableMedia = Pick<\n HTMLVideoElement,\n 'play' | 'pause' | 'paused' | 'ended' | 'muted' | 'addEventListener' | 'removeEventListener'\n>;\n\n/** `.shoji-slide-provider-video` only counts if it's actually been wired up as playable (§4-video's `wirePlayableContract`) — a provider still mid-async-setup, or one that never opted into Autoplay sync at all, isn't. */\nfunction findPlayable(media: HTMLElement | null): PlayableMedia | null {\n const video = media?.querySelector('video');\n if (video) return video;\n const provider = media?.querySelector<HTMLElement & Partial<PlayableMedia>>(\n '.shoji-slide-provider-video',\n );\n if (provider && typeof provider.play === 'function') return provider as PlayableMedia;\n return null;\n}\n\n/** A provider container is attached to the DOM immediately (§4-video), well before its async setup (loading an SDK, constructing a player) finishes wiring `.play` — this is what tells `enterSlide()` \"there's a video here, it's just not playable yet\" apart from \"no video at all,\" so it doesn't mistreat a still-loading video as an ordinary timed slide. */\nfunction isPendingProviderVideo(media: HTMLElement | null): boolean {\n const provider = media?.querySelector<HTMLElement & Partial<PlayableMedia>>(\n '.shoji-slide-provider-video',\n );\n return !!provider && typeof provider.play !== 'function';\n}\n\n// A provider embed's postMessage bridge (DESIGN.md §4.3) can need more real\n// time after \"ready\" before it reliably processes its first command — a\n// play() issued too soon can silently no-op with nothing to catch. Retries\n// a few times with a short delay instead of a single best-effort attempt.\nconst PROVIDER_PLAY_RETRY_MS = 400;\nconst MAX_PROVIDER_PLAY_ATTEMPTS = 8; // + the initial attempt = 9 total, ~3.6s before giving up\n\nexport interface AutoplayOptions {\n /** Milliseconds between advances for timed (photo) slides. Default `5000`. */\n interval?: number;\n /** Shows the thin progress bar (`--shoji-progress`) tracking time-to-next-advance along the dialog's bottom edge, for timed slides only — never shown during video slides, whose own runtime drives advancement instead. Default `true`. Purely presentational: turning it off doesn't change any timing, only whether it's drawn. */\n showProgress?: boolean;\n /** Starts the slideshow automatically as soon as the gallery opens — every `open()`, not just the first — instead of waiting for the toolbar button/`Space`. Default `false`. */\n autoStart?: boolean;\n /**\n * How the slideshow reacts to the viewer zooming in on the active slide\n * (Zoom plugin). `'stop'` (default): pauses immediately and stays paused\n * until Play is pressed again, even once un-zoomed back to neutral — no\n * auto-resume. `'pause'`: same immediate pause, but auto-resumes on its\n * own once genuinely disengaged (see the module-level doc comment on\n * `RESUME_DEBOUNCE_MS` for why that's debounced rather than instant).\n * `false`: a complete no-op, regardless of zoom state. A no-op either way\n * if Zoom isn't loaded. Was a plain `pauseOnZoom` boolean (`true`\n * meaning today's `'stop'`) before `'pause'` existed as an option at all.\n */\n onZoom?: 'stop' | 'pause' | false;\n /**\n * Same shape as `onZoom`, for RotateFlip: `'stop'` (default) pauses on\n * any interaction — including one that lands back on the original\n * orientation, since the click itself is still an active interruption,\n * not just its end state — and stays paused; `'pause'` does the same\n * immediate pause but auto-resumes once genuinely disengaged (debounced,\n * same as `onZoom`); `false` is a no-op. A no-op either way if\n * RotateFlip isn't loaded. Was `pauseOnRotateFlip` before `'pause'`\n * existed.\n */\n onRotateFlip?: 'stop' | 'pause' | false;\n /**\n * Same shape as `onZoom`/`onRotateFlip`, for the viewer expanding a\n * truncated caption to read the rest (core's own caption modal,\n * DESIGN.md §2.3a). `'stop'` (default) pauses and stays paused; `'pause'`\n * auto-resumes once the modal closes (debounced, same as the other two —\n * even though the modal itself makes no *further* engagement possible\n * once closed, the same short window still applies for consistency and\n * because it costs nothing here). `false` is a no-op. Was\n * `pauseOnCaptionExpand` before `'pause'` existed. Unlike `onZoom`/\n * `onRotateFlip`, no re-check on Play is needed either mode: the modal\n * traps both pointer and keyboard input while open (core blocks every\n * key, not just Escape), so Play is physically unreachable until the\n * modal is already closed.\n */\n onCaptionExpand?: 'stop' | 'pause' | false;\n /** Pauses the slideshow the moment the viewer navigates manually — arrow keys/buttons, a completed swipe, a thumbnail click, or any other `goTo()` not caused by Autoplay's own `advance()` — instead of silently re-timing itself on whatever slide they land on. Stays paused until Play is pressed again — always a hard stop, no `'pause'`-style auto-resume variant: unlike zoom/rotate-flip/caption-expand, navigating away has no \"returns to its original state\" to resume from, so there's nothing for an auto-resume to key off. Default `true`, same reasoning as `onZoom`/`onRotateFlip`/`onCaptionExpand` above — reaching for the navigation controls at all is a clear signal of active engagement, and a slideshow that keeps ticking underneath that reads as broken, not helpful. Set `false` to restore the original \"manual nav just re-times the current slide\" behavior. Was `pauseOnManualNavigate` before the other three options gained a `'pause'` mode — renamed alongside them so \"stop\" only ever means stop now, not a mix of stop and pause depending which option you're reading. */\n stopOnManualNavigate?: boolean;\n}\n\n/**\n * Only meaningful for `onZoom`/`onRotateFlip`/`onCaptionExpand`'s `'pause'`\n * mode. A real bug, reported from real usage against this exact plugin's\n * *first* attempt at auto-resume (long before `'pause'` existed as a named\n * option — that attempt just always auto-resumed the moment zoom/rotate-\n * flip reported \"back to neutral\"): un-zooming or un-rotating back to\n * exactly neutral doesn't mean the viewer is done — reaching neutral is\n * just as easily one step *through* on the way to further interaction\n * (e.g. rotating 90 -> 180 -> 270 -> 0, or zooming out then immediately\n * back in) as it is the actual end of one. Resuming instantly on that\n * first neutral reading sprung the slideshow back to life mid-interaction,\n * which reads as more broken than never auto-resuming at all — the\n * original fix for this was simply to remove auto-resume entirely (the\n * `'stop'`-only behavior every `pauseOn*` option had until now). A short\n * idle debounce after the *last* disengage is what actually distinguishes\n * \"done interacting\" from \"just passing through neutral\": each further\n * engagement (re-zooming, another rotate/flip click) cancels and restarts\n * the wait, so the slideshow only ever resumes once nothing has happened\n * for a real pause in activity, not on the instant a single event happens\n * to read as neutral. Not configurable — an internal implementation detail\n * of what \"genuinely disengaged\" means, not a knob a host needs.\n */\nconst RESUME_DEBOUNCE_MS = 1000;\n\n/**\n * DESIGN.md §4-autoplay. Advances on a fixed `interval` (default 5000ms) for\n * ordinary slides; for a video slide, plays it and waits for `ended` instead\n * — the interval never applies to video. A manual pause on that video pauses\n * the *slideshow* too (not just the video); manually resuming the video does\n * NOT resume the slideshow — that requires pressing the slideshow's own\n * play control again. See `enterSlide()`/`onVideoPause()` below for exactly\n * where each half of that rule lives.\n */\nexport const Autoplay: ShojiPlugin = {\n name: 'autoplay',\n defaults: {\n interval: 5000,\n showProgress: true,\n onZoom: 'stop',\n onRotateFlip: 'stop',\n onCaptionExpand: 'stop',\n stopOnManualNavigate: true,\n } satisfies AutoplayOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const interval = Number(ctx.options.interval ?? 5000);\n const showProgress = ctx.options.showProgress !== false;\n const autoStart = ctx.options.autoStart === true;\n const readMode = (value: unknown): 'stop' | 'pause' | false =>\n value === false || value === 'pause' ? value : 'stop';\n const onZoom = readMode(ctx.options.onZoom);\n const onRotateFlip = readMode(ctx.options.onRotateFlip);\n const onCaptionExpand = readMode(ctx.options.onCaptionExpand);\n const stopOnManualNavigate = ctx.options.stopOnManualNavigate !== false;\n const locale = ctx.options.locale as Partial<Record<'play' | 'pause', string>> | undefined;\n const playLabel = locale?.play ?? 'Play slideshow';\n const pauseLabel = locale?.pause ?? 'Pause slideshow';\n\n let playing = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let currentVideo: PlayableMedia | null = null;\n let awaitingProviderVideo = false;\n let wasPlayingBeforeDrag = false;\n // Tracks only the *current* zoom/rotate-flip state, purely for\n // toggle()'s \"was it already engaged the moment Play was pressed\"\n // check below — not reused for the pause-on-event logic itself, which\n // reacts to each zoomChange/rotateFlipChange event directly instead of\n // consulting these.\n let zoomedIn = false;\n let rotatedOrFlipped = false;\n let captionOpen = false;\n // Set only when this plugin itself stopped playback because of an\n // `onX: 'pause'` trigger — never for a manual stop, a `'stop'`-mode\n // trigger, `requestAutoplayStop`, or anything else that calls stop()\n // for an unrelated reason (video pause/end, drag-close, close()). Once\n // any of those flags is true, `maybeScheduleResume()` (below) is what's\n // waiting for the *matching* engagement flag (`zoomedIn`/\n // `rotatedOrFlipped`/`captionOpen`) to clear before it'll actually\n // queue the debounced resume — see `RESUME_DEBOUNCE_MS`'s own doc\n // comment for why that's a debounce and not instant.\n let pausedByZoom = false;\n let pausedByRotateFlip = false;\n let pausedByCaptionExpand = false;\n let resumeTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPendingResume(): void {\n if (resumeTimer !== null) {\n clearTimeout(resumeTimer);\n resumeTimer = null;\n }\n }\n\n /** Called on every hard stop (manual, `'stop'`-mode trigger, `requestAutoplayStop`, manual navigation, or anything else) — a hard stop always wins outright over a softer pending `'pause'`-mode resume from a *different* trigger, otherwise un-rotating after a hard zoom-stop could still spring the slideshow back to life on its own. */\n function clearPauseFlags(): void {\n pausedByZoom = false;\n pausedByRotateFlip = false;\n pausedByCaptionExpand = false;\n cancelPendingResume();\n }\n\n /**\n * Queues the actual resume once every `'pause'`-mode trigger that\n * caused the current stop has genuinely disengaged — not on the first\n * instant all three read as disengaged, but after `RESUME_DEBOUNCE_MS`\n * of that holding true, restarting the wait on every call (so\n * `zoomChange`/`rotateFlipChange`/`captionModalChange` re-engaging\n * before it fires cancels and re-arms it rather than stacking a second\n * timer). A no-op if nothing is actually pending — called from every\n * disengage point regardless of whether anything's waiting, cheaper\n * than each call site checking first.\n */\n function isEngaged(): boolean {\n return (\n (onZoom !== false && zoomedIn) ||\n (onRotateFlip !== false && rotatedOrFlipped) ||\n (onCaptionExpand !== false && captionOpen)\n );\n }\n\n function maybeScheduleResume(): void {\n if (!(pausedByZoom || pausedByRotateFlip || pausedByCaptionExpand)) return;\n if (isEngaged()) return;\n cancelPendingResume();\n resumeTimer = setTimeout(() => {\n resumeTimer = null;\n // Re-checked here, not just at the top of this function above — a\n // real bug, caught by this file's own test: a *different* trigger\n // can re-engage while this timer is already ticking down without\n // ever calling this function again (its own handler only reaches\n // maybeScheduleResume() when *it* transitions to disengaged, not\n // when it transitions to engaged) — e.g. rotating while a zoom\n // resume is already pending. Firing start() unconditionally would\n // resume playback while still visibly rotated. Leaves the pending\n // flags alone rather than clearing them: whichever trigger\n // eventually disengages next calls maybeScheduleResume() again and\n // finds them still set.\n if (isEngaged()) return;\n clearPauseFlags();\n start();\n }, RESUME_DEBOUNCE_MS);\n }\n\n // Set for the exact duration of advance()'s own gallery.next() call —\n // the afterSlide handler below fires synchronously inside it, so it can\n // tell \"this slide change is autoplay's own advance()\" apart from any\n // other navigation (arrows/buttons/swipe/goTo()) without needing the\n // event itself to carry a source. See stopOnManualNavigate above.\n let isAdvancing = false;\n\n // A real bug, regression: this used to capture gallery.getActiveMedia()\n // once here and listen on that node directly, back when a pool slot's\n // own offset never changed after construction (only its *content*\n // moved between slots) — so \"whichever slot has offset 0\" was always\n // the same physical node, safe to capture once. SlideManager's pool now\n // relabels a slot's offset in place instead (§2.3) — the node that\n // happened to be offset 0 when this plugin initialized can become a\n // neighbor after even one navigation, while a *different* node becomes\n // the active one, silently going unheard by this listener. Listening on\n // `ctx.ui.outer()` instead (the whole lightbox, never relabeled) still\n // catches a provider's own error event (§4-video's `onError`, dispatched\n // with `bubbles: true`) regardless of which slide it came from — the\n // `contains()` check below is what actually scopes it to the currently\n // active slide, re-resolved fresh on every error rather than trusting a\n // stale reference.\n const outer = ctx.ui.outer();\n function onVideoError(event: Event): void {\n if (!playing) return;\n const active = gallery.getActiveMedia();\n if (active && event.target instanceof Node && active.contains(event.target)) advance();\n }\n outer.addEventListener('error', onVideoError);\n\n const button = document.createElement('button');\n button.type = 'button';\n // shoji-autoplay-toggle: a stable hook for host code that needs to find\n // this button from outside (e.g. to pause the slideshow before opening\n // its own UI on top) — `title`/`aria-label` swap with `locale`, so\n // matching on those breaks silently the moment a host customizes it.\n button.className = 'shoji-toolbar-button shoji-autoplay-toggle';\n button.setAttribute('aria-label', playLabel);\n button.title = playLabel;\n button.innerHTML = PLAY_ICON;\n\n const progress = document.createElement('div');\n progress.className = 'shoji-autoplay-progress';\n progress.hidden = true;\n const progressBar = document.createElement('div');\n progressBar.className = 'shoji-autoplay-progress-bar';\n progress.appendChild(progressBar);\n\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function resetProgressBar(): void {\n if (!showProgress) return;\n progress.hidden = true;\n progressBar.style.transition = 'none';\n progressBar.style.width = '0%';\n }\n\n function runProgressBar(ms: number): void {\n if (!showProgress) return;\n progress.hidden = false;\n progressBar.style.transition = 'none';\n progressBar.style.width = '0%';\n void progressBar.offsetWidth; // commit the reset before transitioning\n progressBar.style.transition = `width ${ms}ms linear`;\n progressBar.style.width = '100%';\n }\n\n /**\n * DESIGN.md §4.1 — while `onZoom`/`onRotateFlip` is holding\n * playback paused, pressing Play would otherwise just silently\n * re-pause it in the same synchronous tick (`toggle()`'s own check,\n * below) — no `transitionend`, no paint in between the two state\n * flips, so the button never visibly shows \"Pause\" at all before\n * reverting. Reported as looking broken, not just quiet. Disabling\n * the button while blocked (same `aria-disabled`/`tabIndex`/CSS\n * pattern as core's own slide-loading disable, Gallery.ts's\n * `setSlideLoading()`) makes \"you can't resume yet\" an honest, visible\n * state instead of a click that does nothing. Only while *not*\n * playing — while playing, the button always shows/means Pause, and\n * must stay clickable to stop regardless of zoom/rotate state.\n */\n function updateToggleAvailability(): void {\n const blocked =\n !playing &&\n ((onZoom !== false && zoomedIn) || (onRotateFlip !== false && rotatedOrFlipped));\n button.ariaDisabled = blocked ? 'true' : null;\n if (blocked) button.tabIndex = -1;\n else button.removeAttribute('tabindex');\n }\n\n function setButtonState(isPlaying: boolean): void {\n playing = isPlaying;\n button.innerHTML = isPlaying ? PAUSE_ICON : PLAY_ICON;\n button.setAttribute('aria-label', isPlaying ? pauseLabel : playLabel);\n button.title = isPlaying ? pauseLabel : playLabel;\n updateToggleAvailability();\n }\n\n function onVideoEnded(): void {\n if (playing) advance();\n }\n\n // A real user pause, as opposed to the pause some browsers fire\n // immediately alongside 'ended' — `.ended` disambiguates the two.\n // Provider videos (§4.3's renderers) are responsible for holding their\n // own 'pause' dispatch back if it might just be a natural end arriving\n // slightly early — vimeo.ts's `PAUSE_DISPATCH_DELAY_MS` is why.\n function onVideoPause(): void {\n if (currentVideo?.ended) return;\n stop();\n }\n\n function detachVideo(): void {\n if (!currentVideo) return;\n currentVideo.removeEventListener('ended', onVideoEnded);\n currentVideo.removeEventListener('pause', onVideoPause);\n currentVideo = null;\n }\n\n // A provider embed (e.g. YouTube) is cross-origin — unlike native\n // <video>, its own autoplay policy requires a *direct* user gesture on\n // the embed itself, which an automatic play() arriving via this\n // timer/'ended'/slideItemLoad chain never has; it silently no-ops\n // rather than rejecting, so there's nothing to catch. Muting first is\n // what actually gets it to play — the viewer can still unmute via the\n // embed's own controls.\n //\n // A real bug, reported from real usage, found only once a second\n // promise-returning provider (Vimeo) existed to compare against:\n // re-issuing `play()`/`muted = true` on every retry — needed for\n // YouTube, whose fire-and-forget `playVideo()` can silently drop a\n // command issued before its postMessage bridge is fully settled — does\n // the opposite for a provider whose `play()` genuinely returns a\n // promise. Confirmed directly, isolated from Shoji entirely: a single,\n // uninterrupted `play()` call reliably started Vimeo playback in\n // ~1.6s, while calling it again every 400ms (this loop's original,\n // unconditional behavior) kept it stuck indefinitely — each new call\n // resets the progress the previous one had already made, so it never\n // gets an uninterrupted run long enough to actually start. (This is\n // also what point 12 below's retry-exhaustion was actually skipping\n // past: not a broken video, but this loop's own repeated calls\n // preventing it from ever finishing what the first one started.)\n // `video.play()`'s return type only *claims* to be a promise for every\n // provider (see the `PlayableMedia` doc comment above) — branching on\n // whether it genuinely is one is what lets each provider get the\n // retry behavior it actually needs from this one shared function.\n function ensureProviderPlaying(video: PlayableMedia, attemptsLeft: number): void {\n video.muted = true;\n const playResult = video.play();\n if (playResult && typeof playResult.then === 'function') {\n pollWithoutReissuing(video, attemptsLeft, playResult);\n } else {\n reissueOnEachRetry(video, attemptsLeft);\n }\n }\n\n /** Fire-and-forget `play()` (YouTube) — re-issues the command itself on every retry, per this function's own doc comment above. */\n function reissueOnEachRetry(video: PlayableMedia, attemptsLeft: number): void {\n setTimeout(() => {\n if (currentVideo !== video || !playing) return; // stale — slide changed, or already stopped\n if (!video.paused) return; // took effect\n if (attemptsLeft > 0) ensureProviderPlaying(video, attemptsLeft - 1);\n // Exhausted every retry after already muting first — muted\n // autoplay is essentially never blocked by policy, so this means\n // something is genuinely wrong with the embed, not that it's\n // waiting on a gesture. advance() (not stop()) so a slow/late\n // error report (real usage: YouTube's own error can arrive slower\n // than this retry window, e.g. Error 153) can't leave the\n // slideshow stuck if this fires first.\n else advance();\n }, PROVIDER_PLAY_RETRY_MS);\n }\n\n /** A genuine `play()` promise (e.g. Vimeo) — the command itself is only ever issued once (by the caller); this only re-checks `.paused` on the same schedule, over the same total budget, without ever calling `play()` again. */\n function pollWithoutReissuing(\n video: PlayableMedia,\n attemptsLeft: number,\n playResult: Promise<void>,\n ): void {\n // Swallowed deliberately: a rejection here isn't distinguished from\n // \"still pending\" — the .paused poll below is what actually decides\n // whether this took effect, on the same schedule regardless of how\n // the promise itself settles. An unhandled-rejection console warning\n // is the only cost, same tradeoff as the native <video> path below\n // taking a real .catch() instead when it needs to branch on *why*.\n playResult.catch(() => {});\n setTimeout(() => {\n if (currentVideo !== video || !playing) return;\n if (!video.paused) return;\n if (attemptsLeft > 0) pollWithoutReissuing(video, attemptsLeft - 1, playResult);\n else advance();\n }, PROVIDER_PLAY_RETRY_MS);\n }\n\n function enterSlide(): void {\n clearTimer();\n detachVideo();\n resetProgressBar();\n awaitingProviderVideo = false;\n if (!playing) return;\n\n const media = gallery.getActiveMedia();\n const video = findPlayable(media);\n if (video) {\n currentVideo = video;\n video.addEventListener('ended', onVideoEnded);\n video.addEventListener('pause', onVideoPause);\n if (video instanceof HTMLVideoElement) {\n const playResult = video.play();\n // A rejected play() has two different causes that look identical\n // here: the browser blocking an unmuted play() that isn't a direct\n // continuation of a user gesture (NotAllowedError — the video is\n // fine, it just needs the viewer's own click) or the video\n // genuinely being unplayable (NotSupportedError — a broken/missing\n // source, an unsupported format). Only the first pauses the\n // slideshow for the viewer to resolve by hand; anything else means\n // there's nothing to wait for, so it skips ahead instead.\n if (playResult && typeof playResult.catch === 'function') {\n playResult.catch((error: unknown) => {\n if (currentVideo !== video || !playing) return; // stale\n if (error instanceof DOMException && error.name === 'NotAllowedError') stop();\n else advance();\n });\n }\n } else {\n ensureProviderPlaying(video, MAX_PROVIDER_PLAY_ATTEMPTS);\n }\n return;\n }\n\n // A provider video (e.g. YouTube) still mid-setup isn't an ordinary\n // slide either — the slideItemLoad listener below re-enters once it's\n // actually playable. This timer is a fallback in case that never\n // happens (network failure, blocked, ...), so the slideshow can't\n // stall on it forever.\n awaitingProviderVideo = isPendingProviderVideo(media);\n runProgressBar(interval);\n timer = setTimeout(advance, interval);\n }\n\n function advance(): void {\n const before = gallery.currentIndex;\n isAdvancing = true;\n gallery.next();\n isAdvancing = false;\n // loop:false and next() was already at the last item — nothing left\n // to advance to; the 'afterSlide' handler below won't fire for a\n // no-op goTo(), so this is the only place that can catch it.\n if (gallery.currentIndex === before) stop();\n }\n\n function start(): void {\n if (playing) return;\n // A manual start succeeding makes any still-ticking 'pause'-mode\n // resume timer moot — harmless left alone (its own eventual start()\n // call would just no-op against the `if (playing) return` above), but\n // cancelling it here avoids a dangling timer doing nothing for up to\n // RESUME_DEBOUNCE_MS after this already resolved things.\n cancelPendingResume();\n setButtonState(true);\n ctx.emit('autoplayStart', {});\n enterSlide();\n }\n\n function stop(): void {\n if (!playing) return;\n setButtonState(false);\n clearTimer();\n resetProgressBar();\n if (currentVideo && !currentVideo.paused) currentVideo.pause();\n detachVideo();\n ctx.emit('autoplayStop', {});\n }\n\n // A real bug, reported from real usage: zooming in *first*, then\n // pressing Play, never paused at all — clicking Play doesn't itself\n // fire zoomChange/rotateFlipChange, and a single-step \"toggle back to\n // neutral\" action afterward (Actual size, double-tap-to-reset) only\n // ever emits the *already-neutral* event, never one crossing the\n // engaged threshold — so nothing downstream would ever have caught it\n // either. Re-checked here instead, right after a genuine manual\n // start — the one path a viewer can actually reach a non-neutral view\n // state from *before* pressing Play. `zoomedIn`/`rotatedOrFlipped`\n // (below) track only the *current* state, purely for this check —\n // deliberately not reused for the pause-on-event logic itself, which\n // reacts to each event directly. Shared by toggle()'s manual-start path\n // and requestAutoplayStart below — both are \"a genuine manual start,\"\n // just triggered from a different control.\n function reCheckEngagedAfterManualStart(): void {\n const stillZoomed = onZoom !== false && zoomedIn;\n const stillRotated = onRotateFlip !== false && rotatedOrFlipped;\n if (!stillZoomed && !stillRotated) return;\n stop();\n // Threading pause-mode tracking through *this* re-stop too (not just\n // the zoomChange/rotateFlipChange handlers below) is what avoids\n // repeating the first auto-resume attempt's other real bug: a manual\n // restart while still engaged left that design's own edge-tracker\n // permanently \"already engaged,\" silently skipping the next\n // re-pause's resume tracking. Setting the flag here, at the actual\n // moment this stop happens, means it's never missed regardless of\n // which path (button/Space, or a custom plugin's requestAutoplayStart)\n // triggered the manual start.\n if (onZoom === 'pause' && stillZoomed) pausedByZoom = true;\n if (onRotateFlip === 'pause' && stillRotated) pausedByRotateFlip = true;\n }\n\n function toggle(): void {\n if (playing) {\n clearPauseFlags(); // a real manual pause is always a hard stop, never a pending soft-resume\n stop();\n return;\n }\n start();\n reCheckEngagedAfterManualStart();\n }\n\n /**\n * Pauses the slideshow the instant a vertical drag crosses the close\n * threshold, mirroring the controls' own live hide cue\n * (`dragCloseThreshold`) — asked for directly, otherwise the\n * interval/video kept running mid-drag. Resumes only if *this*\n * crossing paused it — a manual pause (toolbar, mid-drag tap) must\n * stay paused even if the drag retreats back under the threshold.\n */\n const offDragThreshold = ctx.on('dragCloseThreshold', ({ hidden }) => {\n if (hidden) {\n wasPlayingBeforeDrag = playing;\n if (playing) {\n clearPauseFlags(); // a hard stop, unrelated to onZoom/onRotateFlip/onCaptionExpand — must not resurrect a pending soft-resume from one of those\n stop();\n }\n } else if (wasPlayingBeforeDrag) {\n wasPlayingBeforeDrag = false;\n start();\n }\n });\n\n /**\n * DESIGN.md §4.1 — a real UX gap, not a reported bug: nothing stopped\n * the slideshow from auto-advancing out from under a viewer actively\n * zoomed into a detail on the current slide. Only reacts to\n * `zoomChange`'s event *shape* (`core/types.ts`) — never imports Zoom\n * directly, so this is a no-op with it not loaded, or with `onZoom:\n * false` set explicitly (events over inheritance, CLAUDE.md).\n *\n * `'stop'` mode never auto-resumes, matching this plugin's *first*\n * attempt at this feature — see `RESUME_DEBOUNCE_MS`'s own doc comment\n * for the two real problems that attempt hit and why `'pause'` mode\n * (below) is built differently, not just re-adding the same thing\n * under a new name. `scale > 1` still gates *which* zoomChange events\n * count (an ordinary scale-1 event can also fire from an unrelated\n * slide-change reset, not a real interaction — `zoom/index.ts`'s\n * `reset()` — so it can't unconditionally pause on every event the way\n * rotateFlipChange below safely can).\n */\n const ZOOM_ENGAGED_THRESHOLD = 1.001; // matches Zoom's own ZOOM_EPSILON — \"just barely above 1\" is float residue, not a real zoom\n const offZoomChange = ctx.on('zoomChange', ({ scale }) => {\n zoomedIn = scale > ZOOM_ENGAGED_THRESHOLD;\n if (onZoom !== false && zoomedIn && playing) {\n if (onZoom === 'stop') clearPauseFlags();\n stop();\n if (onZoom === 'pause') pausedByZoom = true;\n } else {\n // stop() above already refreshes toggle availability; this branch\n // covers zooming in while already paused (stop() wouldn't touch\n // it) and zooming back out, which may have just disengaged the\n // last thing a pending 'pause'-mode resume was waiting on.\n updateToggleAvailability();\n if (!zoomedIn) maybeScheduleResume();\n }\n });\n /**\n * Same UX gap, RotateFlip's own equivalent (see `onRotateFlip`'s own\n * doc comment). Pauses on *any* `rotateFlipChange` event\n * unconditionally, including one that lands back on the original\n * orientation — confirmed directly, reported from real usage: rotate\n * four times back to 0deg still reads as an active interruption of the\n * slideshow, not \"nothing happened,\" so it must still pause too, the\n * same as landing anywhere else, in *both* modes — `'pause'` mode's\n * auto-resume is debounced specifically so this repeated-neutral case\n * doesn't spring it back to life between clicks (`RESUME_DEBOUNCE_MS`).\n * Every `rotateFlipChange` (unlike zoomChange above) only ever fires\n * from a real button/shortcut click — `rotateFlip/index.ts`'s own\n * per-slide `reset()` never emits it — so no extra state check is\n * needed here the way zoomChange's `scale > 1` gate is.\n */\n const offRotateFlipChange = ctx.on('rotateFlipChange', ({ flipH, flipV, rotation }) => {\n rotatedOrFlipped = flipH || flipV || rotation !== 0;\n if (onRotateFlip !== false && playing) {\n if (onRotateFlip === 'stop') clearPauseFlags();\n stop();\n if (onRotateFlip === 'pause') pausedByRotateFlip = true;\n } else {\n updateToggleAvailability(); // stop() above already refreshes this; covers rotating while already paused, which stop() wouldn't touch\n if (onRotateFlip !== false && !rotatedOrFlipped) maybeScheduleResume();\n }\n });\n /**\n * `onCaptionExpand`'s own doc comment above — unlike the two listeners\n * above, no `updateToggleAvailability()` companion call: the caption\n * modal already makes Play physically unreachable while `open: true`\n * (core's own focus trap + capture-phase keydown blocking, not\n * anything this plugin has to enforce), so there's no \"pressed Play\n * while still blocked\" case to disable the button for or re-check on\n * toggle() the way zoom/rotateFlip both need. `captionOpen` is still\n * tracked (unlike before `'pause'` mode existed) purely so\n * `maybeScheduleResume()` can confirm nothing else is also still\n * engaged before it queues a resume.\n */\n const offCaptionModalChange = ctx.on('captionModalChange', ({ open }) => {\n captionOpen = open;\n if (onCaptionExpand !== false && open && playing) {\n if (onCaptionExpand === 'stop') clearPauseFlags();\n stop();\n if (onCaptionExpand === 'pause') pausedByCaptionExpand = true;\n } else if (!open) {\n maybeScheduleResume();\n }\n });\n\n button.addEventListener('click', toggle);\n\n // 'right' — clusters immediately before the close button, per DESIGN.md §3.1.\n const removeButton = ctx.ui.toolbar('right', button);\n const removeProgress = showProgress ? ctx.ui.overlay(progress) : null;\n const removeShortcut = ctx.ui.registerShortcut(' ', toggle);\n // Detaches this plugin's own 'pause'/'ended' listeners from the outgoing\n // video before Gallery.navigate() pauses it (see Gallery.ts's comment on\n // this same event) — otherwise that pause is misread as the viewer\n // manually pausing, which stops the slideshow before the new slide's\n // afterSlide handler below ever runs. enterSlide() below also calls\n // detachVideo(), but by then it's too late for *this* transition; that\n // call is what handles the slide *after* this one instead.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n detachVideo();\n });\n // Any slide change — autoplay's own next(), or the viewer manually\n // navigating mid-slideshow via arrows/buttons/goTo() — re-enters here,\n // tearing down the previous slide's timer/video listeners and setting\n // up fresh ones for whatever is active now. advance() deliberately does\n // NOT call enterSlide() itself: next() already triggers this listener\n // synchronously, so calling it twice would double up the timer/video wiring.\n const offSlide = ctx.on('afterSlide', () => {\n // Zoom/RotateFlip both reset unanimated on navigation (DESIGN.md\n // §2.5) without re-emitting zoomChange/rotateFlipChange — resynced\n // here so a stale \"was engaged\" reading from the *outgoing* slide\n // can't wrongly re-pause toggle()'s next Play press on a slide\n // that's actually neutral now. Also clears any pending 'pause'-mode\n // resume outright, not just the flags it was waiting on — the slide\n // it was paused *for* isn't even the active one anymore, so whether\n // to resume here is genuinely ambiguous; `stopOnManualNavigate`\n // (default true) already decides what actually happens next.\n zoomedIn = false;\n rotatedOrFlipped = false;\n clearPauseFlags();\n updateToggleAvailability();\n if (!playing) return;\n // stopOnManualNavigate (default true, see its own doc comment) —\n // isAdvancing is only ever true for the exact duration of advance()'s\n // own gallery.next() call above, so its absence here means something\n // other than autoplay itself moved the slide.\n if (stopOnManualNavigate && !isAdvancing) stop();\n else enterSlide();\n });\n // A provider video (§4-video) that was still mid-setup when enterSlide()\n // last ran — see awaitingProviderVideo there — becomes playable some\n // time after afterSlide already fired and gave up on it for this pass.\n // Re-enter once it's genuinely ready, scoped to the still-active index\n // so a slide the viewer has already moved past doesn't retroactively\n // hijack the timer.\n const offSlideItemLoad = ctx.on('slideItemLoad', ({ index }) => {\n if (playing && awaitingProviderVideo && index === gallery.currentIndex) enterSlide();\n });\n /**\n * DESIGN.md §4.1 point 20 — a generic command surface, requested\n * directly, so a *custom* (host-authored) plugin's own toolbar button\n * can start/pause the slideshow without importing this plugin at all,\n * the same \"events over inheritance\" decoupling every other listener\n * here already uses for official plugins (`zoomChange`,\n * `rotateFlipChange`, `captionModalChange`, `dragCloseThreshold`).\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestAutoplayStop', {})` from any plugin\n * — official or custom — type-checks with zero core changes; this is\n * just the listening half. Deliberately two separate commands, not one\n * toggle — a custom plugin building its own distinct Play/Pause\n * controls (rather than one button that flips) needs to command each\n * state directly, not guess at the current one. Both no-op in the\n * already-there state (`stop()`'s own existing guard for pause;\n * `start()`'s own existing guard, plus the same manual-start re-check\n * `toggle()`'s button/Space path uses, for start).\n */\n const offRequestStop = ctx.on('requestAutoplayStop', () => {\n if (playing) {\n clearPauseFlags(); // a command from another plugin is treated like a manual pause, not a soft pending resume\n stop();\n }\n });\n const offRequestStart = ctx.on('requestAutoplayStart', () => {\n if (playing) return;\n start();\n reCheckEngagedAfterManualStart();\n });\n const offClose = ctx.on('close', () => {\n clearPauseFlags();\n stop();\n });\n const offOpen = ctx.on('afterOpen', () => {\n zoomedIn = false;\n rotatedOrFlipped = false;\n captionOpen = false;\n clearPauseFlags();\n updateToggleAvailability();\n if (autoStart) start();\n });\n\n return () => {\n cancelPendingResume(); // a pending 'pause'-mode resume must not fire start() after teardown\n stop();\n outer.removeEventListener('error', onVideoError);\n removeButton();\n removeProgress?.();\n removeShortcut();\n offBeforeSlide();\n offSlide();\n offSlideItemLoad();\n offOpen();\n offClose();\n offDragThreshold();\n offZoomChange();\n offRotateFlipChange();\n offCaptionModalChange();\n offRequestStop();\n offRequestStart();\n };\n },\n};\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. Four corner-arrow glyphs, a generic \"expand\"/\"collapse\" pair, not tied to any particular icon set. */\nexport const EXPAND_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5\"/></svg>';\n\nexport const COMPRESS_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { COMPRESS_ICON, EXPAND_ICON } from './icons';\n\n/**\n * Vendor-prefixed Fullscreen API surface (older Safari) — not in standard\n * `lib.dom.d.ts`, so this is a documented interop boundary (CLAUDE.md: `any`\n * only there). Everything else in this file uses the standard,\n * already-typed `Element.requestFullscreen`/`Document.exitFullscreen`/\n * `Document.fullscreenElement`/`Document.fullscreenEnabled`.\n */\ninterface WebkitFullscreenElement extends HTMLElement {\n webkitRequestFullscreen?: () => void;\n}\ninterface WebkitFullscreenDocument extends Document {\n webkitExitFullscreen?: () => void;\n webkitFullscreenElement?: Element | null;\n webkitFullscreenEnabled?: boolean;\n}\n\nfunction isSupported(): boolean {\n return !!(\n document.fullscreenEnabled || (document as WebkitFullscreenDocument).webkitFullscreenEnabled\n );\n}\n\nfunction currentFullscreenElement(): Element | null {\n return (\n document.fullscreenElement ??\n (document as WebkitFullscreenDocument).webkitFullscreenElement ??\n null\n );\n}\n\nfunction requestFullscreen(el: HTMLElement): void {\n const target = el as WebkitFullscreenElement;\n if (target.requestFullscreen) target.requestFullscreen().catch(() => {});\n else target.webkitRequestFullscreen?.();\n}\n\nfunction exitFullscreen(): void {\n const doc = document as WebkitFullscreenDocument;\n if (document.exitFullscreen) document.exitFullscreen().catch(() => {});\n else doc.webkitExitFullscreen?.();\n}\n\n/**\n * DESIGN.md §4 — native Fullscreen API toggle, `.shoji-outer` (`ctx.ui.outer()`,\n * the whole lightbox — backdrop, dialog, controls) is what goes fullscreen,\n * not just the slide media. No toolbar button at all — not a disabled one —\n * on a browser with no Fullscreen API support (checked once at `init()`;\n * historically Safari on iOS), rather than shipping a dead control.\n *\n * `fullscreenchange` (plus the `webkitfullscreenchange` vendor variant) is\n * the single source of truth for button state, not the click handler\n * directly — a real Fullscreen API `request`/`exit` call can be rejected\n * (permission, another element already fullscreen, etc.), and the browser's\n * own Escape-key fullscreen exit doesn't go through this plugin's click\n * handler at all. Reacting to the event instead of the request keeps the\n * button correct regardless of *why* fullscreen state changed.\n */\nexport const Fullscreen: ShojiPlugin = {\n name: 'fullscreen',\n\n init(ctx: PluginContext): (() => void) | void {\n if (!isSupported()) return;\n\n const outer = ctx.ui.outer();\n const locale = (ctx.gallery.options.locale ?? {}) as Record<string, string>;\n const enterLabel = locale.enterFullscreen ?? 'Enter fullscreen';\n const exitLabel = locale.exitFullscreen ?? 'Exit fullscreen';\n\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n button.innerHTML = EXPAND_ICON;\n button.setAttribute('aria-label', enterLabel);\n button.title = enterLabel;\n button.setAttribute('aria-pressed', 'false');\n\n function isActive(): boolean {\n return currentFullscreenElement() === outer;\n }\n\n function setState(active: boolean): void {\n button.innerHTML = active ? COMPRESS_ICON : EXPAND_ICON;\n button.setAttribute('aria-label', active ? exitLabel : enterLabel);\n button.title = active ? exitLabel : enterLabel;\n button.setAttribute('aria-pressed', String(active));\n }\n\n /** Shared by the toolbar button and `requestFullscreenToggle` below. */\n function toggleFullscreen(): void {\n if (isActive()) exitFullscreen();\n else requestFullscreen(outer);\n }\n button.addEventListener('click', toggleFullscreen);\n\n const onChange = (): void => {\n const active = isActive();\n setState(active);\n ctx.emit('fullscreenChange', { fullscreen: active });\n };\n document.addEventListener('fullscreenchange', onChange);\n document.addEventListener('webkitfullscreenchange', onChange);\n\n // 'right' — clusters immediately before the close button (DESIGN.md §3.1).\n const removeButton = ctx.ui.toolbar('right', button);\n\n // Browser-level Escape-to-exit-fullscreen behavior is inconsistent\n // across browsers (some exit fullscreen and still deliver the page its\n // own Escape keydown, some don't) — closing the gallery explicitly\n // exits fullscreen too, rather than risking the page getting stuck\n // fullscreen-on-nothing after the lightbox itself is gone.\n const offClose = ctx.on('close', () => {\n if (isActive()) exitFullscreen();\n });\n /**\n * A generic command surface, requested directly (DESIGN.md §4.4), so a\n * *custom* (host-authored) plugin's own button can toggle fullscreen\n * without importing this plugin at all — same \"events over\n * inheritance\" decoupling `close` above already uses.\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestFullscreenToggle', {})` from any\n * plugin — official or custom — type-checks with zero core changes;\n * this is just the listening half.\n */\n const offRequestToggle = ctx.on('requestFullscreenToggle', toggleFullscreen);\n\n return () => {\n document.removeEventListener('fullscreenchange', onChange);\n document.removeEventListener('webkitfullscreenchange', onChange);\n removeButton();\n offClose();\n offRequestToggle();\n if (isActive()) exitFullscreen();\n };\n },\n};\n","/**\n * DESIGN.md §5.2 — deterministic, measure-free layout: positions come purely\n * from each tile's aspect ratio, never from measuring a loaded image (that's\n * exactly what causes the layout-jump problem most masonry libraries have).\n * Pure functions, no DOM — testable in isolation from rendering.\n */\n\nexport interface MasonryTile {\n /** Natural aspect ratio only — any unit works as long as width/height share one. */\n width: number;\n height: number;\n}\n\nexport interface MasonryPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface MasonryOptions {\n containerWidth: number;\n /** Gap *between* columns (horizontal). */\n gutterX: number;\n /** Gap *between* tiles stacked within a column (vertical). */\n gutterY: number;\n columns: number | 'auto';\n columnWidth: number;\n minColumnWidth: number;\n maxColumnWidth: number;\n fill: 'shortest' | 'ordered';\n}\n\nexport interface MasonryResult {\n positions: MasonryPosition[];\n columnCount: number;\n columnWidth: number;\n /** Per-column running height, incl. trailing gutterY — feed back in as `startHeights` to continue packing (e.g. an appended page) without relaying out earlier tiles. */\n columnHeights: number[];\n containerHeight: number;\n}\n\n/**\n * `'auto'` column count is `containerWidth / columnWidth`, floored — at odd\n * container widths that division can drift the *effective* per-column width\n * well past `columnWidth` before the count itself changes (e.g. 601px at a\n * 200px target floors to 3 columns of ~200px, but 999px floors to 4 columns\n * of ~250px). `minColumnWidth`/`maxColumnWidth` cap how far that drift goes\n * before the column count itself adjusts, so columns never go stringy-narrow\n * or stretch too wide at awkward container sizes. Only `gutterX` (the axis\n * columns are laid out along) factors into this — `gutterY` never affects\n * column count/width.\n */\nexport function computeColumnCount(options: MasonryOptions): number {\n const { containerWidth, gutterX, columns } = options;\n if (typeof columns === 'number') return Math.max(1, Math.floor(columns));\n\n const target = Math.max(\n 1,\n Math.floor((containerWidth + gutterX) / (options.columnWidth + gutterX)),\n );\n const maxAllowedByMin = Math.max(\n 1,\n Math.floor((containerWidth + gutterX) / (options.minColumnWidth + gutterX)),\n );\n const minRequiredByMax = Math.max(\n 1,\n Math.ceil((containerWidth + gutterX) / (options.maxColumnWidth + gutterX)),\n );\n // minRequiredByMax can exceed maxAllowedByMin at a pathological config\n // (minColumnWidth > maxColumnWidth) — minRequiredByMax wins rather than\n // silently violating maxColumnWidth in that case.\n return Math.max(minRequiredByMax, Math.min(target, maxAllowedByMin));\n}\n\nexport function computeColumnWidth(\n containerWidth: number,\n gutterX: number,\n columnCount: number,\n): number {\n return (containerWidth - gutterX * (columnCount - 1)) / columnCount;\n}\n\n/**\n * Packs `tiles` into columns. `startHeights` (one entry per column, from a\n * previous `MasonryResult.columnHeights`) continues packing after already-\n * placed tiles instead of relaying out from scratch — this is what makes an\n * infinite-scroll append O(new items): earlier tiles' positions never change.\n */\nexport function layoutMasonry(\n tiles: readonly MasonryTile[],\n options: MasonryOptions,\n startHeights?: readonly number[],\n): MasonryResult {\n const columnCount = computeColumnCount(options);\n const colWidth = computeColumnWidth(options.containerWidth, options.gutterX, columnCount);\n const columnHeights =\n startHeights && startHeights.length === columnCount\n ? [...startHeights]\n : new Array<number>(columnCount).fill(0);\n\n const positions: MasonryPosition[] = tiles.map((tile, i) => {\n const colIndex = options.fill === 'ordered' ? i % columnCount : indexOfShortest(columnHeights);\n const tileHeight = tile.width > 0 ? colWidth * (tile.height / tile.width) : colWidth;\n const x = colIndex * (colWidth + options.gutterX);\n const y = columnHeights[colIndex]!;\n columnHeights[colIndex] = y + tileHeight + options.gutterY;\n return { x, y, width: colWidth, height: tileHeight };\n });\n\n const containerHeight = tiles.length === 0 ? 0 : Math.max(...columnHeights) - options.gutterY;\n return { positions, columnCount, columnWidth: colWidth, columnHeights, containerHeight };\n}\n\nfunction indexOfShortest(heights: readonly number[]): number {\n let shortest = 0;\n for (let i = 1; i < heights.length; i++) {\n if (heights[i]! < heights[shortest]!) shortest = i;\n }\n return shortest;\n}\n\nexport interface MasonryHorizontalOptions {\n containerWidth: number;\n /** Gap between tiles packed rightward within a row. */\n gutterX: number;\n /** Gap *between* rows (vertical). */\n gutterY: number;\n /** Every row's exact, fixed height — never scaled/solved-for (that's what distinguishes this from `justified`, whose row heights are the free variable it adjusts to make each row's width land exactly on `containerWidth`; here, height is the fixed input and width is left wherever a row's tiles naturally end). */\n rowHeight: number;\n}\n\nexport interface MasonryHorizontalResult {\n positions: MasonryPosition[];\n rowCount: number;\n containerHeight: number;\n}\n\n/**\n * DESIGN.md §5.1 — packs tiles left-to-right into rows of `rowHeight` (each\n * tile scaled to that exact height at its own true aspect ratio, never\n * stretched/cropped), wrapping to a new row the moment the next tile would\n * push the current one past `containerWidth` — never stretching the\n * finished row to close the remaining gap. The result: every row is\n * *exactly* `rowHeight` tall (the fixed constraint), and every row's right\n * edge lands wherever its tiles' natural widths summed to (the free,\n * \"ragged\" one) — the direct masonry-family transpose of vertical masonry,\n * whose *columns* share a fixed width and whose ragged edge is the bottom.\n * `justified` (`justified.ts`) is the inverse tradeoff: width is the fixed\n * constraint (every row forced flush to `containerWidth`) and height is the\n * free variable solved per row to make that work.\n *\n * A single tile whose natural width at `rowHeight` alone already exceeds\n * `containerWidth` (a wide panorama) is still placed on its own row rather\n * than shrunk — nothing narrower to fall back to without violating the\n * fixed-height constraint, the same tradeoff `justified`'s `minRowHeight`\n * makes in its own analogous single-tile edge case.\n */\nexport function layoutMasonryHorizontal(\n tiles: readonly MasonryTile[],\n options: MasonryHorizontalOptions,\n): MasonryHorizontalResult {\n const { containerWidth, gutterX, gutterY, rowHeight } = options;\n const positions: MasonryPosition[] = new Array(tiles.length);\n let currentY = 0;\n let rowStart = 0;\n let rowWidth = 0; // cumulative width of tiles committed to the current row so far, gutters included\n let rowCount = 0;\n\n function tileWidth(tile: MasonryTile): number {\n return tile.height > 0 ? rowHeight * (tile.width / tile.height) : rowHeight;\n }\n\n function placeRow(start: number, endExclusive: number): void {\n let x = 0;\n for (let i = start; i < endExclusive; i++) {\n const w = tileWidth(tiles[i]!);\n positions[i] = { x, y: currentY, width: w, height: rowHeight };\n x += w + gutterX;\n }\n rowCount++;\n currentY += rowHeight + gutterY;\n }\n\n for (let i = 0; i < tiles.length; i++) {\n const w = tileWidth(tiles[i]!);\n const countInRow = i - rowStart;\n const widthIfIncluded = rowWidth + (countInRow > 0 ? gutterX : 0) + w;\n if (countInRow > 0 && widthIfIncluded > containerWidth) {\n placeRow(rowStart, i); // finalize the row without tile i — it starts the next one instead\n rowStart = i;\n rowWidth = w;\n } else {\n rowWidth = widthIfIncluded;\n }\n }\n if (rowStart < tiles.length) placeRow(rowStart, tiles.length);\n\n const containerHeight = tiles.length === 0 ? 0 : currentY - gutterY;\n return { positions, rowCount, containerHeight };\n}\n","/**\n * DESIGN.md §5.2 — Flickr/Google-Photos-style row filler: tiles are grouped\n * into rows, each row scaled as a whole (every tile in it keeps its own\n * aspect ratio, only the shared row height changes) until the row's total\n * width exactly matches the container — the opposite visual signature from\n * masonry: row *right edges* line up flush, row *heights* vary instead of\n * column bottoms varying. Pure, no DOM — same shape/testing pattern as\n * masonry.ts.\n */\n\nexport interface JustifiedTile {\n width: number;\n height: number;\n}\n\nexport interface JustifiedPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface JustifiedOptions {\n containerWidth: number;\n /** Gap between tiles within a row (horizontal). */\n gutterX: number;\n /** Gap *between* rows (vertical). */\n gutterY: number;\n /** Target row height — rows are greedily filled until adding the next tile would exceed containerWidth at this height, then the whole row is rescaled to fit exactly (so actual row heights end up *near*, not always exactly at, this value). */\n rowHeight: number;\n /**\n * Bounds on a row's *scaled* (fill-the-container) height — an unusual mix\n * of aspect ratios (very few tiles, or very narrow/wide ones, e.g. a lone\n * portrait tile stretched to fill the container width under\n * `lastRow: 'justify'`) can otherwise scale a row to an extreme height.\n * `maxRowHeight` clamping means that row no longer exactly fills\n * `containerWidth` at its capped height — it falls short of the right\n * edge instead, the same tradeoff masonry's `maxColumnWidth` already\n * makes for the analogous reason. `minRowHeight` never causes that kind\n * of overflow, though, unlike a naive clamp would: a row that would need\n * to go below `minRowHeight` to fit exactly instead sheds tiles off its\n * end (rolled into the next row) until what's left *does* fit at\n * `minRowHeight` — rows never extend past `containerWidth`. The one\n * unavoidable exception is a single tile so wide/panoramic that even\n * alone it can't satisfy both bounds at once (`minRowHeight` at its own\n * aspect ratio is inherently wider than the container) — there,\n * `minRowHeight` itself yields rather than the row overflowing. Neither\n * bound applies to `lastRow: 'left'`, which already uses `rowHeight` as\n * a fixed, unscaled height rather than deriving one (and, being the\n * left-over *under*-full case by definition, never overflows either).\n */\n minRowHeight: number;\n maxRowHeight: number;\n /** How to handle the trailing row when there aren't enough tiles left to naturally reach containerWidth: 'justify' stretches it like any other row (Flickr-style — the default); 'left' keeps it at natural rowHeight-scaled size, left-aligned, empty space on the right; 'hide' excludes it from `positions` (returned as `null`) entirely. */\n lastRow: 'justify' | 'left' | 'hide';\n}\n\nexport interface JustifiedRow {\n /** Tile index range finalized into this row, `[start, end)`. */\n start: number;\n end: number;\n y: number;\n height: number;\n}\n\nexport interface JustifiedResult {\n /** One entry per input tile, same order — `null` only for a `lastRow: 'hide'`-excluded trailing tile. */\n positions: Array<JustifiedPosition | null>;\n containerHeight: number;\n /** One entry per finalized row, in order — lets a caller find which tiles landed on the same row (e.g. to decide where a compact section label belongs) without re-deriving it from `positions[i].y` equality. */\n rows: JustifiedRow[];\n}\n\nfunction aspectRatioOf(tile: JustifiedTile): number {\n return tile.width > 0 && tile.height > 0 ? tile.width / tile.height : 1;\n}\n\nexport function layoutJustified(\n tiles: readonly JustifiedTile[],\n options: JustifiedOptions,\n): JustifiedResult {\n const { containerWidth, gutterX, gutterY, rowHeight, minRowHeight, maxRowHeight, lastRow } =\n options;\n const positions: Array<JustifiedPosition | null> = new Array(tiles.length).fill(null);\n const rows: JustifiedRow[] = [];\n let currentY = 0;\n let rowStart = 0;\n let aspectSum = 0;\n\n function naturalHeightOf(startIndex: number, endExclusive: number, sum: number): number {\n const availableWidth = containerWidth - gutterX * (endExclusive - startIndex - 1);\n return availableWidth / sum;\n }\n\n function placeRow(startIndex: number, endExclusive: number, height: number): void {\n let x = 0;\n for (let i = startIndex; i < endExclusive; i++) {\n const width = height * aspectRatioOf(tiles[i]!);\n positions[i] = { x, y: currentY, width, height };\n x += width + gutterX;\n }\n rows.push({ start: startIndex, end: endExclusive, y: currentY, height });\n currentY += height + gutterY;\n }\n\n /**\n * Resolves `[startIndex, endExclusive)` (whose combined aspect ratio is\n * `sum`) into its final row, shedding tiles off the end — rolled into\n * whatever comes after — if honoring `minRowHeight` would otherwise push\n * this row's width past `containerWidth`. Returns the `endExclusive`\n * actually used, so the caller knows how many tiles (if any) got rolled\n * over and need to start the next row instead.\n */\n function resolveScaledRow(startIndex: number, endExclusive: number, sum: number): number {\n let end = endExclusive;\n let rowSum = sum;\n let yieldMinRowHeight = false;\n while (end - startIndex > 1 && naturalHeightOf(startIndex, end, rowSum) < minRowHeight) {\n // A real bug, reported from real usage: shedding the trailing tile\n // down to exactly one remaining tile only helps if that lone tile's\n // own natural height doesn't itself need `maxRowHeight` to clamp it\n // — otherwise shedding trades an under-`minRowHeight` row (merely a\n // bit short) for one that instead falls short of the *right edge*\n // (a visible gap, this file's own `maxRowHeight` tradeoff above) —\n // strictly worse, for nothing. Confirmed directly: a lone square\n // tile sandwiched between two wider neighbors landed exactly here.\n // Keep the wider grouping instead and let `minRowHeight` yield for\n // it too, same precedent the single-super-wide-tile case below\n // already establishes.\n if (end - startIndex === 2) {\n const soloNatural = naturalHeightOf(\n startIndex,\n startIndex + 1,\n aspectRatioOf(tiles[startIndex]!),\n );\n if (soloNatural > maxRowHeight) {\n yieldMinRowHeight = true;\n break;\n }\n }\n end--;\n rowSum -= aspectRatioOf(tiles[end]!);\n }\n const natural = naturalHeightOf(startIndex, end, rowSum);\n // Down to one tile and *still* under minRowHeight: that single tile's\n // own aspect ratio makes minRowHeight-at-full-width inherently wider\n // than the container — nothing left to shed, so minRowHeight yields\n // (the natural height keeps width exactly at containerWidth) rather\n // than ever letting the row overflow. `yieldMinRowHeight` extends the\n // same yield to the lone-tile-would-gap case just above.\n const height =\n (end - startIndex === 1 || yieldMinRowHeight) && natural < minRowHeight\n ? natural\n : Math.min(Math.max(natural, minRowHeight), maxRowHeight);\n placeRow(startIndex, end, height);\n return end;\n }\n\n for (let i = 0; i < tiles.length; i++) {\n aspectSum += aspectRatioOf(tiles[i]!);\n const count = i - rowStart + 1;\n const widthAtTargetHeight = rowHeight * aspectSum + gutterX * (count - 1);\n if (widthAtTargetHeight >= containerWidth) {\n const end = resolveScaledRow(rowStart, i + 1, aspectSum);\n rowStart = end;\n aspectSum = 0;\n for (let j = end; j <= i; j++) aspectSum += aspectRatioOf(tiles[j]!); // rolled-over tiles seed the next row\n }\n }\n\n if (rowStart < tiles.length) {\n if (lastRow === 'justify') {\n // resolveScaledRow can itself shed tiles (the same overflow-avoidance\n // as the main loop above) — unlike there, there's no \"next row\" this\n // far down for the outer loop to naturally roll them into, so keep\n // resolving whatever's left until every trailing tile lands\n // somewhere. Always makes forward progress (resolveScaledRow places\n // at least one tile per call), so this always terminates.\n let start = rowStart;\n while (start < tiles.length) {\n let sum = 0;\n for (let j = start; j < tiles.length; j++) sum += aspectRatioOf(tiles[j]!);\n start = resolveScaledRow(start, tiles.length, sum);\n }\n } else if (lastRow === 'left') {\n placeRow(rowStart, tiles.length, rowHeight);\n }\n // 'hide': positions stay null for this trailing range, currentY doesn't advance\n }\n\n const containerHeight = tiles.length === 0 ? 0 : Math.max(0, currentY - gutterY);\n return { positions, containerHeight, rows };\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport type { GalleryItem } from '../../core/types';\nimport { layoutMasonry, layoutMasonryHorizontal, type MasonryTile } from './masonry';\nimport { layoutJustified, type JustifiedOptions, type JustifiedResult } from './justified';\nimport './layout.css';\n\n/**\n * DESIGN.md §5 — `type: 'grid' | 'masonry' | 'justified'`; masonry supports\n * both `orientation`s, `breakpoints` (§5.4), and `groupBy`/headings (§5.2;\n * see that option's own doc comment for the v1 scope cuts vs. the full\n * spec, including why `groupBy` itself is excluded from `orientation:\n * 'horizontal'`). Deliberately still\n * deferred: jump-free *prepend* coordination (§5.2's scroll-anchoring\n * handoff needs the not-yet-built scroll plugin on the other end —\n * prepending today triggers a full relayout, which can shift scroll\n * position if content above the fold grew).\n */\nexport interface LayoutOptions {\n /** Default `'justified'`. */\n type?: 'grid' | 'masonry' | 'justified';\n gutter?: number | { x: number; y: number };\n /**\n * `type: 'grid'` only — every cell's shape, cropped to fit via\n * `object-fit: cover`; default 1 (square). Deliberately *not* each\n * photo's own aspect ratio: plain CSS grid sizes a row's height to its\n * tallest cell, so per-item ratios leave a visible blank gap under every\n * shorter tile sharing a row with a taller one. Masonry/justified are\n * the two types that preserve true per-photo aspect ratios instead (via\n * their own JS packing, which doesn't have this row-height problem).\n */\n aspectRatio?: number;\n /**\n * `type: 'masonry'` only. `'vertical'` (default): fixed-width columns,\n * tiles stack top-to-bottom, ragged *bottom* edge. `'horizontal'`: fixed-\n * height rows, tiles pack left-to-right, ragged *right* edge — the direct\n * transpose. Both wrap/grow within the container and scroll vertically\n * only, same as every other layout type; neither ever needs horizontal\n * scroll. See `rowHeight` for `'horizontal'`'s one fixed input, and\n * `justified` (a different `type` entirely) for the *opposite* tradeoff —\n * width forced flush, height left to solve for.\n */\n orientation?: 'vertical' | 'horizontal';\n columns?: number | 'auto';\n columnWidth?: number;\n minColumnWidth?: number;\n maxColumnWidth?: number;\n fill?: 'shortest' | 'ordered';\n /** `type: 'justified'`, or `type: 'masonry', orientation: 'horizontal'`. For horizontal masonry this is the row's exact, fixed height (see `orientation`'s doc comment) — `minRowHeight`/`maxRowHeight` don't apply there, since nothing is solved/clamped, only for justified, where it's a *target* a solved-for height converges near. */\n rowHeight?: number;\n minRowHeight?: number;\n maxRowHeight?: number;\n lastRow?: 'justify' | 'left' | 'hide';\n animate?: boolean;\n /**\n * Container-width → partial overrides, applied on top of the base options\n * above whenever the container's current width is <= that key (the\n * *narrowest* matching key wins if more than one applies). Re-evaluated on\n * every relayout, so crossing a threshold while resizing takes effect\n * live. Cannot override `type` or `orientation` — swapping the DOM\n * structure/positioning strategy live is a bigger feature than a sizing\n * tweak; use a media query + two `Shoji` instances if that's genuinely\n * needed.\n */\n breakpoints?: Record<number, Omit<LayoutOptions, 'type' | 'orientation' | 'breakpoints'>>;\n /**\n * Derives a section key per item (e.g. a formatted date) — a heading is\n * inserted whenever the key changes between consecutive items, real\n * \"Today / Yesterday / March 2024\" (Google Photos-style) sectioning.\n * Items must already be grouped consecutively; a key reappearing later\n * after a different key started a new section anyway.\n *\n * Section boundaries behave differently per `type`: `grid`'s heading is a\n * full-span (`grid-column: 1 / -1`) element, native CSS grid gives it its\n * own row for free. `masonry`'s heading is a full-width blocking element\n * too — each section is its own fresh column-packing pass, no two\n * sections ever share visual space. `justified` is the odd one out, by\n * design (this is the actual Google Photos behavior, not a simplified\n * approximation of it): sections do **not** force a row break. Row\n * *composition* ignores section boundaries entirely — one continuous\n * `layoutJustified` pass packs every item regardless of section, so a\n * section with too few items to reach a full row's target width (a\n * single lone photo, say) shares that row with whatever comes right\n * after it, instead of getting stretched into its own awkward\n * almost-empty row. A heading only marks *where* a new section starts:\n * a compact, inline label sized to its own content (not full width),\n * positioned at the x-coordinate of the tile that starts its section,\n * in a slim label-band above whichever row that tile landed on — more\n * than one label can share the same band if more than one section\n * happens to start within the same row (see `renderHeading`'s\n * `{title, subtitle}` form for exactly this — that's what the reference\n * behavior actually looks like).\n *\n * v1 scope cuts vs. DESIGN.md §5.2's full spec: (1) any items change\n * while `groupBy` is set does a full relayout, same simplification\n * justified's non-grouped path already makes for appends (§5.4) — the\n * \"merge across load boundaries\" incremental optimization is deferred;\n * (2) headings are always `<h2>`, not a configurable level; (3) not\n * supported with `orientation: 'horizontal'` (warns, ignored) —\n * DESIGN.md itself calls that pairing rare.\n */\n groupBy?: (item: GalleryItem) => string;\n /**\n * Customizes a heading's content; default renders the key as plain text.\n * Three return shapes:\n * - `string` — plain text (default behavior, just with custom content).\n * - `HTMLElement` — full control, own tag/children; the plugin adds its\n * own class/positioning on top of whatever's returned, nothing else.\n * - `{ title: string; subtitle?: string }` — the built-in structured\n * form (bold title + a smaller, muted `subtitle`, e.g. a date + a\n * location) — the only form the plugin can apply automatic overflow\n * handling to (see `headingOverflow`), since it owns the DOM structure\n * (a raw `HTMLElement` is opaque to it, no safe way to guess what's\n * droppable).\n */\n renderHeading?: (\n key: string,\n items: GalleryItem[],\n ) => string | HTMLElement | { title: string; subtitle?: string };\n /**\n * `type: 'justified'` + the `{ title, subtitle }` structured heading\n * form only — controls what happens when a compact label doesn't fit\n * its available width (the gap until the next section's label sharing\n * its row, or the container edge). Ignored otherwise: `grid`/`masonry`\n * headings are full-width and this kind of squeeze can't happen there;\n * a raw `renderHeading`-returned `HTMLElement`/`string` is left exactly\n * as returned regardless, since the plugin has no safe way to guess\n * what's droppable in an opaque element.\n * - `'show'` (default) — always render the full title + subtitle, one\n * line, however wide; a label can visually run past the next\n * section's label or the container edge if the content is long\n * enough. The simple, predictable default — nothing gets silently\n * dropped or reflowed.\n * - `'fit'` — never wraps a label's text. First the subtitle is dropped\n * if title+subtitle together don't fit; if the title *alone* still\n * doesn't fit next to whatever's sharing its row, that section is\n * pushed to start a fresh row instead, giving its label the room it\n * needs — row *composition* responds to label width, not just label\n * content. Real Google Photos behavior; opt in when labels regularly\n * need to share tight row space. The one unavoidable exception is a\n * single label wider than the entire container even alone on its own\n * row — there, nothing left to break onto, so the label is\n * ellipsis-truncated (still one line, never wrapped, never\n * overflowing).\n * - `'wrap'` — the in-between: same continuous row-packing as `'show'`\n * (row *composition* never reacts to label width, unlike `'fit'` — no\n * section is ever pushed to a fresh row), but a label that doesn't fit\n * its available width (same gap `'fit'` measures) wraps its own text\n * onto additional lines instead of running past it. Height is capped\n * at `maxRowHeight` (or its default, 360) — a label tall enough to hit\n * that cap ellipsis-truncates its last visible line rather than\n * growing the row further. Real Google Photos behavior for its date\n * headers; pick this over `'fit'` when you'd rather a label take an\n * extra line than shove a whole section onto its own row.\n */\n headingOverflow?: 'show' | 'fit' | 'wrap';\n /**\n * Pins the active section's heading via `position: sticky`. Only\n * implemented for `type: 'grid'`, where headings sit in normal document\n * flow — masonry/justified headings are absolutely positioned by JS (like\n * their tiles), and `position: sticky` doesn't do anything meaningful\n * layered onto an already explicitly-positioned element. Warns and is\n * ignored for those two types.\n */\n stickyHeadings?: boolean;\n /**\n * When an item is missing `width`/`height`, measure its tile's own `<img>`\n * once it loads (`naturalWidth`/`naturalHeight`) and correct that tile's\n * aspect ratio in place, rather than leaving it at the permanent 4:3\n * placeholder fallback. Default `true`.\n *\n * The *first* layout pass never waits on this — it always uses the 4:3\n * placeholder immediately, same as before this option existed, so opening\n * the gallery is never blocked on image loads (DESIGN.md §5.2's\n * never-measure-mid-layout-pass rule still holds for that first pass).\n * This only ever *corrects* a placeholder after the fact, once a real\n * measurement lands — the same \"async correction after an initial\n * synchronous pass\" pattern already used for a `containerWidth <= 0`\n * container (§5.4) and the zoom transition's origin-rect race (§2.3b),\n * extended to per-item dimensions. Multiple corrections landing close\n * together (e.g. several cached images resolving in the same tick) are\n * coalesced into one relayout via `requestAnimationFrame`, not one\n * relayout per image.\n *\n * Effectively does automatically, for `thumb`/`poster`/`src`, what a host\n * would otherwise have to do by hand before constructing the gallery\n * (`new Image(); img.onload = () => ...`) — set `false` to keep the old\n * behavior (permanent 4:3 fallback, no self-correction) if you'd rather\n * guarantee zero extra relayouts under any circumstance.\n */\n autoMeasure?: boolean;\n}\n\ninterface ResolvedConfig {\n gutter: { x: number; y: number };\n columns: number | 'auto';\n columnWidth: number;\n minColumnWidth: number;\n maxColumnWidth: number;\n fill: 'shortest' | 'ordered';\n rowHeight: number;\n minRowHeight: number;\n maxRowHeight: number;\n lastRow: 'justify' | 'left' | 'hide';\n}\n\nconst DEFAULT_ASPECT: MasonryTile = { width: 4, height: 3 };\n\ninterface Tile {\n index: number;\n root: HTMLAnchorElement;\n /** The tile's own thumbnail `<img>` — reused by `autoMeasure` to read `naturalWidth`/`naturalHeight` once it loads, rather than fetching the same image a second time with a separate `Image()`. */\n img: HTMLImageElement;\n}\n\ninterface HeadingEntry {\n root: HTMLElement;\n /** index into `tiles[]` (== item index) where this section's tiles start. */\n tileStart: number;\n /** Present only for the built-in `{ title, subtitle }` form — the two elements `applyJustified`'s overflow handling is allowed to hide/wrap, since the plugin itself built them (a raw `renderHeading`-returned `HTMLElement` is opaque; nothing is touched there). */\n structured: { titleEl: HTMLElement; subtitleEl: HTMLElement | null } | null;\n}\n\n/** `gutter: 8` means `{x: 8, y: 8}` — a single number applies to both axes; `{x, y}` sets them independently. */\nfunction resolveGutter(raw: unknown): { x: number; y: number } {\n if (raw && typeof raw === 'object') {\n const obj = raw as { x?: number; y?: number };\n return { x: Number(obj.x ?? 8), y: Number(obj.y ?? 8) };\n }\n const n = Number(raw ?? 8);\n return { x: n, y: n };\n}\n\nfunction keyOf(item: GalleryItem): string {\n return item.id ?? item.src;\n}\n\n/** `newItems` is a superset of `oldItems` sharing an identical prefix — i.e. purely appended, nothing reordered/removed/prepended. */\nfunction isPureAppend(oldItems: readonly GalleryItem[], newItems: readonly GalleryItem[]): boolean {\n if (newItems.length <= oldItems.length) return false;\n for (let i = 0; i < oldItems.length; i++) {\n if (keyOf(oldItems[i]!) !== keyOf(newItems[i]!)) return false;\n }\n return true;\n}\n\nexport const Layout: ShojiPlugin = {\n name: 'layout',\n defaults: {\n type: 'justified',\n gutter: 8,\n columns: 'auto',\n columnWidth: 240,\n minColumnWidth: 160,\n maxColumnWidth: 480,\n fill: 'shortest',\n animate: true,\n autoMeasure: true,\n },\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const type = (ctx.options.type as 'grid' | 'masonry' | 'justified' | undefined) ?? 'justified';\n const gutter = resolveGutter(ctx.options.gutter);\n const aspectRatio = Number(ctx.options.aspectRatio ?? 1);\n const orientation =\n (ctx.options.orientation as 'vertical' | 'horizontal' | undefined) ?? 'vertical';\n const columns = (ctx.options.columns as number | 'auto' | undefined) ?? 'auto';\n const columnWidth = Number(ctx.options.columnWidth ?? 240);\n const minColumnWidth = Number(ctx.options.minColumnWidth ?? 160);\n const maxColumnWidth = Number(ctx.options.maxColumnWidth ?? 480);\n const fill = (ctx.options.fill as 'shortest' | 'ordered' | undefined) ?? 'shortest';\n const rowHeight = Number(ctx.options.rowHeight ?? 220);\n const minRowHeight = Number(ctx.options.minRowHeight ?? 120);\n const maxRowHeight = Number(ctx.options.maxRowHeight ?? 360);\n const lastRow = (ctx.options.lastRow as 'justify' | 'left' | 'hide' | undefined) ?? 'justify';\n const animate = ctx.options.animate !== false;\n const autoMeasureEnabled = ctx.options.autoMeasure !== false;\n const horizontal = type === 'masonry' && orientation === 'horizontal';\n const groupByFn = ctx.options.groupBy as ((item: GalleryItem) => string) | undefined;\n const renderHeadingFn = ctx.options.renderHeading as\n | ((\n key: string,\n items: GalleryItem[],\n ) => string | HTMLElement | { title: string; subtitle?: string })\n | undefined;\n const headingOverflow =\n (ctx.options.headingOverflow as 'show' | 'fit' | 'wrap' | undefined) ?? 'show';\n const stickyHeadingsRaw = ctx.options.stickyHeadings === true;\n const stickyHeadings = stickyHeadingsRaw && type === 'grid';\n if (stickyHeadingsRaw && type !== 'grid') {\n console.warn(\n \"Shoji: layout plugin — stickyHeadings is only implemented for type: 'grid'; ignored (see the option's doc comment).\",\n );\n }\n if (groupByFn && horizontal) {\n console.warn(\n \"Shoji: layout plugin — groupBy isn't supported with orientation: 'horizontal'; ignored.\",\n );\n }\n const groupingEnabled = !!groupByFn && !horizontal;\n\n const baseConfig: ResolvedConfig = {\n gutter,\n columns,\n columnWidth,\n minColumnWidth,\n maxColumnWidth,\n fill,\n rowHeight,\n minRowHeight,\n maxRowHeight,\n lastRow,\n };\n\n const breakpointsRaw = ctx.options.breakpoints as\n Record<number, Partial<LayoutOptions>> | undefined;\n const sortedBreakpoints = breakpointsRaw\n ? Object.entries(breakpointsRaw)\n .map(([key, overrides]) => [Number(key), overrides] as const)\n .sort((a, b) => a[0] - b[0])\n : [];\n\n /** Re-run on every relayout — the narrowest breakpoint whose key is still >= the current width wins; falls back to `baseConfig` if none match or no breakpoints were given. */\n function resolveConfig(width: number): ResolvedConfig {\n const match = sortedBreakpoints.find(([maxWidth]) => width <= maxWidth);\n if (!match) return baseConfig;\n const overrides = match[1];\n return {\n gutter:\n overrides.gutter !== undefined ? resolveGutter(overrides.gutter) : baseConfig.gutter,\n columns: overrides.columns ?? baseConfig.columns,\n columnWidth: overrides.columnWidth ?? baseConfig.columnWidth,\n minColumnWidth: overrides.minColumnWidth ?? baseConfig.minColumnWidth,\n maxColumnWidth: overrides.maxColumnWidth ?? baseConfig.maxColumnWidth,\n fill: overrides.fill ?? baseConfig.fill,\n rowHeight: overrides.rowHeight ?? baseConfig.rowHeight,\n minRowHeight: overrides.minRowHeight ?? baseConfig.minRowHeight,\n maxRowHeight: overrides.maxRowHeight ?? baseConfig.maxRowHeight,\n lastRow: overrides.lastRow ?? baseConfig.lastRow,\n };\n }\n\n const container = gallery.element;\n container.classList.add('shoji-layout', `shoji-layout--${type}`);\n if (animate) container.classList.add('shoji-layout--animate');\n\n let tiles: Tile[] = [];\n let headings: HeadingEntry[] = [];\n let columnHeights: number[] | undefined;\n let previousItems: readonly GalleryItem[] = [];\n let warnedMissingDims = false;\n /**\n * A real bug, reported from real usage: `autoMeasureTiles()` used to\n * write its measurement straight onto `item.width`/`item.height` —\n * convenient, since `aspectOf()` already reads those first, but wrong.\n * That measurement comes from the *tile's* own `<img>`\n * (`measurableSrc()`: `item.thumb` first, then `poster`, then `src`) —\n * for layout purposes a thumbnail's aspect ratio is a fine stand-in for\n * the full photo's, close enough almost always. But `item.width`/\n * `height` aren't Layout-private state — RotateFlip's own fit-scale\n * (§4.5) and `SlideManager`'s aspect-ratio loading placeholder both\n * read the exact same fields, under the contract that they mean the\n * full photo's *true* pixel dimensions, not a thumbnail's. A thumbnail\n * genuinely smaller than the lightbox in both orientations always\n * satisfies `fitScaleFor`'s `Math.min(1, ...)` cap on its own, so\n * RotateFlip silently computed a no-op 1x scale for every such\n * item — confirmed directly against a real photo whose thumbnail\n * happened to be a separate, smaller file (an item whose thumbnail\n * happens to equal its full `src` never showed this, since then the\n * \"wrong\" measurement and the real one are simply the same numbers).\n * This cache keeps the auto-measurement entirely Layout-private —\n * `aspectOf()` below still benefits from it, but nothing outside this\n * plugin ever sees a thumbnail's dimensions mistaken for the photo's.\n */\n const measuredAspect = new WeakMap<GalleryItem, MasonryTile>();\n\n /** [startIndex, endExclusive) into `items`/`tiles` per section, split wherever `groupByFn`'s key changes. */\n function computeSections(\n items: readonly GalleryItem[],\n ): Array<{ key: string; startIndex: number; endIndex: number }> {\n const sections: Array<{ key: string; startIndex: number; endIndex: number }> = [];\n for (let i = 0; i < items.length; i++) {\n const key = groupByFn!(items[i]!);\n const current = sections[sections.length - 1];\n if (!current || current.key !== key) {\n sections.push({ key, startIndex: i, endIndex: i + 1 });\n } else {\n current.endIndex = i + 1;\n }\n }\n return sections;\n }\n\n function createHeadingRoot(\n key: string,\n sectionItems: GalleryItem[],\n ): { root: HTMLElement; structured: HeadingEntry['structured'] } {\n const rendered = renderHeadingFn ? renderHeadingFn(key, sectionItems) : key;\n let root: HTMLElement;\n let structured: HeadingEntry['structured'] = null;\n if (typeof rendered === 'string') {\n root = document.createElement('h2');\n root.textContent = rendered;\n } else if (rendered instanceof HTMLElement) {\n root = rendered;\n } else {\n root = document.createElement('h2');\n const titleEl = document.createElement('span');\n titleEl.className = 'shoji-layout-heading-title';\n titleEl.textContent = rendered.title;\n root.appendChild(titleEl);\n let subtitleEl: HTMLElement | null = null;\n if (rendered.subtitle) {\n subtitleEl = document.createElement('span');\n subtitleEl.className = 'shoji-layout-heading-subtitle';\n subtitleEl.textContent = rendered.subtitle;\n root.appendChild(subtitleEl);\n }\n structured = { titleEl, subtitleEl };\n }\n root.classList.add('shoji-layout-heading');\n if (stickyHeadings) root.classList.add('shoji-layout-heading--sticky');\n return { root, structured };\n }\n\n /** Segment boundaries derived from `headings` — `end` is the next heading's `tileStart`, or `tiles.length` for the last one. */\n function headingSegments(): Array<{ heading: HeadingEntry; start: number; end: number }> {\n return headings.map((heading, i) => ({\n heading,\n start: heading.tileStart,\n end: i + 1 < headings.length ? headings[i + 1]!.tileStart : tiles.length,\n }));\n }\n\n /** `undefined` for a video item with neither `thumb` nor `poster` — its tile `<img>` ends up pointed at the unplayable video file itself, which can never load as an image, so there's nothing `autoMeasure` could learn from it either. */\n function measurableSrc(item: GalleryItem): string | undefined {\n return item.thumb ?? item.poster ?? (item.video ? undefined : item.src);\n }\n\n function aspectOf(item: GalleryItem | undefined): MasonryTile {\n if (item?.width && item.height) return { width: item.width, height: item.height };\n const measured = item && measuredAspect.get(item);\n if (measured) return measured;\n const selfCorrecting = autoMeasureEnabled && !!item && !!measurableSrc(item);\n if (!warnedMissingDims && !selfCorrecting) {\n warnedMissingDims = true;\n console.warn(\n autoMeasureEnabled\n ? 'Shoji: layout plugin — item(s) missing width/height with no measurable thumb/poster/src to auto-measure from either; falling back to a 4:3 placeholder ratio permanently for those.'\n : 'Shoji: layout plugin — item(s) missing width/height and autoMeasure is disabled. Masonry/justified positions are computed from aspect ratios up front, never by measuring loaded images (DESIGN.md §5.2 — that causes layout-jump), so items without dimensions fall back to a 4:3 placeholder ratio instead.',\n );\n }\n return DEFAULT_ASPECT;\n }\n\n function createTile(item: GalleryItem, index: number): Tile {\n const root = document.createElement('a');\n root.className = 'shoji-layout-tile';\n if (item.id) root.dataset.shojiId = item.id;\n // Always set, unlike shojiId above (item.id is optional) — the\n // reliable element→item lookup for a `layoutRender` listener that\n // only has the element itself later (e.g. a click handler on content\n // it injected into the tile), not this render pass's own event\n // payload. `gallery.items[Number(el.dataset.shojiIndex)]` always works.\n root.dataset.shojiIndex = String(index);\n\n // item.src is the video *file* for a video item (unplayable as a tile\n // thumbnail) — item.poster is the actual image to show there, checked\n // before falling back to item.src, which is only ever correct for a\n // plain image item.\n const img = document.createElement('img');\n img.src = item.thumb ?? item.poster ?? item.src;\n img.loading = 'lazy';\n img.alt = item.alt ?? '';\n root.appendChild(img);\n\n const tile: Tile = { index, root, img };\n root.addEventListener('click', (event) => {\n event.preventDefault();\n gallery.open(tile.index);\n });\n return tile;\n }\n\n function applyGrid(target: readonly Tile[]): void {\n // Grid otherwise never reads its own size (native CSS grid reflows\n // itself) — only breakpoint resolution needs it read here.\n const containerWidth = container.getBoundingClientRect().width;\n const config = resolveConfig(containerWidth);\n container.style.setProperty('--shoji-layout-column-width', `${config.columnWidth}px`);\n // CSS gap shorthand is \"row-gap column-gap\" — y before x.\n container.style.setProperty(\n '--shoji-layout-gutter',\n `${config.gutter.y}px ${config.gutter.x}px`,\n );\n for (const tile of target) {\n tile.root.style.setProperty('--shoji-layout-tile-aspect', `${aspectRatio}`);\n }\n }\n\n /** `appendOnly`: reposition just these (new) tiles, continuing from the saved `columnHeights`; omit to relayout every tile from scratch (resize, or a non-append items change). Never called with `appendOnly` set when grouping is active — grouped changes always route through `fullRender` (see the `groupBy` option's doc comment). */\n function applyMasonry(appendOnly: readonly Tile[] | null): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet (e.g. display:none) — the resize observer's initial callback will retry once it is\n\n const config = resolveConfig(containerWidth);\n const masonryOptions = {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n columns: config.columns,\n columnWidth: config.columnWidth,\n minColumnWidth: config.minColumnWidth,\n maxColumnWidth: config.maxColumnWidth,\n fill: config.fill,\n };\n\n if (groupingEnabled && headings.length > 0) {\n const segments = headingSegments();\n // Batch-read every heading's height up front, before writing any\n // tile styles below — interleaving reads (which force a layout\n // flush) with the transform writes in the same pass measurably\n // delayed the very first paint under animate: true (each flush\n // gives the browser a \"before\" style to transition away from that\n // it otherwise wouldn't have for freshly-inserted elements).\n const headingHeights = segments.map((s) => s.heading.root.getBoundingClientRect().height);\n\n let y = 0;\n segments.forEach(({ heading, start, end }, i) => {\n const segTiles = tiles.slice(start, end);\n heading.root.style.transform = `translate(0px, ${y}px)`;\n y += headingHeights[i]! + config.gutter.y;\n const segResult = layoutMasonry(\n segTiles.map((t) => aspectOf(gallery.items[t.index])),\n masonryOptions,\n );\n segTiles.forEach((tile, j) => {\n const pos = segResult.positions[j]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${y + pos.y}px)`;\n });\n y += segResult.containerHeight + config.gutter.y;\n });\n columnHeights = undefined; // no cross-segment continuation once grouped\n container.style.height = `${Math.max(0, y - config.gutter.y)}px`;\n return;\n }\n\n const target = appendOnly ?? tiles;\n const masonryTiles = target.map((t) => aspectOf(gallery.items[t.index]));\n const startHeights = appendOnly ? columnHeights : undefined;\n const result = layoutMasonry(masonryTiles, masonryOptions, startHeights);\n\n target.forEach((tile, i) => {\n const pos = result.positions[i]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n columnHeights = result.columnHeights;\n container.style.height = `${result.containerHeight}px`;\n }\n\n /**\n * The masonry-family transpose of applyMasonry: fixed-height rows pack\n * tiles left-to-right, wrapping to a new row rather than stretching —\n * see layoutMasonryHorizontal's doc comment (masonry.ts) for the full\n * algorithm. Like applyJustified, this always relays out every tile\n * from scratch (no `appendOnly`/incremental-continuation param) — a\n * row isn't \"committed\" until enough tiles arrive to overflow it, so an\n * appended tile can extend what was the previous render's trailing row,\n * exactly the same reason applyJustified can't do incremental append.\n */\n function applyMasonryHorizontal(): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet (e.g. display:none) — the resize observer's initial callback will retry once it is\n\n const config = resolveConfig(containerWidth);\n const masonryTiles = tiles.map((t) => aspectOf(gallery.items[t.index]));\n const result = layoutMasonryHorizontal(masonryTiles, {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n rowHeight: config.rowHeight,\n });\n\n tiles.forEach((tile, i) => {\n const pos = result.positions[i]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n container.style.height = `${result.containerHeight}px`;\n }\n\n /**\n * The `groupBy` + `justified` combination — see that option's doc\n * comment for the full behavioral spec (sections don't force a row\n * break by default; a heading is a compact inline label, not a\n * full-width blocking element).\n *\n * `headingOverflow: 'show'` (default) and `'wrap'`: one continuous\n * `layoutJustified` pass packs every tile regardless of section — the\n * simple case, a single \"segment\" covering everything (computeSegments()\n * below only ever splits into multiple segments for `'fit'`). `'wrap'`\n * additionally constrains each label's own box afterward (see\n * applyWrapDecisions) — that's a content-level decision within a fixed\n * layout, not a row-composition one, so it doesn't need its own segment\n * handling here.\n *\n * `headingOverflow: 'fit'`: still prefers continuous packing, but a\n * section whose label (title+subtitle, or title alone once the\n * subtitle's dropped) wouldn't fit the gap to the next label sharing\n * its row gets pushed to start a fresh row instead — the label is\n * never wrapped. This means row *composition itself* has to respond to\n * label width, not just label content — computeSegments() below finds\n * the largest run of sections that can share rows without any label\n * needing to break, by growing a trial `layoutJustified` call one\n * section at a time and backing off the moment a fit check fails; each\n * final segment becomes its own independent `layoutJustified` call\n * (same mechanism as masonry's hard per-section blocks, except the\n * unit here is a dynamically-sized run of sections, not always\n * exactly one).\n */\n function applyJustifiedGrouped(\n justifiedOptions: JustifiedOptions,\n config: ResolvedConfig,\n containerWidth: number,\n ): void {\n // Batch-measure every structured heading's natural (unconstrained,\n // single-line) width up front — both with and without its subtitle —\n // before any segmentation trial runs. Needed by computeSegments()'s\n // fit checks below, and again by the final per-segment content\n // decision pass; measuring once here avoids re-measuring per trial.\n const fullWidths = new Map<number, number>();\n const titleOnlyWidths = new Map<number, number>();\n if (headingOverflow === 'fit') {\n for (const heading of headings) {\n if (!heading.structured) continue;\n const { subtitleEl } = heading.structured;\n heading.root.style.maxWidth = 'none';\n heading.root.style.whiteSpace = 'nowrap';\n if (subtitleEl) subtitleEl.hidden = false;\n fullWidths.set(heading.tileStart, heading.root.getBoundingClientRect().width);\n if (subtitleEl) {\n subtitleEl.hidden = true;\n titleOnlyWidths.set(heading.tileStart, heading.root.getBoundingClientRect().width);\n subtitleEl.hidden = false; // restored — the real decision happens per final segment, below\n } else {\n titleOnlyWidths.set(heading.tileStart, fullWidths.get(heading.tileStart)!);\n }\n }\n }\n\n /** [startSection, endSection) into `headings`, sized `tiles[]` range, and that range's own layoutJustified result. */\n type Segment = {\n startSection: number;\n endSection: number;\n tileStart: number;\n tileEnd: number;\n result: JustifiedResult;\n };\n\n function tileAspects(tileStart: number, tileEnd: number) {\n return tiles.slice(tileStart, tileEnd).map((t) => aspectOf(gallery.items[t.index]));\n }\n\n /** Runs layoutJustified on sections [startSection, endSection) and checks every label in it fits (full or title-only) its row's available width — null if any doesn't. */\n function tryFit(startSection: number, endSection: number): JustifiedResult | null {\n const tileStart = headings[startSection]!.tileStart;\n const tileEnd =\n endSection < headings.length ? headings[endSection]!.tileStart : tiles.length;\n const result = layoutJustified(tileAspects(tileStart, tileEnd), justifiedOptions);\n for (let k = startSection; k < endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue; // raw renderHeading content never triggers a break\n const pos = result.positions[heading.tileStart - tileStart];\n if (!pos) continue; // lastRow: 'hide' trailing range within this trial\n const next = k + 1 < endSection ? headings[k + 1] : undefined;\n const nextPos = next ? result.positions[next.tileStart - tileStart] : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n const bestWidth = Math.min(\n fullWidths.get(heading.tileStart) ?? Infinity,\n titleOnlyWidths.get(heading.tileStart) ?? Infinity,\n );\n if (bestWidth > available) return null;\n }\n return result;\n }\n\n function computeSegments(): Segment[] {\n if (headingOverflow !== 'fit') {\n return [\n {\n startSection: 0,\n endSection: headings.length,\n tileStart: 0,\n tileEnd: tiles.length,\n result: layoutJustified(tileAspects(0, tiles.length), justifiedOptions),\n },\n ];\n }\n const segments: Segment[] = [];\n let segStart = 0;\n while (segStart < headings.length) {\n const base = tryFit(segStart, segStart + 1);\n const tileStart = headings[segStart]!.tileStart;\n if (base === null) {\n // Doesn't fit even alone in its own row — the unavoidable case\n // (a single label wider than the container itself). Nothing\n // narrower to fall back to; take it as its own 1-section\n // segment anyway and let the content-decision pass below\n // ellipsis-truncate it rather than ever wrapping or\n // overflowing.\n const tileEnd =\n segStart + 1 < headings.length ? headings[segStart + 1]!.tileStart : tiles.length;\n segments.push({\n startSection: segStart,\n endSection: segStart + 1,\n tileStart,\n tileEnd,\n result: layoutJustified(tileAspects(tileStart, tileEnd), justifiedOptions),\n });\n segStart += 1;\n continue;\n }\n let end = segStart + 1;\n let best = base;\n while (end < headings.length) {\n const trial = tryFit(segStart, end + 1);\n if (trial === null) break;\n end += 1;\n best = trial;\n }\n const tileEnd = end < headings.length ? headings[end]!.tileStart : tiles.length;\n segments.push({\n startSection: segStart,\n endSection: end,\n tileStart,\n tileEnd,\n result: best,\n });\n segStart = end;\n }\n return segments;\n }\n\n /** Applies the real drop-subtitle/ellipsis decision for every structured heading in one finalized segment, using its actual computed positions (not a trial). */\n function applyContentDecisions(segment: Segment): void {\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (!pos) continue;\n const next = k + 1 < segment.endSection ? headings[k + 1] : undefined;\n const nextPos = next\n ? segment.result.positions[next.tileStart - segment.tileStart]\n : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n\n const { subtitleEl } = heading.structured;\n heading.root.style.whiteSpace = 'nowrap';\n heading.root.style.maxWidth = 'none';\n heading.root.style.overflow = '';\n heading.root.style.textOverflow = '';\n if (subtitleEl) subtitleEl.hidden = false;\n\n const full = fullWidths.get(heading.tileStart) ?? 0;\n if (full <= available) continue; // fits with subtitle, as-is\n\n if (subtitleEl) {\n subtitleEl.hidden = true;\n const titleOnly = titleOnlyWidths.get(heading.tileStart) ?? 0;\n if (titleOnly <= available) continue; // fits with subtitle dropped\n }\n\n // Still too wide title-only — only reachable for a 1-section\n // segment that couldn't be narrowed any further (computeSegments\n // already gave every other case its own row's worth of room).\n // Never wrap: ellipsis-truncate instead, still one line.\n heading.root.style.maxWidth = `${Math.max(0, available)}px`;\n heading.root.style.overflow = 'hidden';\n heading.root.style.textOverflow = 'ellipsis';\n }\n }\n\n /**\n * `headingOverflow: 'wrap'`'s content decision — unlike\n * applyContentDecisions above, this never drops the subtitle or\n * ellipsis-truncates a single line; it lets the label wrap onto\n * additional lines within its available width, then caps *how many*\n * lines via `-webkit-line-clamp` sized from `maxRowHeight` — a label\n * short enough to fit within that many lines is unaffected (nothing\n * for the clamp to do), a longer one ellipsis-truncates its last\n * visible line rather than growing the row past the configured cap.\n * `-webkit-line-clamp` is broadly supported cross-browser despite the\n * prefix (Chrome/Safari/Firefox all implement it) — there's no\n * unprefixed equivalent with comparable support yet.\n */\n function applyWrapDecisions(segment: Segment): void {\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (!pos) continue;\n const next = k + 1 < segment.endSection ? headings[k + 1] : undefined;\n const nextPos = next\n ? segment.result.positions[next.tileStart - segment.tileStart]\n : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n\n heading.root.style.whiteSpace = 'normal';\n heading.root.style.maxWidth = `${Math.max(0, available)}px`;\n\n const style = getComputedStyle(heading.root);\n const parsedLineHeight = parseFloat(style.lineHeight);\n const lineHeight = Number.isFinite(parsedLineHeight)\n ? parsedLineHeight\n : parseFloat(style.fontSize) * 1.2;\n const maxLines = Math.max(1, Math.floor(config.maxRowHeight / lineHeight));\n\n heading.root.style.display = '-webkit-box';\n heading.root.style.overflow = 'hidden';\n heading.root.style.setProperty('-webkit-box-orient', 'vertical');\n heading.root.style.setProperty('-webkit-line-clamp', `${maxLines}`);\n }\n }\n\n const segments = computeSegments();\n let cumulativeExtra = 0;\n let headingPtr = 0;\n\n for (const segment of segments) {\n if (headingOverflow === 'fit') applyContentDecisions(segment);\n else if (headingOverflow === 'wrap') applyWrapDecisions(segment);\n\n // Batch-read this segment's heading heights up front, after content\n // decisions are final — see applyMasonry's identical pattern/comment\n // for why reads and writes shouldn't interleave in the same pass.\n const headingHeights = new Map<number, number>();\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n headingHeights.set(heading.tileStart, heading.root.getBoundingClientRect().height);\n }\n\n for (const row of segment.result.rows) {\n const globalStart = row.start + segment.tileStart;\n const globalEnd = row.end + segment.tileStart;\n\n let bandHeight = 0;\n while (headingPtr < segment.endSection && headings[headingPtr]!.tileStart < globalEnd) {\n const heading = headings[headingPtr]!;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (pos) {\n heading.root.hidden = false;\n heading.root.style.transform = `translate(${pos.x}px, ${row.y + cumulativeExtra}px)`;\n bandHeight = Math.max(bandHeight, headingHeights.get(heading.tileStart) ?? 0);\n }\n headingPtr++;\n }\n if (bandHeight > 0) cumulativeExtra += bandHeight + config.gutter.y;\n\n for (let i = globalStart; i < globalEnd; i++) {\n const pos = segment.result.positions[i - segment.tileStart];\n const tile = tiles[i]!;\n tile.root.hidden = pos === null;\n if (!pos) continue;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y + cumulativeExtra}px)`;\n }\n }\n\n // Tiles beyond this segment's last finalized row (a lastRow: 'hide'\n // trailing range) never got touched above — hide them explicitly.\n const segLastCovered =\n segment.result.rows.length > 0\n ? segment.result.rows[segment.result.rows.length - 1]!.end + segment.tileStart\n : segment.tileStart;\n for (let i = segLastCovered; i < segment.tileEnd; i++) {\n tiles[i]!.root.hidden = true;\n }\n\n // Advance past this whole segment's own content height, so the\n // next segment's rows (a fresh layoutJustified call, local y\n // starting back at 0) stack directly beneath it.\n cumulativeExtra += segment.result.containerHeight + config.gutter.y;\n }\n\n // Any heading whose section starts in the very last segment's hidden\n // trailing range never got positioned above — hide it rather than\n // leaving it at its CSS default top:0/left:0.\n while (headingPtr < headings.length) {\n headings[headingPtr]!.root.hidden = true;\n headingPtr++;\n }\n\n container.style.height = `${Math.max(0, cumulativeExtra - config.gutter.y)}px`;\n }\n\n /**\n * Unlike masonry's `columnHeights`, a justified row isn't \"locked in\"\n * until enough tiles arrive to fill it — an appended tile can extend or\n * complete what was the *previous* render's trailing row. Rather than\n * build a second continuation scheme for that, justified always relays\n * out every tile on any items change (append included); see §5.4.\n */\n function applyJustified(): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet — resize observer's initial callback retries once it is\n\n const config = resolveConfig(containerWidth);\n const justifiedOptions = {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n rowHeight: config.rowHeight,\n minRowHeight: config.minRowHeight,\n maxRowHeight: config.maxRowHeight,\n lastRow: config.lastRow,\n };\n\n if (groupingEnabled && headings.length > 0) {\n applyJustifiedGrouped(justifiedOptions, config, containerWidth);\n return;\n }\n\n const justifiedTiles = tiles.map((t) => aspectOf(gallery.items[t.index]));\n const result = layoutJustified(justifiedTiles, justifiedOptions);\n\n tiles.forEach((tile, i) => {\n const pos = result.positions[i];\n tile.root.hidden = pos === null; // lastRow: 'hide' on this pass's trailing tiles\n if (!pos) return;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n container.style.height = `${result.containerHeight}px`;\n }\n\n function relayoutAll(): void {\n if (horizontal) applyMasonryHorizontal();\n else if (type === 'masonry') applyMasonry(null);\n else if (type === 'justified') applyJustified();\n else applyGrid(tiles);\n }\n\n let destroyed = false;\n let measureFrame: number | null = null;\n\n /**\n * Coalesces every `autoMeasure` correction landing in the same tick (or\n * the same animation frame — several cached images resolving\n * synchronously back-to-back is the common case) into one relayout,\n * never one per image. `groupingEnabled` needs a real `fullRender()`,\n * not just a reposition pass: `groupBy` was evaluated once already\n * during the first render, using whatever `item.width`/etc. was known\n * *then* — if that's exactly the field a correction just filled in,\n * the section boundaries themselves were computed wrong and only a\n * fresh `computeSections()` call (inside `fullRender`) fixes them, not\n * `relayoutAll()`, which only ever repositions the existing tiles/headings.\n */\n function scheduleMeasureRelayout(): void {\n if (measureFrame !== null || destroyed) return;\n measureFrame = requestAnimationFrame(() => {\n measureFrame = null;\n if (destroyed) return;\n if (groupingEnabled) fullRender(gallery.items);\n else relayoutAll();\n });\n }\n\n /**\n * DESIGN.md §5's `autoMeasure` option — never blocks or delays the\n * *first* layout pass (already painted with the 4:3 placeholder by the\n * time this runs); only ever corrects it afterward, once a real\n * measurement lands. Reuses each tile's own `<img>` (already fetching\n * for display) rather than a second `new Image()`, so nothing is\n * fetched twice. A `loading=\"lazy\"` tile far off-screen may not\n * resolve for a long time (or ever, if never scrolled to) — harmless,\n * since nothing visible is waiting on it; it simply keeps its 4:3\n * placeholder until/unless it does.\n */\n function autoMeasureTiles(newTiles: readonly Tile[]): void {\n if (!autoMeasureEnabled) return;\n for (const tile of newTiles) {\n const item = gallery.items[tile.index];\n // measuredAspect.has(item): skip re-measuring (and re-attaching a\n // 'load' listener) an item this cache already has an answer for —\n // item.width/height no longer get set by this function itself\n // (see measuredAspect's own doc comment above), so that alone\n // can't short-circuit repeat work across tile rebuilds the way it\n // used to.\n if (\n !item ||\n (item.width && item.height) ||\n measuredAspect.has(item) ||\n !measurableSrc(item)\n )\n continue;\n\n const onLoad = (): void => {\n if (destroyed) return;\n if (tile.img.naturalWidth > 0 && tile.img.naturalHeight > 0) {\n measuredAspect.set(item, {\n width: tile.img.naturalWidth,\n height: tile.img.naturalHeight,\n });\n scheduleMeasureRelayout();\n }\n };\n if (tile.img.complete) onLoad();\n else tile.img.addEventListener('load', onLoad, { once: true });\n // No 'error' listener needed — aspectOf()'s 4:3 fallback already\n // covers an image that never loads; there's nothing to update.\n }\n }\n\n /** DESIGN.md §5 — fires once a render pass's tile DOM is built and appended, so a host can inject its own content into `element` (a badge, a selection checkbox, anything not itself part of layout) without re-deriving which tiles are newly built this pass. */\n function emitLayoutRender(rendered: readonly Tile[]): void {\n ctx.emit('layoutRender', {\n tiles: rendered.map((tile) => ({ index: tile.index, element: tile.root })),\n });\n }\n\n function fullRender(items: readonly GalleryItem[]): void {\n container.replaceChildren();\n tiles = items.map((item, i) => createTile(item, i));\n headings = [];\n if (groupingEnabled) {\n for (const section of computeSections(items)) {\n const sectionItems = items.slice(section.startIndex, section.endIndex);\n const { root: headingRoot, structured } = createHeadingRoot(section.key, sectionItems);\n container.appendChild(headingRoot);\n headings.push({ root: headingRoot, tileStart: section.startIndex, structured });\n for (let i = section.startIndex; i < section.endIndex; i++) {\n container.appendChild(tiles[i]!.root);\n }\n }\n } else {\n for (const tile of tiles) container.appendChild(tile.root);\n }\n columnHeights = undefined;\n relayoutAll();\n autoMeasureTiles(tiles);\n emitLayoutRender(tiles);\n }\n\n function appendRender(newItems: readonly GalleryItem[], startIndex: number): void {\n const newTiles = newItems.map((item, i) => createTile(item, startIndex + i));\n for (const tile of newTiles) container.appendChild(tile.root);\n tiles = [...tiles, ...newTiles];\n if (horizontal)\n applyMasonryHorizontal(); // full relayout — see applyMasonryHorizontal's doc comment\n else if (type === 'masonry') applyMasonry(newTiles);\n else if (type === 'justified')\n applyJustified(); // full relayout — see applyJustified's doc comment\n else applyGrid(newTiles);\n autoMeasureTiles(newTiles);\n emitLayoutRender(newTiles);\n }\n\n fullRender(gallery.items);\n previousItems = gallery.items;\n\n const offItemsUpdated = ctx.on('itemsUpdated', ({ items }) => {\n if (groupingEnabled) {\n // grouped changes always fully re-render — see the `groupBy` option's doc comment.\n fullRender(items);\n } else if (isPureAppend(previousItems, items)) {\n appendRender(items.slice(previousItems.length), previousItems.length);\n } else {\n fullRender(items);\n }\n previousItems = items;\n });\n\n // Native CSS grid already reflows its own tile positions responsively —\n // it only needs a resize-driven recompute at all when breakpoints are\n // configured (to re-check whether the container crossed a threshold).\n // Masonry/justified always need one, since they're JS-computed.\n let resizeFrame: number | null = null;\n let resizeObserver: ResizeObserver | undefined;\n if (type === 'masonry' || type === 'justified' || sortedBreakpoints.length > 0) {\n resizeObserver = new ResizeObserver(() => {\n if (resizeFrame !== null) return;\n resizeFrame = requestAnimationFrame(() => {\n resizeFrame = null;\n relayoutAll();\n });\n });\n resizeObserver.observe(container);\n }\n\n return () => {\n destroyed = true;\n if (measureFrame !== null) cancelAnimationFrame(measureFrame);\n resizeObserver?.disconnect();\n if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);\n offItemsUpdated();\n container.classList.remove('shoji-layout', `shoji-layout--${type}`, 'shoji-layout--animate');\n container.style.removeProperty('height');\n container.style.removeProperty('width');\n container.replaceChildren();\n };\n },\n};\n","export interface RotateFlipState {\n flipH: boolean;\n flipV: boolean;\n /** Degrees; normalized to one of 0/90/180/270 by `normalizeRotateFlip`. */\n rotation: number;\n}\n\n/**\n * DESIGN.md §8.1's flip/rotation canonicalization table, verbatim — CLAUDE.md:\n * \"Flip + rotate compose non-commutatively. Use the normalization table...\n * don't re-derive it.\" `flipH && flipV` is always visually equivalent to a\n * 180°-rotated state with neither flip set; this collapses any\n * `flipH`/`flipV`/`rotation` combination down to that canonical form, so two\n * states reached via different sequences of clicks compare equal and never\n * accumulate redundant flip+flip-again or unbounded rotation values.\n * Shared between the standalone rotate/flip *view* plugin (§4) and the\n * future Editor plugin (§8), which both need the identical composition —\n * not duplicated per-plugin.\n */\nexport function normalizeRotateFlip(state: RotateFlipState): RotateFlipState {\n const rotation = ((state.rotation % 360) + 360) % 360;\n if (state.flipH && state.flipV) {\n return { flipH: false, flipV: false, rotation: (rotation + 180) % 360 };\n }\n return { flipH: state.flipH, flipV: state.flipV, rotation };\n}\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. */\nexport const ROTATE_LEFT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 14 4 9l5-5\"/><path d=\"M4 9h10a6 6 0 1 1 0 12H9\"/></svg>';\n\nexport const ROTATE_RIGHT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 14 20 9l-5-5\"/><path d=\"M20 9H10a6 6 0 1 0 0 12h5\"/></svg>';\n\nexport const FLIP_H_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 3v18\"/><path d=\"M17 7l3 5-3 5\"/><path d=\"M7 7l-3 5 3 5\"/></svg>';\n\nexport const FLIP_V_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 12h18\"/><path d=\"M7 17l5 3 5-3\"/><path d=\"M7 7l5-3 5 3\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { normalizeRotateFlip, type RotateFlipState } from '../../core/rotateFlipNormalize';\nimport { waitForTransitionEnd } from '../../core/zoomTransition';\nimport { FLIP_H_ICON, FLIP_V_ICON, ROTATE_LEFT_ICON, ROTATE_RIGHT_ICON } from './icons';\n\nconst NEUTRAL: RotateFlipState = { flipH: false, flipV: false, rotation: 0 };\n\n/**\n * Flip axes apply to the *currently visible* (already-rotated) orientation,\n * not the original unrotated image — `scaleX`/`scaleY` listed before\n * `rotate()` in the transform string is what makes that true: CSS transform\n * functions apply right-to-left, so `rotate()` (rightmost) affects the\n * content first, and the flip (leftmost) acts on that already-rotated\n * result.\n *\n * `flipH`/`flipV`/`rotationDeg` here are the *raw, uncanonicalized* visual\n * values (see `visualFlipH`/`visualFlipV`/`visualRotation` below) — never\n * `state`'s own normalized ones. Two real bugs came from feeding the\n * normalized state directly into this animated transform instead:\n *\n * 1. `rotationDeg` must be unbounded, not wrapped to `[0, 360)`: animating\n * straight to a wrapped value (e.g. 270° → 0° after a fourth\n * rotate-right click, instead of continuing on to 360°) makes the\n * browser interpolate a 270° *decrease*, spinning backward almost a\n * full turn instead of continuing the same 90° forward step being\n * clicked through.\n * 2. `flipH`/`flipV` must stay two independent, literal booleans, never\n * collapsed the way `normalizeRotateFlip` collapses `flipH && flipV`\n * into `rotation + 180`: flipping horizontal then vertical while\n * already flipped horizontal would otherwise animate `scaleX` back to\n * 1 *and* `rotate` up to 180° simultaneously (both values are in the\n * transform-function list, so the browser interpolates each\n * independently) — a compound squish-and-spin instead of the plain\n * vertical-flip motion \"Flip vertical\" implies. Keeping the raw\n * booleans means only `scaleY` ever changes for that click, since\n * flipping both axes is algebraically identical to a 180° rotation\n * regardless of what rotation is already applied — the *end* look\n * always matches the canonical state either way, only the *animated\n * path* differs.\n *\n * `rotationDeg === 0` is still a safe, unambiguous \"truly neutral\" check\n * for the shortcut below — every rotate click adds ±90, so it only lands\n * back on exactly `0` at genuine reset/initial state, never a masked\n * multiple of 360.\n *\n * `fitScale` (see `fitScaleFor` below) is folded directly into `scaleX`/\n * `scaleY` — a single uniform factor commutes with everything else already\n * in this transform (rotate, and flip's own -1), so multiplying it in here\n * is exactly equivalent to a separate trailing `scale()` function, without\n * adding a fourth transform function for the browser to interpolate.\n */\nfunction transformFor(\n flipH: boolean,\n flipV: boolean,\n rotationDeg: number,\n fitScale: number,\n): string {\n if (!flipH && !flipV && rotationDeg === 0 && fitScale === 1) return 'none';\n const scaleX = (flipH ? -1 : 1) * fitScale;\n const scaleY = (flipV ? -1 : 1) * fitScale;\n return `scaleX(${scaleX}) scaleY(${scaleY}) rotate(${rotationDeg}deg)`;\n}\n\n/**\n * DESIGN.md §4.5 — shrinks the *visible photo* exactly as much as needed to\n * keep it from getting its edges clipped away when rotated, and grows it\n * back up to fill newly-available space on rotation, but never past its\n * own native pixel resolution.\n *\n * **A real bug in the previous version of this fix, caught from real usage\n * on the docs site itself: it assumed `.shoji-slide-img` always scales to\n * *touch* the container on at least one axis (`object-fit: contain`'s\n * usual behavior), which is wrong.** The actual CSS is `max-width: 100%;\n * max-height: 100%` — a *cap*, not a forced fill (documented in\n * `shoji.css`'s own comment: real photos are assumed bigger than the\n * slide area, so never growing past natural size is the correct default).\n * A small placeholder photo, comfortably smaller than the dialog, simply\n * renders at its own native size — untouching every edge, nothing scaled.\n * The previous formula didn't know this: it computed an imagined\n * \"as if `object-fit: contain` always scales to fill\" pre-rotation size\n * (e.g. an 800×600 photo hypothetically stretched to ~1267×950 in a\n * 1920×950 window), then shrank *from that invented size* — a real,\n * visible shrink relative to what was actually on screen a moment\n * earlier, even though nothing should have changed at all. Confirmed\n * directly: measuring the real `<img>` on the real deployed docs page\n * showed it rendered at exactly its 800×600 native size, not the\n * \"contain-fit\" size the old formula assumed.\n *\n * **The fix: compute the photo's real render scale at each orientation\n * the same way the browser's own CSS does, then compare the two —\n * instead of computing an idealized target size and separately capping\n * it.** `scaleAt0`/`scaleAt90` are each `Math.min(1, mediaWidth /\n * relevantNaturalWidth, mediaHeight / relevantNaturalHeight)` — exactly\n * mirroring `max-width/max-height: 100%`'s own \"shrink to fit, never grow\n * past native size\" rule, once for the current (unrotated) orientation\n * and once for the rotated one (natural width/height swapped). The result\n * is simply their ratio: how much *more* (or less) of its own native\n * resolution the rotated orientation can use compared to what's already\n * on screen. This single ratio does everything the old two-step\n * idealFit-then-cap formula tried to do, correctly and for free: neither\n * `scaleAt0` nor `scaleAt90` can ever exceed `1` (native resolution is\n * never exceeded, in *either* orientation, not just relative to a\n * possibly-wrong assumed starting point), and whichever one is more\n * constrained by the container — rather than by native resolution —\n * still shrinks or grows the ratio exactly as far as that constraint\n * requires.\n *\n * `1` (a no-op) for 0°/180° — a rectangle's own bounding box is unchanged\n * by a half-turn, nothing to re-fit — and whenever either media dimension\n * isn't known yet (not yet laid out) or the photo's own natural dimensions\n * aren't known at all (video, or an image that hasn't decoded) — skipped\n * entirely rather than guessing.\n */\nfunction fitScaleFor(\n mediaWidth: number,\n mediaHeight: number,\n rotationDeg: number,\n naturalWidth: number | undefined,\n naturalHeight: number | undefined,\n): number {\n if (!mediaWidth || !mediaHeight || !naturalWidth || !naturalHeight) return 1;\n if ((rotationDeg / 90) % 2 === 0) return 1;\n const scaleAt0 = Math.min(1, mediaWidth / naturalWidth, mediaHeight / naturalHeight);\n const scaleAt90 = Math.min(1, mediaWidth / naturalHeight, mediaHeight / naturalWidth);\n return scaleAt90 / scaleAt0;\n}\n\n/**\n * DESIGN.md §4 — rotate ±90°/flip H/V of the *view*: a CSS transform on the\n * active `.shoji-slide-media`, non-destructive, resets to neutral on every\n * `afterOpen`/`afterSlide` (per-slide, not per-gallery — DESIGN.md's own\n * wording). Emits `rotateFlipChange` on every change so a host that wants\n * this to persist can store it themselves and re-apply later (e.g. by\n * feeding a starting orientation back in some other way) — this plugin\n * itself has no persistence of its own, matching \"resets per slide\".\n *\n * Distinct from the (unbuilt) Editor plugin's own rotate/flip (§8), which\n * is destructive/persisted server-side via `item.edits`. Both share the\n * same composition math (`normalizeRotateFlip`, `src/core/`) rather than\n * each re-deriving flip+rotate's non-commutative composition — a real bug\n * class CLAUDE.md calls out by name.\n */\nexport const RotateFlip: ShojiPlugin = {\n name: 'rotateFlip',\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const locale = (gallery.options.locale ?? {}) as Record<string, string>;\n const rotateLeftLabel = locale.rotateLeft ?? 'Rotate left';\n const rotateRightLabel = locale.rotateRight ?? 'Rotate right';\n const flipHLabel = locale.flipHorizontal ?? 'Flip horizontal';\n const flipVLabel = locale.flipVertical ?? 'Flip vertical';\n\n let state: RotateFlipState = { ...NEUTRAL };\n /** Unbounded — never wrapped like `state.rotation` is. Drives only the CSS transform's rotate() degrees, so every rotate click continues smoothly in the same direction (90, 180, 270, 360, 450, ...) instead of snapping backward whenever the normalized state wraps past 0/360. See `transformFor`'s own doc comment for the full reasoning. */\n let visualRotation = 0;\n /** Raw, independent toggles — never collapsed into a rotation the way `state.flipH`/`state.flipV` are. See `transformFor`'s own doc comment. */\n let visualFlipH = false;\n let visualFlipV = false;\n\n /**\n * `animate` mirrors the Zoom plugin's own \"discrete jumps animate\"\n * pattern (`zoom/index.ts`'s `withTransition`) — a button click is a\n * one-shot state change, not a continuous gesture, so it eases instead\n * of snapping. `reset()` stays unanimated: the viewer never rotated the\n * new slide, so there's nothing to visibly animate *from*. The\n * transition is cleared once it ends so it doesn't linger onto the\n * open/close zoom transition's own later use of this same element's\n * `transform` (`zoomTransition.ts`, `.shoji-slide-media`).\n */\n /** `item.width`/`height` when known, else the active image's own natural dimensions — same fallback order the zoom transition (§2.3b) uses for its own aspect ratio, just sourced from the slide itself rather than the origin thumbnail, and kept as a real width/height pair (not collapsed to a ratio) since `fitScaleFor` needs the actual pixel counts for its resolution ceiling, not just their proportion. `undefined` for anything else (video, an image not yet decoded) — `fitScaleFor` treats that as nothing to fit, not a guess. */\n function resolveNaturalSize(media: HTMLElement): { width: number; height: number } | undefined {\n const item = gallery.items[gallery.currentIndex];\n if (item?.width && item.height) return { width: item.width, height: item.height };\n const img = media.querySelector('img');\n if (img?.naturalWidth && img.naturalHeight) {\n return { width: img.naturalWidth, height: img.naturalHeight };\n }\n return undefined;\n }\n\n function apply(animate: boolean): void {\n const media = gallery.getActiveMedia();\n if (!media) return;\n const natural = resolveNaturalSize(media);\n const fitScale = fitScaleFor(\n media.clientWidth,\n media.clientHeight,\n visualRotation,\n natural?.width,\n natural?.height,\n );\n const transform = transformFor(visualFlipH, visualFlipV, visualRotation, fitScale);\n if (!animate) {\n media.style.transform = transform;\n return;\n }\n media.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n media.style.transform = transform;\n waitForTransitionEnd(media, () => {\n media.style.transition = '';\n });\n }\n\n function buildButton(icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n button.innerHTML = icon;\n button.setAttribute('aria-label', label);\n button.title = label;\n return button;\n }\n\n const rotateLeftBtn = buildButton(ROTATE_LEFT_ICON, rotateLeftLabel);\n const rotateRightBtn = buildButton(ROTATE_RIGHT_ICON, rotateRightLabel);\n const flipHBtn = buildButton(FLIP_H_ICON, flipHLabel);\n const flipVBtn = buildButton(FLIP_V_ICON, flipVLabel);\n flipHBtn.setAttribute('aria-pressed', 'false');\n flipVBtn.setAttribute('aria-pressed', 'false');\n\n /**\n * `visualRotationDelta`, when given, is a rotate click's own known\n * direction (±90) — applied as-is to the unbounded `visualRotation`.\n * Flip clicks omit it entirely: `visualFlipH`/`visualFlipV` are toggled\n * directly at each call site instead, completely independent of\n * `state`'s own canonicalized rotation/flip collapse (`transformFor`'s\n * doc comment has the full reasoning for why the two must stay\n * decoupled).\n */\n function update(patch: Partial<RotateFlipState>, visualRotationDelta?: number): void {\n state = normalizeRotateFlip({ ...state, ...patch });\n if (visualRotationDelta !== undefined) visualRotation += visualRotationDelta;\n apply(true);\n flipHBtn.setAttribute('aria-pressed', String(state.flipH));\n flipVBtn.setAttribute('aria-pressed', String(state.flipV));\n ctx.emit('rotateFlipChange', { index: gallery.currentIndex, ...state });\n }\n\n /**\n * A real bug, reported from real usage: with exactly one flip axis\n * active, \"Rotate right\" visually spun the image counter-clockwise\n * instead — a `+90` raw `rotate()` delta composed with a single\n * `scaleX(-1)`/`scaleY(-1)` mirror reverses the rotation's visual\n * handedness (a mirror is a reflection — determinant -1 — so a\n * clockwise turn *inside* it reads as counter-clockwise once mirrored\n * back onto the screen). Flipping *both* axes doesn't have this problem\n * — two reflections compose back into a rotation (determinant +1, same\n * as no flip at all), which is exactly why `normalizeRotateFlip`\n * already collapses that combination into a plain 180° rotation.\n * Inverting the raw delta whenever `visualFlipH !== visualFlipV` (XOR —\n * \"exactly one axis flipped\") makes the buttons always spin the image\n * the way they're visually labeled, regardless of flip state; `state`\n * (the canonicalized, emitted value) gets the same inverted delta, so\n * it stays an accurate description of what's actually on screen.\n */\n function rotateDelta(clockwise: boolean): number {\n const flippedOnOneAxis = visualFlipH !== visualFlipV;\n return clockwise !== flippedOnOneAxis ? 90 : -90;\n }\n\n /** Shared by the rotate-left toolbar button and `requestRotateLeft` below. */\n function rotateLeft(): void {\n const delta = rotateDelta(false);\n update({ rotation: state.rotation + delta }, delta);\n }\n /** Shared by the rotate-right toolbar button and `requestRotateRight` below. */\n function rotateRight(): void {\n const delta = rotateDelta(true);\n update({ rotation: state.rotation + delta }, delta);\n }\n /** Shared by the flip-horizontal toolbar button and `requestFlipHorizontal` below. */\n function flipHorizontal(): void {\n visualFlipH = !visualFlipH;\n update({ flipH: !state.flipH });\n }\n /** Shared by the flip-vertical toolbar button and `requestFlipVertical` below. */\n function flipVertical(): void {\n visualFlipV = !visualFlipV;\n update({ flipV: !state.flipV });\n }\n\n rotateLeftBtn.addEventListener('click', rotateLeft);\n rotateRightBtn.addEventListener('click', rotateRight);\n flipHBtn.addEventListener('click', flipHorizontal);\n flipVBtn.addEventListener('click', flipVertical);\n\n function reset(): void {\n state = { ...NEUTRAL };\n visualRotation = 0;\n visualFlipH = false;\n visualFlipV = false;\n apply(false);\n flipHBtn.setAttribute('aria-pressed', 'false');\n flipVBtn.setAttribute('aria-pressed', 'false');\n }\n\n /**\n * DESIGN.md §2.5/§4.5 — a real bug: clicking next/prev on a\n * rotated/flipped slide snapped it back to neutral *before* the slide\n * transition started, instead of un-rotating as part of it.\n * `beforeSlide`'s own `reset()` (below) still has to stay unanimated and\n * still has to run before `SlideManager.render()` reparents the\n * outgoing slide (the sixth real bug above) — that constraint doesn't\n * go away. What changes: the transform about to be wiped is captured\n * here first and handed to `SlideTransition` via\n * `registerSlideLeaveDecorator()` (Zoom registers its own, for the same\n * reason) — the decorator runs once, right after the ghost clones the\n * outgoing slide (the real node's already been reset by then, so the\n * clone alone wouldn't carry it), freezes the captured transform onto\n * that clone, and animates it back to neutral over the same window the\n * ghost itself is leaving in. Only the ghost animates away from it now.\n */\n let pendingLeaveTransform: string | null = null;\n function captureLeaveTransform(): void {\n const media = gallery.getActiveMedia();\n const transform = media?.style.transform;\n pendingLeaveTransform = transform && transform !== 'none' ? transform : null;\n }\n\n // 'right' — registered in this order, so they cluster left-to-right as\n // rotateLeft, rotateRight, flipH, flipV, then whatever later plugin (or\n // the close button) follows (DESIGN.md §3.1).\n const removeButtons = [rotateLeftBtn, rotateRightBtn, flipHBtn, flipVBtn].map((button) =>\n ctx.ui.toolbar('right', button),\n );\n\n /**\n * A generic command surface, requested directly (DESIGN.md §4.5), so a\n * *custom* (host-authored) plugin's own button can rotate/flip without\n * importing this plugin at all — same \"events over inheritance\"\n * decoupling every other listener here already uses.\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestRotateLeft', {})` from any plugin —\n * official or custom — type-checks with zero core changes; this is\n * just the listening half. Each mirrors its real toolbar button\n * exactly — same functions, same behavior.\n */\n const offRequestRotateLeft = ctx.on('requestRotateLeft', rotateLeft);\n const offRequestRotateRight = ctx.on('requestRotateRight', rotateRight);\n const offRequestFlipHorizontal = ctx.on('requestFlipHorizontal', flipHorizontal);\n const offRequestFlipVertical = ctx.on('requestFlipVertical', flipVertical);\n const offOpen = ctx.on('afterOpen', reset);\n // Un-animated, and on beforeSlide rather than only afterSlide below —\n // same fix, same reasoning, as the Zoom plugin's own identical bug\n // (zoom/index.ts's own beforeSlide handler): SlideManager.render()\n // (called synchronously between the two) reuses a still-cached slide's\n // node via a plain reparent (moveIn(), no state clearing of its own)\n // into whichever pool slot its new offset needs — there is no code\n // path afterward that can still find *this* slide to reset it.\n // Reported from real usage: rotate, click next — the old, still-\n // rotated slide, now reparented into the (unclipped, per shoji.css)\n // neighboring slot, visibly bled into the new slide instead of\n // sitting invisibly off-screen the way an unrotated one always does.\n // Resetting here, while getActiveMedia() still resolves to the\n // about-to-move slide, clears it before that reparent ever happens.\n // afterSlide (below) still separately resets whichever *incoming*\n // slide becomes active — it may carry its own stale rotation from an\n // earlier visit, unrelated to whatever the outgoing slide had.\n // captureLeaveTransform() (see its own doc comment) runs first, while\n // the about-to-be-cleared transform is still readable.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n captureLeaveTransform();\n reset();\n });\n const offSlide = ctx.on('afterSlide', reset);\n const unregisterLeaveDecorator = gallery.registerSlideLeaveDecorator((clonedMedia) => {\n if (!pendingLeaveTransform) return;\n const transform = pendingLeaveTransform;\n pendingLeaveTransform = null;\n clonedMedia.style.transform = transform;\n return () => {\n clonedMedia.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n clonedMedia.style.transform = 'none';\n };\n });\n\n return () => {\n for (const remove of removeButtons) remove();\n offRequestRotateLeft();\n offRequestRotateRight();\n offRequestFlipHorizontal();\n offRequestFlipVertical();\n offOpen();\n offBeforeSlide();\n offSlide();\n unregisterLeaveDecorator();\n };\n },\n};\n","import type { VideoProviderRenderer } from '../../core/plugin';\n\n/**\n * The bits of Vimeo's Player SDK actually used here — not in `lib.dom.d.ts`\n * (a third-party global loaded on demand), so this is a documented interop\n * boundary (CLAUDE.md: `any` only there). Kept intentionally minimal, not a\n * full mirror of Vimeo's own typings. Unlike YouTube's IFrame API, every\n * method here is genuinely Promise-based — Vimeo has no synchronous\n * \"isMuted()\"-style query at all, which is why `wirePlayableContract` below\n * mirrors `muted` locally instead of reading it live (see its own comment).\n */\ninterface VimeoPlayer {\n play(): Promise<void>;\n pause(): Promise<void>;\n setMuted(muted: boolean): Promise<boolean>;\n ready(): Promise<void>;\n destroy(): Promise<void>;\n /** The video's own real native pixel dimensions — used to correct `--shoji-provider-video-aspect` (see the `player.ready()` handler below) if a host's declared `item.width`/`item.height` doesn't match. */\n getVideoWidth(): Promise<number>;\n getVideoHeight(): Promise<number>;\n on(event: 'play' | 'pause' | 'ended', callback: () => void): void;\n on(event: 'error', callback: (error: VimeoErrorEvent) => void): void;\n}\n\n/** Vimeo's own error event shape (`name`/`message`, plus an undocumented `method` sometimes) — e.g. `name: 'PrivacyError'` (embedding disabled), `'PasswordError'` (password-protected). */\ninterface VimeoErrorEvent {\n name: string;\n message: string;\n}\n\ninterface VimeoNamespace {\n Player: new (\n element: HTMLElement,\n options: { id?: number; url?: string; playsinline?: boolean },\n ) => VimeoPlayer;\n}\n\ndeclare global {\n interface Window {\n Vimeo?: VimeoNamespace;\n }\n}\n\nlet apiPromise: Promise<VimeoNamespace> | null = null;\n\n// See the 'pause'/'ended' race comment where this is used, below.\nconst PAUSE_DISPATCH_DELAY_MS = 250;\n\n/**\n * Loads `https://player.vimeo.com/api/player.js` exactly once however many\n * Vimeo slides/galleries end up on a page — `window.Vimeo` is a single\n * global. Simpler than `youtube.ts`'s `loadYouTubeApi`: Vimeo's script has\n * no global-callback side channel to compose with (nothing else could\n * already be watching for it the way `onYouTubeIframeAPIReady` can be), so\n * a plain `script.onload` is enough.\n */\nfunction loadVimeoApi(): Promise<VimeoNamespace> {\n if (window.Vimeo?.Player) return Promise.resolve(window.Vimeo);\n if (apiPromise) return apiPromise;\n\n apiPromise = new Promise((resolve) => {\n const script = document.createElement('script');\n script.src = 'https://player.vimeo.com/api/player.js';\n script.onload = () => resolve(window.Vimeo!);\n document.head.appendChild(script);\n });\n return apiPromise;\n}\n\n/**\n * DESIGN.md §4-autoplay — Autoplay looks for exactly this shape (`.play`/\n * `.pause`/`.paused`/`.ended`, plus real `play`/`pause`/`ended` DOM events)\n * on whatever's active, native `<video>` or not. Augmenting `container` this\n * way is what makes slideshow sync work without Autoplay ever having to\n * know Vimeo — or any other provider — exists. `play` genuinely returns\n * `player.play()`'s own promise (unlike `youtube.ts`'s fire-and-forget\n * `.play`) — Autoplay's own `ensureProviderPlaying` (§4.1 point 12) branches\n * its retry strategy on whether this is a real thenable at runtime.\n */\ntype PlayableElement = HTMLElement & {\n play: () => Promise<void>;\n pause: () => void;\n paused: boolean;\n ended: boolean;\n muted: boolean;\n};\n\n/**\n * `muted`'s setter genuinely forwards to `player.setMuted()` (fire-and-\n * forget, same as `youtube.ts`'s `mute()`/`unMute()` calls), but the getter\n * mirrors a locally-tracked value instead of reading the player live —\n * unlike YouTube's `isMuted()`, Vimeo's `getMuted()` is Promise-based, so\n * there's no synchronous value to read at all. Harmless here: nothing in\n * Autoplay ever reads `.muted` back, only sets it (DESIGN.md §4.1 point 8's\n * `video.muted = true` before an automatic play).\n */\nfunction wirePlayableContract(container: HTMLElement, player: VimeoPlayer): PlayableElement {\n const playable = container as PlayableElement;\n playable.paused = true;\n playable.ended = false;\n playable.play = () => player.play();\n playable.pause = () => player.pause();\n let mutedState = false;\n Object.defineProperty(playable, 'muted', {\n configurable: true,\n get: () => mutedState,\n set: (value: boolean) => {\n mutedState = value;\n player.setMuted(value);\n },\n });\n return playable;\n}\n\n/**\n * DESIGN.md §4-video — `item.poster`, if the host supplied one, is already\n * shown by the time this runs (core's own doing, `SlideManager.ts`) and\n * always wins over the fallback below. Without one, this falls back to a\n * real thumbnail fetched from Vimeo's own oEmbed endpoint — unlike\n * YouTube's predictable, request-free thumbnail URL (`youtube.ts`), Vimeo\n * has no such pattern; its thumbnails live at unpredictable, per-video\n * CDN paths only oEmbed's response actually reveals — before finally\n * falling back to the plain spinner if that request never resolves.\n */\nexport const renderVimeo: VideoProviderRenderer = (container, item, onReady, signal, setPoster) => {\n if (item.video?.provider !== 'vimeo') return;\n const { id, url } = item.video;\n if (!id && !url) {\n // A misconfigured item — scan.ts already warned about this at\n // normalization time. Same placeholder SlideManager itself uses for \"no\n // source\"/\"provider not registered\", so the spinner doesn't hang\n // forever waiting for a ready() that would never resolve otherwise.\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n container.appendChild(placeholder);\n onReady();\n return;\n }\n\n if (!item.poster) {\n // `url` (carrying an unlisted video's privacy hash, same reasoning as\n // the player construction below) is preferred over a bare numeric id\n // when both exist; oEmbed accepts either a full vimeo.com URL or one\n // built from just the id.\n const oembedTarget = url ?? `https://vimeo.com/${id}`;\n fetch(`https://vimeo.com/api/oembed.json?url=${encodeURIComponent(oembedTarget)}`)\n .then((response) => (response.ok ? response.json() : null))\n .then((data: { thumbnail_url?: unknown } | null) => {\n if (signal.aborted) return; // navigated away before the request resolved\n if (typeof data?.thumbnail_url === 'string') setPoster(data.thumbnail_url);\n })\n // Swallowed deliberately, same reasoning as youtube.ts's 404 case —\n // a failed request (network error, CORS, rate limit, a private/\n // deleted video oEmbed itself rejects) just leaves whatever's\n // already showing (the plain spinner) alone.\n .catch(() => {});\n }\n\n // shoji-video-mount (styles/shoji.css) — several real bugs, reported from\n // real usage, chased through in sequence:\n //\n // 1. Left at its own defaults, Vimeo's SDK sizes `mount` to a small fixed\n // box (its own embed default, ~640x360) via inline styles — CSS's own\n // `width/height: 100%` on the iframe only ever resolves relative to\n // that fixed-size `mount`, not the actual slide, so the embed rendered\n // small, in a corner, instead of filling the dialog.\n //\n // 2. `responsive: true` looked like the fix (and does make `mount` fill\n // its parent's *width*) but doesn't actually solve this: it computes\n // `mount`'s *height* from that width times the video's own native\n // aspect ratio via a padding-percentage trick, entirely ignoring how\n // much vertical space the slide actually has — confirmed directly at a\n // wide-but-short viewport, the resulting iframe came out taller than\n // its container, pushing the bottom of the video (and Vimeo's own\n // scrubber/controls bar, always along that same edge) below the\n // visible area.\n //\n // 3. Fully stretching `mount` to the container's own box instead (no\n // aspect-ratio at all) fixed that, but traded it for a third bug:\n // stretching regardless of the video's real 16:9 shape exposed\n // Vimeo's own internal letterbox color (white — not overridable from\n // here, that content is cross-origin) wherever the box wasn't already\n // 16:9 itself, instead of Shoji's own dark backdrop.\n //\n // `shoji-video-mount`'s CSS rules are what actually solve all three at\n // once now: contained to a real 16:9 box via container query units\n // (`!important` still doing the \"discard whatever Vimeo tries to set\n // inline\" job point 1 needed), so any leftover gap is *outside* the\n // iframe, showing this element's own transparent background — Shoji's\n // dark backdrop — rather than the provider's white. YouTube's plain\n // iframe (no such wrapper) gets the identical treatment directly, see\n // `.shoji-slide-provider-video > iframe` in shoji.css.\n const mount = document.createElement('div');\n mount.className = 'shoji-video-mount';\n container.appendChild(mount);\n\n loadVimeoApi().then((Vimeo) => {\n if (signal.aborted) return; // navigated away before the (possibly first-ever, slow) API load resolved\n\n const playable = container as PlayableElement;\n // `url` (the original data-shoji-video/video.url, when present) is\n // preferred over a bare id: it's what carries an unlisted video's\n // privacy hash (vimeo.com/{id}/{hash}) through to the player, which a\n // numeric id alone can't express. Only dynamic-mode items authored\n // without a url ever fall back to id-only.\n const player = new Vimeo.Player(mount, {\n ...(url ? { url } : { id: Number(id) }),\n playsinline: true,\n });\n\n // A real bug, reported from real usage: reaching the end of the video\n // stopped the slideshow instead of advancing it, and — the tell —\n // manually pressing play again restarted the same video from 0 instead\n // of resuming anywhere. Confirmed directly: Vimeo's own 'pause' arrives\n // as a genuinely separate postMessage event shortly *before* 'ended'\n // (~20ms apart in testing) when a video reaches its natural end, unlike\n // native `<video>`, whose `.ended` property the browser sets\n // synchronously before firing either event — Autoplay's own\n // `onVideoPause` (DESIGN.md §4.1 point 3) checks `.ended` to tell a\n // real pause from an end-adjacent one, and that check reliably lost the\n // race, reading `false` and treating a natural end as a manual pause.\n // Fixed by not dispatching 'pause' immediately: it's held for\n // `PAUSE_DISPATCH_DELAY_MS`, comfortably above the observed gap, and\n // dropped entirely if 'ended' arrives first — which is also then the\n // *only* event a natural end ever produces, matching how a single\n // native `<video>` 'pause' alongside 'ended' was already a non-issue\n // via the `.ended` check alone. A genuine manual pause (no 'ended'\n // following) still dispatches, just delayed by that same short window\n // — imperceptible for a real pause, and worth it for a correct one.\n let pendingPauseTimer: ReturnType<typeof setTimeout> | null = null;\n function clearPendingPause(): void {\n if (pendingPauseTimer !== null) {\n clearTimeout(pendingPauseTimer);\n pendingPauseTimer = null;\n }\n }\n player.on('play', () => {\n clearPendingPause();\n playable.paused = false;\n playable.dispatchEvent(new Event('play'));\n });\n player.on('pause', () => {\n playable.paused = true;\n clearPendingPause();\n pendingPauseTimer = setTimeout(() => {\n pendingPauseTimer = null;\n playable.dispatchEvent(new Event('pause'));\n }, PAUSE_DISPATCH_DELAY_MS);\n });\n player.on('ended', () => {\n clearPendingPause();\n playable.paused = true;\n playable.ended = true;\n playable.dispatchEvent(new Event('ended'));\n });\n // bubbles: true — reaches .shoji-slide-media (the pool slot, always\n // present regardless of readiness) without needing wirePlayableContract\n // to have run first; matches youtube.ts's onError — a player can error\n // out (bad id, privacy-restricted, password-protected) without ever\n // becoming ready. Autoplay (DESIGN.md §4.1) listens for this to skip to\n // the next slide instead of stalling.\n player.on('error', (error) =>\n playable.dispatchEvent(\n new CustomEvent('error', { bubbles: true, detail: { name: error.name } }),\n ),\n );\n\n player.ready().then(() => {\n wirePlayableContract(container, player);\n // A real bug, reported from real usage: a host's declared\n // `item.width`/`item.height` (what `--shoji-provider-video-aspect`,\n // shoji.css, is normally set from — SlideManager.ts's `applyAspect()`)\n // doesn't always match the video's own real shape — confirmed\n // directly against a real 2.4:1 cinematic-widescreen video declared\n // as a plain 4:3 item. Vimeo's own player fits *itself* to the real\n // shape regardless of what box it's given, so a mismatch here leaves\n // Shoji's outer box a different aspect ratio than what Vimeo actually\n // renders inside it — exposing the iframe's own default white\n // background (not overridable from here, that content is\n // cross-origin) in the gap, instead of a clean, uniform letterbox.\n // Corrected here, before `onReady()` reveals the container, using the\n // one thing that can't be wrong: the player's own real dimensions.\n // Setting this directly on `container` (`.shoji-slide-provider-video`)\n // overrides the inherited value from `applyAspect()`'s own\n // `.shoji-slide-media` — no coordination with SlideManager needed.\n // Swallowed on rejection: a declared item.width/height (if any) is a\n // fine fallback, and this must never block onReady().\n Promise.all([player.getVideoWidth(), player.getVideoHeight()])\n .then(([width, height]) => {\n if (width && height) {\n container.style.setProperty(\n '--shoji-provider-video-aspect',\n `calc(${width} / ${height})`,\n );\n }\n })\n .catch(() => {})\n .then(() => onReady());\n });\n\n signal.addEventListener(\n 'abort',\n () => {\n clearPendingPause();\n void player.destroy();\n },\n { once: true },\n );\n });\n};\n","import type { VideoProviderRenderer } from '../../core/plugin';\n\n/**\n * The bits of the YouTube IFrame Player API actually used here — not in\n * `lib.dom.d.ts` (a third-party global loaded on demand), so this is a\n * documented interop boundary (CLAUDE.md: `any` only there). Kept\n * intentionally minimal, not a full mirror of YouTube's own typings.\n */\ninterface YTPlayer {\n playVideo(): void;\n pauseVideo(): void;\n mute(): void;\n unMute(): void;\n isMuted(): boolean;\n destroy(): void;\n}\n\ninterface YTPlayerStateEvent {\n data: number;\n}\n\n/**\n * Same `{ data: number }` shape as `YTPlayerStateEvent` — `data` holds an\n * error code there (2 invalid parameter, 5 HTML5 player error, 100 video\n * not found/private, 101/150 embedding disabled by the owner; undocumented\n * codes like 153 are also reported in the wild) rather than a player state.\n * Named separately from `YTPlayerStateEvent` for readability at the call\n * site, not because the shape actually differs.\n */\ninterface YTPlayerErrorEvent {\n data: number;\n}\n\ninterface YTNamespace {\n Player: new (\n el: HTMLElement,\n opts: {\n videoId: string;\n playerVars?: { playsinline?: 0 | 1; rel?: 0 | 1 };\n events?: {\n onReady?: () => void;\n onStateChange?: (event: YTPlayerStateEvent) => void;\n onError?: (event: YTPlayerErrorEvent) => void;\n };\n },\n ) => YTPlayer;\n PlayerState: { ENDED: number; PLAYING: number; PAUSED: number };\n}\n\ndeclare global {\n interface Window {\n YT?: YTNamespace;\n onYouTubeIframeAPIReady?: () => void;\n }\n}\n\nlet apiPromise: Promise<YTNamespace> | null = null;\n\n/**\n * Loads `https://www.youtube.com/iframe_api` exactly once however many\n * YouTube slides/galleries end up on a page — the API itself is a single\n * global (`window.YT`), and re-injecting the script tag would be wasteful\n * and risks a second, conflicting `onYouTubeIframeAPIReady` firing. Composes\n * with a host's own `onYouTubeIframeAPIReady`, if one already exists\n * (e.g. the host embeds YouTube elsewhere too), instead of clobbering it.\n */\nfunction loadYouTubeApi(): Promise<YTNamespace> {\n if (window.YT?.Player) return Promise.resolve(window.YT);\n if (apiPromise) return apiPromise;\n\n apiPromise = new Promise((resolve) => {\n const previous = window.onYouTubeIframeAPIReady;\n window.onYouTubeIframeAPIReady = () => {\n previous?.();\n resolve(window.YT!);\n };\n const script = document.createElement('script');\n script.src = 'https://www.youtube.com/iframe_api';\n document.head.appendChild(script);\n });\n return apiPromise;\n}\n\n/**\n * DESIGN.md §4-autoplay — Autoplay looks for exactly this shape (`.play`/\n * `.pause`/`.paused`/`.ended`, plus real `play`/`pause`/`ended` DOM events)\n * on whatever's active, native `<video>` or not. Augmenting `container`\n * this way is what makes slideshow sync work without Autoplay ever having\n * to know YouTube — or any other provider — exists.\n */\ntype PlayableElement = HTMLElement & {\n play: () => void;\n pause: () => void;\n paused: boolean;\n ended: boolean;\n muted: boolean;\n};\n\n/**\n * `muted` is a real accessor (not a plain property) backed by the player's\n * own `mute()`/`unMute()`/`isMuted()` — DESIGN.md §4.1's autoplay-policy fix\n * sets `video.muted = true` right before an *automatic* play, the same way\n * it would for a native `<video>`; a plain property here would just be\n * inert state that never actually silences the embed.\n */\nfunction wirePlayableContract(container: HTMLElement, player: YTPlayer): PlayableElement {\n const playable = container as PlayableElement;\n playable.paused = true;\n playable.ended = false;\n playable.play = () => player.playVideo();\n playable.pause = () => player.pauseVideo();\n Object.defineProperty(playable, 'muted', {\n configurable: true,\n get: () => player.isMuted(),\n set: (value: boolean) => (value ? player.mute() : player.unMute()),\n });\n return playable;\n}\n\nfunction handleStateChange(\n event: YTPlayerStateEvent,\n YT: YTNamespace,\n playable: PlayableElement,\n): void {\n if (event.data === YT.PlayerState.PLAYING) {\n playable.paused = false;\n playable.dispatchEvent(new Event('play'));\n } else if (event.data === YT.PlayerState.PAUSED) {\n playable.paused = true;\n playable.dispatchEvent(new Event('pause'));\n } else if (event.data === YT.PlayerState.ENDED) {\n playable.paused = true;\n playable.ended = true;\n playable.dispatchEvent(new Event('ended'));\n }\n}\n\n/**\n * DESIGN.md §4-video — `item.poster`, if the host supplied one, is already\n * shown by the time this runs (core's own doing, `SlideManager.ts`) and\n * always wins over the fallback below. Without one, this falls back to\n * YouTube's own predictable, unauthenticated thumbnail URL — no API call\n * needed, unlike Vimeo's oEmbed-based equivalent (`vimeo.ts`) — before\n * finally falling back to the plain spinner if even that never resolves.\n */\nexport const renderYouTube: VideoProviderRenderer = (\n container,\n item,\n onReady,\n signal,\n setPoster,\n) => {\n if (item.video?.provider !== 'youtube') return;\n const videoId = item.video.id;\n if (!videoId) {\n // A misconfigured item — scan.ts (data-shoji-video-id / video: true /\n // video.id auto-fill) already warned about this at normalization time.\n // Same placeholder SlideManager itself uses for \"no source\"/\"provider\n // not registered\", so the spinner doesn't hang forever waiting for an\n // onReady that would never fire otherwise.\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n container.appendChild(placeholder);\n onReady();\n return;\n }\n\n // hqdefault.jpg exists for essentially every uploaded video (unlike\n // maxresdefault.jpg, which many older/short videos never got generated);\n // a 404 here just leaves the plain spinner showing, same as never calling\n // setPoster at all — no error handling needed for that.\n if (!item.poster) setPoster(`https://img.youtube.com/vi/${videoId}/hqdefault.jpg`);\n\n const mount = document.createElement('div');\n container.appendChild(mount);\n\n loadYouTubeApi().then((YT) => {\n if (signal.aborted) return; // navigated away before the (possibly first-ever, slow) API load resolved\n\n const playable = container as PlayableElement;\n const player = new YT.Player(mount, {\n videoId,\n playerVars: { playsinline: 1, rel: 0 },\n events: {\n // `new YT.Player()` returns before the embed's own internal bootstrap\n // (its postMessage handshake with youtube.com) finishes — calling\n // `player.mute()`/`playVideo()`/etc. before that completes can throw\n // (\"player.isMuted is not a function\") or silently no-op, even though\n // the constructor already returned an object. `onReady` is YouTube's\n // own signal that the real API surface is actually callable now, so\n // wiring the contract here — not synchronously after construction —\n // is what makes `findPlayable()`'s \"is `.play` wired?\" check in\n // Autoplay (DESIGN.md §4.1) an accurate proxy for \"is it really\n // ready?\" instead of just \"did we build the wrapper closures?\".\n onReady: () => {\n wirePlayableContract(container, player);\n onReady();\n },\n onStateChange: (event) => handleStateChange(event, YT, playable),\n // bubbles: true — reaches .shoji-slide-media (the pool slot, always\n // present regardless of readiness) without needing wirePlayableContract\n // to have run first; onError can fire instead of onReady entirely\n // (e.g. a removed/private video), so playable isn't a safe assumption\n // here the way it is in onStateChange. Autoplay (DESIGN.md §4.1)\n // listens for this to skip to the next slide instead of stalling.\n onError: (event) =>\n playable.dispatchEvent(\n new CustomEvent('error', { bubbles: true, detail: { code: event.data } }),\n ),\n },\n });\n signal.addEventListener('abort', () => player.destroy(), { once: true });\n });\n};\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { renderVimeo } from './vimeo';\nimport { renderYouTube } from './youtube';\n\n/**\n * DESIGN.md §4-video — renders `{ video: { provider: 'youtube' | 'vimeo', id } }`\n * items (produced by `scan.ts`'s `data-shoji-video` host detection, or\n * authored directly in dynamic mode) as a real embed instead of\n * `SlideManager`'s native-`<video>` fallback, which can't play either URL at\n * all. Purely a renderer: no options, no toolbar button, no poster/\n * thumbnail handling — the slide shows nothing until the embed itself is\n * ready, same as every other slide type. Autoplay (§4-autoplay) picks up\n * real play/pause/ended sync automatically; see `youtube.ts`'s/`vimeo.ts`'s\n * `wirePlayableContract`.\n */\nexport const Video: ShojiPlugin = {\n name: 'video',\n\n init(ctx: PluginContext): () => void {\n const offYouTube = ctx.ui.registerVideoProvider('youtube', renderYouTube);\n const offVimeo = ctx.ui.registerVideoProvider('vimeo', renderVimeo);\n return () => {\n offYouTube();\n offVimeo();\n };\n },\n};\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. A magnifying glass with a +/− in the lens, and a plain expand-corners glyph for \"actual size\" (distinct from fullscreen's EXPAND_ICON — no diagonal corner arrows, just a frame, so the two aren't visually confusable when both plugins are enabled). */\nexport const ZOOM_IN_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"10\" cy=\"10\" r=\"7\"/><path d=\"M21 21l-5.5-5.5M10 7v6M7 10h6\"/></svg>';\n\nexport const ZOOM_OUT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"10\" cy=\"10\" r=\"7\"/><path d=\"M21 21l-5.5-5.5M7 10h6\"/></svg>';\n\nexport const ZOOM_ACTUAL_SIZE_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"1\"/><path d=\"M9 15l6-6M9 9h0M15 15h0\"/></svg>';\n","/** A viewport-relative rect: `{left, top, width, height}`, same shape as `DOMRect` but plain-object so it's trivial to mock in tests. */\nexport interface ZoomBox {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\nexport interface PanOffset {\n tx: number;\n ty: number;\n}\n\nexport function clampScale(scale: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, scale));\n}\n\n/** The 2x2 linear part of a CSS transform matrix — `{a, b, c, d}` from `matrix(a, b, c, d, e, f)`, translation (`e`/`f`) deliberately excluded, since everything below only ever uses this to remap a *delta* or a *local offset*, never an absolute position. */\nexport interface LinearTransform {\n a: number;\n b: number;\n c: number;\n d: number;\n}\n\n/** No parent transform — used as the default wherever a caller doesn't have (or need) one, so every function below stays backward-compatible with a pre-RotateFlip-aware caller. */\nexport const IDENTITY_TRANSFORM: LinearTransform = { a: 1, b: 0, c: 0, d: 1 };\n\n/**\n * `getComputedStyle().transform`'s own `matrix(a, b, c, d, e, f)` (or\n * `none`) string, parsed by hand rather than via the `DOMMatrix`\n * constructor — jsdom (`tests/unit/`) doesn't implement it, so relying on\n * it broke every unit test that exercises a pan drag; a plain regex needs\n * nothing environment-specific and works identically in a real browser.\n * RotateFlip only ever emits a 2D `matrix(...)` (never `matrix3d(...)`),\n * so that's the only form handled — `none` and anything unparseable both\n * fall back to the identity matrix.\n */\nexport function parseLinearTransform(transform: string): LinearTransform {\n const match = /^matrix\\(\\s*([^,]+),\\s*([^,]+),\\s*([^,]+),\\s*([^,]+),/.exec(transform);\n if (!match) return { ...IDENTITY_TRANSFORM };\n return { a: Number(match[1]), b: Number(match[2]), c: Number(match[3]), d: Number(match[4]) };\n}\n\n/**\n * DESIGN.md §4.6 — a real bug, reported from real usage: dragging to pan a\n * zoomed photo that RotateFlip (§4.5) had also rotated moved it in the\n * *wrong* direction (e.g. dragging down moved the image sideways instead)\n * — `onPointerMove`'s raw `event.clientX/Y` delta (screen space) was being\n * applied directly as `pan.tx`/`ty` (the `<img>`'s own *local* space,\n * nested inside `.shoji-slide-media`), with nothing correcting for\n * whatever transform that parent has — RotateFlip's rotation, in this\n * case, but this doesn't need to know that specifically: it corrects for\n * *any* linear transform on the parent, read live off its own computed\n * style, not by reaching into RotateFlip.\n *\n * Standard 2x2 matrix inversion: for `M = [[a, c], [b, d]]`, `M⁻¹ =\n * 1/det * [[d, -c], [-b, a]]` — applying `M⁻¹` to a screen-space delta\n * converts it into the local space `M` itself maps *from*, which is\n * exactly what a child nested inside that transformed parent needs to\n * move by to track the pointer 1:1 on screen regardless of the parent's\n * own rotation/scale/flip. `det === 0` is a degenerate parent transform\n * (zero scale on some axis) that can't be un-done at all — returns the\n * raw delta unchanged rather than dividing by zero into `NaN`.\n */\nexport function screenDeltaToLocal(dx: number, dy: number, m: LinearTransform): PanOffset {\n const det = m.a * m.d - m.b * m.c;\n if (det === 0) return { tx: dx, ty: dy };\n return {\n tx: (m.d * dx - m.c * dy) / det,\n ty: (m.a * dy - m.b * dx) / det,\n };\n}\n\n/** The forward companion to `screenDeltaToLocal` above: `M * [dx; dy]`, converting a *local* delta into the screen-space delta it produces once composed through the parent's current transform `m`. */\nexport function localDeltaToScreen(dx: number, dy: number, m: LinearTransform): PanOffset {\n return { tx: m.a * dx + m.c * dy, ty: m.b * dx + m.d * dy };\n}\n\n/**\n * DESIGN.md §4.6 — the img's own true, *unrotated* layout size (its\n * `offsetWidth`/`offsetHeight` — CSS `transform` is paint-only and never\n * affects these, unlike `natural`'s own `getBoundingClientRect()`, which\n * *does* reflect the parent's current rotation) as an offset from the\n * img's own local origin `(0, 0)` to its own layout center, negated:\n * `{tx: -width/2, ty: -height/2}`. See `localOriginScreen`'s own doc\n * comment for why this specific offset is what a rotated parent needs.\n * Defaults to deriving it from `natural` itself (assuming `natural` *is*\n * already the true, unrotated size) — correct whenever the parent has no\n * rotation, wrong whenever it does; real callers with a possibly-rotated\n * parent should always pass the img's real `offsetWidth`/`offsetHeight`\n * explicitly instead of relying on this default.\n */\nexport function trueOriginOffset(natural: ZoomBox): PanOffset {\n return { tx: -natural.width / 2, ty: -natural.height / 2 };\n}\n\n/**\n * DESIGN.md §4.6 — a real bug, found immediately after the pan-drag fix\n * above while testing the analogous double-click-to-zoom case: `natural`'s\n * own `left`/`top` (from `getBoundingClientRect()` on the *rotated* img)\n * is **not** the screen position of the img's local origin `(0, 0)` —\n * rotating a rectangle moves *which of its own corners* ends up at the\n * bounding box's own top-left. For a 90°-rotated landscape photo, the\n * corner that lands at `natural`'s own top-left is the photo's original\n * *bottom*-left, not its top-left — confirmed directly, by hand, against\n * real `getBoundingClientRect()` numbers: treating `natural.left + pan.tx`\n * as \"the origin's screen position\" (what `zoomTowardPoint`/`clampPan`\n * both did) was off by the img's own full width on one axis, which is\n * exactly why double-clicking to zoom toward the pointer, after a\n * rotation, zoomed toward the wrong point instead — sometimes a\n * plausible-looking wrong point, sometimes (as reported) toward an edge\n * of the image instead of the actual click.\n *\n * The one point immune to this ambiguity is the bounding box's own\n * *center* — rotating a rectangle around its own center (the default\n * `transform-origin`, and where `.shoji-slide-media`'s flex-centering\n * already puts the img) never moves that center, on screen or off. Used\n * as a pivot: the img's local origin, relative to its own *true* (layout,\n * pre-rotation) center, is a fixed offset (`originOffset`, `-width/2,\n * -height/2` in the img's own local space) — that offset plus the current\n * `pan`, mapped through the parent's rotation matrix `m` and added back to\n * the pivot's own (rotation-invariant) screen position, gives the origin's\n * *real* current screen position, correct for any axis-aligned rotation\n * RotateFlip can produce. At the default identity `m` and the default\n * `originOffset` (derived from `natural` itself, correct exactly when\n * there's no rotation to begin with), this reduces to plain\n * `natural.left + pan.tx` — the original, pre-fix formula.\n */\nexport function localOriginScreen(\n natural: ZoomBox,\n pan: PanOffset,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): { x: number; y: number } {\n const pivotX = natural.left + natural.width / 2;\n const pivotY = natural.top + natural.height / 2;\n const fromPivot = localDeltaToScreen(originOffset.tx + pan.tx, originOffset.ty + pan.ty, m);\n return { x: pivotX + fromPivot.tx, y: pivotY + fromPivot.ty };\n}\n\n/** One axis of `clampEdgeToContainer` below — see `clampPan`'s own doc comment for the geometry. Keeps the scaled content's edge from retreating inside the container's edge (no empty gap beyond the image); when the content is already smaller than the container on this axis, no position can avoid a gap on *both* sides at once, so centered is the only sensible answer. */\nfunction clampEdge(\n contentPos: number,\n contentSize: number,\n containerPos: number,\n containerSize: number,\n): number {\n if (contentSize <= containerSize) {\n return containerPos + (containerSize - contentSize) / 2;\n }\n const minPos = containerPos + containerSize - contentSize;\n const maxPos = containerPos;\n return Math.min(maxPos, Math.max(minPos, contentPos));\n}\n\n/**\n * The content's own current screen-space bounding box, for `clampPan`\n * below — the four corners of the img's true (unrotated) `width x height`\n * rect (from `originOffset`, negated), scaled and panned in the wrapper's\n * own unrotated frame, then each mapped to screen space individually via\n * `m` before taking the min/max. Four corners, not one edge scaled\n * directly, because `m` can swap which axis grows with which — RotateFlip\n * only ever produces axis-aligned (90°-multiple) rotations, so the result\n * is still a plain axis-aligned box, just not derivable from a single\n * corner the way an unrotated one is.\n */\nfunction contentScreenBounds(\n natural: ZoomBox,\n pan: PanOffset,\n scale: number,\n m: LinearTransform,\n originOffset: PanOffset,\n): { left: number; top: number; right: number; bottom: number } {\n const trueWidth = -originOffset.tx * 2;\n const trueHeight = -originOffset.ty * 2;\n const pivotX = natural.left + natural.width / 2;\n const pivotY = natural.top + natural.height / 2;\n const localCorners = [\n { x: 0, y: 0 },\n { x: trueWidth, y: 0 },\n { x: 0, y: trueHeight },\n { x: trueWidth, y: trueHeight },\n ];\n const screenCorners = localCorners.map(({ x, y }) => {\n const wrapperFrame = {\n x: originOffset.tx + pan.tx + x * scale,\n y: originOffset.ty + pan.ty + y * scale,\n };\n const screen = localDeltaToScreen(wrapperFrame.x, wrapperFrame.y, m);\n return { x: pivotX + screen.tx, y: pivotY + screen.ty };\n });\n const xs = screenCorners.map((p) => p.x);\n const ys = screenCorners.map((p) => p.y);\n return {\n left: Math.min(...xs),\n top: Math.min(...ys),\n right: Math.max(...xs),\n bottom: Math.max(...ys),\n };\n}\n\n/**\n * Keeps the scaled+panned content's edges from retreating inside\n * `container`'s edges (no empty gap beyond the image), on both screen axes\n * independently.\n *\n * `m`/`originOffset` (default identity / derived from `natural`, DESIGN.md\n * §4.6) — same real bug and same root cause as `localOriginScreen`'s own\n * doc comment: the old per-axis formula compared `natural.left + pan.tx`\n * (mixing screen-space and, once rotated, the wrong corner entirely)\n * against the container's screen bounds. The content's actual screen\n * bounding box is computed properly via `contentScreenBounds` (which\n * itself only ever needs `m`/`originOffset` to do that correctly), each\n * edge is clamped against the container the same way as before, and the\n * *difference* — a screen-space delta — is mapped back to local space and\n * folded into `pan`. At the defaults, every step is a no-op and this\n * reduces to exactly the original per-axis formula.\n */\nexport function clampPan(\n natural: ZoomBox,\n container: ZoomBox,\n scale: number,\n pan: PanOffset,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): PanOffset {\n const bounds = contentScreenBounds(natural, pan, scale, m, originOffset);\n const clampedLeft = clampEdge(\n bounds.left,\n bounds.right - bounds.left,\n container.left,\n container.width,\n );\n const clampedTop = clampEdge(\n bounds.top,\n bounds.bottom - bounds.top,\n container.top,\n container.height,\n );\n const screenDelta = { tx: clampedLeft - bounds.left, ty: clampedTop - bounds.top };\n const localDelta = screenDeltaToLocal(screenDelta.tx, screenDelta.ty, m);\n return { tx: pan.tx + localDelta.tx, ty: pan.ty + localDelta.ty };\n}\n\n/**\n * The standard \"zoom toward a point\" formula: adjusts pan so the viewport\n * point `(anchorX, anchorY)` stays visually fixed as scale changes from\n * `oldScale` to `newScale`, given `transform-origin: 0 0` (scaling never\n * moves the img's own local origin on screen, only `pan` does). Callers\n * still need to clamp the result with `clampPan` afterward; this only\n * solves the anchor-fixed part, not boundary containment.\n *\n * `m`/`originOffset` (default identity / derived from `natural`, DESIGN.md\n * §4.6) — a real bug, reported from real usage: double-clicking to zoom\n * toward the pointer, after RotateFlip had rotated the slide, zoomed\n * toward the wrong point — sometimes badly (see `localOriginScreen`'s own\n * doc comment for the root cause and how these two parameters fix it,\n * shared with `clampPan` above). At the defaults, every step is a no-op\n * and this reduces to exactly the original formula.\n */\nexport function zoomTowardPoint(\n natural: ZoomBox,\n pan: PanOffset,\n oldScale: number,\n newScale: number,\n anchorX: number,\n anchorY: number,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): PanOffset {\n const origin = localOriginScreen(natural, pan, m, originOffset);\n const screenDx = anchorX - origin.x;\n const screenDy = anchorY - origin.y;\n const local = screenDeltaToLocal(screenDx, screenDy, m);\n const factor = 1 - newScale / oldScale;\n return {\n tx: pan.tx + local.tx * factor,\n ty: pan.ty + local.ty * factor,\n };\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { waitForTransitionEnd } from '../../core/zoomTransition';\nimport { ZOOM_ACTUAL_SIZE_ICON, ZOOM_IN_ICON, ZOOM_OUT_ICON } from './icons';\nimport {\n clampPan,\n clampScale,\n parseLinearTransform,\n screenDeltaToLocal,\n zoomTowardPoint,\n type PanOffset,\n type ZoomBox,\n} from './zoomMath';\nimport './zoom.css';\n\nexport interface ZoomOptions {\n /** Multiplier cap for pinch/wheel/button zoom. \"Actual size\" can exceed this deliberately — it's an explicit action, not continuous gesture zoom. Default 4. */\n maxScale?: number;\n /** Scale a double-tap/double-click jumps to; a second one while already zoomed resets to 1 instead. Default 2. */\n doubleTapScale?: number;\n /** Multiplier applied per zoom-in/zoom-out toolbar button click. Default 1.5. */\n buttonStep?: number;\n}\n\nconst ZOOM_EPSILON = 1.001; // treat \"just barely above 1\" as unzoomed — avoids float residue pinning isZoomed() true forever\n\n/** A click/drag starting on a real control shouldn't engage pan — same exclusion list GestureController's shouldIgnoreGesture uses, duplicated rather than imported since that function isn't part of core's exported surface. */\nfunction isRealControl(event: PointerEvent): boolean {\n return event\n .composedPath()\n .some(\n (node) =>\n node instanceof Element &&\n node.matches(\n 'button, video, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption',\n ),\n );\n}\n\n/**\n * DESIGN.md §4-zoom — pinch, double-tap/click, wheel+ctrl, and three toolbar\n * buttons (zoom in/out/actual-size) all drive a single `scale`/pan state on\n * the active slide's `<img>` — never `.shoji-slide-media` itself, which the\n * rotateFlip plugin (§4) already transforms; nesting on the inner element\n * instead of fighting over the same transform string means a rotated *and*\n * zoomed photo behaves correctly for free (the outer rotate carries the\n * inner pan/scale along with it as a rigid unit, which is also the visually\n * expected result — see DESIGN.md's note on this plugin for the full\n * reasoning). Pinch/double-tap/wheel are core's own gesture relay (§2.4) —\n * scaffolding that existed specifically for this plugin to consume, not\n * reimplemented here. Pan (single-pointer drag while zoomed) is the one\n * piece core's relay doesn't cover — core's own drag-to-navigate/\n * drag-to-close would otherwise fight over the same drag — so this plugin\n * registers a zoom gate (`Gallery.registerZoomGate`, §4-zoom) that suspends\n * core's drag handling entirely while zoomed, and tracks pan with its own\n * minimal raw pointer listeners instead of reusing `GestureEngine` (whose\n * axis-locked model — pick horizontal *or* vertical per gesture — is the\n * wrong shape for a 2D pan that needs both at once).\n */\nexport const Zoom: ShojiPlugin = {\n name: 'zoom',\n defaults: {\n maxScale: 4,\n doubleTapScale: 2,\n buttonStep: 1.5,\n } satisfies ZoomOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const maxScale = Number(ctx.options.maxScale ?? 4);\n const doubleTapScale = Number(ctx.options.doubleTapScale ?? 2);\n const buttonStep = Number(ctx.options.buttonStep ?? 1.5);\n const locale = (gallery.options.locale ?? {}) as Record<string, string>;\n const zoomInLabel = locale.zoomIn ?? 'Zoom in';\n const zoomOutLabel = locale.zoomOut ?? 'Zoom out';\n const actualSizeLabel = locale.zoomActualSize ?? 'Actual size';\n\n let scale = 1;\n let pan: PanOffset = { tx: 0, ty: 0 };\n let natural: ZoomBox | null = null;\n let container: ZoomBox | null = null;\n // The img's own true, unrotated local origin, as an offset from its\n // (rotation-invariant) layout center — see zoomTowardPoint/clampPan's\n // own doc comments (DESIGN.md §4.6) for why natural's left/top/width/\n // height alone aren't a safe stand-in for this once RotateFlip has\n // rotated the parent.\n let originOffset: PanOffset | null = null;\n let pinchStartScale = 1;\n\n function getImg(): HTMLImageElement | null {\n const media = gallery.getActiveMedia();\n const child = media?.firstElementChild;\n return child instanceof HTMLImageElement ? child : null;\n }\n\n function boxOf(el: Element): ZoomBox {\n const rect = el.getBoundingClientRect();\n return { left: rect.left, top: rect.top, width: rect.width, height: rect.height };\n }\n\n /** Only valid to measure while scale===1 (untransformed) — the very first zoom action on a slide; every subsequent action within the same slide reuses the cached box, since measuring an already-scaled element would capture the scaled size, not the natural one. */\n function ensureNatural(img: HTMLImageElement): boolean {\n if (natural && container && originOffset) return true;\n if (scale !== 1) return false; // shouldn't happen — defensive\n natural = boxOf(img);\n container = boxOf(img.parentElement ?? img);\n // offsetWidth/Height, not natural's own width/height above — CSS\n // transform (RotateFlip's rotation on the parent) is paint-only and\n // never affects layout size, unlike getBoundingClientRect(), which\n // reports the *rotated* bounding box (DESIGN.md §4.6). Falls back to\n // natural's own (unrotated-assuming) size when offsetWidth/Height\n // read 0 — real layout engines only report 0 for a genuinely\n // unrendered element, but jsdom (tests/unit/) never computes layout\n // at all and always reports 0, so this also keeps every rotation-\n // unaware unit test's mocked getBoundingClientRect() meaningful.\n originOffset = {\n tx: -(img.offsetWidth || natural.width) / 2,\n ty: -(img.offsetHeight || natural.height) / 2,\n };\n return true;\n }\n\n /**\n * A real bug: `ensureNatural`'s first measurement of a slide is only\n * trustworthy once the lightbox's own open FLIP transition (`zoomIn`,\n * `core/zoomTransition.ts`) has actually settled — that transition\n * applies its own transform directly to `.shoji-slide-media`, the exact\n * element `ensureNatural` measures as `container`. A zoom action firing\n * before it settles (any interaction within `--shoji-duration` of\n * opening — a fast click, or a test that only waits for the dialog to\n * become visible) captured a wildly wrong, mid-animation rect,\n * permanently poisoning that slide's zoom math (every later action\n * reuses the same cached, wrong box). `zoomIn` is fire-and-forget by\n * design (nothing to await when opening) and clears this exact inline\n * style once its own transition ends — the one signal available for\n * \"is it still running.\" Runs `action` immediately once settled, which\n * is right away in the overwhelming common case (any real interaction\n * more than ~300ms after open).\n */\n function whenSettled(action: () => void): void {\n const media = gallery.getActiveMedia();\n if (!media || media.style.transition === '') {\n action();\n return;\n }\n waitForTransitionEnd(media, action);\n }\n\n /**\n * `translate3d`/`scale3d`, not the 2D `translate`/`scale` this used to\n * use — a real bug, reported from real usage: evenly-spaced horizontal\n * lines visible across a zoomed photo, at certain zoom levels, on real\n * GPU hardware (not reproducible in headless/software rendering, so\n * this can't be verified here). The regular spacing matches Chromium's\n * own raster-tile boundaries — a known quirk where scaling large\n * content via a 2D `scale()` transform can show seams between GPU\n * tiles. Forcing the fully 3D compositing path instead (functionally\n * identical — `scale3d(s, s, 1)` and `scale(s)` produce the same\n * on-screen result) is the commonly effective fix, since it takes a\n * different rasterization path than the 2D one.\n */\n function apply(): void {\n const img = getImg();\n if (!img) return;\n img.style.transformOrigin = '0 0';\n img.style.transform =\n scale === 1 && pan.tx === 0 && pan.ty === 0\n ? 'none'\n : `translate3d(${pan.tx}px, ${pan.ty}px, 0) scale3d(${scale}, ${scale}, 1)`;\n img.classList.toggle('shoji-zoomed', scale > 1);\n }\n\n function emitChange(): void {\n ctx.emit('zoomChange', { index: gallery.currentIndex, scale });\n }\n\n /** Wraps a transform-setting `run` in a transition, for discrete jumps (buttons, double-tap, actual-size) — never for pinch/pan/wheel, which already track the input 1:1 and would visibly lag behind it under a transition. `afterEnd`, if given, runs once the transition actually completes, not before — `reset()` uses it to clear `transformOrigin` only once it's safe to (see its own comment for why clearing it any earlier is a real bug). The transition itself is always cleared afterward, so it doesn't linger onto the next, possibly-continuous, zoom action. */\n function withTransition(img: HTMLImageElement, run: () => void, afterEnd?: () => void): void {\n img.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n run();\n waitForTransitionEnd(img, () => {\n img.style.transition = '';\n afterEnd?.();\n });\n }\n\n /** Shared by every zoom-in/out entry point (pinch, wheel, buttons, double-tap, actual-size) — anchors on (anchorX, anchorY), clamps scale to [1, ceiling] and pan to the container bounds. `ceiling` defaults to maxScale; actual-size passes its own (possibly larger) target so it isn't capped by the gesture-zoom limit. Deferred via `whenSettled` — see its doc comment — so a zoom action landing right as the lightbox opens doesn't measure mid-animation. `animate` — see `withTransition`. */\n function zoomTo(\n targetScale: number,\n anchorX: number,\n anchorY: number,\n ceiling = maxScale,\n animate = false,\n ): void {\n whenSettled(() => {\n const img = getImg();\n if (!img || !ensureNatural(img)) return;\n const clampedScale = clampScale(targetScale, 1, Math.max(ceiling, 1));\n // DESIGN.md §4.6 — zoomTowardPoint's own doc comment has the full\n // reasoning: the anchor point needs the same screen-vs-local\n // correction as onPointerMove's own pan drag, since RotateFlip may\n // have rotated/flipped `.shoji-slide-media` in the meantime.\n const media = gallery.getActiveMedia();\n const parentTransform = parseLinearTransform(\n media ? getComputedStyle(media).transform : 'none',\n );\n pan = zoomTowardPoint(\n natural!,\n pan,\n scale,\n clampedScale,\n anchorX,\n anchorY,\n parentTransform,\n originOffset!,\n );\n scale = clampedScale;\n // Same correction, same reason — clampAxis compares against the\n // container's screen bounds, so the candidate pan needs to be in\n // screen space too, or a 90/270deg rotation clamps the wrong edge\n // and can undo the anchor-preserving pan just computed above.\n pan = clampPan(natural!, container!, scale, pan, parentTransform, originOffset!);\n if (animate) withTransition(img, apply);\n else apply();\n emitChange();\n });\n }\n\n function reset(animate = false): void {\n // A real gap, found auditing this against its own documented contract\n // (\"emits zoomChange on every scale change, gesture or button-driven\",\n // DESIGN.md §4.6): resetting from an engaged scale back to 1 is a\n // scale change like any other, but every call site here (beforeSlide,\n // afterSlide, beforeClose, afterOpen, and zoomOutStep/toggleZoom\n // reaching neutral) silently skipped emitting it — a host listening\n // for zoomChange to reflect \"is this slide currently zoomed\" would\n // never learn it stopped being true unless something else zoomed in\n // again first. Only when there's an actual change: the overwhelming\n // majority of these calls fire while already at scale 1 (nothing\n // engaged to begin with), and emitting on every no-op reset would be\n // noisy against the \"on every *change*\" contract, not a fix for it.\n const wasEngaged = scale !== 1;\n scale = 1;\n pan = { tx: 0, ty: 0 };\n natural = null;\n container = null;\n originOffset = null;\n if (wasEngaged) emitChange(); // after scale is already 1, so listeners see the real new value\n const img = getImg();\n if (!img) return;\n const clearTransform = (): void => {\n img.style.transform = '';\n img.classList.remove('shoji-zoomed');\n };\n if (animate) {\n // transform-origin has to stay put (0 0) for the duration of the\n // transition — clearing it to the browser default (center) in the\n // same tick as starting the transition snaps the scale anchor\n // instantly, which visibly jumped the image before it eased down\n // to neutral. Deferred to `afterEnd`, once the transition is done\n // and transform-origin no longer affects anything visible.\n withTransition(img, clearTransform, () => {\n img.style.transformOrigin = '';\n });\n } else {\n clearTransform();\n img.style.transformOrigin = '';\n }\n }\n\n /** DESIGN.md §2.5/§4.6 — same fix, same reasoning, as RotateFlip's own equivalent (`rotateFlip/index.ts`): `beforeSlide`'s unanimated `reset()` above can't itself animate (it has to finish before `SlideManager.render()` reparents the outgoing image), so the live `transform`/`transformOrigin` about to be wiped are captured here first and handed to `SlideTransition` via `registerSlideLeaveDecorator()` below, to animate away on the leave-ghost's own clone instead of just vanishing. */\n let pendingLeaveTransform: string | null = null;\n let pendingLeaveOrigin = '';\n function captureLeaveTransform(): void {\n const img = getImg();\n const transform = img?.style.transform;\n pendingLeaveTransform = transform && transform !== 'none' ? transform : null;\n pendingLeaveOrigin = img?.style.transformOrigin || '0 0';\n }\n\n /** Each slide gets a freshly-created `<img>` (SlideManager never reuses elements across renders), so the cursor-affordance marker (`zoom.css`) needs reapplying every time the active media changes, not just once. */\n function markEnabled(): void {\n getImg()?.classList.add('shoji-zoom-enabled');\n }\n\n function toggleZoom(x: number, y: number): void {\n if (scale > ZOOM_EPSILON) reset(true);\n else zoomTo(doubleTapScale, x, y, maxScale, true);\n }\n\n // --- pinch (relayed by core, §2.4 — no built-in effect until this plugin exists) ---\n const offPinchStart = ctx.on('pinchStart', () => {\n pinchStartScale = scale;\n });\n const offPinchMove = ctx.on('pinchMove', ({ scale: relative, centerX, centerY }) => {\n zoomTo(pinchStartScale * relative, centerX, centerY);\n });\n const offPinchEnd = ctx.on('pinchEnd', () => {\n if (scale <= ZOOM_EPSILON) reset(); // snap fully back to neutral rather than leaving float residue\n });\n\n // --- double-tap / double-click (relayed by core; Pointer Events unify the two, see GestureEngine) ---\n const offDoubleTap = ctx.on('doubleTap', ({ x, y }) => toggleZoom(x, y));\n\n // --- ctrl+wheel / trackpad pinch (relayed by core) ---\n const offWheelZoom = ctx.on('wheelZoom', ({ deltaScale, x, y }) => {\n zoomTo(scale + deltaScale, x, y);\n });\n\n /**\n * A generic command surface, requested directly (DESIGN.md §4.6), so a\n * *custom* (host-authored) plugin's own button can drive zoom without\n * importing this plugin at all — same \"events over inheritance\"\n * decoupling `pinchStart`/`doubleTap`/`wheelZoom` above already use,\n * just in the opposite direction (a command in, not a gesture relay).\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestZoomIn', {})` from any plugin —\n * official or custom — type-checks with zero core changes; this is\n * just the listening half. Each mirrors its real toolbar button\n * exactly — same functions, same behavior on a video slide (a no-op,\n * `zoomInStep`/`zoomOutStep`/`actualSizeToggle` all bail via `getImg()`\n * returning null there).\n */\n const offRequestZoomIn = ctx.on('requestZoomIn', zoomInStep);\n const offRequestZoomOut = ctx.on('requestZoomOut', zoomOutStep);\n const offRequestZoomActualSize = ctx.on('requestZoomActualSize', actualSizeToggle);\n const offRequestZoomReset = ctx.on('requestZoomReset', () => reset(true));\n\n // --- pan while zoomed — the one gesture core's relay doesn't cover; see the plugin doc comment for why this can't reuse GestureEngine. ---\n let panPointerId: number | null = null;\n let lastX = 0;\n let lastY = 0;\n const outer = ctx.ui.outer();\n\n function onPointerDown(event: PointerEvent): void {\n if (scale <= ZOOM_EPSILON || isRealControl(event)) return;\n const img = getImg();\n // A real bug, reported from real usage: this listens on `outer` (the\n // whole lightbox, not just the image) so a fast pan can be tracked\n // even once the pointer leaves the image's own bounds — but with no\n // check on where the pointerdown itself landed, a click on the plain\n // backdrop (between the image and a nav arrow, say) engaged pan and\n // captured the pointer onto `img` regardless, which — see below —\n // retargets the click and makes it misread as \"on the image,\" not\n // backdrop, silently defeating click-to-close while zoomed.\n if (!img || !event.composedPath().includes(img)) return;\n panPointerId = event.pointerId;\n lastX = event.clientX;\n lastY = event.clientY;\n // Without this, a fast pan whose pointer exits `outer`'s bounds\n // stops receiving pointermove/pointerup entirely (no capture = only\n // elements actually under the cursor get events), leaving\n // panPointerId stuck non-null until the next pointerdown — the\n // gesture just goes dead mid-drag. Captured on the `<img>` itself,\n // not `outer`: capturing retargets the subsequent synthetic `click`\n // to whatever captured it, and `img` — unlike `outer` — already\n // matches isBackdropClick's own exclusion selector (Gallery.ts), so\n // a captured pan's release still can't misread as a backdrop click.\n // GestureEngine's own capture needs a separate suppressRetargetedClick\n // step for exactly this reason; this doesn't, since the retarget\n // lands somewhere already excluded.\n img.setPointerCapture(event.pointerId);\n }\n function onPointerMove(event: PointerEvent): void {\n if (panPointerId !== event.pointerId || !natural || !container || !originOffset) return;\n event.preventDefault();\n const rawDx = event.clientX - lastX;\n const rawDy = event.clientY - lastY;\n lastX = event.clientX;\n lastY = event.clientY;\n // DESIGN.md §4.6 — screenDeltaToLocal's own doc comment has the full\n // reasoning: the raw pointer delta is screen space, but pan.tx/ty are\n // local to the <img>, nested inside whatever transform (e.g.\n // RotateFlip's rotation) `.shoji-slide-media` currently has.\n const media = gallery.getActiveMedia();\n const m = parseLinearTransform(media ? getComputedStyle(media).transform : 'none');\n const { tx: dx, ty: dy } = screenDeltaToLocal(rawDx, rawDy, m);\n pan = clampPan(\n natural,\n container,\n scale,\n { tx: pan.tx + dx, ty: pan.ty + dy },\n m,\n originOffset,\n );\n apply();\n }\n function onPointerUp(event: PointerEvent): void {\n if (panPointerId === event.pointerId) panPointerId = null;\n }\n\n outer.addEventListener('pointerdown', onPointerDown);\n outer.addEventListener('pointermove', onPointerMove, { passive: false });\n outer.addEventListener('pointerup', onPointerUp);\n outer.addEventListener('pointercancel', onPointerUp);\n\n // --- toolbar buttons ---\n function buildButton(icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n button.innerHTML = icon;\n button.setAttribute('aria-label', label);\n button.title = label;\n return button;\n }\n\n function centerAnchor(): { x: number; y: number } {\n const media = gallery.getActiveMedia();\n const rect = media?.getBoundingClientRect();\n return rect\n ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }\n : { x: 0, y: 0 };\n }\n\n /** Shared by the zoom-in toolbar button and the `w` keyboard shortcut — same fixed `buttonStep` multiplier either way. */\n function zoomInStep(): void {\n const { x, y } = centerAnchor();\n zoomTo(scale * buttonStep, x, y, maxScale, true);\n }\n\n /** Shared by the zoom-out toolbar button and the `s` keyboard shortcut. */\n function zoomOutStep(): void {\n const { x, y } = centerAnchor();\n if (scale / buttonStep <= ZOOM_EPSILON) reset(true);\n else zoomTo(scale / buttonStep, x, y, maxScale, true);\n }\n\n /** Shared by the actual-size toolbar button and `requestZoomActualSize` below. Reads natural.width directly (unlike every other entry point, which just hands zoomTo a target and lets it call ensureNatural itself) — needs its own whenSettled wrap for that reason, not just zoomTo's. */\n function actualSizeToggle(): void {\n whenSettled(() => {\n const img = getImg();\n if (!img || !img.naturalWidth) return;\n if (!ensureNatural(img)) return;\n if (scale > ZOOM_EPSILON) {\n reset(true);\n return;\n }\n const targetScale = img.naturalWidth / natural!.width;\n const { x, y } = centerAnchor();\n zoomTo(targetScale, x, y, targetScale, true); // ceiling = targetScale — bypasses maxScale deliberately\n });\n }\n\n const zoomInBtn = buildButton(ZOOM_IN_ICON, zoomInLabel);\n const zoomOutBtn = buildButton(ZOOM_OUT_ICON, zoomOutLabel);\n const actualSizeBtn = buildButton(ZOOM_ACTUAL_SIZE_ICON, actualSizeLabel);\n\n zoomInBtn.addEventListener('click', zoomInStep);\n zoomOutBtn.addEventListener('click', zoomOutStep);\n actualSizeBtn.addEventListener('click', actualSizeToggle);\n\n // 'right' — registered in this order, so they cluster left-to-right as\n // zoomIn, zoomOut, actualSize, then whatever later plugin (or the close\n // button) follows (DESIGN.md §3.1).\n const removeButtons = [zoomInBtn, zoomOutBtn, actualSizeBtn].map((button) =>\n ctx.ui.toolbar('right', button),\n );\n\n /** All three zoom buttons are no-ops on a video slide — `getImg()` returns null, so `apply()`/`ensureNatural()` bail out immediately. Hidden rather than left clickable-but-dead. */\n function updateButtonVisibility(): void {\n const isVideo = !!gallery.items[gallery.currentIndex]?.video;\n zoomInBtn.hidden = isVideo;\n zoomOutBtn.hidden = isVideo;\n actualSizeBtn.hidden = isVideo;\n }\n\n // w/s zoom in/out, same step as the toolbar buttons — both cases\n // registered explicitly (registerShortcut matches event.key verbatim,\n // no case-insensitive matching of its own) so Shift/CapsLock still work.\n const removeShortcuts = [\n ctx.ui.registerShortcut('w', zoomInStep),\n ctx.ui.registerShortcut('W', zoomInStep),\n ctx.ui.registerShortcut('s', zoomOutStep),\n ctx.ui.registerShortcut('S', zoomOutStep),\n ];\n\n const offOpen = ctx.on('afterOpen', () => {\n reset();\n markEnabled();\n updateButtonVisibility();\n });\n // Un-animated, and on beforeSlide rather than only afterSlide below:\n // SlideManager.render() (called synchronously between the two) reuses a\n // still-cached slide's node via a plain reparent (moveIn(), no state\n // clearing of its own) into whichever pool slot its new offset needs —\n // there is no code path afterward that can still find *this* image to\n // reset it. A real bug, reported from real usage: zoom in via \"Actual\n // size\", click next — the old, still-scaled image, now reparented into\n // the (unclipped, per shoji.css) neighboring slot, visibly bled into the\n // new slide instead of being invisible off-screen like an unzoomed one\n // always is. Resetting here, while getActiveMedia() still resolves to\n // the about-to-move image, clears it before that reparent ever happens.\n // captureLeaveTransform() (see registerSlideLeaveDecorator below) reads\n // the live transform first, while it's still there to read.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n captureLeaveTransform();\n reset();\n });\n const offSlide = ctx.on('afterSlide', () => {\n reset();\n markEnabled();\n updateButtonVisibility();\n });\n // Fires synchronously, before Gallery.close() measures the active\n // media's rect to compute the zoom-out-to-thumbnail animation — reset\n // here (not just afterOpen/afterSlide) so that measurement sees the\n // image at its natural position/scale, not wherever it was left\n // zoomed/panned to. Skipping this made closing while zoomed animate\n // from the image's current (zoomed, often partly off-screen) rect\n // instead of its real thumbnail-relative size, landing \"closed\" at a\n // seemingly random spot instead of visibly shrinking into the thumbnail.\n const offBeforeClose = ctx.on('beforeClose', () => reset());\n const unregisterGate = gallery.registerZoomGate(() => scale > ZOOM_EPSILON);\n // Read by Gallery.beginClose() *before* the beforeClose reset above\n // runs, so a button-close continues the zoom-out from wherever the\n // viewer was actually zoomed/panned to, instead of the reset above\n // making it (correctly, for the measurement) but also making the\n // close itself snap back to neutral first. The image's own real\n // rendered rect, not this plugin's raw scale/pan numbers — see\n // zoomTransition.ts's ZoomTransitionTarget.zoomStart for why a direct\n // scale/pan replay doesn't work once it lands on a different element.\n const unregisterZoomStart = gallery.registerZoomStartProvider(() =>\n scale > ZOOM_EPSILON ? (getImg()?.getBoundingClientRect() ?? null) : null,\n );\n const unregisterLeaveDecorator = gallery.registerSlideLeaveDecorator((clonedMedia) => {\n if (!pendingLeaveTransform) return;\n const transform = pendingLeaveTransform;\n const origin = pendingLeaveOrigin;\n pendingLeaveTransform = null;\n const clonedImg = clonedMedia.querySelector<HTMLImageElement>('img');\n if (!clonedImg) return;\n clonedImg.style.transformOrigin = origin;\n clonedImg.style.transform = transform;\n return () => {\n clonedImg.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n clonedImg.style.transform = 'none';\n };\n });\n markEnabled(); // covers the (unusual but possible) case of the gallery already being open when this plugin initializes\n updateButtonVisibility();\n\n return () => {\n for (const remove of removeButtons) remove();\n for (const remove of removeShortcuts) remove();\n offOpen();\n offBeforeSlide();\n offSlide();\n offBeforeClose();\n offPinchStart();\n offPinchMove();\n offPinchEnd();\n offDoubleTap();\n offWheelZoom();\n offRequestZoomIn();\n offRequestZoomOut();\n offRequestZoomActualSize();\n offRequestZoomReset();\n outer.removeEventListener('pointerdown', onPointerDown);\n outer.removeEventListener('pointermove', onPointerMove);\n outer.removeEventListener('pointerup', onPointerUp);\n outer.removeEventListener('pointercancel', onPointerUp);\n unregisterGate();\n unregisterZoomStart();\n unregisterLeaveDecorator();\n reset();\n getImg()?.classList.remove('shoji-zoom-enabled');\n };\n },\n};\n","import { Gallery } from './core';\nimport { ActiveThumbnail } from './plugins/activeThumbnail';\nimport { Autoplay } from './plugins/autoplay';\nimport { Fullscreen } from './plugins/fullscreen';\nimport { Layout } from './plugins/layout';\nimport { RotateFlip } from './plugins/rotateFlip';\nimport { Video } from './plugins/video';\nimport { Zoom } from './plugins/zoom';\nimport { version } from '../package.json';\n\nimport './styles/shoji.css';\n\nexport type {\n GalleryItem,\n GalleryOptions,\n GalleryEvents,\n MediaSource,\n VideoDescriptor,\n Unsubscribe,\n} from './core';\nexport type { ShojiPlugin, PluginContext, VideoProviderRenderer } from './core/plugin';\n\n/**\n * `new Shoji(el, options)` — the UMD global (CLAUDE.md: \"UMD build exposes\n * exactly one global\"). The default export *is* the constructor, not a\n * namespace object, so `<script src=\"shoji.js\">` usage matches the default\n * import used by bundler/ESM consumers. Headless/tree-shaking consumers who\n * want the class as a named import can pull it from the `shoji/core`\n * subpath instead.\n *\n * Official plugins are attached as static properties (`Shoji.Autoplay`) so\n * the single-file build stays \"one global\" (CLAUDE.md) while still shipping\n * every official plugin's code — self-registering, no extra <script> tags —\n * per CLAUDE.md's single-file distribution requirement. A host opts a\n * gallery into one with `new Shoji(el, { plugins: [Shoji.Autoplay] })`.\n * Bundler users who only want to pull in specific plugins' code (tree-shaking\n * this static attachment away) should import from the `shoji/plugins/*`\n * subpath instead of this default export.\n */\nconst Shoji = Object.assign(Gallery, {\n Autoplay,\n Layout,\n ActiveThumbnail,\n Fullscreen,\n RotateFlip,\n Video,\n Zoom,\n /** `package.json`'s own version — the single source of truth, read via a named JSON import so a bundler can tree-shake away everything else in package.json (devDependencies, scripts, ...) rather than embedding the whole file. */\n version,\n});\n\nexport default Shoji;\n"],"names":["lockCount","savedHtmlOverflow","savedHtmlPaddingRight","savedHtmlPaddingLeft","savedScrollX","savedScrollY","styleObserver","intentionalScrollOccurred","LIGHTBOX_SELECTOR","markIntentionalScroll","isRtl","hasScrollableAncestor","node","el","style","touchAllowsScrollThrough","onTouchStart","event","target","onTouchMove","onStyleMutation","html","lockBodyScroll","scrollbarWidth","rtl","currentPaddingLeft","currentPaddingRight","unlockBodyScroll","EventBus","__publicField","fn","set","_a","detail","CLOSE_ICON","PREV_ICON","NEXT_ICON","CAPTION_ICON","CARET_ICON","idCounter","iconButton","className","icon","label","button","buildLightboxDom","slides","labels","labelId","outer","backdrop","dialog","toolbar","toolbarLeft","toolbarCenter","toolbarRight","closeButton","captionToggleButton","toolbarOverflowButton","toolbarOverflowPanel","counter","prevButton","nextButton","caption","captionModal","captionModalPanel","captionModalCloseButton","captionModalContent","FOCUSABLE_SELECTOR","FocusTrap","focusable","first","last","active","activeIsInside","container","DOUBLE_TAP_MAX_DELAY_MS","DOUBLE_TAP_MAX_DISTANCE","TAP_MAX_DELAY_MS","GestureEngine","callbacks","options","_b","a","b","distanceBetween","center","centerOf","_d","_c","state","distance","scale","dx","dy","absX","absY","_f","_e","delta","_h","_g","deltaScale","cancelled","elapsed","totalDelta","velocity","completed","done","cleanup","x","y","now","prefersReducedMotion","parseCssTime","value","containedBox","aspectRatio","naturalSize","containerRatio","width","height","cap","effectiveTargetBox","child","isPlaceholder","rect","containerRect","transformBetween","from","to","translateX","translateY","effectiveOriginBox","origin","img","computeTransform","originRect","targetRect","waitForTransitionEnd","cb","property","durationMs","finish","onEnd","clearInlineTransform","expectedTransform","zoomIn","transform","zoomOut","dragStart","zoomStart","onComplete","existing","jump","appliedTransform","DRAG_SETTLE_TRANSITION","DRAG_FEEDBACK_TRANSITION","VERTICAL_FEEDBACK_DISTANCE","INTERACTIVE_CONTROL_SELECTOR","GESTURE_IGNORE_SELECTOR","isInVideoControlsMargin","video","margin","suppressNextClick","isOverVideoCaption","shouldIgnoreGesture","path","GestureController","host","relay","direction","_velocity","centerX","centerY","goingNext","canMove","targetPx","onSettled","settleEl","progress","pastThreshold","animate","wasHiddenForDrag","frozen","LiveRegion","text","DEFAULT_SELECTOR","scanContainer","selector","elements","scanned","element","item","scanVideo","scanImage","attr","name","numAttr","raw","n","NO_OWN_DATA_FIELD","applyCommon","src","data","key","thumb","alt","srcset","sizes","videoIdAttr","videoEl","sources","s","poster","videoUrl","providerAttr","resolved","resolveExplicitVideo","KNOWN_VIDEO_PROVIDERS","html5Fallback","url","guessVideoType","idAttr","youtube","resolveDetectedProvider","isYouTubeUrl","detectYouTubeId","vimeo","isVimeoUrl","detectVimeoId","provider","isHost","detectId","explicit","id","YOUTUBE_HOSTS","VIMEO_HOSTS","normalizeVideoHost","hostname","parsed","match","DETECTABLE_PROVIDERS","resolveDynamicVideoItems","items","detected","p","clean","ext","SlideManager","count","_","i","offset","root","media","slot","px","transition","centerIndex","onLoad","openPlaceholderSrc","loop","canWrap","targets","rawIndex","index","windowIndices","t","entry","releaseVideoNode","claimedIndices","claimedSlots","owner","freeSlots","releaseVideo","createSpinner","reveal","createOpenPlaceholder","box","placeholder","source","renderFn","showProviderPoster","controller","providerAbortControllers","revealed","onReady","setPoster","spinner","pauseMedia","releaseProviderNode","resolveAxis","config","sign","parts","tx","ty","preset","spec","PRESET_LIST","TRANSITION_PRESETS","waitForEnd","applyEnter","opacity","applyLeave","SlideTransition","decorateLeave","swapContent","ghost","incoming","leave","enter","mode","dirAttr","kickOff","cleanupIncoming","outgoing","clonedMedia","settleLeave","itemKey","resolveElement","instanceRegistry","allInstances","DEFAULT_LOCALE","isBackdropClick","isDangerousHtmlCaption","Gallery","shortcut","selection","isZoomed","decorator","settlers","decorate","settle","dom","clamped","frozenDrag","hidden","declared","validNames","plugin","changed","missing","pluginOptions","ctx","layer","render","isRawElement","unhover","rowHeight","fitsOneRow","slotEl","pinnedCeiling","dialogRight","caretRight","paddingRight","right","columnCount","onEnter","onLeave","marked","markIntentionalScrollInternal","loading","half","noCaption","isVideo","hiddenByToggle","btn","truncated","paddingBottom","budget","elTop","range","lastFittingBottom","nextLineTop","relTop","relBottom","desired","loadedIndex","total","fadeInOnOpen","dataThumb","swap","modeName","builtin","thumbImg","currentIndex","activeItem","activeKey","nextIndex","preserved","atIndex","next","matches","indices","m","keys","ActiveThumbnail","gallery","activeClass","scrollIntoView","highlight","borderColor","highlightDuration","highlightFadeDuration","HIGHLIGHT_CLASS","current","scrollTimer","fadeTimer","cancelPendingScroll","cancelFade","applyClass","performScroll","apply","onClose","pending","teardown","offOpen","offSlide","offClose","offLayoutRender","PLAY_ICON","PAUSE_ICON","findPlayable","isPendingProviderVideo","PROVIDER_PLAY_RETRY_MS","MAX_PROVIDER_PLAY_ATTEMPTS","RESUME_DEBOUNCE_MS","Autoplay","interval","showProgress","autoStart","readMode","onZoom","onRotateFlip","onCaptionExpand","stopOnManualNavigate","locale","playLabel","pauseLabel","playing","timer","currentVideo","awaitingProviderVideo","wasPlayingBeforeDrag","zoomedIn","rotatedOrFlipped","captionOpen","pausedByZoom","pausedByRotateFlip","pausedByCaptionExpand","resumeTimer","cancelPendingResume","clearPauseFlags","isEngaged","maybeScheduleResume","start","isAdvancing","onVideoError","advance","progressBar","clearTimer","resetProgressBar","runProgressBar","ms","updateToggleAvailability","blocked","setButtonState","isPlaying","onVideoEnded","onVideoPause","stop","detachVideo","ensureProviderPlaying","attemptsLeft","playResult","pollWithoutReissuing","reissueOnEachRetry","enterSlide","error","before","reCheckEngagedAfterManualStart","stillZoomed","stillRotated","toggle","offDragThreshold","ZOOM_ENGAGED_THRESHOLD","offZoomChange","offRotateFlipChange","flipH","flipV","rotation","offCaptionModalChange","open","removeButton","removeProgress","removeShortcut","offBeforeSlide","offSlideItemLoad","offRequestStop","offRequestStart","EXPAND_ICON","COMPRESS_ICON","isSupported","currentFullscreenElement","requestFullscreen","exitFullscreen","doc","Fullscreen","enterLabel","exitLabel","isActive","setState","toggleFullscreen","onChange","offRequestToggle","computeColumnCount","containerWidth","gutterX","columns","maxAllowedByMin","minRequiredByMax","computeColumnWidth","layoutMasonry","tiles","startHeights","colWidth","columnHeights","positions","tile","colIndex","indexOfShortest","tileHeight","containerHeight","heights","shortest","layoutMasonryHorizontal","gutterY","currentY","rowStart","rowWidth","rowCount","tileWidth","placeRow","endExclusive","w","countInRow","widthIfIncluded","aspectRatioOf","layoutJustified","minRowHeight","maxRowHeight","lastRow","rows","aspectSum","naturalHeightOf","startIndex","sum","resolveScaledRow","end","rowSum","yieldMinRowHeight","natural","j","DEFAULT_ASPECT","resolveGutter","obj","keyOf","isPureAppend","oldItems","newItems","Layout","type","gutter","orientation","columnWidth","minColumnWidth","maxColumnWidth","fill","autoMeasureEnabled","horizontal","groupByFn","renderHeadingFn","headingOverflow","stickyHeadingsRaw","stickyHeadings","groupingEnabled","baseConfig","breakpointsRaw","sortedBreakpoints","overrides","resolveConfig","maxWidth","headings","previousItems","warnedMissingDims","measuredAspect","computeSections","sections","createHeadingRoot","sectionItems","rendered","structured","titleEl","subtitleEl","headingSegments","heading","measurableSrc","aspectOf","measured","selfCorrecting","createTile","applyGrid","applyMasonry","appendOnly","masonryOptions","segments","headingHeights","segTiles","segResult","pos","masonryTiles","result","applyMasonryHorizontal","applyJustifiedGrouped","justifiedOptions","fullWidths","titleOnlyWidths","tileAspects","tileStart","tileEnd","tryFit","startSection","endSection","k","nextPos","available","computeSegments","segStart","base","best","trial","applyContentDecisions","segment","applyWrapDecisions","parsedLineHeight","lineHeight","maxLines","cumulativeExtra","headingPtr","row","globalStart","globalEnd","bandHeight","segLastCovered","applyJustified","justifiedTiles","relayoutAll","destroyed","measureFrame","scheduleMeasureRelayout","fullRender","autoMeasureTiles","newTiles","emitLayoutRender","section","headingRoot","appendRender","offItemsUpdated","resizeFrame","resizeObserver","normalizeRotateFlip","ROTATE_LEFT_ICON","ROTATE_RIGHT_ICON","FLIP_H_ICON","FLIP_V_ICON","NEUTRAL","transformFor","rotationDeg","fitScale","scaleX","scaleY","fitScaleFor","mediaWidth","mediaHeight","naturalWidth","naturalHeight","scaleAt0","RotateFlip","rotateLeftLabel","rotateRightLabel","flipHLabel","flipVLabel","visualRotation","visualFlipH","visualFlipV","resolveNaturalSize","buildButton","rotateLeftBtn","rotateRightBtn","flipHBtn","flipVBtn","update","patch","visualRotationDelta","rotateDelta","clockwise","rotateLeft","rotateRight","flipHorizontal","flipVertical","reset","pendingLeaveTransform","captureLeaveTransform","removeButtons","offRequestRotateLeft","offRequestRotateRight","offRequestFlipHorizontal","offRequestFlipVertical","unregisterLeaveDecorator","remove","apiPromise","PAUSE_DISPATCH_DELAY_MS","loadVimeoApi","resolve","script","wirePlayableContract","player","playable","mutedState","renderVimeo","signal","oembedTarget","response","mount","Vimeo","pendingPauseTimer","clearPendingPause","loadYouTubeApi","previous","handleStateChange","YT","renderYouTube","videoId","Video","offYouTube","offVimeo","ZOOM_IN_ICON","ZOOM_OUT_ICON","ZOOM_ACTUAL_SIZE_ICON","clampScale","min","max","IDENTITY_TRANSFORM","parseLinearTransform","screenDeltaToLocal","det","localDeltaToScreen","trueOriginOffset","localOriginScreen","pan","originOffset","pivotX","pivotY","fromPivot","clampEdge","contentPos","contentSize","containerPos","containerSize","minPos","contentScreenBounds","trueWidth","trueHeight","screenCorners","wrapperFrame","screen","xs","ys","clampPan","bounds","clampedLeft","clampedTop","screenDelta","localDelta","zoomTowardPoint","oldScale","newScale","anchorX","anchorY","screenDx","screenDy","local","factor","ZOOM_EPSILON","isRealControl","maxScale","doubleTapScale","buttonStep","zoomInLabel","zoomOutLabel","actualSizeLabel","pinchStartScale","getImg","boxOf","ensureNatural","whenSettled","action","emitChange","withTransition","run","afterEnd","zoomTo","targetScale","ceiling","clampedScale","parentTransform","wasEngaged","clearTransform","pendingLeaveOrigin","markEnabled","toggleZoom","offPinchStart","offPinchMove","relative","offPinchEnd","offDoubleTap","offWheelZoom","offRequestZoomIn","zoomInStep","offRequestZoomOut","zoomOutStep","offRequestZoomActualSize","actualSizeToggle","offRequestZoomReset","panPointerId","lastX","lastY","onPointerDown","onPointerMove","rawDx","rawDy","onPointerUp","centerAnchor","zoomInBtn","zoomOutBtn","actualSizeBtn","updateButtonVisibility","removeShortcuts","offBeforeClose","unregisterGate","unregisterZoomStart","clonedImg"],"mappings":"0ZACA,IAAIA,GAAY,EACZC,GAAoB,GACpBC,GAAwB,GACxBC,GAAuB,GACvBC,GAAe,EACfC,GAAe,EACfC,GAAyC,KAczCC,GAA4B,GAEhC,MAAMC,GAAoB,eAGnB,SAASC,IAA8B,CAC5CF,GAA4B,EAC9B,CAEA,SAASG,IAAiB,CACxB,OAAO,iBAAiB,SAAS,eAAe,EAAE,YAAc,KAClE,CAUA,SAASC,GAAsBC,EAA4B,CACzD,IAAIC,EAAKD,aAAgB,QAAUA,GAAQA,GAAA,YAAAA,EAAM,gBAAiB,KAClE,KAAOC,GAAMA,IAAO,SAAS,iBAAiB,CAC5C,MAAMC,EAAQ,iBAAiBD,CAAE,EACjC,IACGC,EAAM,YAAc,QAAUA,EAAM,YAAc,WACnDD,EAAG,aAAeA,EAAG,aAErB,MAAO,GAETA,EAAKA,EAAG,aACV,CACA,MAAO,EACT,CASA,IAAIE,GAA2B,GAE/B,SAASC,GAAaC,EAAyB,CAC7C,MAAMC,EAASD,EAAM,OAErBF,GAA2B,EADJG,aAAkB,SAAWA,EAAO,QAAQV,EAAiB,IAAM,OAC5CG,GAAsBO,CAAqB,CAC3F,CAwBA,SAASC,GAAYF,EAAyB,CAC5C,MAAMC,EAASD,EAAM,OAEjB,EADmBC,aAAkB,SAAWA,EAAO,QAAQV,EAAiB,IAAM,OACnE,CAACO,MAAgC,eAAA,CAC1D,CAcA,SAASK,IAAwB,CAC/B,GAAIpB,KAAc,EAAG,OACrB,MAAMqB,EAAO,SAAS,gBAClB,iBAAiBA,CAAI,EAAE,WAAa,WACtCA,EAAK,MAAM,SAAW,SACtBf,IAAA,MAAAA,GAAe,cAEnB,CAEO,SAASgB,IAAuB,CACrC,GAAItB,KAAc,EAAG,CAUnBI,GAAe,OAAO,QACtBC,GAAe,OAAO,QACtBE,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EAAI,GAAG,cAAe,IAAM+W,GAAO,EACpD2I,EAAiBpc,EAAQ,iBAAiB,IAAMnT,EAAQ+rB,EAAY,EASpEyD,EAAsBrc,EAAQ,0BAA0B,IAAA,OAC5D,OAAAnT,EAAQ+rB,KAAgB3vB,EAAAowB,MAAA,YAAApwB,EAAU,0BAA2B,KAAQ,KAAA,EAEjEgrB,EAA2BjU,EAAQ,4BAA6BjF,GAAgB,CACpF,GAAI,CAAC2Y,EAAuB,OAC5B,MAAMrjB,EAAYqjB,EACZnkB,EAAS8qB,EACf3G,EAAwB,KACxB,MAAM4I,EAAYvhB,EAAY,cAAgC,KAAK,EACnE,GAAKuhB,EACL,OAAAA,EAAU,MAAM,gBAAkB/sB,EAClC+sB,EAAU,MAAM,UAAYjsB,EACrB,IAAM,CACXisB,EAAU,MAAM,WAAa,sDAC7BA,EAAU,MAAM,UAAY,MAC9B,CACF,CAAC,EACD,OAAAhC,GAAA,EACA2B,GAAA,EAEO,IAAM,OACX,UAAW/H,KAAUN,GAAeM,EAAA,EACpC,UAAWA,KAAUgI,GAAiBhI,EAAA,EACtC/S,GAAA,EACAgF,EAAA,EACA/E,EAAA,EACA+a,EAAA,EACA3B,EAAA,EACAC,EAAA,EACAE,GAAA,EACAC,EAAA,EACAC,GAAA,EACAC,GAAA,EACAE,GAAA,EACAE,EAAA,EACAE,EAAA,EACAlxB,GAAM,oBAAoB,cAAesxB,EAAa,EACtDtxB,GAAM,oBAAoB,cAAeuxB,EAAa,EACtDvxB,GAAM,oBAAoB,YAAa0xB,EAAW,EAClD1xB,GAAM,oBAAoB,gBAAiB0xB,EAAW,EACtDQ,EAAA,EACAC,EAAA,EACApI,EAAA,EACAR,EAAA,GACAxqB,EAAAowB,MAAA,MAAApwB,EAAU,UAAU,OAAO,qBAC7B,CACF,CACF,ECxgBE,uBACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"shoji.min.js","sources":["../src/core/bodyScrollLock.ts","../src/core/EventBus.ts","../src/core/icons.ts","../src/core/dom.ts","../src/core/FocusTrap.ts","../src/gestures/GestureEngine.ts","../src/core/zoomTransition.ts","../src/core/GestureController.ts","../src/core/LiveRegion.ts","../src/core/scan.ts","../src/core/SlideManager.ts","../src/transitions/presets.ts","../src/transitions/SlideTransition.ts","../src/core/Gallery.ts","../src/plugins/activeThumbnail/index.ts","../src/core/iconSwap.ts","../src/plugins/autoplay/icons.ts","../src/plugins/autoplay/index.ts","../src/plugins/fullscreen/icons.ts","../src/plugins/fullscreen/index.ts","../src/plugins/layout/masonry.ts","../src/plugins/layout/justified.ts","../src/plugins/layout/index.ts","../src/core/rotateFlipNormalize.ts","../src/plugins/rotateFlip/icons.ts","../src/plugins/rotateFlip/index.ts","../src/plugins/video/vimeo.ts","../src/plugins/video/youtube.ts","../src/plugins/video/index.ts","../src/plugins/zoom/icons.ts","../src/plugins/zoom/zoomMath.ts","../src/plugins/zoom/index.ts","../src/index.ts"],"sourcesContent":["/** DESIGN.md §2.6a — reference-counted page scroll lock. */\nlet lockCount = 0;\nlet savedHtmlOverflow = '';\nlet savedHtmlPaddingRight = '';\nlet savedHtmlPaddingLeft = '';\nlet savedScrollX = 0;\nlet savedScrollY = 0;\nlet styleObserver: MutationObserver | null = null;\n// Set by markIntentionalScroll() (ActiveThumbnail's own scrollIntoView while\n// locked, DESIGN.md §2.6a/§4.2) — a real bug/regression: unlockBodyScroll()\n// unconditionally restoring savedScrollX/Y (below) was meant to undo\n// *unrelated* code hijacking scroll during the lock (a router, a stray\n// \"scroll to top\" button), but it just as unconditionally undid Shoji's own\n// legitimate background-page scrolling too, making ActiveThumbnail's\n// scrollIntoView a complete no-op the instant the lightbox that triggers it\n// is also what's holding the lock — every navigation while open, always.\n// Once anything marks an intentional scroll during this lock session, skip\n// the restore entirely rather than try to track a smooth-scroll animation's\n// eventual resting position (no reliable completion signal across browsers)\n// — same \"leave it where legitimate code put it\" reasoning, just without\n// pinpointing the exact pixel.\nlet intentionalScrollOccurred = false;\n\nconst LIGHTBOX_SELECTOR = '.shoji-outer';\n\n/** Call after intentionally scrolling something on the host page while the lock is active (e.g. ActiveThumbnail's own `scrollIntoView`) — tells `unlockBodyScroll()` not to undo it. */\nexport function markIntentionalScroll(): void {\n intentionalScrollOccurred = true;\n}\n\nfunction isRtl(): boolean {\n return getComputedStyle(document.documentElement).direction === 'rtl';\n}\n\n/**\n * Walks up from `node` looking for a real scrollable container — lets\n * `onTouchMove` below allow touch-scrolling through to something like a\n * host-app modal/sidebar opened on top of the lightbox, instead of\n * blocking it just because it's outside `.shoji-outer`. Stops at\n * `document.documentElement` deliberately — that's the exact background\n * scroll this lock exists to block, not a container to exempt from it.\n */\nfunction hasScrollableAncestor(node: Node | null): boolean {\n let el = node instanceof Element ? node : (node?.parentElement ?? null);\n while (el && el !== document.documentElement) {\n const style = getComputedStyle(el);\n if (\n (style.overflowY === 'auto' || style.overflowY === 'scroll') &&\n el.scrollHeight > el.clientHeight\n ) {\n return true;\n }\n el = el.parentElement;\n }\n return false;\n}\n\n// Computed once per gesture, in onTouchStart below, not recomputed on every\n// onTouchMove — a touch's `event.target` stays fixed to the original\n// touchstart target for the whole gesture regardless of where the finger\n// moves (Touch Events spec), so re-walking the ancestor chain and calling\n// getComputedStyle again on every move would just repeat the same, not-free\n// answer for no benefit (CLAUDE.md: no forced synchronous layout in hot\n// paths like gestures/scroll).\nlet touchAllowsScrollThrough = false;\n\nfunction onTouchStart(event: TouchEvent): void {\n const target = event.target;\n const insideLightbox = target instanceof Element && target.closest(LIGHTBOX_SELECTOR) !== null;\n touchAllowsScrollThrough = !insideLightbox && hasScrollableAncestor(target as Node | null);\n}\n\n/**\n * A real gap: `overflow: hidden` on `<html>` doesn't reliably block iOS\n * Safari's own touch-driven rubber-band/bounce scroll in every case — a\n * well-known limitation of this technique across the ecosystem. The common\n * workaround (flipping `body` to `position: fixed` while locked) has its\n * own real tradeoffs: a full reflow, plus manual scroll-position capture/\n * restore that's a frequent source of bugs in other libraries (the exact\n * class of bug this whole lock has already had twice — see the other real\n * bugs in this file's history). Lighter alternative: block the browser's\n * default only for a touchmove that didn't start inside a lightbox,\n * leaving Shoji's own in-dialog gesture handling (which already manages\n * its own `preventDefault`, see `GestureEngine.ts`) completely untouched.\n * Not a passive listener — `preventDefault` is genuinely required here to\n * suppress the browser's native scroll, not just observe it.\n *\n * Also untouched: a touch that started on a genuinely scrollable ancestor\n * outside the lightbox (`touchAllowsScrollThrough`, set in `onTouchStart`\n * above) — a real bug, reported from real usage: this used to block\n * touch-scrolling in *any* host-app UI outside `.shoji-outer`, including\n * something like a Bootstrap modal or sidebar opened on top of the\n * lightbox, not just the page body behind it.\n */\nfunction onTouchMove(event: TouchEvent): void {\n const target = event.target;\n const insideLightbox = target instanceof Element && target.closest(LIGHTBOX_SELECTOR) !== null;\n if (!insideLightbox && !touchAllowsScrollThrough) event.preventDefault();\n}\n\n/**\n * A real gap: this lock is reference-counted against other `Gallery`\n * instances, but has no way to know about unrelated code on the host page\n * — another modal/dropdown library that also sets\n * `document.documentElement.style.overflow`, then clears it back to `''`\n * on its own close, would silently undo this lock mid-lightbox with\n * neither library aware of the other. Watching the one attribute this\n * lock itself owns is the only way to detect and correct that reactively.\n * `takeRecords()` discards the mutation record our own corrective write\n * below just queued — otherwise the observer would fire again for a\n * change it caused itself, forever.\n */\nfunction onStyleMutation(): void {\n if (lockCount === 0) return;\n const html = document.documentElement;\n if (getComputedStyle(html).overflow !== 'hidden') {\n html.style.overflow = 'hidden';\n styleObserver?.takeRecords();\n }\n}\n\nexport function lockBodyScroll(): void {\n if (lockCount === 0) {\n // A real gap: `overflow: hidden` blocks wheel/touch/keyboard-driven\n // scrolling, but not a programmatic `window.scrollTo()`/`scrollTop`\n // write — confirmed directly. If the host's own code scrolls the\n // window while the lightbox is open (a router restoring scroll\n // position, an unrelated \"scroll to top\" button), the page ends up\n // somewhere different than where the viewer left it once the lock\n // releases. Restored unconditionally on unlock below — a scroll\n // *lock* implies the background stays frozen in place for the whole\n // time the lightbox is open, not just protected from direct input.\n savedScrollX = window.scrollX;\n savedScrollY = window.scrollY;\n intentionalScrollOccurred = false;\n\n // A real bug: hiding overflow below reclaims the scrollbar's own\n // gutter, widening <html>'s content box by however many px the\n // scrollbar was — on a host page whose content spans the full viewport\n // width, that reflow is visible as a shift right when the lightbox\n // opens/closes (and reverses on close). Measured *before* overflow is\n // hidden (clientWidth only grows once the gutter is actually reclaimed,\n // so measuring after would always read 0) and only compensated for when\n // a real scrollbar was actually there — a page that never had one gets\n // no padding at all, nothing to compensate for.\n //\n // Two rejected approaches, both real bugs of their own: padding-right\n // on `document.body` compensates the wrong element — a page whose body\n // is narrower than the viewport (a centered, `max-width`-capped layout,\n // this docs site included) never touches the scrollbar's gutter in the\n // first place, so padding body just shrinks its own content box by an\n // *extra* scrollbar-width's worth, a new, self-inflicted reflow.\n // `scrollbar-gutter: stable` compensates the right element (`<html>`,\n // the same one the width is measured on) but paints its own visible,\n // if non-interactive, scrollbar-track styling for as long as the lock\n // is active — trading a brief shift for a permanent scrollbar-shaped\n // strip sitting over the page the whole time the lightbox is open,\n // which reads as more wrong, not less. Padding is genuinely invisible\n // — the same blank space a wider margin would be — and, applied to\n // `<html>` (not `body`), compensates the actual element the scrollbar's\n // gutter belongs to either way.\n const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n const rtl = isRtl();\n savedHtmlPaddingRight = document.documentElement.style.paddingRight;\n savedHtmlPaddingLeft = document.documentElement.style.paddingLeft;\n if (scrollbarWidth > 0) {\n // A real gap: a classic scrollbar renders on the *left* on a\n // `direction: rtl` page, not the right — compensating the wrong\n // side would reintroduce the exact reflow this exists to prevent,\n // just mirrored. Checked at lock time, not baked in as a fixed\n // assumption.\n if (rtl) {\n const currentPaddingLeft =\n parseFloat(getComputedStyle(document.documentElement).paddingLeft) || 0;\n document.documentElement.style.paddingLeft = `${currentPaddingLeft + scrollbarWidth}px`;\n } else {\n const currentPaddingRight =\n parseFloat(getComputedStyle(document.documentElement).paddingRight) || 0;\n document.documentElement.style.paddingRight = `${currentPaddingRight + scrollbarWidth}px`;\n }\n }\n\n // A real bug: `document.body.style.overflow = 'hidden'` (this function's\n // original, and until now only, scroll-blocking mechanism) was still\n // set here alongside <html>'s own below — redundant, and not harmless:\n // any value of `overflow` other than `visible` makes an element\n // establish a new block-formatting context, which blocks top-margin\n // collapsing between it and its first child. Confirmed directly via\n // real-browser instrumentation: with body's overflow locked, an h1\n // immediately inside it rendered `bodyMarginTop + h1's own default\n // margin-top` below the viewport top (its margin no longer collapsing\n // into body's own); the instant `unlockBodyScroll()` restored body's\n // overflow, collapsing resumed and the h1 snapped back up by its own\n // margin's worth — reading as the page shifting upward right as the\n // lightbox closes, on *any* page where the first child's margin would\n // otherwise collapse with body's (essentially any page without padding/\n // border on body itself — not a corner case). <html>'s own overflow:\n // hidden below is sufficient on its own to block user-driven scrolling\n // (wheel/touch/keyboard) — confirmed directly — since it's the real\n // scrolling element in standards mode; body's lock was never adding\n // independent protection, only this side effect.\n //\n // <html>'s own overflow, not just body's — mobile viewport-widening\n // bug, see DESIGN.md §2.6a. Both axes, not just overflow-x: setting\n // only one non-'visible' axis forces the browser to silently promote\n // the other from 'visible' to 'auto' (mixing hidden+visible isn't\n // allowed per spec), which revealed a real scrollbar that wasn't\n // there before.\n savedHtmlOverflow = document.documentElement.style.overflow;\n document.documentElement.style.overflow = 'hidden';\n\n // passive: true — onTouchStart only ever reads/caches, never calls\n // preventDefault(), unlike onTouchMove below.\n document.addEventListener('touchstart', onTouchStart, { passive: true });\n document.addEventListener('touchmove', onTouchMove, { passive: false });\n\n // Starts observing only after the writes above have already landed, so\n // it never reacts to its own initial setup — only to a later, external\n // change.\n styleObserver = new MutationObserver(onStyleMutation);\n styleObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['style'],\n });\n }\n lockCount++;\n}\n\nexport function unlockBodyScroll(): void {\n lockCount = Math.max(0, lockCount - 1);\n if (lockCount === 0) {\n styleObserver?.disconnect();\n styleObserver = null;\n document.removeEventListener('touchstart', onTouchStart);\n document.removeEventListener('touchmove', onTouchMove);\n\n document.documentElement.style.overflow = savedHtmlOverflow;\n document.documentElement.style.paddingRight = savedHtmlPaddingRight;\n document.documentElement.style.paddingLeft = savedHtmlPaddingLeft;\n\n if (!intentionalScrollOccurred) {\n window.scrollTo({ left: savedScrollX, top: savedScrollY, behavior: 'instant' });\n }\n }\n}\n","export type EventMap = Record<string, unknown>;\n\nexport type Unsubscribe = () => void;\n\ntype Listener<T> = (detail: T) => void;\n\n/**\n * Typed pub/sub used by Gallery and every plugin (`ctx.on`). Plugin\n * subscriptions are unsubscribed automatically on destroy by the caller\n * that owns the PluginContext, not by this class.\n */\nexport class EventBus<Events extends EventMap> {\n private listeners = new Map<keyof Events, Set<Listener<unknown>>>();\n\n on<K extends keyof Events>(event: K, fn: Listener<Events[K]>): Unsubscribe {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(fn as Listener<unknown>);\n return () => this.off(event, fn);\n }\n\n off<K extends keyof Events>(event: K, fn: Listener<Events[K]>): void {\n this.listeners.get(event)?.delete(fn as Listener<unknown>);\n }\n\n emit<K extends keyof Events>(event: K, detail: Events[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const fn of set) (fn as Listener<Events[K]>)(detail);\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, overridable per-button. */\n\nexport const CLOSE_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg>';\n\nexport const PREV_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 6l-6 6 6 6\"/></svg>';\n\nexport const NEXT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 6l6 6-6 6\"/></svg>';\n\nexport const CAPTION_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><path d=\"M7 10h10M7 14h6\"/></svg>';\n\nexport const CARET_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"20\" height=\"20\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M6 9l6 6 6-6\"/></svg>';\n","import { CAPTION_ICON, CARET_ICON, CLOSE_ICON, NEXT_ICON, PREV_ICON } from './icons';\n\nlet idCounter = 0;\n\nexport interface LightboxLabels {\n close: string;\n previous: string;\n next: string;\n showCaption: string;\n hideCaption: string;\n fullCaption: string; // DESIGN.md §2.3a — aria-label for the caption modal's own dialog role\n moreControls: string; // DESIGN.md §3.1a — the toolbar overflow popover's own toggle/dialog label\n}\n\nexport interface LightboxDom {\n outer: HTMLElement;\n backdrop: HTMLElement;\n dialog: HTMLElement;\n counter: HTMLElement;\n caption: HTMLElement;\n closeButton: HTMLButtonElement;\n prevButton: HTMLButtonElement;\n nextButton: HTMLButtonElement;\n captionToggleButton: HTMLButtonElement; // DESIGN.md §2.3a\n /** DESIGN.md §2.3a — a truncated caption's click/Enter/Space target opens this, showing the full text scrollable, so a long caption never has to cover the nav arrows to be readable. Hidden (`[hidden]`) whenever not open. */\n captionModal: HTMLElement;\n captionModalPanel: HTMLElement;\n captionModalContent: HTMLElement;\n captionModalCloseButton: HTMLButtonElement;\n /** The whole toolbar bar — DESIGN.md §2.3a's toolbar-height measurement observes this, not any one slot, since it's what actually wraps to multiple rows. */\n toolbar: HTMLElement;\n /** DESIGN.md §3 — `ctx.ui.toolbar(slot, ...)` inserts into these; close lives in `right`. */\n toolbarLeft: HTMLElement;\n toolbarCenter: HTMLElement;\n toolbarRight: HTMLElement;\n /** DESIGN.md §3.1a — hidden unless the toolbar actually overflows; toggles `toolbarOverflowPanel`. Lives in `toolbarRight`, just before `closeButton`. */\n toolbarOverflowButton: HTMLButtonElement;\n /** DESIGN.md §3.1a — the floating popover collapsed plugin buttons relocate into once they don't fit. */\n toolbarOverflowPanel: HTMLElement;\n}\n\nfunction iconButton(className: string, icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = className;\n button.ariaLabel = button.title = label;\n button.innerHTML = icon;\n return button;\n}\n\n/**\n * DESIGN.md §2.6 — `.shoji-outer` is the exact element `ctx.ui.outer()` (§3)\n * will return to plugins once the real plugin loader exists. Close/prev/next\n * are core-owned baseline controls, not routed through any plugin API.\n */\nexport function buildLightboxDom(slides: HTMLElement, labels: LightboxLabels): LightboxDom {\n const labelId = `shoji-counter-${++idCounter}`;\n\n const outer = document.createElement('div');\n outer.className = 'shoji-outer';\n\n const backdrop = document.createElement('div');\n backdrop.className = 'shoji-backdrop';\n outer.appendChild(backdrop);\n\n const dialog = document.createElement('div');\n dialog.className = 'shoji-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.setAttribute('aria-labelledby', labelId);\n dialog.tabIndex = -1;\n\n const toolbar = document.createElement('div');\n toolbar.className = 'shoji-toolbar';\n const toolbarLeft = document.createElement('div');\n toolbarLeft.className = 'shoji-toolbar-slot shoji-toolbar-left';\n const toolbarCenter = document.createElement('div');\n toolbarCenter.className = 'shoji-toolbar-slot shoji-toolbar-center';\n const toolbarRight = document.createElement('div');\n toolbarRight.className = 'shoji-toolbar-slot shoji-toolbar-right';\n const closeButton = iconButton('shoji-close', CLOSE_ICON, labels.close);\n // Ahead of close so plugin buttons (always inserted right before close) land between the two.\n const captionToggleButton = iconButton(\n 'shoji-toolbar-button shoji-caption-toggle',\n CAPTION_ICON,\n labels.showCaption,\n );\n captionToggleButton.setAttribute('aria-pressed', 'false');\n captionToggleButton.hidden = true;\n // DESIGN.md §3.1a — requested directly: close stays the absolute\n // rightmost control, with the (usually hidden) overflow caret just to its\n // left — `pluginToolbar()` inserts new buttons immediately before the\n // caret now, not before close, so they still land to the left of both\n // fixed controls.\n const toolbarOverflowButton = iconButton(\n 'shoji-toolbar-button shoji-toolbar-overflow',\n CARET_ICON,\n labels.moreControls,\n );\n toolbarOverflowButton.setAttribute('aria-haspopup', 'true');\n toolbarOverflowButton.setAttribute('aria-expanded', 'false');\n toolbarOverflowButton.hidden = true;\n toolbarRight.append(captionToggleButton, toolbarOverflowButton, closeButton);\n\n const toolbarOverflowPanel = document.createElement('div');\n toolbarOverflowPanel.className = 'shoji-toolbar-overflow-panel';\n toolbarOverflowPanel.setAttribute('role', 'dialog');\n toolbarOverflowPanel.setAttribute('aria-label', labels.moreControls);\n toolbarOverflowPanel.tabIndex = -1;\n toolbarOverflowPanel.hidden = true;\n\n // The counter lives in the toolbar's own left slot (flex flow, not\n // independent absolute positioning) specifically so a plugin button\n // sharing that slot (e.g. autoplay's play/pause, ctx.ui.toolbar('left', ...))\n // sits next to it instead of the two overlapping and fighting over clicks.\n const counter = document.createElement('div');\n counter.className = 'shoji-counter';\n counter.id = labelId;\n toolbarLeft.appendChild(counter);\n\n toolbar.append(toolbarLeft, toolbarCenter, toolbarRight);\n dialog.appendChild(toolbar);\n // Appended to `dialog` directly, not nested in `.shoji-toolbar` — the\n // toolbar's own `pointer-events: none` base rule (re-enabled per-slot,\n // not per-descendant) would otherwise need remembering to re-enable here\n // too; sidestepped entirely by living outside it, same placement pattern\n // `.shoji-caption-modal` already uses below.\n dialog.appendChild(toolbarOverflowPanel);\n\n const prevButton = iconButton('shoji-nav shoji-nav-prev', PREV_ICON, labels.previous);\n const nextButton = iconButton('shoji-nav shoji-nav-next', NEXT_ICON, labels.next);\n dialog.appendChild(prevButton);\n dialog.appendChild(nextButton);\n\n dialog.appendChild(slides);\n\n const caption = document.createElement('div');\n caption.className = 'shoji-caption';\n dialog.appendChild(caption);\n\n const captionModal = document.createElement('div');\n captionModal.className = 'shoji-caption-modal';\n captionModal.hidden = true;\n const captionModalPanel = document.createElement('div');\n captionModalPanel.className = 'shoji-caption-modal-panel';\n captionModalPanel.setAttribute('role', 'dialog');\n captionModalPanel.setAttribute('aria-modal', 'true');\n captionModalPanel.setAttribute('aria-label', labels.fullCaption);\n captionModalPanel.tabIndex = -1;\n const captionModalCloseButton = iconButton('shoji-caption-modal-close', CLOSE_ICON, labels.close);\n const captionModalContent = document.createElement('div');\n captionModalContent.className = 'shoji-caption-modal-content';\n captionModalPanel.append(captionModalCloseButton, captionModalContent);\n captionModal.appendChild(captionModalPanel);\n dialog.appendChild(captionModal);\n\n outer.appendChild(dialog);\n\n return {\n outer,\n backdrop,\n dialog,\n counter,\n caption,\n captionModal,\n captionModalPanel,\n captionModalContent,\n captionModalCloseButton,\n closeButton,\n prevButton,\n nextButton,\n captionToggleButton,\n toolbar,\n toolbarLeft,\n toolbarCenter,\n toolbarRight,\n toolbarOverflowButton,\n toolbarOverflowPanel,\n };\n}\n","const FOCUSABLE_SELECTOR =\n 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), video[controls], [tabindex]:not([tabindex=\"-1\"])';\n\n/** DESIGN.md §2.6 — focus trap on open, focus restore on close, Tab cycles within the dialog. */\nexport class FocusTrap {\n private container: HTMLElement | null = null;\n private previouslyFocused: HTMLElement | null = null;\n\n private readonly onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== 'Tab' || !this.container) return;\n\n const focusable = this.getFocusable();\n if (focusable.length === 0) {\n event.preventDefault();\n this.container.focus();\n return;\n }\n\n const first = focusable[0]!;\n const last = focusable[focusable.length - 1]!;\n const active = document.activeElement;\n const activeIsInside = active instanceof HTMLElement && focusable.includes(active);\n\n if (event.shiftKey) {\n if (!activeIsInside || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else if (!activeIsInside || active === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n private getFocusable(): HTMLElement[] {\n if (!this.container) return [];\n return Array.from(this.container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n }\n\n activate(container: HTMLElement): void {\n this.previouslyFocused = document.activeElement as HTMLElement | null;\n this.container = container;\n document.addEventListener('keydown', this.onKeydown, true);\n container.focus();\n }\n\n /**\n * DESIGN.md §2.3a — narrows (or widens back) which subtree Tab cycles\n * within, without touching `previouslyFocused`/the listener registration\n * — a caption modal nested inside the already-trapped dialog needs Tab\n * confined to just itself while open, then back to the whole dialog on\n * close, but must NOT trigger `activate()`'s own focus-capture (that's\n * reserved for the real open/close boundary; re-running it mid-session\n * would capture the wrong \"previously focused\" element and restore focus\n * to it too early). `getFocusable()` reads `this.container` fresh on\n * every keydown, so simply reassigning it is enough — no need for a\n * second, independent `FocusTrap` instance, which would double-handle\n * every Tab keypress (two capture-phase `document` listeners, each\n * computing its own overlapping focusable list).\n */\n retarget(container: HTMLElement): void {\n this.container = container;\n container.focus();\n }\n\n deactivate(): void {\n document.removeEventListener('keydown', this.onKeydown, true);\n this.container = null;\n // preventScroll: true — a bare focus() call auto-scrolls the target\n // into view within any scrollable ancestor by default. A real bug:\n // previouslyFocused is captured once at activate() time and never\n // updated afterward (nothing re-focuses the current thumbnail as the\n // viewer navigates), so restoring it on close can drag a host's own\n // scrollable thumbnail strip all the way back to wherever the gallery\n // was originally opened from, discarding whatever it had scrolled to\n // since — e.g. ActiveThumbnail's auto-scroll, entirely undone by a\n // focus restoration that has nothing to do with it.\n this.previouslyFocused?.focus({ preventScroll: true });\n this.previouslyFocused = null;\n }\n}\n","/**\n * DESIGN.md §2.4 — one Pointer-Events-based engine feeding all consumers:\n * core drag-to-navigate, core vertical-swipe-to-close, and (via `onPinch`/\n * `onDoubleTap`/`onWheelZoom`) a future zoom plugin that doesn't exist yet.\n * Pointer Events (not separate mouse/touch listeners) give mouse-drag and\n * touch-swipe parity for free — one code path, one set of thresholds.\n *\n * State machine: `idle → pending → dragging(h|v) → idle`. `pending` is the\n * window before `lockThreshold` is crossed, where it's still ambiguous\n * whether this is a tap, a horizontal drag, or a vertical drag; `dragging`\n * is entered once one axis's delta exceeds the threshold first, and the\n * *other* axis is ignored for the rest of that gesture (an axis lock, not\n * a snapped direction — diagonal drags don't fight the engine). There's no\n * literal blocking `settling` state after release: `onDragEnd` reports the\n * outcome synchronously and the caller owns however long its own\n * snap-back/completion animation takes; a new `pointerdown` before that\n * finishes is allowed to interrupt it (matches real touch-carousel UX —\n * grabbing a still-settling slide feels responsive, not broken).\n *\n * Pinch tracking is a separate concern layered on top of the same pointer\n * map: a second simultaneous pointer suspends whatever single-pointer drag\n * state was in progress (real pinches start from a single touch already\n * down) and switches to distance-ratio tracking until back down to one\n * pointer or zero.\n */\n\nexport type GestureDirection = 'horizontal' | 'vertical';\n\nexport interface GestureEngineOptions {\n /** px of movement before a direction locks in. DESIGN.md §2.4 default: 10. */\n lockThreshold: number;\n /** px of movement past which a released drag counts as \"swiped\" (completes), independent of velocity. DESIGN.md §2.4 default: 50. */\n swipeThreshold: number;\n /** px/ms release velocity past which a drag completes even under swipeThreshold — a fast flick counts. DESIGN.md §2.4 default: 0.3. */\n swipeVelocity: number;\n}\n\nexport interface GestureEngineCallbacks {\n /** Direction has just locked in for this gesture — the first move past lockThreshold. */\n onDragStart?(direction: GestureDirection, event: PointerEvent): void;\n /** delta: signed px moved along the locked axis so far (this move's cumulative total, not a per-frame diff). */\n onDragMove?(direction: GestureDirection, delta: number, event: PointerEvent): void;\n /** Pointer released (or cancelled) after a drag was in progress. velocity is signed px/ms over the whole gesture; completed reflects swipeThreshold/swipeVelocity. cancelled is true for pointercancel (e.g. an OS gesture took over) — always treated as not-completed regardless of delta/velocity. */\n onDragEnd?(\n direction: GestureDirection,\n delta: number,\n velocity: number,\n completed: boolean,\n cancelled: boolean,\n ): void;\n /** A pointerdown that never crossed lockThreshold before release — not a drag. Used to detect double-tap (the engine tracks tap timing/position itself and calls onDoubleTap instead when two land close enough together) as well as being a simple tap signal on its own. */\n onTap?(x: number, y: number, event: PointerEvent): void;\n onDoubleTap?(x: number, y: number, event: PointerEvent): void;\n /** scale is relative to the pinch's own start distance (1 = unchanged), not a cumulative multiplier across multiple pinch gestures. */\n onPinchStart?(centerX: number, centerY: number): void;\n onPinchMove?(scale: number, centerX: number, centerY: number): void;\n onPinchEnd?(): void;\n /** Ctrl+wheel (trackpad pinch reports this way in every major browser) or a genuine ctrl+scroll-wheel. deltaScale is a small increment (positive = zoom in), not an absolute scale — the caller accumulates it. */\n onWheelZoom?(deltaScale: number, x: number, y: number, event: WheelEvent): void;\n /** Only consulted on pointerdown — returning true means this pointer is ignored for the rest of its lifetime (a click on a real button/control shouldn't also start a drag). */\n ignore?(event: PointerEvent): boolean;\n /** Consulted right before capturing a locked drag's pointer — `false` skips capture for this gesture entirely (not just its drag effect). Default `true` if omitted. See onPointerMove's capture branch for why this needs to be a real skip, not just a suppressed effect. */\n shouldCapture?(): boolean;\n}\n\nconst DOUBLE_TAP_MAX_DELAY_MS = 300;\nconst DOUBLE_TAP_MAX_DISTANCE = 30;\nconst TAP_MAX_DELAY_MS = 500; // a pointerdown→up this slow isn't a \"tap\" even if it never crossed lockThreshold\n\ninterface PointerState {\n startX: number;\n startY: number;\n startTime: number;\n lastX: number;\n lastY: number;\n lastTime: number;\n}\n\nexport class GestureEngine {\n private readonly target: HTMLElement;\n private readonly options: GestureEngineOptions;\n private readonly callbacks: GestureEngineCallbacks;\n\n private readonly pointers = new Map<number, PointerState>();\n private primaryPointerId: number | null = null;\n private direction: GestureDirection | null = null;\n private dragStartDistance = 0; // along the locked axis, at the moment direction locked — subtracted so onDragStart's delta is 0\n\n private pinching = false;\n private pinchStartDistance = 0;\n\n /** True once `setPointerCapture` has actually been called for the gesture currently in progress — see `suppressRetargetedClick`'s own doc comment for why this needs tracking separately from `direction`. */\n private capturedThisGesture = false;\n\n // -Infinity, not 0: `event.timeStamp` is time-since-navigation-start, so a\n // real first tap is always some large positive number and 0 would seem\n // like a safe \"no previous tap\" sentinel in practice — but not always: a\n // tap in the first 300ms of the page's life, near the viewport's top-left\n // corner, would satisfy registerTap's isDouble check against this\n // sentinel and get wrongly reported as a double-tap on nothing. -Infinity\n // can never be within DOUBLE_TAP_MAX_DELAY_MS of any real timestamp.\n private lastTapTime = -Infinity;\n private lastTapX = 0;\n private lastTapY = 0;\n\n constructor(\n target: HTMLElement,\n callbacks: GestureEngineCallbacks,\n options?: Partial<GestureEngineOptions>,\n ) {\n this.target = target;\n this.callbacks = callbacks;\n this.options = {\n lockThreshold: options?.lockThreshold ?? 10,\n swipeThreshold: options?.swipeThreshold ?? 50,\n swipeVelocity: options?.swipeVelocity ?? 0.3,\n };\n\n this.target.addEventListener('pointerdown', this.onPointerDown);\n // Not passive: once a horizontal/vertical drag direction has locked in,\n // preventDefault() on move is required so the browser's own\n // scroll/back-navigation gesture doesn't fight the drag — see\n // onPointerMove. Before that lock, moves don't preventDefault, so\n // ordinary page scroll/tap behavior is unaffected until a real drag is\n // actually recognized.\n this.target.addEventListener('pointermove', this.onPointerMove);\n this.target.addEventListener('pointerup', this.onPointerUp);\n this.target.addEventListener('pointercancel', this.onPointerCancel);\n // ctrl+wheel must preventDefault (documented, not passive) — otherwise\n // the browser zooms the whole page instead of this becoming a gesture\n // the caller can hand to a zoom plugin.\n this.target.addEventListener('wheel', this.onWheel, { passive: false });\n }\n\n destroy(): void {\n this.target.removeEventListener('pointerdown', this.onPointerDown);\n this.target.removeEventListener('pointermove', this.onPointerMove);\n this.target.removeEventListener('pointerup', this.onPointerUp);\n this.target.removeEventListener('pointercancel', this.onPointerCancel);\n this.target.removeEventListener('wheel', this.onWheel);\n this.pointers.clear();\n }\n\n private readonly onPointerDown = (event: PointerEvent): void => {\n if (event.isPrimary === false && this.pointers.size === 0) return; // stray non-primary with no primary tracked yet — ignore\n if (this.pointers.size === 0 && this.callbacks.ignore?.(event)) return;\n\n this.pointers.set(event.pointerId, {\n startX: event.clientX,\n startY: event.clientY,\n startTime: event.timeStamp,\n lastX: event.clientX,\n lastY: event.clientY,\n lastTime: event.timeStamp,\n });\n\n if (this.pointers.size === 1) {\n this.primaryPointerId = event.pointerId;\n this.direction = null;\n this.capturedThisGesture = false;\n // Deliberately NOT captured here — see onPointerMove's direction-lock\n // branch for why.\n } else if (this.pointers.size === 2) {\n // A second pointer arriving mid-drag suspends the single-pointer\n // gesture (real pinches start from an already-down single touch) and\n // starts pinch tracking instead.\n this.direction = null;\n this.pinching = true;\n const [a, b] = [...this.pointers.values()];\n this.pinchStartDistance = distanceBetween(a!, b!);\n const center = centerOf(a!, b!);\n this.callbacks.onPinchStart?.(center.x, center.y);\n }\n };\n\n private readonly onPointerMove = (event: PointerEvent): void => {\n const state = this.pointers.get(event.pointerId);\n if (!state) return;\n state.lastX = event.clientX;\n state.lastY = event.clientY;\n state.lastTime = event.timeStamp;\n\n if (this.pinching) {\n if (this.pointers.size < 2) return;\n const [a, b] = [...this.pointers.values()];\n const distance = distanceBetween(a!, b!);\n const scale = this.pinchStartDistance > 0 ? distance / this.pinchStartDistance : 1;\n const center = centerOf(a!, b!);\n this.callbacks.onPinchMove?.(scale, center.x, center.y);\n return;\n }\n\n if (event.pointerId !== this.primaryPointerId) return;\n\n const dx = event.clientX - state.startX;\n const dy = event.clientY - state.startY;\n\n if (this.direction === null) {\n const absX = Math.abs(dx);\n const absY = Math.abs(dy);\n if (Math.max(absX, absY) < this.options.lockThreshold) return; // still pending — too small to call yet\n this.direction = absX > absY ? 'horizontal' : 'vertical';\n this.dragStartDistance = this.direction === 'horizontal' ? dx : dy;\n // Captured only once a real drag is confirmed (direction locked), not\n // on every pointerdown — capturing eagerly retargets the browser's\n // synthesized mousedown/click to the capturing element, breaking any\n // click-target-based logic downstream on an ordinary tap. Deferring\n // capture to here fixes that — but a *confirmed* drag still captures,\n // and a captured pointer's release still fires a real click\n // afterward, still retargeted to `target`. See\n // `suppressRetargetedClick` below for that other half of the fix.\n if (this.callbacks.shouldCapture?.() ?? true) {\n this.target.setPointerCapture(event.pointerId);\n this.capturedThisGesture = true;\n }\n this.callbacks.onDragStart?.(this.direction, event);\n }\n\n if (this.direction === 'horizontal') event.preventDefault(); // stop page/back-gesture scroll from fighting the drag\n\n const delta = (this.direction === 'horizontal' ? dx : dy) - this.dragStartDistance;\n this.callbacks.onDragMove?.(this.direction, delta, event);\n };\n\n private readonly onPointerUp = (event: PointerEvent): void => {\n this.finishPointer(event, false);\n };\n\n private readonly onPointerCancel = (event: PointerEvent): void => {\n this.finishPointer(event, true);\n };\n\n private finishPointer(event: PointerEvent, cancelled: boolean): void {\n const state = this.pointers.get(event.pointerId);\n if (!state) return;\n // pointerup/pointercancel carry their own release coordinates — these\n // don't necessarily match the last pointermove (coalesced/throttled\n // move events, or a release with no intervening move at all), so total\n // delta/velocity/tap-position must be computed from *this* event's\n // position, not whatever onPointerMove last recorded.\n state.lastX = event.clientX;\n state.lastY = event.clientY;\n state.lastTime = event.timeStamp;\n this.pointers.delete(event.pointerId);\n\n if (this.pinching) {\n if (this.pointers.size < 2) {\n this.pinching = false;\n this.callbacks.onPinchEnd?.();\n }\n // Still >= 2 pointers (a third was down) — stay in pinch mode; not\n // handled further here, an unusual case not worth extra state for.\n return;\n }\n\n if (event.pointerId !== this.primaryPointerId) return;\n\n if (this.direction === null) {\n // Never crossed lockThreshold — a tap, not a drag (unless it was\n // cancelled, or took too long to plausibly be an intentional tap).\n if (!cancelled && event.timeStamp - state.startTime <= TAP_MAX_DELAY_MS) {\n this.registerTap(state.lastX, state.lastY, event);\n }\n } else {\n const elapsed = Math.max(1, state.lastTime - state.startTime); // avoid divide-by-zero on a same-tick move\n const totalDelta =\n (this.direction === 'horizontal'\n ? state.lastX - state.startX\n : state.lastY - state.startY) - this.dragStartDistance;\n const velocity = totalDelta / elapsed;\n const completed =\n !cancelled &&\n (Math.abs(totalDelta) >= this.options.swipeThreshold ||\n Math.abs(velocity) >= this.options.swipeVelocity);\n this.callbacks.onDragEnd?.(this.direction, totalDelta, velocity, completed, cancelled);\n if (this.capturedThisGesture) this.suppressRetargetedClick();\n }\n\n this.primaryPointerId = null;\n this.direction = null;\n this.capturedThisGesture = false;\n }\n\n /**\n * A captured pointer's release still fires a real `click`, retargeted to\n * `target` regardless of where the pointer visually ends up — misread by\n * Gallery's click-outside-to-close as landing nowhere recognizable.\n * Consumes exactly one `click` on `target` in the capture phase, then\n * removes itself; a fallback timeout also removes it in case no `click`\n * ever comes, so it can't swallow a later, unrelated one.\n */\n private suppressRetargetedClick(): void {\n let done = false;\n const cleanup = (event?: MouseEvent): void => {\n if (done) return;\n done = true;\n event?.stopPropagation();\n this.target.removeEventListener('click', cleanup, { capture: true });\n };\n this.target.addEventListener('click', cleanup, { capture: true });\n setTimeout(cleanup, 500);\n }\n\n private registerTap(x: number, y: number, event: PointerEvent): void {\n const now = event.timeStamp;\n const isDouble =\n now - this.lastTapTime <= DOUBLE_TAP_MAX_DELAY_MS &&\n Math.hypot(x - this.lastTapX, y - this.lastTapY) <= DOUBLE_TAP_MAX_DISTANCE;\n if (isDouble) {\n this.callbacks.onDoubleTap?.(x, y, event);\n this.lastTapTime = 0; // consumed — a third tap starts fresh, isn't a triple-double\n } else {\n this.callbacks.onTap?.(x, y, event);\n this.lastTapTime = now;\n this.lastTapX = x;\n this.lastTapY = y;\n }\n }\n\n private readonly onWheel = (event: WheelEvent): void => {\n if (!event.ctrlKey) return;\n event.preventDefault();\n // Browsers report trackpad pinch as ctrl+wheel with deltaY roughly\n // proportional to pinch speed; negate so pinching out (deltaY < 0,\n // conventionally) reads as zooming in (positive deltaScale).\n const deltaScale = -event.deltaY * 0.01;\n this.callbacks.onWheelZoom?.(deltaScale, event.clientX, event.clientY, event);\n };\n}\n\nfunction distanceBetween(\n a: { lastX: number; lastY: number },\n b: { lastX: number; lastY: number },\n): number {\n return Math.hypot(a.lastX - b.lastX, a.lastY - b.lastY);\n}\n\nfunction centerOf(\n a: { lastX: number; lastY: number },\n b: { lastX: number; lastY: number },\n): { x: number; y: number } {\n return { x: (a.lastX + b.lastX) / 2, y: (a.lastY + b.lastY) / 2 };\n}\n","/** The drag's exact on-screen appearance at the moment it completed a close — `translateY(px)`/`scale`/`opacity`, all as last shown live (translateY clamped, see `GestureController.takeFrozenDragTransform`). `zoomOut()` jumps `target` here instantly (after measuring its natural box — see `ZoomTransitionTarget.dragStart`) before transitioning away from it, so the close continues in one motion from exactly where the drag left off. */\nexport interface FrozenDragTransform {\n translateY: number;\n scale: number;\n opacity: number;\n}\n\nexport interface ZoomTransitionTarget {\n /** The thumbnail element to animate to/from. */\n origin: HTMLElement;\n /** The `.shoji-slide-media` element being animated — not `.shoji-slide` itself, whose transform is already owned by pool-offset positioning. */\n target: HTMLElement;\n /** `item.width / item.height`, when known, else the origin thumbnail's own `naturalWidth`/`naturalHeight` ratio — just a *shape* guess; see `effectiveTargetBox`. */\n aspectRatio?: number;\n /** The real photo's true pixel size — `item.width`/`item.height` only, never the thumbnail's own natural size (would under-cap a large photo). Caps `containedBox` below at native resolution, mirroring `.shoji-slide-img`'s own `max-width/max-height: 100%`, instead of always growing toward filling the dialog. */\n naturalSize?: { width: number; height: number };\n /**\n * A completed drag-close's own last appearance (`GestureController.\n * takeFrozenDragTransform`) — `zoomOut()` (the only consumer) jumps\n * `target` here instantly, *after* measuring its natural box for the\n * landing math, then transitions away from it. Order matters: applying\n * this before measuring would make `effectiveTargetBox()` read the\n * child `<img>`'s rect *already* shrunk by this scale, double-counting\n * it once `zoomOut()`'s own transform (computed from that shrunk\n * measurement) then wholesale replaces — not composes with — it.\n */\n dragStart?: FrozenDragTransform;\n /**\n * The zoomed `<img>`'s own real on-screen rect (`getBoundingClientRect()`)\n * at the moment a button-close (or any non-drag close) starts, if it's\n * currently zoomed in — captured by `Gallery.beginClose()` from\n * `registerZoomStartProvider()` *before* the Zoom plugin's own\n * `beforeClose` handler resets it back to neutral (so `zoomOut()`'s own\n * measurement below stays correct — same ordering requirement `dragStart`\n * has, and the same reason).\n *\n * A rect, not the Zoom plugin's raw scale/pan numbers — an earlier version\n * passed those through directly and re-applied them to `target`\n * (`.shoji-slide-media`) the same way `dragStart` reapplies its own\n * translateY/scale. That doesn't work here: Zoom's own pan math is\n * relative to the `<img>` itself with `transform-origin: 0 0`\n * (`zoom/index.ts`), a *different* element with a *different* origin than\n * `target`'s `transform-origin: center` below — reapplying the same\n * numbers onto the wrong element/origin pair visibly shifted the image\n * toward its top-left corner the instant close started, worse the more\n * zoomed in it was. A rect sidesteps this entirely: `zoomOut()` computes\n * the jump the same center-to-center way it computes everything else\n * (`transformBetween`), from `target`'s own freshly-measured natural box\n * to this rect — origin-and-coordinate-system-agnostic, so it doesn't\n * matter what internal convention produced the rect.\n *\n * `zoomOut()` jumps `target` here instantly, then transitions away from\n * it, so closing while zoomed continues in one motion from the zoomed-in\n * view instead of snapping back to neutral first and only then shrinking\n * to the thumbnail. Mutually exclusive with `dragStart` in practice — you\n * can't complete a vertical drag-close while the zoom plugin is also\n * mid-pan, since `GestureController` suspends its own drag handling\n * entirely while zoomed (`isZoomed()`, DESIGN.md §4.6).\n */\n zoomStart?: Box;\n}\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/** `\"300ms\"` / `\"0.3s\"` → milliseconds. Reads the *actual* computed value, not an assumed default, so a host overriding `--shoji-duration` still gets a correct fallback timeout below. */\nfunction parseCssTime(value: string): number {\n const first = value.split(',')[0]?.trim() ?? '';\n if (first.endsWith('ms')) return parseFloat(first);\n if (first.endsWith('s')) return parseFloat(first) * 1000;\n return 0;\n}\n\nexport interface Box {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\n/** The `object-fit: contain` box for `aspectRatio` within `container`, computed analytically since the real image may not be loaded yet. `naturalSize` caps the result at the photo's own true pixel size, never stretching past native resolution. Exported — `SlideManager.ts`'s open-transition placeholder (§2.3) reuses this same math. */\nexport function containedBox(\n container: Box,\n aspectRatio: number,\n naturalSize?: { width: number; height: number },\n): Box {\n const containerRatio = container.width / container.height;\n let width = aspectRatio > containerRatio ? container.width : container.height * aspectRatio;\n let height = aspectRatio > containerRatio ? container.width / aspectRatio : container.height;\n if (naturalSize && naturalSize.width > 0 && naturalSize.height > 0) {\n const cap = Math.min(1, naturalSize.width / width, naturalSize.height / height);\n width *= cap;\n height *= cap;\n }\n return {\n left: container.left + (container.width - width) / 2,\n top: container.top + (container.height - height) / 2,\n width,\n height,\n };\n}\n\n/**\n * `target`'s effective visual box, not necessarily its own\n * `getBoundingClientRect()`. `target` is always its full flex-box size; the\n * photo inside is usually *smaller*, letterboxed to its own aspect ratio —\n * a real bug used the container's full rect, making the animation scale\n * from/to a box far bigger than the photo ever renders at, visibly\n * shrinking it to something much smaller than the thumbnail whenever the\n * aspect ratios didn't match (the common case). Preferred sources: the real\n * rendered media child, if attached; else an analytical contain-box from\n * `aspectRatio`; else the container's own rect as a last resort.\n *\n * A real bug this guards against: on a fresh open with nothing decoded yet,\n * `target`'s only child at this point is the loading spinner (§2.3) — a\n * fixed ~40px circle, not the photo. Trusting its rect as \"the real\n * rendered media child\" made the FLIP transition scale toward/from a box\n * far smaller than the actual photo, so the scale factor came out inverted\n * (>1 instead of <1) and the spinner rendered wildly oversized for the\n * transition's first frames before shrinking back down — never the actual\n * photo, which hadn't swapped in yet either way.\n *\n * Same reasoning excludes `.shoji-slide-open-placeholder` (§2.3's low-res\n * open() stand-in): it's a real, non-spinner `<img>`, but its own rendered\n * rect reflects *its* crop/aspect ratio, not the real photo's — trusting it\n * would scale toward the placeholder's shape instead of the real photo's,\n * only to visibly jump again once the real photo swaps in and this\n * transition (already run) no longer applies. Excluding it falls through to\n * the analytical `aspectRatio`-based box below, sized for the real photo\n * regardless of what shape the placeholder happens to be.\n */\nfunction effectiveTargetBox(\n target: HTMLElement,\n aspectRatio?: number,\n naturalSize?: { width: number; height: number },\n): Box {\n const child = target.firstElementChild;\n const isPlaceholder =\n child instanceof HTMLElement &&\n (child.classList.contains('shoji-slide-spinner') ||\n child.classList.contains('shoji-slide-open-placeholder'));\n if (child instanceof HTMLElement && !isPlaceholder) {\n const rect = child.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return rect;\n }\n const containerRect = target.getBoundingClientRect();\n if (aspectRatio && containerRect.width > 0 && containerRect.height > 0) {\n return containedBox(containerRect, aspectRatio, naturalSize);\n }\n return containerRect;\n}\n\n/**\n * Center-to-center translate + a single uniform scale that lands `target`'s\n * effective box (`effectiveTargetBox` above) *within* `origin`'s box,\n * without distorting it. `null` if either has no real size — nothing sane\n * to animate. One scale factor, not independent scaleX/scaleY: origin and\n * the photo essentially never share an exact aspect ratio, and scaling each\n * axis independently to force a rect match visibly squeezes/stretches the\n * image. `Math.min` keeps the box fully contained within origin's rect\n * (same tradeoff `object-fit: contain` makes); center always lands exactly\n * on origin's center, only the unconstrained axis's edges fall short.\n */\n/**\n * The actual translate3d/scale3d math `computeTransform` below needs —\n * pulled out on its own so `zoomOut`'s `zoomStart` jump (a *second* use of\n * the exact same center-to-center box-fitting math, landing on a captured\n * live rect instead of `origin`'s) can reuse it directly, rather than\n * re-deriving Zoom's own transform-origin/coordinate conventions on a\n * different element — see `ZoomTransitionTarget.zoomStart`'s own doc\n * comment for why that direct-replication approach doesn't work.\n */\nfunction transformBetween(from: Box, to: Box): string {\n const scale = Math.min(to.width / from.width, to.height / from.height);\n const translateX = to.left + to.width / 2 - (from.left + from.width / 2);\n const translateY = to.top + to.height / 2 - (from.top + from.height / 2);\n // translate3d/scale3d, not translate()/scale() — forces the GPU\n // compositing path instead of a main-thread-painted 2D transform, the\n // same fix already validated for the Zoom plugin's own scale animation\n // (DESIGN.md §4.6): this is the identical technique (a large photo\n // scaled via `transform`) on the same element, just driven by open/close\n // instead of pinch/toolbar zoom.\n return `translate3d(${translateX}px, ${translateY}px, 0) scale3d(${scale}, ${scale}, 1)`;\n}\n\n/**\n * `origin`'s effective visual box, not necessarily its own\n * `getBoundingClientRect()`. In selector/DOM-markup mode without Layout,\n * `origin` is typically a plain `<a>` wrapping a `<img>` — an inline element\n * by default, whose own box is sized to a text-line-height sliver (its\n * `font-size`/`line-height`), not the image it visually contains, even\n * though the image itself paints at full size. A real bug: the zoom\n * open/close transform used that sliver directly as the FLIP target,\n * landing the animation at a tiny, essentially-random offset instead of the\n * real thumbnail's visible position and size. Layout tiles aren't affected\n * (`display: block`, sized to match their child image exactly) — preferring\n * the child's rect there returns the same box either way.\n *\n * `querySelector('img')`, not `firstElementChild` — matches `scan.ts`'s own\n * `scanImage()` convention for locating a thumbnail inside arbitrary host\n * markup, where the `<img>` isn't necessarily the first child (a badge or\n * caption element placed before it in the DOM would otherwise get measured\n * instead, no more correct than the wrapper's own sliver).\n */\nfunction effectiveOriginBox(origin: HTMLElement): Box {\n const img = origin.querySelector('img');\n if (img) {\n const rect = img.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return rect;\n }\n return origin.getBoundingClientRect();\n}\n\nfunction computeTransform(\n origin: HTMLElement,\n target: HTMLElement,\n aspectRatio?: number,\n naturalSize?: { width: number; height: number },\n): string | null {\n const originRect = effectiveOriginBox(origin);\n const targetRect = effectiveTargetBox(target, aspectRatio, naturalSize);\n if (\n targetRect.width === 0 ||\n targetRect.height === 0 ||\n originRect.width === 0 ||\n originRect.height === 0\n ) {\n return null;\n }\n return transformBetween(targetRect, originRect);\n}\n\n/**\n * Waits for `target`'s own transition (on `property`, default `'transform'`)\n * to end (with a safety-net timeout in case transitionend never fires — an\n * interrupted/removed element, a browser quirk, or `--shoji-duration: 0ms`\n * under `prefers-reduced-motion`, which some browsers never fire a real\n * transitionend for at all) then calls `cb` exactly once. Exported: the\n * gesture-driven drag-to-navigate/drag-to-close settle animations (§2.4,\n * `Gallery.ts`) reuse this same wait-with-fallback logic rather than\n * duplicating it — same instant-jump-then-transition FLIP family of moves\n * as the zoom transition, just on a different element/property pairing.\n * `close()`'s own controls-fade-before-zoom-out sequencing (§2.6a) reuses it\n * a second way, waiting on `opacity` instead.\n */\nexport function waitForTransitionEnd(\n target: HTMLElement,\n cb: () => void,\n property = 'transform',\n): void {\n const durationMs = parseCssTime(getComputedStyle(target).transitionDuration);\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n target.removeEventListener('transitionend', onEnd);\n cb();\n };\n const onEnd = (event: Event): void => {\n if (event.target === target && (event as TransitionEvent).propertyName === property) finish();\n };\n target.addEventListener('transitionend', onEnd);\n setTimeout(finish, durationMs + 100);\n}\n\n/**\n * A real bug: unconditionally clearing `transform` here could wipe out a\n * value another plugin (rotateFlip) legitimately set on the *same* element\n * in the time between this animation starting and its cleanup callback\n * firing (transitionend, or the fallback timeout — either can land well\n * after a quick click elsewhere). Only clears `transform` if it still\n * matches what this animation itself last wrote — nothing else has touched\n * it since — otherwise leaves it alone. `transition`/`transformOrigin`\n * are always safe to clear; nothing else in this codebase sets them.\n *\n * A second real bug, found via reopening the lightbox: `expectedTransform`\n * must be the value *read back* from `target.style.transform` right after\n * assigning it, not the raw string `computeTransform()` produced. Setting\n * `element.style.transform` to a string containing an arbitrary JS float\n * (e.g. `scale(0.10416666666666667)`, `computeTransform`'s un-rounded\n * `Math.min(...)` result) and reading it back gives a *differently\n * formatted* string — the browser's CSSOM serializer rounds/reformats\n * numeric values on its own (observed in Chromium: `scale(0.104167)`).\n * Comparing the raw JS string against that reformatted one here always\n * failed for any scale factor without a short, clean decimal, silently\n * skipping the clear — permanently leaving `zoomOut`'s shrink transform\n * applied to `.shoji-slide-media` after the lightbox closed. The next\n * `open()`'s `computeTransform` then measured that *already-shrunk*\n * element's `getBoundingClientRect()` as if it were the natural size,\n * computing a near-1 (barely visible) scale instead of a real zoom-in —\n * reads as \"doesn't zoom, just appears,\" and compounds on every further\n * open/close cycle since the stuck transform is never cleared either way.\n * `zoomIn`'s own `'none'` literal never hit this — a fixed string round-trips\n * through the CSSOM unchanged, unlike an arbitrary computed float.\n *\n * `opacity` is cleared unconditionally, same as `transition`/\n * `transformOrigin` — a completed drag-close (`Gallery.beginClose`) bakes\n * the drag's own dim onto `target` before this animation starts; nothing\n * else in this codebase sets `.shoji-slide-media`'s opacity, so there's\n * nothing else's value this could ever clobber.\n */\nfunction clearInlineTransform(target: HTMLElement, expectedTransform: string): void {\n target.style.transition = '';\n target.style.transformOrigin = '';\n target.style.willChange = '';\n target.style.opacity = '';\n if (target.style.transform === expectedTransform) target.style.transform = '';\n}\n\n/**\n * FLIP-style open: `target` starts visually at `origin`'s position/size (an\n * instant, untransitioned jump), then transitions to its natural layout —\n * reads as \"growing out of the thumbnail.\" Fire-and-forget: cleans up its\n * own inline styles once the transition ends, nothing to await.\n */\nexport function zoomIn({ origin, target, aspectRatio, naturalSize }: ZoomTransitionTarget): void {\n if (prefersReducedMotion()) return;\n const transform = computeTransform(origin, target, aspectRatio, naturalSize);\n if (!transform) return;\n\n target.style.transition = 'none';\n // computeTransform's translateX/Y is center-to-center math — must pair with\n // a center transform-origin (the CSS default), not 'top left', or the\n // scaled box ends up offset from origin by however far origin's center\n // sits from its own top-left corner.\n target.style.transformOrigin = 'center';\n // Promotes target onto its own compositing layer before the animated\n // transform starts, not mid-animation — same GPU-seam mitigation as the\n // Zoom plugin (DESIGN.md §4.6). Cleared in clearInlineTransform once the\n // transition ends, not left on permanently: this is the offset-0 pool\n // slot, alive for the gallery's whole lifetime, not a class scoped to\n // only-while-zoomed.\n target.style.willChange = 'transform';\n target.style.transform = transform;\n void target.offsetHeight; // force the instant jump to commit before transitioning away from it\n target.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n target.style.transform = 'none';\n\n waitForTransitionEnd(target, () => clearInlineTransform(target, 'none'));\n}\n\n/**\n * Reverse of `zoomIn`: `target` transitions from its natural position down\n * to `origin`'s rect — \"shrinking back into the thumbnail.\" `onComplete`\n * always fires exactly once, synchronously if there's nothing to animate\n * (reduced motion, or no valid rect), otherwise once the transition ends —\n * callers use this to know when it's safe to actually hide/finalize.\n */\nexport function zoomOut(\n { origin, target, aspectRatio, naturalSize, dragStart, zoomStart }: ZoomTransitionTarget,\n onComplete: () => void,\n): void {\n if (prefersReducedMotion()) {\n onComplete();\n return;\n }\n // Measured before dragStart/zoomStart is ever applied to `target` — see\n // ZoomTransitionTarget.dragStart's doc comment for why the order matters.\n const transform = computeTransform(origin, target, aspectRatio, naturalSize);\n if (!transform) {\n onComplete();\n return;\n }\n\n // computeTransform's translateX/Y is center-to-center math — must pair with\n // a center transform-origin (the CSS default), not 'top left', or the\n // scaled box ends up offset from origin by however far origin's center\n // sits from its own top-left corner.\n target.style.transformOrigin = 'center';\n target.style.willChange = 'transform'; // see zoomIn's doc comment on this line\n if (dragStart) {\n // Instant jump to exactly where the drag left off — same FLIP\n // technique `zoomIn()` uses to jump onto origin's box before\n // transitioning away from it, just jumping to wherever the drag left\n // off instead of a fixed point. translate3d/scale3d (not the 2D forms),\n // matching the landing transform's own function list below — mismatched\n // function types between the transition's start/end values force the\n // browser into matrix-decomposition interpolation instead of simple\n // per-parameter interpolation, and lose the GPU-compositing path this\n // codebase otherwise always uses for this element (DESIGN.md §2.3b).\n target.style.transition = 'none';\n target.style.transform = `translate3d(0px, ${dragStart.translateY}px, 0px) scale3d(${dragStart.scale}, ${dragStart.scale}, 1)`;\n target.style.opacity = String(dragStart.opacity);\n void target.offsetHeight; // commit the jump before transitioning away from it\n } else if (zoomStart) {\n // Same FLIP jump as dragStart above, computed the same center-to-center\n // way as `transform` above (not dragStart's raw translate/scale reuse\n // — see ZoomTransitionTarget.zoomStart's doc comment for why that\n // doesn't work here). `target`'s own effective box, re-measured fresh:\n // cheap, and guaranteed unchanged since the read inside\n // computeTransform() above — nothing's touched `target` in between.\n // Still correct even if `target` is currently rotated/flipped (the\n // RotateFlip plugin, applied directly to this same element, unlike\n // Zoom's own scale/pan — see below): both this measurement and\n // `zoomStart` itself were captured at the same rotation, so the\n // scale/translate between their two (equally rotated) bounding boxes\n // still isolates the zoom-only delta correctly.\n const targetRect = effectiveTargetBox(target, aspectRatio, naturalSize);\n if (targetRect.width > 0 && targetRect.height > 0) {\n // Composed onto whatever's already there, never replacing it outright\n // — a real bug, reported from real usage: closing while both rotated/\n // flipped *and* zoomed wholesale-overwrote RotateFlip's own\n // scaleX/scaleY/rotate() with this jump's plain translate/scale,\n // un-rotating *instantly* right here, before the real transition\n // below even starts — a snap to neutral rotation, then a separate\n // zoom-out, instead of the smooth combined un-rotate-while-shrinking\n // motion closing while rotated (without zoomStart at all) already\n // gets for free: transitioning target's transform from *whatever it\n // currently is* to the final plain shrink value is what makes that\n // work, and it needs target's rotation to still be sitting there\n // when the transition starts, not already erased by this jump.\n const existing = target.style.transform;\n const jump = transformBetween(targetRect, zoomStart);\n target.style.transition = 'none';\n target.style.transform = existing && existing !== 'none' ? `${existing} ${jump}` : jump;\n void target.offsetHeight;\n }\n }\n target.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n void target.offsetHeight;\n target.style.transform = transform;\n // Read back what the browser actually stored, not the raw string just\n // assigned — see clearInlineTransform's own doc comment for why the two\n // can differ (CSSOM float reformatting) and why that difference matters.\n const appliedTransform = target.style.transform;\n\n waitForTransitionEnd(target, () => {\n clearInlineTransform(target, appliedTransform);\n onComplete();\n });\n}\n","import {\n GestureEngine,\n type GestureDirection,\n type GestureEngineOptions,\n} from '../gestures/GestureEngine';\nimport type { SlideManager } from './SlideManager';\nimport { waitForTransitionEnd, type FrozenDragTransform } from './zoomTransition';\n\n/** DESIGN.md §2.4 — the drag-released settle easing, distinct from `--shoji-easing`'s open/close/zoom curve. */\nconst DRAG_SETTLE_TRANSITION = 'transform var(--shoji-duration) var(--shoji-momentum-easing)';\nconst DRAG_FEEDBACK_TRANSITION =\n 'transform var(--shoji-duration) var(--shoji-momentum-easing), opacity var(--shoji-duration) var(--shoji-momentum-easing)';\n/** px of vertical drag at which live close-feedback maxes out — independent of `swipeThreshold`, which decides actual completion. */\nconst VERTICAL_FEEDBACK_DISTANCE = 160;\n\n/**\n * A real interactive control, plus `.shoji-caption` — a click/drag starting\n * there should select/scroll its text natively, not get captured as a\n * gesture. Also used by `Gallery.ts`'s `isBackdropClick`, which used to have\n * its own narrower list (missing select/input/textarea/a[href]) — a\n * plugin-mounted non-button control got misread as a backdrop click and\n * closed the gallery. One shared selector so that can't recur.\n *\n * `.shoji-caption-modal` (DESIGN.md §2.3a) — a real bug, reported from real\n * usage: `GestureEngine`'s own tap recognition (`ignore` gates it before\n * any pointer tracking starts, `GestureEngine.ts`) runs entirely on\n * pointer events, independent of whatever a click listener's own\n * `stopPropagation()` does — a tap anywhere inside the caption modal\n * (its content area specifically; the close button was already covered as\n * a real `<button>`) still read as a legitimate tap on the dialog and fired\n * the `tap` bus event, which the Autoplay plugin listens to for its own\n * tap-to-toggle-play/pause. Excluding the whole modal here is what\n * actually stops that, not anything at the click-event layer.\n */\nexport const INTERACTIVE_CONTROL_SELECTOR =\n 'button, video, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption, .shoji-caption-modal, .shoji-toolbar-overflow-panel';\n\n/**\n * `INTERACTIVE_CONTROL_SELECTOR` minus `video` — everything else there still\n * needs a real click/drag to behave natively (select/scroll caption text,\n * a plugin's own control, etc.), same reasoning as that selector's own doc\n * comment. `video` is carved out separately, below: unlike those, a native\n * `<video controls>`'s own interactive surface (tap-to-toggle, the\n * scrub-bar drag) isn't the *whole* element — DESIGN.md §2.4/§4.3's\n * swipe-to-navigate-video-slides feature needs gestures to reach the rest\n * of it, not be blocked outright the way the shared selector above still\n * blocks it for backdrop-click/caption-selection purposes.\n */\nconst GESTURE_IGNORE_SELECTOR =\n 'button, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption, .shoji-caption-modal, .shoji-toolbar-overflow-panel';\n\n/**\n * A native `<video controls>`'s own scrub-bar/tap-to-toggle chrome is\n * browser-rendered, not real DOM Shoji can measure — there's no element to\n * exclude by selector the way `GESTURE_IGNORE_SELECTOR` excludes a real\n * `<button>`. Approximated instead as a fixed bottom margin\n * (`--shoji-video-gesture-margin`, shoji.css), reserved for the browser's\n * own touch handling; a touch starting above it is fair game for Shoji's\n * own gestures, same as anywhere on a photo slide.\n */\nfunction isInVideoControlsMargin(event: PointerEvent, video: HTMLVideoElement): boolean {\n const rect = video.getBoundingClientRect();\n const margin = parseFloat(\n getComputedStyle(video).getPropertyValue('--shoji-video-gesture-margin'),\n );\n return event.clientY >= rect.bottom - (Number.isFinite(margin) ? margin : 0);\n}\n\n/**\n * A real bug, found auditing this feature end to end with a real browser\n * (not caught by any jsdom unit test — real `click`-after-drag retargeting\n * only happens in a real browser, same gap `GestureEngine`'s own\n * `suppressRetargetedClick` doc comment describes): a drag starting inside\n * a video's reserved bottom margin is correctly never tracked as a Shoji\n * gesture (see `isInVideoControlsMargin` above) — left alone for the\n * browser's own scrub-bar handling. But the pointer is free to move\n * anywhere before release, the same way a real scrub-bar drag routinely\n * does, and an un-captured pointer's trailing `click` lands wherever it\n * actually ends up — often well past the video's own rendered bounds, in\n * `.shoji-slide-media`'s empty letterbox padding around it. That's not a\n * real interactive control (`INTERACTIVE_CONTROL_SELECTOR`), so `Gallery.ts`'s\n * `isBackdropClick` read it as a genuine backdrop click and closed the\n * gallery — defeating \"left alone for the browser's own controls\" the\n * moment a real scrub-bar interaction moved vertically at all. Confirmed\n * directly: a drag starting 5px above a video's bottom edge, moving 200px\n * down, closed the gallery even though `isInVideoControlsMargin` correctly\n * ignored the pointerdown. Same fix as a captured drag's own retargeted\n * click — swallow exactly one trailing click, capture phase, so it never\n * reaches `isBackdropClick` at all. A fallback timeout also removes the\n * listener in case no `click` ever comes, so it can't swallow a later,\n * unrelated one.\n */\nfunction suppressNextClick(dialog: HTMLElement): void {\n let done = false;\n const cleanup = (event?: MouseEvent): void => {\n if (done) return;\n done = true;\n event?.stopPropagation();\n dialog.removeEventListener('click', cleanup, { capture: true });\n };\n dialog.addEventListener('click', cleanup, { capture: true });\n setTimeout(cleanup, 500);\n}\n\n/**\n * `.shoji-caption--video` (shoji.css, DESIGN.md §2.3a/§4-video) sets\n * `pointer-events: none` on a video slide's caption, letting a click reach\n * the video/provider controls underneath it — which also means it never\n * appears in `event.composedPath()` there at all, so\n * `GESTURE_IGNORE_SELECTOR`'s selector-based check can't see it, the same\n * gap `Gallery.ts`'s `isBackdropClick()` already solves the same way:\n * checked by coordinates instead, the one place this function has to be.\n * A real bug this fixes: swipe-to-navigate/drag-to-close over a provider\n * video's own letterboxed margins (below) would otherwise engage right\n * through the caption sitting over them.\n */\nfunction isOverVideoCaption(event: PointerEvent, caption: HTMLElement): boolean {\n if (caption.hidden || !caption.classList.contains('shoji-caption--video')) return false;\n const rect = caption.getBoundingClientRect();\n return (\n event.clientX >= rect.left &&\n event.clientX <= rect.right &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom\n );\n}\n\n/** A click/drag starting on a real control (or, on a video slide, its click-through caption — see `isOverVideoCaption`) shouldn't also be captured as a gesture — see `GESTURE_IGNORE_SELECTOR`/`isInVideoControlsMargin`. Ignoring specifically for the video-margin reason also arms `suppressNextClick` — see its own doc comment. */\nfunction shouldIgnoreGesture(\n event: PointerEvent,\n caption: HTMLElement,\n dialog: HTMLElement,\n): boolean {\n if (isOverVideoCaption(event, caption)) return true;\n const path = event.composedPath();\n const video = path.find((node): node is HTMLVideoElement => node instanceof HTMLVideoElement);\n if (video) {\n if (!isInVideoControlsMargin(event, video)) return false;\n suppressNextClick(dialog);\n return true;\n }\n return path.some((node) => node instanceof Element && node.matches(GESTURE_IGNORE_SELECTOR));\n}\n\n/** What `GestureController` needs from `Gallery` — narrow on purpose, so this module never reaches into Gallery internals beyond this contract. */\nexport interface GestureControllerHost {\n dialog: HTMLElement;\n /** Read live, not snapshotted — `shouldIgnoreGesture()` needs its current bounding box/visibility on every gesture start, not whatever it was when `GestureController` was constructed. See `isOverVideoCaption`. */\n caption: HTMLElement;\n slides: SlideManager;\n canGoNext(): boolean;\n canGoPrev(): boolean;\n next(): void;\n prev(): void;\n close(): void;\n /** Same effect as `close()`, but for a completed vertical swipe — skips the separate controls-fade pause in front of the zoom-out (see `finishVerticalDrag`). */\n closeFromSwipe(frozenDrag: FrozenDragTransform): void;\n /** Live, reversible — crossing the close threshold mid-drag hides the toolbar/nav/counter/caption (a \"let go now and this closes\" cue); dragging back under it before release reveals them again. See `applyVerticalDragFeedback`. */\n setControlsHiddenForDrag(hidden: boolean): void;\n /** `closable: false` (GalleryOptions) — false suspends vertical drag-to-close entirely: no live feedback, release never calls `close()`. */\n canClose(): boolean;\n onActivity(): void;\n /** DESIGN.md §4-zoom — true while zoomed; suspends drag-to-navigate/close. */\n isZoomed(): boolean;\n}\n\n/** Relays for gestures core has no built-in behavior for — DESIGN.md §2.4; the zoom plugin (§4-zoom) consumes these via the gallery event bus. */\nexport interface GestureRelayCallbacks {\n onTap(x: number, y: number): void;\n onDoubleTap(x: number, y: number): void;\n onPinchStart(centerX: number, centerY: number): void;\n onPinchMove(scale: number, centerX: number, centerY: number): void;\n onPinchEnd(): void;\n onWheelZoom(deltaScale: number, x: number, y: number): void;\n}\n\n/**\n * DESIGN.md §2.4 — owns the gesture-driven side of the lightbox: horizontal\n * drag-to-navigate and vertical drag-to-close, built on `GestureEngine`\n * (`src/gestures/`) plus the live-feedback/settle-animation mechanics\n * specific to this lightbox's DOM. Split out of `Gallery.ts` (CLAUDE.md:\n * files ≤ ~400 lines) — `Gallery` only constructs this, forwards the host\n * callbacks it needs, and relays no-built-in-effect gestures onto its bus.\n */\nexport class GestureController {\n private readonly engine: GestureEngine;\n /** Same distance `GestureEngine` itself uses to decide a release would complete the close — reused here so the live controls-hide cue in `applyVerticalDragFeedback` actually means what it visually claims. */\n private readonly controlsHideThreshold: number;\n private controlsHiddenForDrag = false;\n private lastDragDelta = 0;\n\n constructor(\n private readonly host: GestureControllerHost,\n relay: GestureRelayCallbacks,\n options?: Partial<GestureEngineOptions>,\n ) {\n this.controlsHideThreshold = options?.swipeThreshold ?? 50;\n this.engine = new GestureEngine(\n host.dialog,\n {\n ignore: (event) => shouldIgnoreGesture(event, host.caption, host.dialog),\n shouldCapture: () => !host.isZoomed(),\n onDragStart: () => host.onActivity(),\n onDragMove: this.onDragMove,\n onDragEnd: this.onDragEnd,\n onTap: (x, y) => relay.onTap(x, y),\n onDoubleTap: (x, y) => relay.onDoubleTap(x, y),\n onPinchStart: (centerX, centerY) => relay.onPinchStart(centerX, centerY),\n onPinchMove: (scale, centerX, centerY) => relay.onPinchMove(scale, centerX, centerY),\n onPinchEnd: () => relay.onPinchEnd(),\n onWheelZoom: (deltaScale, x, y) => relay.onWheelZoom(deltaScale, x, y),\n },\n options,\n );\n }\n\n destroy(): void {\n this.engine.destroy();\n }\n\n /** Horizontal follows the finger 1:1; vertical drives close-feedback instead. Axis-locked, one branch per drag. */\n private readonly onDragMove = (direction: GestureDirection, delta: number): void => {\n if (this.host.isZoomed()) return; // the zoom plugin owns pan while zoomed\n if (direction === 'horizontal') {\n this.host.slides.setDragOffset(delta, null);\n } else if (this.host.canClose()) {\n this.applyVerticalDragFeedback(delta);\n }\n };\n\n private readonly onDragEnd = (\n direction: GestureDirection,\n delta: number,\n _velocity: number,\n completed: boolean,\n ): void => {\n if (this.host.isZoomed()) return;\n if (direction === 'horizontal') {\n this.finishHorizontalDrag(delta, completed);\n } else {\n this.finishVerticalDrag(completed);\n }\n };\n\n /** `completed` decides intent; `canGoNext`/`canGoPrev` guard whether that's actually possible (`loop: false` at an end item). */\n private finishHorizontalDrag(delta: number, completed: boolean): void {\n const goingNext = delta < 0;\n const canMove = goingNext ? this.host.canGoNext() : this.host.canGoPrev();\n\n if (!completed || delta === 0 || !canMove) {\n this.settleDragOffset(0, () => {});\n return;\n }\n\n const width = this.host.dialog.getBoundingClientRect().width || 1;\n const target = goingNext ? -width : width;\n this.settleDragOffset(target, () => {\n // Instant, untransitioned reset in the same synchronous tick as the\n // index change — same FLIP-family trick as zoomTransition.ts's\n // instant-jump: the slot that just animated into the center position\n // is about to receive that exact same \"new current\" item's content\n // (its structural offset already matches, since preload keeps it\n // rendered), so resetting to offset 0 while simultaneously swapping\n // content is visually seamless, not a jump.\n this.host.slides.setDragOffset(0, null);\n if (goingNext) this.host.next();\n else this.host.prev();\n });\n }\n\n private settleDragOffset(targetPx: number, onSettled: () => void): void {\n const settleEl = this.host.slides.getSlotRoot(0);\n this.host.slides.setDragOffset(targetPx, DRAG_SETTLE_TRANSITION);\n if (!settleEl) {\n onSettled();\n return;\n }\n waitForTransitionEnd(settleEl, onSettled);\n }\n\n /**\n * Purely presentational — scales/fades the *image* as it's dragged away,\n * without closing until release decides. Applied to `host.slides.element`,\n * not `host.dialog` — requested directly: toolbar/nav/counter/caption are\n * siblings, not descendants, so they stay anchored, not moving with it.\n */\n private applyVerticalDragFeedback(delta: number): void {\n const progress = Math.min(Math.abs(delta) / VERTICAL_FEEDBACK_DISTANCE, 1);\n const slides = this.host.slides.element;\n this.lastDragDelta = delta;\n slides.style.transition = '';\n slides.style.transform = `translateY(${delta}px) scale(${1 - progress * 0.15})`;\n slides.style.opacity = String(1 - progress * 0.6);\n\n // Requested directly: past the same distance a release would close,\n // controls disappear — a \"let go now\" cue, distinct from the image's own\n // dim above (capped at 0.4, never fully hides). Reversible: retreating\n // under it before release reveals them. Only on a crossing, not every move.\n const pastThreshold = Math.abs(delta) >= this.controlsHideThreshold;\n if (pastThreshold !== this.controlsHiddenForDrag) {\n this.controlsHiddenForDrag = pastThreshold;\n this.host.setControlsHiddenForDrag(pastThreshold);\n }\n }\n\n private clearVerticalDragFeedback(animate: boolean): void {\n const slides = this.host.slides.element;\n slides.style.transition = animate ? DRAG_FEEDBACK_TRANSITION : '';\n slides.style.transform = '';\n slides.style.opacity = '';\n }\n\n private finishVerticalDrag(completed: boolean): void {\n const wasHiddenForDrag = this.controlsHiddenForDrag;\n this.controlsHiddenForDrag = false;\n if (completed && this.host.canClose()) {\n this.host.closeFromSwipe(this.takeFrozenDragTransform());\n } else {\n // Not completed, or closable: false suspended the drag entirely (no\n // feedback was ever applied by onDragMove) — either way, a clean\n // reset (harmless no-op in the suspended case, nothing to clear).\n this.clearVerticalDragFeedback(true);\n // Not closing — controls must come back if the cue above left them\n // hidden, regardless of exactly where release landed (e.g.\n // swipeVelocity deciding \"not completed\" past this threshold).\n if (wasHiddenForDrag) this.host.setControlsHiddenForDrag(false);\n }\n }\n\n /**\n * Reads the drag's last live appearance, instantly resets `.shoji-slides`\n * back to neutral (nothing left on it to visibly snap — `Gallery` bakes\n * these same values onto the photo itself in the same synchronous tick,\n * so the rendered result is unchanged, just re-homed), and returns them\n * for that hand-off. Translate is the raw, unclamped drag distance —\n * requested directly: the close animation must continue from exactly\n * where the drag left off, full stop, not recenter first. (A previous\n * version clamped this to the same 160px the dim/scale feedback ramps\n * over, to bound how far away the close animation could start — but\n * clamping is itself an instant correction: for any drag past that\n * distance, release visibly snapped the photo from wherever it actually\n * was back to the clamped point, before the real shrink-to-thumbnail\n * motion continued from there. That snap — not the shrink itself — is\n * what reads as \"jumps to a small image in the middle of the screen.\"\n * Reported from real usage, confirmed on video: released past the clamp,\n * the photo visibly jumped from off-screen back to near-center in a\n * single frame.)\n */\n private takeFrozenDragTransform(): FrozenDragTransform {\n const progress = Math.min(Math.abs(this.lastDragDelta) / VERTICAL_FEEDBACK_DISTANCE, 1);\n const frozen: FrozenDragTransform = {\n translateY: this.lastDragDelta,\n scale: 1 - progress * 0.15,\n opacity: 1 - progress * 0.6,\n };\n this.clearVerticalDragFeedback(false);\n return frozen;\n }\n}\n","/** DESIGN.md §2.6 — visually-hidden `aria-live` region announcing slide changes. */\nexport class LiveRegion {\n readonly element: HTMLElement;\n\n constructor() {\n this.element = document.createElement('div');\n this.element.className = 'shoji-live-region';\n this.element.setAttribute('role', 'status');\n this.element.setAttribute('aria-live', 'polite');\n }\n\n announce(text: string): void {\n // Clear-then-set (with a forced reflow between) so repeated identical\n // announcements still fire in real assistive tech, which otherwise\n // ignores a text node set to the same value it already held.\n this.element.textContent = '';\n void this.element.offsetWidth;\n this.element.textContent = text;\n }\n}\n","import type { GalleryItem, GalleryItemInput, MediaSource, VideoDescriptor } from './types';\n\n/** DESIGN.md §2.1 zero-config quickstart. */\nexport const DEFAULT_SELECTOR =\n ':scope > a, :scope > [data-shoji-src], :scope > [data-shoji-video]';\n\nexport interface ScannedItem {\n element: HTMLElement;\n item: GalleryItem;\n}\n\nexport function scanContainer(\n container: HTMLElement,\n selector: string = DEFAULT_SELECTOR,\n): ScannedItem[] {\n const elements = Array.from(container.querySelectorAll<HTMLElement>(selector));\n const scanned: ScannedItem[] = [];\n for (const element of elements) {\n const item = scanVideo(element) ?? scanImage(element);\n if (item) scanned.push({ element, item });\n }\n return scanned;\n}\n\nfunction attr(el: Element, name: string): string | undefined {\n return el.getAttribute(name) ?? undefined;\n}\n\nfunction numAttr(el: Element, name: string): number | undefined {\n const raw = el.getAttribute(name);\n if (raw === null) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) ? n : undefined;\n}\n\n/**\n * `caption`/`id` first, then any other `data-shoji-*` attribute with no\n * matching `GalleryItem` field lands in `item.data`, keyed verbatim (not\n * camelCased) — DESIGN.md §2.1. By this point every named field above is\n * already set, so `key in item` alone tells known suffixes (src/thumb/\n * alt/.../poster) apart from custom ones — except attributes that fold into\n * a *nested* field (`video-id`/`video-provider` → `item.video.id`/\n * `.provider`, both already applied in `scanVideo` by the time this runs)\n * or have no field of their own at all (`no-drag`, GestureController's\n * drag-opt-out); `key in item` can't see either case, so both are excluded\n * by name instead.\n */\nconst NO_OWN_DATA_FIELD = new Set(['no-drag', 'video-id', 'video-provider']);\n\nfunction applyCommon(element: HTMLElement, item: GalleryItem, src: string): void {\n const caption = attr(element, 'data-shoji-caption');\n if (caption) item.caption = caption;\n item.id = attr(element, 'data-shoji-id') ?? src;\n\n let data: Record<string, string> | undefined;\n for (const a of element.attributes) {\n if (!a.name.startsWith('data-shoji-')) continue;\n const key = a.name.slice(11);\n if (!NO_OWN_DATA_FIELD.has(key) && !(key in item)) (data ??= {})[key] = a.value;\n }\n if (data) item.data = data;\n}\n\nfunction scanImage(element: HTMLElement): GalleryItem | undefined {\n const src = attr(element, 'href') ?? attr(element, 'data-shoji-src');\n if (!src) return undefined;\n\n const item: GalleryItem = { src };\n const img = element.querySelector('img');\n const thumb = img?.getAttribute('src') ?? attr(element, 'data-shoji-thumb');\n if (thumb) item.thumb = thumb;\n const alt = img?.getAttribute('alt') ?? attr(element, 'data-shoji-alt');\n if (alt) item.alt = alt;\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n // On the wrapping element, not the inner <img> (that's the thumb; `src`\n // above is the full-resolution image, so it needs its own attribute).\n const srcset = attr(element, 'data-shoji-srcset');\n if (srcset) item.srcset = srcset;\n const sizes = attr(element, 'data-shoji-sizes');\n if (sizes) item.sizes = sizes;\n applyCommon(element, item, src);\n return item;\n}\n\n/**\n * DESIGN.md §2.1 — a nested `<video>` is always html5; `data-shoji-video`\n * checks known provider hosts first. `data-shoji-video-id`/\n * `data-shoji-video-provider` (both optional) can override what would\n * otherwise be parsed out of that URL — see `resolveExplicitVideo`.\n */\nfunction scanVideo(element: HTMLElement): GalleryItem | undefined {\n const videoIdAttr = attr(element, 'data-shoji-video-id');\n const videoEl = element.querySelector('video');\n if (videoEl) {\n if (videoIdAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${videoIdAttr}\" ignored — no effect on a nested <video> (always html5).`,\n );\n }\n const sources: MediaSource[] = Array.from(videoEl.querySelectorAll('source'))\n .map((s) => ({ src: s.getAttribute('src') ?? '', type: s.getAttribute('type') ?? '' }))\n .filter((s) => s.src);\n const src = videoEl.getAttribute('src') ?? sources[0]?.src;\n if (!src) return undefined;\n\n const item: GalleryItem = { src, video: { provider: 'html5' } };\n if (sources.length) item.sources = sources;\n const poster = videoEl.getAttribute('poster');\n if (poster) item.poster = poster;\n // Same bug as the data-shoji-video branch below: without this, these\n // fall through into item.data.width/height as strings instead.\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n applyCommon(element, item, src);\n return item;\n }\n\n const videoUrl = attr(element, 'data-shoji-video');\n if (videoUrl) {\n const providerAttr = attr(element, 'data-shoji-video-provider');\n const resolved = resolveExplicitVideo(videoUrl, providerAttr, videoIdAttr);\n const item: GalleryItem = { src: videoUrl, video: resolved.video };\n if (resolved.sources) item.sources = resolved.sources;\n const poster = attr(element, 'data-shoji-poster');\n if (poster) item.poster = poster;\n // A real bug: unlike `scanImage`, this never read these — they fell\n // through into `item.data.width`/`item.data.height` as strings instead\n // of `item.width`/`item.height`, silently losing `applyAspect()`'s\n // aspect-ratio and the open-placeholder's explicit natural-size box for\n // every DOM-mode (`data-shoji-*`) provider-video item.\n const width = numAttr(element, 'data-shoji-width');\n if (width !== undefined) item.width = width;\n const height = numAttr(element, 'data-shoji-height');\n if (height !== undefined) item.height = height;\n applyCommon(element, item, videoUrl);\n return item;\n }\n\n if (videoIdAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${videoIdAttr}\" ignored — requires a data-shoji-video URL.`,\n );\n }\n return undefined;\n}\n\nconst KNOWN_VIDEO_PROVIDERS = new Set(['youtube', 'vimeo', 'html5']);\n\nfunction html5Fallback(url: string): { video: VideoDescriptor; sources: MediaSource[] } {\n return { video: { provider: 'html5' }, sources: [{ src: url, type: guessVideoType(url) }] };\n}\n\n/**\n * `data-shoji-video-provider` declares the provider outright — trusts an id\n * even off a non-YouTube/non-Vimeo host (e.g. an internal proxy URL).\n * Mirrors dynamic mode's `video: { provider: '...' }`.\n */\nfunction resolveExplicitVideo(\n url: string,\n providerAttr: string | undefined,\n idAttr: string | undefined,\n): { video: VideoDescriptor; sources?: MediaSource[] } {\n if (providerAttr && !KNOWN_VIDEO_PROVIDERS.has(providerAttr)) {\n console.warn(`Shoji: data-shoji-video-provider=\"${providerAttr}\" isn't recognized — ignored.`);\n providerAttr = undefined;\n }\n\n if (providerAttr === 'html5') {\n if (idAttr)\n console.warn(`Shoji: data-shoji-video-id=\"${idAttr}\" ignored — provider html5 has no id.`);\n return html5Fallback(url);\n }\n\n const youtube = resolveDetectedProvider(\n 'youtube',\n url,\n providerAttr,\n idAttr,\n isYouTubeUrl,\n detectYouTubeId,\n );\n if (youtube) return youtube;\n const vimeo = resolveDetectedProvider(\n 'vimeo',\n url,\n providerAttr,\n idAttr,\n isVimeoUrl,\n detectVimeoId,\n );\n if (vimeo) return vimeo;\n\n if (idAttr) {\n console.warn(\n `Shoji: data-shoji-video-id=\"${idAttr}\" ignored — data-shoji-video=\"${url}\" isn't a recognized YouTube/Vimeo URL; falling back to html5.`,\n );\n }\n return html5Fallback(url);\n}\n\n/** Shared logic for youtube/vimeo, the only two providers with URL-based host detection. `undefined` means \"not this provider, try the next one\"; anything else is final, explicit trusting `idAttr` off any host, unset falling back to html5 quietly. */\nfunction resolveDetectedProvider(\n provider: 'youtube' | 'vimeo',\n url: string,\n providerAttr: string | undefined,\n idAttr: string | undefined,\n isHost: (url: string) => boolean,\n detectId: (url: string) => string | undefined,\n): { video: VideoDescriptor; sources?: MediaSource[] } | undefined {\n const explicit = providerAttr === provider;\n if (!explicit && !isHost(url)) return undefined;\n const id = idAttr ?? detectId(url);\n if (!id) {\n if (!explicit) return html5Fallback(url);\n console.warn(\n `Shoji: data-shoji-video-provider=\"${provider}\" but no id could be parsed from \"${url}\".`,\n );\n }\n return { video: { provider, id, url } };\n}\n\nconst YOUTUBE_HOSTS = new Set(['youtu.be', 'youtube.com', 'youtube-nocookie.com']);\nconst VIMEO_HOSTS = new Set(['vimeo.com', 'player.vimeo.com']);\n\n/** Strips the `www.`/`m.`/`music.` subdomain YouTube/Vimeo serve the same content under either way. */\nfunction normalizeVideoHost(hostname: string): string {\n return hostname.replace(/^(www|m|music)\\./, '');\n}\n\n/** Host-only, weaker than `detectYouTubeId` on purpose — tells \"wrong site\" (a real misconfig with an explicit id set) apart from \"right site, unparsed path\" (what an explicit id is for). */\nfunction isYouTubeUrl(url: string): boolean {\n try {\n return YOUTUBE_HOSTS.has(normalizeVideoHost(new URL(url, window.location.href).hostname));\n } catch {\n return false;\n }\n}\n\n/** Same reasoning as `isYouTubeUrl`, for Vimeo's two hosts (`vimeo.com` for an ordinary page link, `player.vimeo.com` for an already-embed-shaped URL). */\nfunction isVimeoUrl(url: string): boolean {\n try {\n return VIMEO_HOSTS.has(normalizeVideoHost(new URL(url, window.location.href).hostname));\n } catch {\n return false;\n }\n}\n\n/**\n * `youtu.be/{id}`, `watch?v=`, `/embed/`, `/shorts/`, `/live/` (streams/\n * premieres), `/v/` (legacy), on `youtube.com` or `youtube-nocookie.com`\n * (the privacy-enhanced embed domain) — `www.`/`m.`/`music.` subdomains all\n * normalize the same way. `undefined` otherwise.\n */\nfunction detectYouTubeId(url: string): string | undefined {\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n const host = normalizeVideoHost(parsed.hostname);\n if (host === 'youtu.be') return parsed.pathname.slice(1).split('/')[0] || undefined;\n if (!YOUTUBE_HOSTS.has(host)) return undefined;\n if (parsed.pathname === '/watch') return parsed.searchParams.get('v') ?? undefined;\n const match = parsed.pathname.match(/^\\/(?:embed|shorts|live|v)\\/([^/?]+)/);\n return match?.[1];\n}\n\n/** First numeric path segment on a recognized Vimeo host — covers `vimeo.com/{id}`, `vimeo.com/{id}/{hash}` (unlisted-video privacy hash, kept in `url` not the id), `player.vimeo.com/video/{id}`, and an id buried deeper (`vimeo.com/channels/x/{id}`). `undefined` on an unrecognized host too. */\nfunction detectVimeoId(url: string): string | undefined {\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n return undefined;\n }\n if (!VIMEO_HOSTS.has(normalizeVideoHost(parsed.hostname))) return undefined;\n return parsed.pathname.match(/\\/(\\d+)(?:\\/|$)/)?.[1];\n}\n\n/** youtube/vimeo, in host-detection preference order — same pair `resolveDetectedProvider` covers for selector mode. */\nconst DETECTABLE_PROVIDERS = [\n { provider: 'youtube' as const, isHost: isYouTubeUrl, detectId: detectYouTubeId },\n { provider: 'vimeo' as const, isHost: isVimeoUrl, detectId: detectVimeoId },\n];\n\n/**\n * Dynamic mode skips `scanContainer()` entirely, so it never gets the same\n * src-based detection `data-shoji-video`/`data-shoji-video-id` have.\n * Mirrors it here: `video: true` infers the whole descriptor from `src`\n * (youtube or vimeo if the host matches, else html5); `{provider:'youtube'|\n * 'vimeo'}` with no `id` fills in just the id. An explicit `id` always\n * wins. Warns (doesn't throw) when a detectable-provider item ends up with\n * no id — the renderer guards this at render time too, showing a\n * placeholder instead of a broken embed.\n */\nexport function resolveDynamicVideoItems(items: GalleryItemInput[]): GalleryItem[] {\n return items.map((item): GalleryItem => {\n if (item.video === true) {\n const detected = DETECTABLE_PROVIDERS.find((p) => p.isHost(item.src));\n const video: VideoDescriptor = detected\n ? { provider: detected.provider, id: detected.detectId(item.src) }\n : { provider: 'html5' };\n if ((video.provider === 'youtube' || video.provider === 'vimeo') && !video.id) {\n console.warn(\n `Shoji: item \"${item.id ?? item.src}\" has video: true, but no id could be parsed from src (\"${item.src}\") — the embed won't load. Use an explicit video.id instead.`,\n );\n }\n return { ...item, video };\n }\n // TS narrows `item.video` past this point, but not `item`'s own type —\n // hence the cast (the map's `: GalleryItem` annotation is what actually\n // catches a mistake here).\n const resolved = item as GalleryItem;\n const provider = resolved.video?.provider;\n if (provider !== 'youtube' && provider !== 'vimeo') return resolved;\n if (resolved.video && 'id' in resolved.video && resolved.video.id) return resolved;\n const id = DETECTABLE_PROVIDERS.find((p) => p.provider === provider)!.detectId(resolved.src);\n if (!id) {\n console.warn(\n `Shoji: item \"${resolved.id ?? resolved.src}\" has video.provider: '${provider}' with no id, and src (\"${resolved.src}\") isn't a recognized ${provider === 'youtube' ? 'YouTube' : 'Vimeo'} URL — the embed won't load. Set video.id explicitly.`,\n );\n return resolved;\n }\n return { ...resolved, video: { provider, id, url: resolved.video?.url } };\n });\n}\n\nfunction guessVideoType(url: string): string {\n const clean = url.split(/[?#]/)[0] ?? url;\n const ext = clean.slice(clean.lastIndexOf('.') + 1).toLowerCase();\n if (ext === 'webm') return 'video/webm';\n if (ext === 'ogg' || ext === 'ogv') return 'video/ogg';\n return 'video/mp4';\n}\n","import type { VideoProviderRenderer } from './plugin';\nimport type { GalleryItem } from './types';\nimport { containedBox } from './zoomTransition';\n\ninterface Slot {\n root: HTMLElement;\n media: HTMLElement;\n /** Which pool position (`-preload…+preload`) this slot represents — reassigned by `render()`, not fixed at construction (see the class comment below). */\n offset: number;\n /** The index this slot currently wants to show, whether or not content has arrived — also how a later-resolving decode (`pending` below) finds the right slot. */\n assignedIndex: number | null;\n /** False from the moment a slot is (re)assigned a new index until that index's content has actually swapped in — see `isActiveReady()`. */\n ready: boolean;\n}\n\n/** A fully-built, ready-to-display node for a given item index — survives slot reassignment (see `cache` below), unlike `Slot.ready`, which resets the moment its slot moves on to a different index. */\ninterface CacheEntry {\n node: HTMLElement;\n item: GalleryItem;\n}\n\nexport interface SlideManagerOptions {\n preload: number;\n videoProviders: Map<string, VideoProviderRenderer>;\n}\n\n/**\n * DESIGN.md §2.3 — only `currentIndex ± preload` exist in the DOM. Content\n * already resident and ready is never moved between slots — the slot that\n * already holds it just gets its own `offset` relabeled to its new pool\n * position; only content resident nowhere yet gets built fresh into\n * whatever's left over. O(preload) re-render cost either way, but never a\n * DOM reparent — which matters for a provider video's `<iframe>` (§4.3):\n * most browsers reload an iframe moved to a new parent, so a live embed can\n * only safely change position by relabeling, never by being moved.\n */\nexport class SlideManager {\n readonly element: HTMLElement;\n private readonly slots: Slot[];\n private readonly preload: number;\n private readonly videoProviders: Map<string, VideoProviderRenderer>;\n private dragOffsetPx = 0;\n\n /** Ready nodes keyed by item index — trimmed to `centerIndex ± preload` each `render()`, same window the slots cover, so an evicted entry's video/iframe resources get released even if no slot ever reclaims it. */\n private readonly cache = new Map<number, CacheEntry>();\n\n /**\n * Image decodes in flight, keyed by item index, not by whichever slot\n * started them — a real bug this fixes: navigating before a preload\n * decode resolved used to reassign that slot, abandoning the decode and\n * starting a duplicate elsewhere, so a slow preload could never finish,\n * only restart. `reveal()` looks up which slot currently wants this\n * index at resolve time, so a reshuffled pool still lands it correctly.\n */\n private readonly pending = new Map<number, HTMLImageElement>();\n\n constructor(options: SlideManagerOptions) {\n this.element = document.createElement('div');\n this.element.className = 'shoji-slides';\n this.preload = options.preload;\n this.videoProviders = options.videoProviders;\n\n const count = options.preload * 2 + 1;\n this.slots = Array.from({ length: count }, (_, i) => {\n const offset = i - options.preload;\n const root = document.createElement('div');\n root.className = 'shoji-slide';\n\n const media = document.createElement('div');\n media.className = 'shoji-slide-media';\n root.appendChild(media);\n\n this.element.appendChild(root);\n return { root, media, offset, assignedIndex: null, ready: false };\n });\n this.applyTransforms(null);\n }\n\n /** The active slot's `.shoji-slide-media` — not `.shoji-slide`, whose transform is owned by pool-offset positioning. */\n getActiveMedia(): HTMLElement | null {\n return this.slots.find((slot) => slot.offset === 0)?.media ?? null;\n }\n\n /** False while the active slot's content is still decoding — Gallery.ts uses this right after `render()` to show the loading state immediately, without waiting for `onLoad`. */\n isActiveReady(): boolean {\n return this.slots.find((slot) => slot.offset === 0)?.ready ?? false;\n }\n\n /**\n * DESIGN.md §2.4 — live drag-to-navigate feedback: every slot's\n * structural `offset * 100%` position gets this same `px` added on top,\n * so dragging left/right visually slides the whole pool together (the\n * adjacent preloaded slot already exists at `±100%`) — no new DOM, no\n * content re-render mid-drag. `transition`: `null` during the live drag\n * (1:1 with the pointer); a real value only for the post-release settle\n * animation, reset back to `null` once that transition ends.\n */\n setDragOffset(px: number, transition: string | null): void {\n this.dragOffsetPx = px;\n this.applyTransforms(transition);\n }\n\n /** The pool slot's `.shoji-slide` root at a structural offset — what the drag settle animation (§2.4) waits for `transitionend` on. */\n getSlotRoot(offset: number): HTMLElement | null {\n return this.slots.find((slot) => slot.offset === offset)?.root ?? null;\n }\n\n private applyTransforms(transition: string | null): void {\n for (const slot of this.slots) {\n slot.root.style.transition = transition ?? '';\n slot.root.style.transform = `translateX(calc(${slot.offset * 100}% + ${this.dragOffsetPx}px))`;\n }\n }\n\n /** Re-renders whichever slots need a different item; `onLoad` fires per index once its media settles. `openPlaceholderSrc` (only from `Gallery.open()`) swaps the centerIndex slot's spinner for a low-res placeholder once it decodes, if not already ready. `loop` matches `Gallery.ts`'s own `nextIndex()`/`prevIndex()` wrap-around — without it, the pool slot just past the last (or before the first) item has no item to preload at all, so a boundary drag reveals nothing even though the completed navigation itself already wraps correctly. */\n render(\n items: readonly GalleryItem[],\n centerIndex: number,\n onLoad: (index: number) => void,\n openPlaceholderSrc?: string,\n loop = false,\n ): void {\n // A real bug found wiring this up, in two parts:\n // 1. Wrapping is only safe from an *index-collision* standpoint when\n // there are enough real items to fill the whole pool without\n // revisiting one twice. `items.length === this.slots.length`\n // (`2*preload + 1`) looks like exactly enough — but that's the\n // degenerate case where the pool *is* the whole gallery: the \"prev\"\n // slot at the first item and the \"next\" slot at the last item both\n // wrap to the *other* end, making the first and last items adjacent\n // in the pool even though nothing actually collides on one index.\n // Confirmed directly, reproduced in CI: a real fixture built\n // specifically to keep two provider-video items apart (never within\n // `preload` of each other, so at most one `.shoji-slide-provider-\n // video` is ever resident) broke exactly this way once its\n // `demo/assets/`-dependent photo tiles were empty (gitignored, so a\n // fresh CI checkout has none) — collapsing it down to precisely\n // `items.length === this.slots.length`, wrapping the two video items\n // into each other's pool despite the fixture's own spacer tile still\n // sitting between them in the array. Requiring *strictly* more items\n // than pool slots (`>`, not `>=`) is what actually guarantees the\n // first and last items are never both in the wrapped pool at once.\n // 2. Below that threshold, an out-of-range offset just shows nothing at\n // that edge, same as `loop: false` — correct for a gallery too small\n // to usefully \"loop\" through anyway.\n const canWrap = loop && items.length > this.slots.length;\n const targets = this.slots.map((_, i) => {\n const offset = i - this.preload;\n const rawIndex = centerIndex + offset;\n const index = canWrap ? ((rawIndex % items.length) + items.length) % items.length : rawIndex;\n const item = index >= 0 && index < items.length ? items[index] : undefined;\n return { offset, index, item };\n });\n\n // Trim the cache to the same window the slots above now cover — the\n // *wrapped* set of indices, not a raw numeric range, matching `loop`;\n // a raw-range check would otherwise immediately evict a just-cached\n // wrapped entry (e.g. index 0, preloaded one slot past the last item)\n // since it falls far outside `centerIndex ± preload` as plain numbers.\n // Releases a dropped video here rather than just letting the reference\n // disappear (which would leave it paused-in-place, never released).\n const windowIndices = new Set(targets.map((t) => t.index));\n for (const [index, entry] of this.cache) {\n if (!windowIndices.has(index)) {\n releaseVideoNode(entry.node);\n this.cache.delete(index);\n }\n }\n\n // Phase 1 — claim in place, before anything gets destructively\n // released. A target already resident and ready in *some* slot (not\n // necessarily the one whose own offset happens to match) stays exactly\n // where it is — only that slot's `offset` moves (see the class comment\n // above). Still mid-decode elsewhere isn't claimed here (no `ready`\n // slot yet) — falls through to phase 2, where `ensureImageDecoding`'s\n // in-flight guard reconciles it once the one real decode resolves.\n const claimedIndices = new Set<number>();\n const claimedSlots = new Set<Slot>();\n for (const target of targets) {\n if (!target.item) continue;\n const owner = this.slots.find((s) => s.assignedIndex === target.index && s.ready);\n if (!owner) continue;\n claimedIndices.add(target.index);\n claimedSlots.add(owner);\n if (owner.offset === target.offset) continue; // already exactly right, nothing to do\n owner.offset = target.offset;\n onLoad(target.index);\n }\n\n // Phase 2 — whatever's left: slots phase 1 didn't claim are free to\n // clear (out-of-range target) or take on fresh content (a genuinely\n // new index, or one already mid-decode elsewhere).\n const freeSlots = this.slots.filter((s) => !claimedSlots.has(s));\n const freeTargets = targets.filter((t) => !t.item || !claimedIndices.has(t.index));\n\n freeTargets.forEach((target, i) => {\n const slot = freeSlots[i]!;\n slot.offset = target.offset;\n const { index, item } = target;\n\n if (!item) {\n slot.assignedIndex = null;\n slot.ready = false;\n releaseVideo(slot.media);\n slot.media.replaceChildren();\n return;\n }\n if (slot.assignedIndex === index) return; // unchanged — a decode already in flight here\n\n slot.assignedIndex = index;\n slot.ready = false;\n releaseVideo(slot.media);\n slot.media.replaceChildren(createSpinner());\n // Early, not just from swapIn/moveIn/onReady below — a provider\n // video's poster (shown synchronously, well before onReady) needs\n // --shoji-provider-video-aspect (shoji.css) set before it ever\n // paints, or it always letterboxes to the 16:9 fallback regardless of\n // the item's own declared shape.\n this.applyAspect(slot, item);\n if (index === centerIndex && openPlaceholderSrc) {\n const naturalSize =\n item.width && item.height ? { width: item.width, height: item.height } : undefined;\n this.revealOpenPlaceholder(openPlaceholderSrc, slot, index, naturalSize);\n }\n\n if (item.video?.provider === 'html5') {\n this.renderVideo(item, slot, index, onLoad);\n } else if (item.video) {\n this.renderProviderVideo(item, slot, index, onLoad);\n } else {\n this.ensureImageDecoding(item, index, onLoad); // no-ops if index is already being decoded elsewhere\n }\n });\n\n // Reflect any relabeling above immediately, never animated — masked\n // either by SlideTransition's own ghost-clone crossfade, or by landing\n // exactly on a completed drag's already-settled position (§2.4);\n // animating this too would fight both.\n this.applyTransforms(null);\n }\n\n private applyAspect(slot: Slot, item: GalleryItem): void {\n if (item.width && item.height) {\n slot.media.style.aspectRatio = `${item.width} / ${item.height}`;\n } else {\n slot.media.style.removeProperty('aspect-ratio');\n }\n // A provider video's real shape (YouTube/Vimeo iframe, via\n // shoji.css's cqw/cqh sizing) — kept separate from the aspect-ratio\n // above since that alone can't shape a non-replaced element like an\n // iframe/div (see shoji.css's own comment on this). Only set for a\n // video item: harmless either way, but meaningless for a photo, whose\n // own object-fit: contain already uses its real decoded dimensions\n // directly.\n if (item.video && item.width && item.height) {\n slot.media.style.setProperty(\n '--shoji-provider-video-aspect',\n `calc(${item.width} / ${item.height})`,\n );\n } else {\n slot.media.style.removeProperty('--shoji-provider-video-aspect');\n }\n }\n\n /** Releases the slot's old content and swaps the new node in, caching it. `ensureImageDecoding` goes through `moveIn` instead. */\n private swapIn(slot: Slot, node: HTMLElement, item: GalleryItem, index: number): void {\n releaseVideo(slot.media);\n this.applyAspect(slot, item);\n slot.media.replaceChildren(node);\n slot.ready = true;\n this.cache.set(index, { node, item });\n }\n\n /**\n * Inserts a just-decoded node into the slot waiting on it — skips\n * `releaseVideo`, unlike `swapIn`: this is its first insertion anywhere,\n * nothing outgoing to release. `render()`'s claim pass (Phase 1) never\n * calls this — it reuses `ready` content in place, no DOM touch at all.\n */\n private moveIn(slot: Slot, entry: CacheEntry, index: number): void {\n this.applyAspect(slot, entry.item);\n slot.media.replaceChildren(entry.node);\n slot.ready = true;\n this.cache.set(index, entry);\n }\n\n /** Starts decoding `item` for `index`, only if nothing already is (see `pending`). Resolves by looking up whichever slot currently wants this index, not the one active when the decode started. */\n private ensureImageDecoding(\n item: GalleryItem,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n if (this.pending.has(index)) return;\n\n const img = document.createElement('img');\n img.className = 'shoji-slide-img';\n img.alt = item.alt ?? '';\n // A real bug: <img> is natively draggable by default in every browser\n // (drag-to-save-elsewhere). Left on, a real drag gesture — navigate,\n // vertical-close, or the zoom plugin's own pan — can lose the race to\n // the browser's own \"start a native image drag\" recognition, which\n // fires pointercancel and hands the interaction off to dragstart/drag\n // instead: the gesture appears to move once, then stop dead, since\n // every pointer event after the cancel is simply never dispatched here\n // again. Disabling native drag makes Pointer Events own the gesture\n // unconditionally.\n img.draggable = false;\n // The one image the viewer is actually waiting on — hint the browser to\n // schedule it ahead of any lower-priority background fetches contending\n // for the same connection pool.\n if ('fetchPriority' in img) img.fetchPriority = 'high';\n if (item.srcset) img.srcset = item.srcset;\n if (item.sizes) img.sizes = item.sizes;\n img.src = item.src;\n this.pending.set(index, img);\n\n const reveal = (): void => {\n this.pending.delete(index);\n const entry: CacheEntry = { node: img, item };\n this.cache.set(index, entry);\n const slot = this.slots.find((s) => s.assignedIndex === index);\n if (!slot) return; // nobody currently wants it anymore\n this.moveIn(slot, entry, index);\n onLoad(index);\n };\n\n if (typeof img.decode === 'function') {\n img.decode().then(reveal, reveal);\n } else {\n img.addEventListener('load', reveal, { once: true });\n img.addEventListener('error', reveal, { once: true });\n }\n }\n\n /**\n * DESIGN.md §2.3 — swaps the spinner for the placeholder once *it*\n * decodes, not immediately: `item.thumb` is often just `item.src` again,\n * so an undecoded placeholder can leave as long a blank gap as the\n * spinner it replaces.\n *\n * A real bug: `.shoji-slide-open-placeholder`'s CSS unconditionally\n * force-fills the frame (deliberate default: a real photo is usually\n * bigger than the dialog). Wrong for a genuinely small photo with known\n * `item.width`/`item.height` — same \"grows too big, snaps down once real\"\n * symptom the zoom-in transition itself had (§2.3b), but that fix only\n * governs the animated *transform*, not this placeholder's own CSS box\n * once it settles. When `naturalSize` is known, sizes the placeholder\n * explicitly instead, reusing `containedBox` (`zoomTransition.ts`) —\n * unknown-size items keep the original force-fill guess.\n *\n * A second real bug in that same fix: measured `slot.media`'s own rect as\n * \"the container\" — but `slot.media` is the exact element the zoom-in\n * transition (§2.3b) animates a `scale()` transform on. `getBoundingClientRect()`\n * reflects whatever transform is *currently* applied, and the placeholder's\n * own decode typically resolves before that ~300ms animation settles — so\n * this measured a still-small, mid-animation rect (often the origin\n * thumbnail's own tiny size) instead of the real dialog size. `slot.root`\n * (`.shoji-slide`) fixes it: same box, only ever `translateX`'d for\n * pool-offset positioning, never scaled — a stable read regardless of\n * what its child is mid-animation through.\n */\n private revealOpenPlaceholder(\n src: string,\n slot: Slot,\n index: number,\n naturalSize?: { width: number; height: number },\n ): void {\n const img = createOpenPlaceholder(src);\n const reveal = (): void => {\n if (slot.assignedIndex !== index || slot.ready) return; // stale, or the real content already won the race\n // Only loading indicators, not slot.media wholesale — a provider video\n // may have already appended its own (still-hidden) container alongside\n // it. A real bug: this only ever cleared the spinner, not a\n // `.shoji-slide-provider-poster` a provider video's `item.poster`\n // (`showProviderPoster`, below) may have *already* synchronously\n // inserted by the time this async decode resolves — leaving both\n // visible at once, the poster at its own small natural size next to\n // this placeholder's explicitly-computed large box.\n slot.media\n .querySelectorAll('.shoji-slide-spinner, .shoji-slide-provider-poster')\n .forEach((el) => el.remove());\n slot.media.appendChild(img);\n if (naturalSize) {\n const containerRect = slot.root.getBoundingClientRect();\n const box = containedBox(\n { left: 0, top: 0, width: containerRect.width, height: containerRect.height },\n naturalSize.width / naturalSize.height,\n naturalSize,\n );\n img.style.width = `${box.width}px`;\n img.style.height = `${box.height}px`;\n }\n };\n if (typeof img.decode === 'function') {\n img.decode().then(reveal, reveal);\n } else {\n img.addEventListener('load', reveal, { once: true });\n img.addEventListener('error', reveal, { once: true });\n }\n }\n\n /** Native `<video controls>` — real playback, not just a poster. Not autoplayed/muted: a deliberate click-to-play, not a background loop. */\n private renderVideo(\n item: GalleryItem,\n slot: Slot,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n const hasSource = Boolean(item.src) || Boolean(item.sources && item.sources.length > 0);\n if (!hasSource) {\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n this.swapIn(slot, placeholder, item, index);\n onLoad(index);\n return;\n }\n\n const video = document.createElement('video');\n video.className = 'shoji-slide-video';\n video.controls = true;\n video.playsInline = true;\n // Same real bug as the image path's own `img.draggable = false` above\n // (`ensureImageDecoding()`), never fixed here since no e2e test\n // previously drove a real mouse drag over an actual native\n // `<video controls>` element to catch it: a `<video>` is natively\n // draggable by default too (drag-to-save-elsewhere), and left on, a\n // real drag gesture (navigate, vertical-close) can lose the race to the\n // browser's own \"start a native media drag\" recognition — it fires\n // `pointercancel` and hands the interaction to `dragstart`/`drag`\n // instead, so the gesture appears to move once, then stop dead, since\n // every pointer event after the cancel is simply never dispatched here\n // again. Confirmed directly: reproduced consistently (every browser\n // project) for a horizontal drag specifically, though the same\n // mechanism can affect vertical too. Disabling native drag makes\n // Pointer Events own the gesture unconditionally, same as for photos.\n video.draggable = false;\n if (item.poster) video.poster = item.poster;\n // Before `loadedmetadata`, a <video> has no real intrinsic size to\n // contain itself against (object-fit: contain, above) — the UA default\n // (300x150) until then, visibly jumping to the real shape once it\n // loads. item.width/item.height (already known up front, unlike a\n // photo's real dimensions) sidesteps that: same shape from the first\n // frame the poster shows, no jump once metadata actually arrives.\n if (item.width && item.height) {\n video.style.aspectRatio = `${item.width} / ${item.height}`;\n }\n\n if (item.sources && item.sources.length > 0) {\n for (const s of item.sources) {\n const source = document.createElement('source');\n source.src = s.src;\n source.type = s.type;\n video.appendChild(source);\n }\n } else {\n video.src = item.src;\n }\n\n // Inserted immediately (unlike the image path above) — the native\n // `poster` attribute already shows something meaningful without\n // waiting on `loadedmetadata`, so there's no decode-style gap to close\n // here; deferring would only make video slides slower to show anything.\n this.swapIn(slot, video, item, index);\n const reveal = (): void => onLoad(index);\n video.addEventListener('loadedmetadata', reveal, { once: true });\n video.addEventListener('error', reveal, { once: true });\n }\n\n /** DESIGN.md §4-video. Unregistered provider → same placeholder as no-source video. */\n private renderProviderVideo(\n item: GalleryItem,\n slot: Slot,\n index: number,\n onLoad: (index: number) => void,\n ): void {\n const video = item.video!;\n const renderFn =\n video.provider === 'custom' ? video.render : this.videoProviders.get(video.provider);\n\n if (!renderFn) {\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n this.swapIn(slot, placeholder, item, index);\n onLoad(index);\n return;\n }\n\n // DESIGN.md §4.3 — shows item.poster immediately, in place of the\n // generic spinner Phase 2 already put in slot.media, if the host\n // supplied one; same idea as native <video poster>, just applied to a\n // provider embed instead. A renderer without a host-supplied poster can\n // still resolve a fallback of its own via the setPoster callback below.\n if (item.poster) showProviderPoster(slot, item.poster);\n\n const container = document.createElement('div');\n container.className = 'shoji-slide-provider-video';\n container.hidden = true;\n const controller = new AbortController();\n providerAbortControllers.set(container, controller);\n\n // Unlike an <img> decode, an iframe embed only actually loads once\n // attached to the live document — attach now, hidden behind the\n // still-visible spinner (or poster, above), instead of deferring\n // attachment until ready.\n slot.media.appendChild(container);\n\n let revealed = false;\n const onReady = (): void => {\n if (revealed || controller.signal.aborted) return;\n revealed = true;\n container.hidden = false;\n // Whichever loading indicator(s) — Phase 2's spinner, a poster, an\n // open placeholder — are still sitting behind the now-visible embed,\n // never the embed itself. A real bug: a host-supplied `item.poster`\n // (`showProviderPoster`, above) and `Gallery.open()`'s own low-res\n // placeholder (`revealOpenPlaceholder`, below) are added independently\n // of each other and neither replaces the other, so *both* can be\n // sitting in `slot.media` at once by the time this runs.\n // `querySelector(...).remove()` only ever removed the first match in\n // DOM order, permanently leaking whichever indicator lost that\n // race — visible as the leaked one's image bleeding through the\n // transparent letterboxing gaps around a provider embed that isn't\n // exactly the container's own aspect ratio.\n slot.media\n .querySelectorAll(\n '.shoji-slide-spinner, .shoji-slide-open-placeholder, .shoji-slide-provider-poster',\n )\n .forEach((el) => el.remove());\n this.applyAspect(slot, item);\n slot.ready = true;\n this.cache.set(index, { node: container, item });\n onLoad(index);\n };\n const setPoster = (url: string): void => {\n // A host-supplied poster (above) always wins over a renderer's own\n // fallback — and once the real embed is showing, or this slide's\n // moved on, a fallback resolving late (e.g. an async fetch) must\n // never replace or paint over it.\n if (item.poster || revealed || controller.signal.aborted) return;\n showProviderPoster(slot, url);\n };\n renderFn(container, item, onReady, controller.signal, setPoster);\n }\n\n destroy(): void {\n for (const slot of this.slots) {\n releaseVideo(slot.media);\n slot.media.replaceChildren();\n slot.assignedIndex = null; // any decode still in `pending` correctly finds no slot wanting it once it resolves\n slot.ready = false;\n }\n this.cache.clear();\n this.pending.clear();\n this.element.remove();\n }\n}\n\n/** DESIGN.md §4.3 — a provider video's loading placeholder, host-supplied (`item.poster`) or a renderer's own fallback (`setPoster`) — replaces whichever generic indicator (spinner, or an earlier poster call) is currently in `slot.media`, same \"only one loading indicator at a time\" rule `createOpenPlaceholder`'s own callers already follow. Reuses `.shoji-slide-img`'s sizing, same reasoning as that function. */\nfunction showProviderPoster(slot: Slot, url: string): void {\n // A real bug: this only ever cleared the spinner/a previous poster, never\n // an already-shown `.shoji-slide-open-placeholder` (`revealOpenPlaceholder`,\n // above) — that placeholder's async image decode can resolve *before*\n // this (e.g. `setPoster`'s fallback, resolved later than the initial\n // synchronous poster call), leaving both visible at once.\n slot.media\n .querySelectorAll(\n '.shoji-slide-spinner, .shoji-slide-open-placeholder, .shoji-slide-provider-poster',\n )\n .forEach((el) => el.remove());\n const img = document.createElement('img');\n img.className = 'shoji-slide-img shoji-slide-provider-poster';\n img.alt = '';\n img.draggable = false;\n img.src = url;\n slot.media.appendChild(img);\n}\n\n/** DESIGN.md §2.3 — low-res open() placeholder; reuses .shoji-slide-img's sizing so the zoom-in FLIP measures it like real content (zoomTransition.ts's effectiveTargetBox only special-cases the spinner as non-content). */\nfunction createOpenPlaceholder(src: string): HTMLImageElement {\n const img = document.createElement('img');\n img.className = 'shoji-slide-img shoji-slide-open-placeholder';\n img.alt = '';\n img.draggable = false;\n img.src = src;\n return img;\n}\n\n/** DESIGN.md §2.3 — shown in a slot while its content is still decoding/loading, replacing whatever a stale \"keep the old image visible\" approach would have left there (a previous version of this did that; it read as broken, not helpful, since the old image no longer matches the caption/counter/URL that already moved on). Purely CSS-animated (a rotating ring via `border`), no JS-driven layout. */\nfunction createSpinner(): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = 'shoji-slide-spinner';\n spinner.setAttribute('aria-hidden', 'true');\n return spinner;\n}\n\nconst providerAbortControllers = new WeakMap<HTMLElement, AbortController>();\n\n/** Pause/release a slot's previous <video> or provider content, if any. */\nfunction releaseVideo(media: HTMLElement): void {\n const video = media.querySelector('video');\n if (video) releaseVideoNode(video);\n const provider = media.querySelector<HTMLElement>('.shoji-slide-provider-video');\n if (provider) releaseProviderNode(provider);\n}\n\n/**\n * Pauses whatever's playing in `media` — native `<video>`, or a provider\n * embed wired via `wirePlayableContract` (§4-video) — without\n * releasing/destroying it, unlike `releaseVideo` above. `Gallery` calls\n * this on `close()` and before every navigation, on the outgoing slide.\n */\nexport function pauseMedia(media: HTMLElement | null): void {\n const video = media?.querySelector('video');\n if (video) {\n video.pause();\n return;\n }\n const provider = media?.querySelector<HTMLElement & { pause?: () => void }>(\n '.shoji-slide-provider-video',\n );\n if (provider && typeof provider.pause === 'function') provider.pause();\n}\n\n/** Cache-eviction counterpart — the node itself might *be* the content. */\nfunction releaseVideoNode(node: HTMLElement): void {\n if (node.tagName !== 'VIDEO') {\n releaseProviderNode(node);\n return;\n }\n const video = node as HTMLVideoElement;\n video.pause();\n video.removeAttribute('src');\n video.load();\n}\n\nfunction releaseProviderNode(node: HTMLElement): void {\n const controller = providerAbortControllers.get(node);\n if (!controller) return;\n providerAbortControllers.delete(node);\n controller.abort();\n}\n","/**\n * DESIGN.md §2.5 — built-in presets, generated from a small config→transform\n * DSL rather than ~20 hand-written keyframe functions. `enter(direction)` is\n * where the incoming slide starts (then transitions to natural: `transform:\n * none; opacity: 1`); `leave(direction)` is where the outgoing clone (see\n * `SlideTransition.ts`) ends up (starts at natural, transitions to this).\n * `direction` is `1` for next()-style, `-1` for prev()-style — presets that\n * don't care (fade, zoom, flipX, deck, drop...) never read it. transform/\n * opacity only, per CLAUDE.md's hardware-accelerated-CSS3 constraint.\n */\n\nexport interface TransitionState {\n transform: string;\n opacity: number;\n}\n\nexport interface TransitionPreset {\n name: string;\n enter(direction: 1 | -1): TransitionState;\n leave(direction: 1 | -1): TransitionState;\n}\n\n/** One end of one preset. `directional: true` multiplies translateX/Y/rotateZ/Y by nav direction (mirror-image next vs prev — the \"slide\" family); omitted means the same fixed transform either way (the \"fade\" family — fadeUp always rises). */\ninterface AxisConfig {\n directional?: boolean;\n translateX?: number; // %\n translateY?: number; // %\n scale?: number;\n rotateX?: number; // deg, never direction-multiplied\n rotateY?: number; // deg\n rotateZ?: number; // deg\n perspective?: number; // px, needed alongside rotateX/Y for real 3D depth\n opacity?: number; // default 1\n}\n\nfunction resolveAxis(config: AxisConfig, direction: 1 | -1): TransitionState {\n const sign = config.directional ? direction : 1;\n const parts: string[] = [];\n if (config.perspective) parts.push(`perspective(${config.perspective}px)`);\n const tx = config.translateX !== undefined ? config.translateX * sign : 0;\n const ty = config.translateY ?? 0;\n if (tx !== 0 || ty !== 0) parts.push(`translate(${tx}%, ${ty}%)`);\n if (config.rotateY !== undefined) parts.push(`rotateY(${config.rotateY * sign}deg)`);\n if (config.rotateX !== undefined) parts.push(`rotateX(${config.rotateX}deg)`);\n if (config.rotateZ !== undefined) parts.push(`rotateZ(${config.rotateZ * sign}deg)`);\n if (config.scale !== undefined) parts.push(`scale(${config.scale})`);\n return { transform: parts.length > 0 ? parts.join(' ') : 'none', opacity: config.opacity ?? 1 };\n}\n\ninterface PresetSpec {\n name: string;\n enter: AxisConfig;\n leave: AxisConfig;\n}\n\nfunction preset(spec: PresetSpec): TransitionPreset {\n return {\n name: spec.name,\n enter: (direction) => resolveAxis(spec.enter, direction),\n leave: (direction) => resolveAxis(spec.leave, direction),\n };\n}\n\nconst PRESET_LIST: TransitionPreset[] = [\n // The four DESIGN.md calls out by name: default mode, plus fade/zoom/deck.\n preset({\n name: 'slide',\n enter: { directional: true, translateX: 100 },\n leave: { directional: true, translateX: -100 },\n }),\n preset({\n name: 'fade',\n enter: { opacity: 0 },\n leave: { opacity: 0 },\n }),\n preset({\n name: 'zoom',\n enter: { scale: 0.6, opacity: 0 },\n leave: { scale: 1.4, opacity: 0 },\n }),\n preset({\n // \"lg-style deck\": the incoming slide drops into place from slightly\n // above/small while the outgoing one recedes back and fades, like a\n // card being placed on top of a deck — not direction-dependent, a deck\n // doesn't care whether the card came from the left or right.\n name: 'deck',\n enter: { translateY: 6, scale: 0.85, opacity: 0 },\n leave: { translateY: -4, scale: 0.92, opacity: 0 },\n }),\n\n // Positional siblings of `slide`.\n preset({\n name: 'slideVertical',\n enter: { directional: true, translateY: 100 },\n leave: { directional: true, translateY: -100 },\n }),\n preset({\n name: 'push',\n // Same geometry as `slide` but travels further (120% vs 100%) and with\n // no cross-fade at all — a harder, snappier \"shove it off\" feel.\n enter: { directional: true, translateX: 120 },\n leave: { directional: true, translateX: -120 },\n }),\n\n // Fixed-direction fades (not nav-direction-aware — a named entrance style).\n preset({\n name: 'fadeUp',\n enter: { translateY: 12, opacity: 0 },\n leave: { translateY: -12, opacity: 0 },\n }),\n preset({\n name: 'fadeDown',\n enter: { translateY: -12, opacity: 0 },\n leave: { translateY: 12, opacity: 0 },\n }),\n preset({\n name: 'fadeLeft',\n enter: { translateX: -12, opacity: 0 },\n leave: { translateX: 12, opacity: 0 },\n }),\n preset({\n name: 'fadeRight',\n enter: { translateX: 12, opacity: 0 },\n leave: { translateX: -12, opacity: 0 },\n }),\n\n // Zoom family.\n preset({ name: 'zoomOut', enter: { scale: 1.4, opacity: 0 }, leave: { scale: 0.6, opacity: 0 } }),\n preset({ name: 'scaleUp', enter: { scale: 0.7 }, leave: { scale: 1.3 } }),\n preset({ name: 'scaleDown', enter: { scale: 1.3 }, leave: { scale: 0.7 } }),\n\n // Rotation family — `rotate` is fixed-direction; `rotateLeft`/`rotateRight`\n // tie their spin to nav direction instead.\n preset({\n name: 'rotate',\n enter: { rotateZ: 15, opacity: 0 },\n leave: { rotateZ: -15, opacity: 0 },\n }),\n preset({\n name: 'rotateLeft',\n enter: { directional: true, rotateZ: -25, opacity: 0 },\n leave: { directional: true, rotateZ: 25, opacity: 0 },\n }),\n preset({\n name: 'rotateRight',\n enter: { directional: true, rotateZ: 25, opacity: 0 },\n leave: { directional: true, rotateZ: -25, opacity: 0 },\n }),\n\n // 3D family — needs `perspective()` in the same transform for real depth.\n preset({\n name: 'flipX',\n enter: { rotateX: 90, perspective: 1200, opacity: 0 },\n leave: { rotateX: -90, perspective: 1200, opacity: 0 },\n }),\n preset({\n name: 'flipY',\n enter: { directional: true, rotateY: 90, perspective: 1200, opacity: 0 },\n leave: { directional: true, rotateY: -90, perspective: 1200, opacity: 0 },\n }),\n preset({\n name: 'cube',\n enter: { directional: true, rotateY: 70, translateX: 40, perspective: 1600, opacity: 1 },\n leave: { directional: true, rotateY: -70, translateX: -40, perspective: 1600, opacity: 1 },\n }),\n preset({\n name: 'coverflow',\n enter: {\n directional: true,\n rotateY: 35,\n translateX: 60,\n scale: 0.8,\n perspective: 1400,\n opacity: 0,\n },\n leave: {\n directional: true,\n rotateY: -35,\n translateX: -60,\n scale: 0.8,\n perspective: 1400,\n opacity: 0,\n },\n }),\n\n // Fixed-direction drop.\n preset({\n name: 'drop',\n enter: { translateY: -30, opacity: 0 },\n leave: { translateY: 20, opacity: 0 },\n }),\n];\n\n/** Keyed by name for `Gallery`'s `mode` lookup — an unrecognized string is treated as a custom CSS-class-pair mode instead (see `SlideTransition.animateCustom`), not an error. */\nexport const TRANSITION_PRESETS: Readonly<Record<string, TransitionPreset>> = Object.fromEntries(\n PRESET_LIST.map((p) => [p.name, p]),\n);\n","import type { SlideManager } from '../core/SlideManager';\nimport type { TransitionPreset } from './presets';\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/** `\"300ms\"` / `\"0.3s\"` → milliseconds — same parser as `zoomTransition.ts`, duplicated rather than shared: two independent transition subsystems that happen to share a timing format. */\nfunction parseCssTime(value: string): number {\n const first = value.split(',')[0]?.trim() ?? '';\n if (first.endsWith('ms')) return parseFloat(first);\n if (first.endsWith('s')) return parseFloat(first) * 1000;\n return 0;\n}\n\n/** Waits for `transitionend` *or* `animationend` (with a timeout fallback) then calls `cb` once — the custom CSS-class-pair path (§2.5) may use either, since \"no JS needed\" for the host means Shoji can't assume which. */\nfunction waitForEnd(el: HTMLElement, cb: () => void): void {\n const style = getComputedStyle(el);\n const durationMs = Math.max(\n parseCssTime(style.transitionDuration),\n parseCssTime(style.animationDuration),\n );\n let done = false;\n const finish = (): void => {\n if (done) return;\n done = true;\n el.removeEventListener('transitionend', onEnd);\n el.removeEventListener('animationend', onEnd);\n cb();\n };\n const onEnd = (event: Event): void => {\n if (event.target === el) finish();\n };\n el.addEventListener('transitionend', onEnd);\n el.addEventListener('animationend', onEnd);\n setTimeout(finish, durationMs + 100);\n}\n\n/** Incoming slide: instant jump to `(transform, opacity)` (same FLIP trick as `zoomTransition.ts`'s `zoomIn`), then transitions to natural. */\nfunction applyEnter(el: HTMLElement, transform: string, opacity: number): void {\n el.style.transition = 'none';\n el.style.transformOrigin = 'center';\n el.style.transform = transform;\n el.style.opacity = String(opacity);\n void el.offsetHeight; // force the instant jump to commit before transitioning away from it\n el.style.transition =\n 'transform var(--shoji-duration) var(--shoji-easing), opacity var(--shoji-duration) var(--shoji-easing)';\n el.style.transform = 'none';\n el.style.opacity = '1';\n}\n\n/** Outgoing ghost: already sits at natural (a fresh clone has no inline transform yet), so it transitions the other way — natural → `(transform, opacity)`, mirroring `zoomOut`'s shape. */\nfunction applyLeave(el: HTMLElement, transform: string, opacity: number): void {\n el.style.transformOrigin = 'center';\n el.style.transition =\n 'transform var(--shoji-duration) var(--shoji-easing), opacity var(--shoji-duration) var(--shoji-easing)';\n void el.offsetHeight;\n el.style.transform = transform;\n el.style.opacity = String(opacity);\n}\n\nfunction clearInlineTransform(el: HTMLElement): void {\n el.style.transition = '';\n el.style.transform = '';\n el.style.opacity = '';\n el.style.transformOrigin = '';\n}\n\n/**\n * DESIGN.md §2.5 — animates a slide-to-slide navigation via a temporary\n * \"ghost\": a clone of the outgoing `.shoji-slide-media`, positioned over\n * the real slot, playing the preset's `leave` keyframe while `swapContent`\n * (the real `SlideManager.render()` reassignment) runs invisibly underneath\n * it. The newly-swapped-in real active media then plays `enter`. Both\n * animate concurrently.\n *\n * Deliberately separate from the gesture engine's own live-drag/settle\n * animation (`GestureController.ts`, §2.4): `mode` is a discrete \"jump\" for\n * programmatic navigation, not layered onto a continuous drag — a completed\n * swipe always uses its own pool-shift regardless of `mode`. See\n * `Gallery.navigate()`'s `animate` flag.\n */\nexport class SlideTransition {\n constructor(\n private readonly slides: SlideManager,\n private readonly decorateLeave: (clonedMedia: HTMLElement) => () => void = () => () => {},\n ) {}\n\n /** A recognized built-in preset (`TRANSITION_PRESETS`). */\n animate(preset: TransitionPreset, direction: 1 | -1, swapContent: () => void): void {\n this.run(swapContent, (ghost, incoming) => {\n const leave = preset.leave(direction);\n applyLeave(ghost, leave.transform, leave.opacity);\n const enter = preset.enter(direction);\n applyEnter(incoming, enter.transform, enter.opacity);\n });\n }\n\n /** An unrecognized `mode` string: a host-supplied CSS class pair (`shoji-transition-<mode>-leave`/`-enter`), not an error — §2.5's \"custom animation = a CSS class pair, no JS needed.\" */\n animateCustom(mode: string, direction: 1 | -1, swapContent: () => void): void {\n const dirAttr = direction === 1 ? 'next' : 'prev';\n this.run(\n swapContent,\n (ghost, incoming) => {\n ghost.dataset.shojiDirection = dirAttr;\n ghost.classList.add(`shoji-transition-${mode}-leave`);\n incoming.dataset.shojiDirection = dirAttr;\n incoming.classList.add(`shoji-transition-${mode}-enter`);\n },\n (incoming) => {\n incoming.classList.remove(`shoji-transition-${mode}-enter`);\n delete incoming.dataset.shojiDirection;\n },\n );\n }\n\n private run(\n swapContent: () => void,\n kickOff: (ghost: HTMLElement, incoming: HTMLElement) => void,\n cleanupIncoming: (incoming: HTMLElement) => void = clearInlineTransform,\n ): void {\n if (prefersReducedMotion()) {\n swapContent();\n return;\n }\n const outgoing = this.slides.getActiveMedia();\n if (!outgoing) {\n swapContent();\n return;\n }\n\n const ghost = document.createElement('div');\n ghost.className = 'shoji-slide-ghost';\n const clonedMedia = ghost.appendChild(outgoing.cloneNode(true) as HTMLElement);\n this.slides.element.appendChild(ghost);\n // DESIGN.md §2.5/§4.5 — plugins with a per-slide visual override (e.g.\n // RotateFlip's rotate/flip, Zoom's scale/pan) freeze it onto the clone\n // here, before the reflow below commits it as the leave animation's\n // start — the real node was already reset by now, so the clone alone\n // wouldn't otherwise carry it. `settleLeave` (called after `kickOff`\n // below) is what starts each one transitioning back to neutral.\n const settleLeave = this.decorateLeave(clonedMedia);\n void ghost.offsetHeight; // commit the ghost's (and clone's) starting appearance before anything changes it\n\n swapContent();\n\n const incoming = this.slides.getActiveMedia();\n if (!incoming) {\n ghost.remove();\n return;\n }\n\n kickOff(ghost, incoming);\n settleLeave();\n waitForEnd(ghost, () => ghost.remove());\n waitForEnd(incoming, () => cleanupIncoming(incoming));\n }\n}\n","import {\n lockBodyScroll,\n unlockBodyScroll,\n markIntentionalScroll as markIntentionalScrollInternal,\n} from './bodyScrollLock';\nimport { EventBus, type Unsubscribe } from './EventBus';\nimport { buildLightboxDom, type LightboxDom } from './dom';\nimport { FocusTrap } from './FocusTrap';\nimport { GestureController, INTERACTIVE_CONTROL_SELECTOR } from './GestureController';\nimport { LiveRegion } from './LiveRegion';\nimport type { ButtonSpec, PluginContext, ShojiPlugin, VideoProviderRenderer } from './plugin';\nimport { DEFAULT_SELECTOR, resolveDynamicVideoItems, scanContainer } from './scan';\nimport { pauseMedia, SlideManager } from './SlideManager';\nimport type {\n DangerousHtmlCaption,\n GalleryEvents,\n GalleryItem,\n GalleryItemInput,\n GalleryOptions,\n} from './types';\nimport { TRANSITION_PRESETS } from '../transitions/presets';\nimport { SlideTransition } from '../transitions/SlideTransition';\nimport { zoomIn, zoomOut, type Box, type FrozenDragTransform } from './zoomTransition';\n\nfunction itemKey(item: GalleryItem | GalleryItemInput): string {\n return item.id ?? item.src;\n}\n\nfunction resolveElement(target: HTMLElement | string): HTMLElement {\n if (typeof target !== 'string') return target;\n const el = document.querySelector<HTMLElement>(target);\n if (!el) throw new Error(`Shoji: no element matches selector \"${target}\"`);\n return el;\n}\n\n/**\n * DESIGN.md §2.7 — lets code that never held a closure reference to a\n * gallery (a callback resolving long after the call site is gone, a\n * separate `<script>`, devtools) reach the live instance anyway, via\n * `Gallery.getInstance()`/`Gallery.instances()`. Two structures kept in\n * lockstep rather than one: the `WeakMap` gives O(1) lookup-by-element\n * without leaking (an entry is only reachable through an element the host\n * still holds a reference to itself), but WeakMaps aren't iterable, so\n * `instances()` needs the parallel `Set` too. The constructor adds to\n * both; `destroy()` removes from both.\n */\nconst instanceRegistry = new WeakMap<HTMLElement, Gallery>();\nconst allInstances = new Set<Gallery>();\n\n/** CLAUDE.md — all user-visible strings go through `locale`; these are the fallback defaults. */\nconst DEFAULT_LOCALE = {\n close: 'Close',\n previous: 'Previous image',\n next: 'Next image',\n showCaption: 'Show caption',\n hideCaption: 'Hide caption',\n fullCaption: 'Full caption', // DESIGN.md §2.3a\n moreControls: 'More controls', // DESIGN.md §3.1a\n};\n\n/**\n * A click that isn't on the image, a button, a video, or an overlay\n * (counter/caption) counts as \"clicked outside the content.\" Walks\n * `event.composedPath()` (captured at dispatch time) rather than\n * `event.target.closest(...)` — a click handler earlier in the same bubble\n * phase can synchronously replace the clicked element's subtree (e.g. a\n * toolbar button swapping its own icon via `innerHTML` in its click\n * handler), which detaches the original target from the document before\n * this listener (attached higher up, on `.shoji-outer`) ever runs;\n * `.closest()` on a detached node finds no ancestors and would wrongly\n * read as \"clicked outside,\" closing the gallery. `composedPath()` isn't\n * affected by DOM mutations that happen after dispatch.\n *\n * Provider video (YouTube/Vimeo): exclude only the actual iframe/mount\n * element, not the entire `.shoji-slide-provider-video` container. This\n * allows clicks on the blank space around the embed (sides, padding-top\n * toolbar inset) to close the gallery, matching image and HTML5 video\n * behaviour. Clicks that land inside the cross-origin iframe never bubble\n * to the parent at all, so no special handling is needed there; `iframe`\n * covers the edge case where the frame hasn't yet captured focus and a\n * click registers on the element itself from the parent-page perspective.\n * `.shoji-video-mount` is the Vimeo SDK wrapper; YouTube uses a bare\n * `<iframe>` directly inside `.shoji-slide-provider-video`.\n *\n * `caption` — a real bug, reported from real usage: `.shoji-caption--video`\n * (DESIGN.md §2.3a) is `pointer-events: none` so a click on it reaches the\n * video's own native controls underneath, which works fine when the video\n * fills enough of the slide to actually BE underneath it. A letterboxed\n * video (narrower or shorter than the dialog, so the caption's own\n * bottom-left position sits over plain `.shoji-slide-media` background\n * instead) has nothing there to click through *to* — the click fell all\n * the way through to a genuine backdrop click, closing the gallery on what\n * was meant as an interaction with the caption/video area, not \"click\n * outside to close.\" `pointer-events: none` is exactly what removes the\n * caption from `composedPath()` in the first place, so this can't be fixed\n * by adding `.shoji-caption` to the selector above (already there — it\n * already protects a normal, non-click-through caption on a photo slide)\n * — checked by coordinates instead, the one place in this function that\n * has to be.\n */\nfunction isBackdropClick(event: MouseEvent, caption: HTMLElement | null): boolean {\n const hitsProtectedElement = event\n .composedPath()\n .some(\n (node) =>\n node instanceof Element &&\n node.matches(\n `.shoji-slide-img, .shoji-video-mount, iframe, .shoji-counter, ${INTERACTIVE_CONTROL_SELECTOR}`,\n ),\n );\n if (hitsProtectedElement) return false;\n\n if (caption && !caption.hidden && caption.classList.contains('shoji-caption--video')) {\n const rect = caption.getBoundingClientRect();\n const withinCaption =\n event.clientX >= rect.left &&\n event.clientX <= rect.right &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom;\n if (withinCaption) return false;\n }\n\n return true;\n}\n\nfunction isDangerousHtmlCaption(value: unknown): value is DangerousHtmlCaption {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as DangerousHtmlCaption).dangerouslySetInnerHTML === 'string'\n );\n}\n\n/**\n * Core lifecycle (DESIGN.md §2.2), item model / DOM scanning (§2.1), and the\n * lightbox itself: pooled slides (§2.3), dialog semantics/focus trap/live\n * region (§2.6, non-optional), gestures (§2.4, via `GestureController`) and\n * slide-to-slide transitions (§2.5, via `SlideTransition`).\n */\nexport class Gallery {\n /** DESIGN.md §2.7 — the live instance mounted on `el`, or `undefined` if none exists there (or it's since been destroyed). */\n static getInstance(el: HTMLElement): Gallery | undefined {\n return instanceRegistry.get(el);\n }\n\n /** DESIGN.md §2.7 — every live instance, e.g. for page-wide teardown or devtools inspection. */\n static instances(): IterableIterator<Gallery> {\n return allInstances.values();\n }\n\n /** Not `readonly` — `reinit()` (§2.7) reassigns this + every option-derived field below; initializers here just satisfy strict-init. */\n options: GalleryOptions = {};\n readonly element: HTMLElement;\n\n private readonly bus = new EventBus<GalleryEvents>();\n private selector: string = DEFAULT_SELECTOR;\n private isDynamicMode = false;\n private preload = 1;\n private locale: typeof DEFAULT_LOCALE = DEFAULT_LOCALE;\n private showCounter = true;\n private captionVisibleOnVideo = false; // DESIGN.md §2.3a\n // DESIGN.md §2.5 — true from the moment transitionCaption()/open()'s own\n // fade-in starts hiding the caption until the midpoint (or, for open(),\n // the end) where content is swapped and it's revealed again. The async\n // image-load callback in renderCurrentSlide() checks this too, not just\n // the synchronous call in the same function — decode() resolves on a\n // microtask, which can beat the caption's own self-timed reveal for an\n // already-preloaded slide, and updating caption content the instant it\n // fires would show the *new* slide's caption fading, not the outgoing\n // one — same content-swap-timing bug either call site could cause alone.\n private captionFadePending = false;\n private loop = true;\n private closable = true;\n private autoHideDelay: number | false = 5000;\n /** DESIGN.md §3.1a — GalleryOptions.maxPinnedToolbarButtons; see measureToolbarOverflow(). */\n private maxPinnedToolbarButtons = 2;\n private readonly focusTrap = new FocusTrap();\n private readonly liveRegion = new LiveRegion();\n private autoHideTimer: ReturnType<typeof setTimeout> | null = null;\n private autoHidden = false;\n /**\n * Every control `wireControlHover()` has ever wired — the full candidate\n * list `reconcileHover()` (below) checks `:hover` against, kept separate\n * from `hoveringElements` (elements *believed* to be hovered) so\n * reconciliation can also *add* one currently missing from that set, not\n * just remove a stale one.\n */\n private readonly hoverableElements = new Set<HTMLElement>();\n /**\n * The subset of `hoverableElements` the pointer is currently considered\n * to be over — a `Set`, not a plain incrementing counter, so\n * `onActivity()` (below) can reconcile it against the browser's own live\n * `:hover` ground truth on every real pointer movement, self-healing from\n * a `pointerenter`/`pointerleave` pair that never fired at all. Two real\n * bugs, both reported from real usage, both variations on the same\n * browser behavior already leveraged elsewhere in this file (`hidden`\n * doesn't fire `pointerleave` under a stationary cursor, §2.3a): (1) a\n * control that synchronously replaces its own children while the pointer\n * sits stationary over it (Autoplay's own play/pause icon swap) can\n * desync the browser's internal hover-chain tracking badly enough that\n * the *next* real pointer movement away from it never fires `pointerleave`\n * — a plain counter has no way to detect a leave that never reports\n * itself. (2) the mirror image: a control that *appears* under an\n * already-stationary cursor (the common case right after `open()` —\n * whatever the viewer clicked to get here is often right where a\n * toolbar/caption/nav control ends up) never gets a `pointerenter`\n * either, since browsers only recompute hover state on actual pointer\n * movement, not on an element materializing under one already sitting\n * still — so idle auto-hide could fire and hide a control the viewer's\n * cursor is, visibly, still resting directly on top of. Re-deriving \"is\n * this actually hovered\" fresh from the browser on every real pointer\n * move fixes both directions at once, since neither depends on any\n * event having fired correctly in the first place.\n */\n private readonly hoveringElements = new Set<HTMLElement>();\n private isClosing = false;\n /** True while a vertical drag has hidden controls past its own distance threshold (`setControlsHiddenForDrag`) — `onActivity()` defers to it, since the drag's own continuous pointermove stream would otherwise immediately re-reveal what it just hid on every single move. */\n private controlsHiddenByDrag = false;\n private itemList: GalleryItem[] = [];\n private scannedElements: HTMLElement[] = [];\n private activeIndex = 0;\n private opened = false;\n private destroyed = false;\n private slides: SlideManager | null = null;\n private dom: LightboxDom | null = null;\n private gesture: GestureController | null = null;\n private transition: SlideTransition | null = null;\n /** DESIGN.md §2.3a — measures `.shoji-toolbar`'s real rendered height (it can wrap to multiple rows on a narrow viewport with many toolbar buttons registered) so the caption's own height cap can reserve exactly that much space, not a fixed single-row guess. */\n private toolbarHeightObserver: ResizeObserver | null = null;\n private toolbarHeightFrame: number | null = null;\n private captionTruncationFrame: number | null = null;\n /** DESIGN.md §2.3a — a truncated caption's own click/Enter/Space target opens this; also gates `GestureController`'s `isZoomed` (alongside the real zoom gate) so a drag over the open modal can't also navigate/close the lightbox underneath it. */\n private captionModalOpen = false;\n private captionModalReturnFocus: HTMLElement | null = null;\n /**\n * DESIGN.md §2.3a — every real path into `openCaptionModal()` starts from\n * a click *or* a keydown on the caption, so `captionModalReturnFocus`\n * above is always the caption itself either way; this instead\n * distinguishes *how* it got there, so `closeCaptionModal()` only\n * actually calls `.focus()` for the keyboard path (a real Tab+Enter user,\n * where restoring focus continues their tab sequence correctly) and\n * leaves it alone for a mouse click (where the resulting focus was\n * purely incidental — nothing about clicking to read a caption means the\n * *next* keypress, e.g. a plugin's own Space shortcut, should still\n * silently target it).\n */\n private captionModalOpenedViaKeyboard = false;\n /**\n * DESIGN.md §3.1a — every `ctx.ui.toolbar()`-registered button, in\n * registration order, alongside the slot it was registered into (so a\n * collapsed one can be restored to the right place, not just anywhere).\n * Registration order is what decides overflow priority: up to\n * `maxPinnedToolbarButtons` stay pinned, the rest collapse into the\n * popover before them, latest-registered first — see\n * `measureToolbarOverflow()`.\n */\n private readonly pluginToolbarButtons: Array<{\n el: HTMLElement;\n slot: 'left' | 'center' | 'right';\n }> = [];\n private toolbarOverflowOpen = false;\n private toolbarOverflowReturnFocus: HTMLElement | null = null;\n private readonly shortcuts = new Map<string, (e: KeyboardEvent) => void>();\n private readonly pluginStorage = new Map<string, unknown>();\n /** Backs `getActivePlugins()`. */\n private readonly activePluginNames = new Set<string>();\n private readonly videoProviders = new Map<string, VideoProviderRenderer>();\n private zoomGate: (() => boolean) | null = null;\n /** DESIGN.md §2.6a/§4.6 — the zoomed `<img>`'s own real on-screen rect, read by `beginClose()` before `beforeClose` fires (see `registerZoomStartProvider()`), so a button-close continues the zoom-out from wherever the viewer was actually zoomed/panned to instead of snapping back to neutral first. */\n private zoomStartProvider: (() => Box | null) | null = null;\n /** DESIGN.md §2.5/§4.5 — plugins with a per-slide visual override (RotateFlip's rotate/flip, Zoom's scale/pan) that reset unanimated on `beforeSlide` (must clear before `SlideManager.render()` reparents the outgoing node). Multi-slot: more than one can be active on the same slide, each targeting a different part of the clone, so they don't conflict. See `registerSlideLeaveDecorator()`. */\n private readonly slideLeaveDecorators = new Set<\n (clonedMedia: HTMLElement) => (() => void) | void\n >();\n private pluginCleanups: Array<() => void> = [];\n\n private readonly onContainerClick = (event: MouseEvent): void => {\n let node = event.target as Node | null;\n while (node && node !== this.element) {\n if (node instanceof HTMLElement) {\n const index = this.scannedElements.indexOf(node);\n if (index !== -1) {\n event.preventDefault();\n this.open(index);\n return;\n }\n }\n node = node.parentNode;\n }\n };\n\n private readonly onOuterClick = (event: MouseEvent): void => {\n if (this.closable && isBackdropClick(event, this.dom?.caption ?? null)) this.close();\n };\n\n /**\n * DESIGN.md §2.8 — any interaction re-shows controls, restarts the idle\n * clock. `autoHideDelay: 0` = \"never show controls\" — a no-op here.\n * `autoHideDelay: false` = \"always visible\" — also a no-op: nothing to\n * reveal (already shown) or reschedule (no timer ever runs). Also a no-op\n * once `isClosing` — a real bug, reported from real usage: moving the\n * mouse during close()'s own controls-fade-then-zoom-out sequence (§2.6a)\n * re-showed the just-hidden controls mid-animation, since these listeners\n * stay wired for the whole close sequence. Same reasoning for\n * `controlsHiddenByDrag` (§2.4/§2.8): a vertical drag's own `pointermove`\n * stream would otherwise re-reveal what it just hid, every single frame.\n */\n private readonly onActivity = (): void => {\n this.reconcileHover();\n if (\n this.autoHideDelay === 0 ||\n this.autoHideDelay === false ||\n this.isClosing ||\n this.controlsHiddenByDrag ||\n // DESIGN.md §2.3a — requested directly: mouse movement/interaction\n // over the open caption modal shouldn't re-reveal controls already\n // hidden behind it — `dom.outer`'s own pointermove/pointerdown/etc.\n // listeners (below) still see it bubble through, same as any other\n // activity, so without this an idle-hidden toolbar would pop back\n // the instant the viewer so much as moved the mouse to read.\n this.captionModalOpen\n )\n return;\n this.showControls();\n this.scheduleAutoHide();\n };\n\n /** x */\n private controlsHiddenAtGestureStart = false;\n private readonly captureGestureStartState = (): void => {\n this.controlsHiddenAtGestureStart = this.autoHidden;\n };\n\n private readonly onKeydown = (event: KeyboardEvent): void => {\n // A focused <video>'s native controls own arrow/space/home/end for\n // seeking, volume, and play/pause — don't let slide navigation hijack\n // those while the viewer is actually interacting with the video. Escape\n // still closes the gallery regardless.\n if (document.activeElement instanceof HTMLVideoElement && event.key !== 'Escape') return;\n\n this.onActivity();\n switch (event.key) {\n case 'Escape':\n if (this.closable) this.close();\n break;\n case 'ArrowLeft':\n case 'a':\n case 'A':\n this.prev();\n break;\n case 'ArrowRight':\n case 'd':\n case 'D':\n this.next();\n break;\n case 'Home':\n this.goTo(0);\n break;\n case 'End':\n this.goTo(this.itemList.length - 1);\n break;\n default: {\n // DESIGN.md §3 — ctx.ui.registerShortcut(); unhandled keys still\n // fall through with no preventDefault, same as before plugins existed.\n const shortcut = this.shortcuts.get(event.key);\n if (!shortcut) return;\n shortcut(event);\n }\n }\n event.preventDefault();\n };\n\n /**\n * DESIGN.md §2.3a — capture phase, added only while the caption modal is\n * open (not from `open()` onward like `onKeydown`, which is bubble\n * phase): capture always finishes before bubble starts, so\n * `stopPropagation()` here reliably beats `onKeydown`'s own bubble-phase\n * handling regardless of where in the dialog focus happens to be. A real\n * bug, reported from real usage: an earlier version of this only special-\n * cased `Escape`, leaving every other key (`Space` — Autoplay's own\n * play/pause shortcut if that plugin's loaded, arrow keys, `w`/`s` for\n * Zoom, any plugin-registered shortcut) to fall straight through to\n * `onKeydown` while the modal sat open on screen. A modal dialog should\n * make the background fully inert to keyboard input while it's open, not\n * just for one key — so this now stops propagation for *every* key\n * unconditionally, closing the modal as the one piece of extra behavior\n * layered on top for `Escape` specifically. Deliberately no\n * `preventDefault()` here — the modal's own contents (the close button,\n * a scrollable panel) keep their normal native key behavior (Space\n * activating a focused button, arrow/Space scrolling), only the\n * *background* gallery is what this isolates it from.\n */\n private readonly onCaptionModalKeydown = (event: KeyboardEvent): void => {\n event.stopPropagation();\n if (event.key === 'Escape') this.closeCaptionModal();\n };\n\n constructor(target: HTMLElement | string, options: GalleryOptions = {}) {\n this.element = resolveElement(target);\n instanceRegistry.set(this.element, this);\n allInstances.add(this);\n this.applyOptions(options);\n }\n\n /** Everything the constructor does after `this.element` is resolved — shared with `reinit()` (§2.7). */\n private applyOptions(options: GalleryOptions): void {\n this.options = options;\n this.selector = options.selector ?? DEFAULT_SELECTOR;\n this.isDynamicMode = options.items !== undefined;\n this.preload = options.preload ?? 1;\n this.locale = { ...DEFAULT_LOCALE, ...options.locale };\n this.showCounter = options.counter ?? true;\n this.loop = options.loop ?? true;\n this.closable = options.closable ?? true;\n this.autoHideDelay = options.autoHideDelay ?? 5000;\n this.maxPinnedToolbarButtons = options.maxPinnedToolbarButtons ?? 2;\n // Reset explicitly — a reinit() call must not inherit these from before.\n this.activeIndex = 0;\n this.scannedElements = [];\n\n if (this.isDynamicMode) {\n this.itemList = resolveDynamicVideoItems(options.items ?? []);\n } else {\n const scanned = scanContainer(this.element, this.selector);\n this.itemList = scanned.map((s) => s.item);\n this.scannedElements = scanned.map((s) => s.element);\n this.element.addEventListener('click', this.onContainerClick);\n }\n\n // DESIGN.md §3.1 — plugins init here, at construction, not lazily on\n // first open(): a layout plugin needs to render the *inline* container\n // (this.element, always available) before open() is ever called — it's\n // what the viewer clicks to open in the first place. ensureLightbox()'s\n // `if (this.dom) return;` guard makes the later, harmless no-op call\n // from open() safe; building the (hidden, display:none until opened)\n // lightbox DOM this early costs one inert subtree per instance, which is\n // negligible next to the thumbnail images already loading regardless.\n this.ensureLightbox();\n // Set after ensureLightbox() (not inside it) so a reinit() with a\n // different `closable` value updates the already-built button too —\n // ensureLightbox() only builds the DOM once (`if (this.dom) return;`).\n this.dom!.closeButton.hidden = !this.closable;\n\n // Default is closed — the host clicks a thumbnail or calls open()\n // itself. openOnInit is the explicit, opt-in exception (deep-link-style\n // integrations); guarded on having at least one item so an empty\n // gallery can't \"open\" onto nothing.\n if (options.openOnInit && this.itemList.length > 0) {\n this.open(options.index ?? 0);\n }\n }\n\n get items(): readonly GalleryItem[] {\n return this.itemList;\n }\n\n get currentIndex(): number {\n return this.activeIndex;\n }\n\n /** True from the first `open()` until `close()`/`destroy()`. */\n get isOpen(): boolean {\n return this.opened;\n }\n\n /** True once `destroy()` has run. */\n get isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /** Whether auto-hide (§2.8) currently has controls faded. */\n get controlsHidden(): boolean {\n return this.autoHidden;\n }\n\n /** Names of plugins that actually initialized. */\n getActivePlugins(): string[] {\n return [...this.activePluginNames];\n }\n\n /** The active slide's `.shoji-slide-media` container. Empty before the first `open()`; `null` only after `destroy()`. */\n getActiveMedia(): HTMLElement | null {\n return this.slides?.getActiveMedia() ?? null;\n }\n\n /** DESIGN.md §4-zoom — suspends drag-to-navigate/close while zoomed. Single slot, not a multi-subscriber event. */\n registerZoomGate(isZoomed: () => boolean): () => void {\n this.zoomGate = isZoomed;\n return () => {\n if (this.zoomGate === isZoomed) this.zoomGate = null;\n };\n }\n\n /** DESIGN.md §2.6a/§4.6 — returns the zoomed image's current on-screen rect (`getBoundingClientRect()`), or `null` when not zoomed. Single slot, same pattern as `registerZoomGate` above. */\n registerZoomStartProvider(provider: () => Box | null): () => void {\n this.zoomStartProvider = provider;\n return () => {\n if (this.zoomStartProvider === provider) this.zoomStartProvider = null;\n };\n }\n\n /**\n * DESIGN.md §2.5/§4.5 — called once per navigation with the leave-\n * ghost's clone, right after `SlideTransition` creates it. Freeze\n * whatever per-slide visual state is about to be reset onto the clone\n * (or a descendant, e.g. Zoom's own `<img>`) and return a `() => void`\n * to trigger the transition back to neutral once committed — or return\n * nothing if there's nothing to animate away this time.\n */\n registerSlideLeaveDecorator(\n decorator: (clonedMedia: HTMLElement) => (() => void) | void,\n ): () => void {\n this.slideLeaveDecorators.add(decorator);\n return () => {\n this.slideLeaveDecorators.delete(decorator);\n };\n }\n\n on<K extends keyof GalleryEvents>(event: K, fn: (detail: GalleryEvents[K]) => void): Unsubscribe {\n return this.bus.on(event, fn);\n }\n\n private clampToRange(index: number): number {\n return Math.min(Math.max(index, 0), Math.max(this.itemList.length - 1, 0));\n }\n\n private ensureLightbox(): void {\n if (this.dom) return;\n this.slides = new SlideManager({\n preload: this.preload,\n videoProviders: this.videoProviders,\n });\n this.transition = new SlideTransition(this.slides, (clonedMedia) => {\n const settlers: Array<() => void> = [];\n for (const decorate of this.slideLeaveDecorators) {\n const settle = decorate(clonedMedia);\n if (settle) settlers.push(settle);\n }\n return () => {\n for (const settle of settlers) settle();\n };\n });\n const dom = buildLightboxDom(this.slides.element, this.locale);\n this.dom = dom;\n if (this.options.backdropOpacity != null) {\n const clamped = Math.min(Math.max(this.options.backdropOpacity, 0), 1);\n dom.outer.style.setProperty('--shoji-backdrop-opacity', String(clamped));\n }\n if (this.options.transitionDuration != null) {\n const clamped = Math.max(this.options.transitionDuration, 0);\n dom.outer.style.setProperty('--shoji-duration', `${clamped}ms`);\n }\n // DESIGN.md §2.8 — autoHideDelay: 0 means Shoji's own controls stay\n // permanently invisible (a host building fully custom chrome), not that\n // the whole gallery should behave like nothing is there — the mouse\n // cursor itself should still behave normally, not force-hidden along\n // with controls that were never meant to be seen in the first place.\n // Requested directly; `.shoji-cursor-visible` overrides the\n // `.shoji-controls-hidden` cursor:none rule via higher specificity.\n if (this.autoHideDelay === 0) dom.dialog.classList.add('shoji-cursor-visible');\n dom.outer.appendChild(this.liveRegion.element);\n dom.closeButton.addEventListener('click', () => this.close());\n dom.prevButton.addEventListener('click', () => this.prev());\n dom.nextButton.addEventListener('click', () => this.next());\n dom.captionToggleButton.addEventListener('click', () => {\n this.captionVisibleOnVideo = !this.captionVisibleOnVideo;\n this.updateCaptionVisibility();\n });\n dom.caption.addEventListener('click', this.onCaptionActivate);\n dom.caption.addEventListener('keydown', this.onCaptionActivate);\n dom.captionModalCloseButton.addEventListener('click', () => this.closeCaptionModal());\n // Closes on a genuine backdrop click (the modal element itself, not a\n // descendant) — always stops propagation regardless, since without it\n // *any* click anywhere inside the modal (the panel, its content, even\n // the close button) would keep bubbling up to onOuterClick below and\n // get misread as \"clicked outside the real content,\" closing the whole\n // lightbox out from under it.\n dom.captionModal.addEventListener('click', (event) => {\n event.stopPropagation();\n if (event.target === dom.captionModal) this.closeCaptionModal();\n });\n dom.toolbarOverflowButton.addEventListener('click', (event) => {\n event.stopPropagation();\n this.toggleToolbarOverflow();\n });\n // Closes on any click outside the panel and off the caret itself —\n // registered ahead of onOuterClick below (same-node listeners run in\n // registration order) so it can stop the click there too, the same\n // reasoning the caption modal's own backdrop-click listener above uses:\n // without it, a click that closes the popover would also keep bubbling\n // and get misread by onOuterClick as \"clicked outside the real\n // content,\" closing the whole lightbox in the same click.\n dom.outer.addEventListener('click', (event) => {\n if (!this.toolbarOverflowOpen) return;\n // event.composedPath(), not event.target — a real bug, found testing\n // this against Autoplay's own play/pause button (icon-swap-on-click,\n // same class of button CLAUDE.md/DESIGN.md §2.8 already documents):\n // if the click's own handler replaces the button's innerHTML\n // synchronously (as that pattern does), `event.target` can already be\n // a now-detached node by the time this bubble-phase listener runs —\n // `.contains(target)` then reads false even though the click\n // genuinely originated inside the panel, and the popover (wrongly)\n // closes out from under the very button that was just clicked.\n // composedPath() is captured at dispatch time, before any such\n // mutation, so it stays accurate regardless.\n const insidePanel = event\n .composedPath()\n .some((node) => node === dom.toolbarOverflowPanel || node === dom.toolbarOverflowButton);\n if (insidePanel) return;\n event.stopPropagation();\n this.closeToolbarOverflow();\n });\n dom.outer.addEventListener('click', this.onOuterClick);\n dom.outer.addEventListener('pointermove', this.onActivity, { passive: true });\n // Registered before onActivity's own pointerdown listener — order matters, see captureGestureStartState's doc comment.\n dom.outer.addEventListener('pointerdown', this.captureGestureStartState, { passive: true });\n dom.outer.addEventListener('pointerdown', this.onActivity, { passive: true });\n dom.outer.addEventListener('touchstart', this.onActivity, { passive: true });\n dom.outer.addEventListener('wheel', this.onActivity, { passive: true });\n dom.outer.addEventListener('focusin', this.onActivity);\n dom.outer.addEventListener('focusout', () => this.scheduleAutoHide());\n\n // Hovering pauses auto-hide (pointermove alone wouldn't catch a still\n // mouse) — every part of the overlay, not just individual buttons\n // (toolbarLeft/Center/Right cover the bar's own padding/gaps too, not\n // just the buttons already nested inside them). Plugin toolbar\n // buttons/overlays get this wiring at their own call sites.\n for (const el of [\n dom.closeButton,\n dom.prevButton,\n dom.nextButton,\n dom.captionToggleButton,\n dom.caption,\n dom.captionModalPanel,\n dom.counter,\n dom.toolbarLeft,\n dom.toolbarCenter,\n dom.toolbarRight,\n ]) {\n this.wireControlHover(el);\n }\n\n document.body.appendChild(dom.outer);\n\n // DESIGN.md §2.3a — a fixed single-row assumption undercounted a busy\n // toolbar (many plugins registering buttons) wrapping to multiple rows\n // on a narrow viewport, letting the caption's own height cap grow up\n // over the real controls instead of stopping below them. Measuring the\n // real rendered height instead of guessing is correct regardless of\n // plugin count or viewport width. rAF-batched, same pattern the Layout\n // plugin's own resize handling already uses (CLAUDE.md: batch DOM\n // writes that can thrash layout).\n this.toolbarHeightObserver = new ResizeObserver(() => this.scheduleToolbarOverflowMeasure());\n this.toolbarHeightObserver.observe(dom.toolbar);\n\n // DESIGN.md §2.4 — attached to the whole dialog (not just .shoji-slides)\n // so vertical swipe-to-close works from anywhere in it, not only over\n // the image; shouldIgnoreGesture() excludes real controls so their\n // native click/touch behavior is unaffected.\n this.gesture = new GestureController(\n {\n dialog: dom.dialog,\n caption: dom.caption,\n slides: this.slides,\n canGoNext: () => this.loop || this.activeIndex < this.itemList.length - 1,\n canGoPrev: () => this.loop || this.activeIndex > 0,\n // animate:false — a completed swipe already played its own\n // live-drag/settle animation (§2.4); running the §2.5 `mode`\n // transition on top would double-animate. See navigate()'s doc.\n next: () => this.navigate(this.nextIndex(), 1, false),\n prev: () => this.navigate(this.prevIndex(), -1, false),\n close: () => this.close(),\n closeFromSwipe: (frozenDrag) => this.closeFromSwipe(frozenDrag),\n setControlsHiddenForDrag: (hidden) => this.setControlsHiddenForDrag(hidden),\n canClose: () => this.closable,\n onActivity: () => this.onActivity(),\n // DESIGN.md §2.3a — also suspends drag-to-navigate/close while the\n // caption modal is open, same mechanism the Zoom plugin's own gate\n // already uses, so a drag starting over the modal can't also\n // navigate/close the lightbox underneath it.\n isZoomed: () =>\n (this.zoomGate?.() ?? false) || this.captionModalOpen || this.toolbarOverflowOpen,\n },\n {\n onTap: (x, y) =>\n this.bus.emit('tap', {\n x,\n y,\n controlsWereHidden: this.controlsHiddenAtGestureStart,\n }),\n onDoubleTap: (x, y) => this.bus.emit('doubleTap', { x, y }),\n onPinchStart: (centerX, centerY) => this.bus.emit('pinchStart', { centerX, centerY }),\n onPinchMove: (scale, centerX, centerY) =>\n this.bus.emit('pinchMove', { scale, centerX, centerY }),\n onPinchEnd: () => this.bus.emit('pinchEnd', {}),\n onWheelZoom: (deltaScale, x, y) => this.bus.emit('wheelZoom', { deltaScale, x, y }),\n },\n this.options.gestures,\n );\n\n this.initPlugins();\n }\n\n /**\n * DESIGN.md §3 — which of `declared`'s plugins will actually load,\n * resolved as a fixed point rather than a single pass: start with every\n * *structurally* valid entry (a real object with an `init` function),\n * then repeatedly drop any whose `requires` points at a name no longer\n * in the set, until a full pass drops nothing. That repetition is what\n * makes a chain cascade correctly — if a plugin gets dropped because\n * *its* own requirement failed, anything requiring that plugin drops on\n * the very next pass, the same as if the original problem were its own.\n * A genuine mutual requirement (A needs B, B needs A, both otherwise\n * fine) never gets caught in this — each still finds the other present\n * whenever it's checked, so both stay valid. That's correct, not a\n * missed case: this only ever decides *whether* something loads, never\n * *when* — nothing here reorders execution, so two plugins depending on\n * each other creates no actual ordering conflict to detect in the first\n * place.\n */\n private resolveValidPluginNames(declared: readonly ShojiPlugin[]): Set<string> {\n const validNames = new Set<string>();\n for (const plugin of declared) {\n if (plugin && typeof plugin.init === 'function') validNames.add(plugin.name);\n }\n let changed = true;\n while (changed) {\n changed = false;\n for (const plugin of declared) {\n if (!plugin || typeof plugin.init !== 'function' || !validNames.has(plugin.name)) continue;\n const unmet = (plugin.requires ?? []).some((name) => !validNames.has(name));\n if (unmet) {\n validNames.delete(plugin.name);\n changed = true;\n }\n }\n }\n return validNames;\n }\n\n /**\n * DESIGN.md §3 — plugins init here, not the constructor. `requires` is\n * resolved against the *whole* declared `plugins` list up front, not\n * registration order — a real friction point, reported directly: a host\n * with a `requires` chain had to carefully order the array by hand, with\n * no actual reason to (nothing about *execution* order needs to match\n * declaration order for a name-presence check). `resolveValidPluginNames()`\n * decides who's actually going to load, independent of position; this\n * loop still runs — and every `ctx.ui.toolbar()` registration still\n * lands — in exactly the array's own order regardless, so toolbar/\n * collapse-priority order (also array-order-driven, DESIGN.md §3.1a)\n * is completely unaffected by this. Cleared up front so a `reinit()`\n * doesn't inherit names from before.\n */\n private initPlugins(): void {\n this.activePluginNames.clear();\n this.videoProviders.clear();\n const declared = this.options.plugins ?? [];\n const validNames = this.resolveValidPluginNames(declared);\n\n for (const plugin of declared) {\n // Guards a real, easy-to-hit host mistake: `plugins: [Shoji.SomePlugin]`\n // silently becomes `plugins: [undefined]` if the referenced static\n // (e.g. Shoji.Autoplay) doesn't actually exist yet — a stale dist\n // build predating that plugin's addition is the most common cause.\n // One bad entry shouldn't crash plugin init for every entry after it.\n if (!plugin || typeof plugin.init !== 'function') {\n console.error(\n 'Shoji: skipping an invalid plugins[] entry (not a ShojiPlugin object):',\n plugin,\n );\n continue;\n }\n if (!validNames.has(plugin.name)) {\n const missing = (plugin.requires ?? []).filter((name) => !validNames.has(name));\n console.error(\n `Shoji: plugin \"${plugin.name}\" requires [${missing.join(', ')}], which failed to load (missing, invalid, or itself had an unmet requires) — skipping.`,\n );\n continue;\n }\n\n const pluginOptions: Record<string, unknown> = {\n ...plugin.defaults,\n ...(this.options[plugin.name] as Record<string, unknown> | undefined),\n };\n const ctx: PluginContext = {\n gallery: this,\n options: pluginOptions,\n on: this.on.bind(this),\n emit: (event, detail) => this.bus.emit(event, detail),\n ui: {\n toolbar: (slot, el) => this.pluginToolbar(slot, el),\n overlay: (el, layer) => this.pluginOverlay(el, layer),\n outer: () => this.dom!.outer,\n registerShortcut: (key, fn) => {\n this.shortcuts.set(key, fn);\n return () => this.shortcuts.delete(key);\n },\n registerVideoProvider: (name, render) => {\n this.videoProviders.set(name, render);\n return () => {\n if (this.videoProviders.get(name) === render) this.videoProviders.delete(name);\n };\n },\n },\n storage: {\n get: (key) => this.pluginStorage.get(key),\n set: (key, value) => {\n this.pluginStorage.set(key, value);\n },\n },\n };\n\n const cleanup = plugin.init(ctx);\n if (typeof cleanup === 'function') this.pluginCleanups.push(cleanup);\n this.activePluginNames.add(plugin.name);\n }\n }\n\n /**\n * DESIGN.md §3.1 — 'right' inserts immediately before the overflow caret\n * (DESIGN.md §3.1a — never after, and never after close either), so\n * close stays fixed absolute-rightmost, the caret sits just to its left,\n * and plugins cluster further left still, in registration order:\n * `plugins: [A, B, C]` reads A, B, C, caret, close. 'left'/'center' are\n * independent zones for a plugin that doesn't want to sit next to close.\n */\n private pluginToolbar(\n slot: 'left' | 'center' | 'right',\n el: HTMLElement | ButtonSpec,\n ): Unsubscribe {\n const dom = this.dom!;\n // buildToolbarButton() below already wires hover for ButtonSpec; a raw\n // element needs it here instead, once, not double-wired either way.\n const isRawElement = el instanceof HTMLElement;\n const node = isRawElement ? el : this.buildToolbarButton(el);\n const unhover = isRawElement ? this.wireControlHover(node) : null;\n if (slot === 'right') {\n dom.toolbarRight.insertBefore(node, dom.toolbarOverflowButton);\n } else {\n (slot === 'left' ? dom.toolbarLeft : dom.toolbarCenter).appendChild(node);\n }\n this.pluginToolbarButtons.push({ el: node, slot });\n this.scheduleToolbarOverflowMeasure();\n return () => {\n unhover?.();\n node.remove();\n const index = this.pluginToolbarButtons.findIndex((b) => b.el === node);\n if (index !== -1) this.pluginToolbarButtons.splice(index, 1);\n this.scheduleToolbarOverflowMeasure();\n };\n }\n\n private buildToolbarButton(spec: ButtonSpec): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n if (spec.icon) {\n button.ariaLabel = button.title = spec.label;\n button.innerHTML = spec.icon;\n } else {\n button.textContent = spec.label;\n }\n button.addEventListener('click', spec.onClick);\n this.wireControlHover(button);\n return button;\n }\n\n /**\n * DESIGN.md §3.1a — coalesces both toolbar-overflow measurement and the\n * pre-existing `--shoji-toolbar-height` update into one rAF-batched pass\n * (CLAUDE.md: batch DOM writes that can thrash layout), triggered by the\n * toolbar's own `ResizeObserver` (width *or* height changes — a busy\n * toolbar wrapping counts as both) and by `pluginToolbar()` registering\n * or unregistering a button. Order matters: overflow collapse has to run\n * *before* the height read, so the height custom property reflects the\n * settled (ideally single-row, post-collapse) toolbar, not a momentarily\n * wrapped one the caption's own height cap would otherwise over-reserve\n * space for.\n */\n private scheduleToolbarOverflowMeasure(): void {\n if (this.toolbarHeightFrame !== null) return;\n this.toolbarHeightFrame = requestAnimationFrame(() => {\n this.toolbarHeightFrame = null;\n if (!this.dom) return;\n this.measureToolbarOverflow();\n this.dom.dialog.style.setProperty(\n '--shoji-toolbar-height',\n `${this.dom.toolbar.getBoundingClientRect().height}px`,\n );\n });\n }\n\n /**\n * DESIGN.md §3.1a — collapses plugin toolbar buttons into\n * `toolbarOverflowPanel` once they don't fit in one row, instead of\n * letting the toolbar wrap to a second/third one. Always restores every\n * plugin button to its own original slot first and recomputes from that\n * clean slate, rather than incrementally adjusting whatever the previous\n * pass left behind — the *set* of buttons and the viewport width can\n * both have changed since then, and a fresh, deterministic pass is both\n * simpler and self-correcting than trying to reason about a delta.\n *\n * \"Fits in one row\" is measured, not assumed: each slot's own rendered\n * height is compared against `closeButton`'s (always exactly one row\n * tall, always present) — a slot has wrapped if it's taller than that,\n * regardless of *which* slot a plugin happened to register into (the\n * three slots wrap independently, DESIGN.md §3.1a's own CSS notes).\n *\n * Collapses latest-registered first (DESIGN.md §3's own registration-\n * order-is-priority convention — `plugins: [A, B, C]` keeps A pinned\n * before B/C). `maxPinnedToolbarButtons` (default 2, see\n * `GalleryOptions.maxPinnedToolbarButtons`) is a ceiling, not a\n * guarantee: collapsing always goes down to at most that many pinned,\n * but keeps going *below* it — down to zero if it must — whenever even\n * that many still leaves a slot wrapped. `closeButton` and the counter\n * (`toolbarLeft`) must never wrap onto their own line, and `fitsOneRow()`\n * already checks every slot's height, not just `toolbarRight`'s, so a\n * wide counter or other left-slot content competing for the same row\n * pushes the pinned count down too, not just the right slot's own\n * button count. `closeButton`/`toolbarOverflowButton` themselves are\n * never candidates for collapse — everything else relocates into the\n * popover, which renders directly below that row.\n */\n private measureToolbarOverflow(): void {\n if (!this.dom) return;\n const dom = this.dom;\n for (const { el, slot } of this.pluginToolbarButtons) {\n if (slot === 'right') dom.toolbarRight.insertBefore(el, dom.toolbarOverflowButton);\n else (slot === 'left' ? dom.toolbarLeft : dom.toolbarCenter).appendChild(el);\n }\n dom.toolbarOverflowPanel.replaceChildren();\n dom.toolbarOverflowButton.hidden = true;\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n\n const rowHeight = dom.closeButton.getBoundingClientRect().height;\n const fitsOneRow = (): boolean =>\n [dom.toolbarLeft, dom.toolbarCenter, dom.toolbarRight].every(\n (slotEl) => slotEl.getBoundingClientRect().height <= rowHeight + 1,\n );\n\n if (fitsOneRow()) return;\n\n const pinnedCeiling = Math.min(this.maxPinnedToolbarButtons, this.pluginToolbarButtons.length);\n dom.toolbarOverflowButton.hidden = false;\n for (let i = this.pluginToolbarButtons.length - 1; i >= 0; i--) {\n // Below the ceiling, stop as soon as it fits; at/above it, keep\n // collapsing regardless of fit — the ceiling is enforced first, then\n // fit is what decides whether to go further still.\n if (i < pinnedCeiling && fitsOneRow()) break;\n // Collapsed latest-registered first (the decision above), but\n // inserted at the *front* of the panel each time — the panel should\n // read in the same left-to-right registration order the toolbar row\n // itself would have shown, not reversed just because that's the order\n // they were evaluated in.\n dom.toolbarOverflowPanel.insertBefore(\n this.pluginToolbarButtons[i]!.el,\n dom.toolbarOverflowPanel.firstChild,\n );\n }\n }\n\n private readonly onToolbarOverflowKeydown = (event: KeyboardEvent): void => {\n event.stopPropagation();\n if (event.key === 'Escape') this.closeToolbarOverflow();\n };\n\n private toggleToolbarOverflow(): void {\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n else this.openToolbarOverflow();\n }\n\n private openToolbarOverflow(): void {\n if (!this.dom || this.toolbarOverflowOpen) return;\n this.toolbarOverflowReturnFocus = document.activeElement as HTMLElement | null;\n this.dom.toolbarOverflowPanel.hidden = false;\n this.positionToolbarOverflowPanel();\n this.dom.toolbarOverflowButton.setAttribute('aria-expanded', 'true');\n this.toolbarOverflowOpen = true;\n this.focusTrap.retarget(this.dom.toolbarOverflowPanel);\n document.addEventListener('keydown', this.onToolbarOverflowKeydown, true);\n }\n\n /**\n * DESIGN.md §3.1a — the panel's `right` offset is set here, per open,\n * rather than as a fixed CSS value: the caret's own x-position isn't\n * fixed, it shifts with how many buttons are pinned ahead of it\n * (`maxPinnedToolbarButtons` is host-configurable, and can itself be\n * reduced further at measure time, DESIGN.md §3.1a), so a static\n * `right: var(--shoji-spacing-md)` only happened to line up with the\n * caret at one particular pinned-button count and viewport width. It\n * otherwise anchored to the toolbar/dialog's own right edge — under\n * `closeButton`, which sits to the right of the caret, not under the\n * caret that actually opens it.\n *\n * Aligns the panel's own *content* edge (inside its padding), not just\n * its border box, with the caret's right edge — the panel's grid pitch\n * (44px columns, `--shoji-spacing-sm` gaps, `.shoji-toolbar-overflow-\n * panel` in shoji.css) already matches the toolbar row's own button\n * size/gap, so subtracting the panel's own right padding here is what\n * makes the popover's icon columns actually line up with the toolbar\n * row's icons above them, not just the panel block sitting roughly\n * nearby.\n *\n * Also sets the grid's own column count to match the toolbar row's own\n * column count right now: however many buttons are *actually* still\n * pinned on `toolbarRight`, *plus the caret itself* — requested directly:\n * the popover should read as the same row of columns continuing\n * downward, caret included, not a fixed 3 columns regardless of how many\n * ended up pinned. At the default `maxPinnedToolbarButtons` (2), that's 2\n * pinned + the caret = 3 columns. Collapsed buttons beyond that count\n * still wrap onto further rows within it, same as before.\n *\n * **A real bug: \"pinned\" is counted from `this.pluginToolbarButtons`\n * (registered via `ctx.ui.toolbar()`), never by querying `toolbarRight`'s\n * DOM children.** The old filter (`toolbarRight.children`, excluding\n * `closeButton`/`toolbarOverflowButton` by identity, `!el.hidden`) broke\n * once a host appended an unrelated element straight into `toolbarRight`\n * — not a documented extension point, but nothing stops it. Reported from\n * real usage: a plugin's own loading spinner, toggled via `style.display`\n * rather than the `hidden` attribute, passed `!el.hidden` and got\n * miscounted as a pinned button, turning a 3-column popover into 4.\n * Counting from the registry instead is immune to this regardless of how\n * such an element manages its own visibility. `closeButton`/\n * `toolbarOverflowButton` were never in `pluginToolbarButtons`, so\n * excluding them by identity is no longer needed either.\n */\n private positionToolbarOverflowPanel(): void {\n if (!this.dom) return;\n const {\n dialog,\n toolbarOverflowButton,\n toolbarOverflowPanel,\n toolbarRight,\n captionToggleButton,\n } = this.dom;\n const dialogRight = dialog.getBoundingClientRect().right;\n const caretRight = toolbarOverflowButton.getBoundingClientRect().right;\n const paddingRight = parseFloat(getComputedStyle(toolbarOverflowPanel).paddingRight) || 0;\n const right = dialogRight - caretRight - paddingRight;\n toolbarOverflowPanel.style.right = `${Math.max(0, right)}px`;\n\n // A second real bug, reported from real usage on a video slide: still\n // over/undercounts, even immune to the DOM-parentage issue above.\n // Undercounts by not knowing about `captionToggleButton` at all — a\n // real, space-consuming, never-collapsible button that only exists on\n // video slides, added directly in dom.ts rather than through\n // `ctx.ui.toolbar()`, so it was never in `pluginToolbarButtons` to\n // begin with. Overcounts separately, in the other direction: a\n // registered button hidden for its own content reasons (e.g. Zoom's\n // zoomIn/zoomOut/actualSize buttons hiding themselves on video slides,\n // §4.6) still passes the parentage check — hidden means zero layout\n // size, so `measureToolbarOverflow()`'s collapse loop never needed to\n // move it into the panel, leaving it sitting in `toolbarRight`,\n // invisible but still counted as if it occupied a column. Both fixed\n // by also checking `!b.el.hidden`, and adding one more for\n // `captionToggleButton` whenever it's currently shown.\n const pinnedCount =\n this.pluginToolbarButtons.filter(\n (b) => b.slot === 'right' && b.el.parentElement === toolbarRight && !b.el.hidden,\n ).length + (captionToggleButton.hidden ? 0 : 1);\n const columnCount = pinnedCount + 1; // + the caret itself\n toolbarOverflowPanel.style.gridTemplateColumns = `repeat(${columnCount}, 44px)`;\n }\n\n private closeToolbarOverflow(): void {\n if (!this.dom || !this.toolbarOverflowOpen) return;\n document.removeEventListener('keydown', this.onToolbarOverflowKeydown, true);\n this.dom.toolbarOverflowPanel.hidden = true;\n this.dom.toolbarOverflowButton.setAttribute('aria-expanded', 'false');\n this.toolbarOverflowOpen = false;\n this.focusTrap.retarget(this.dom.dialog);\n this.toolbarOverflowReturnFocus?.focus({ preventScroll: true });\n this.toolbarOverflowReturnFocus = null;\n }\n\n private pluginOverlay(el: HTMLElement, layer?: number): Unsubscribe {\n if (layer !== undefined) el.style.zIndex = String(layer);\n this.dom!.dialog.appendChild(el);\n const unhover = this.wireControlHover(el);\n return () => {\n unhover();\n el.remove();\n };\n }\n\n /** DESIGN.md §2.8/§3 — pauses auto-hide while genuinely hovered: controls, caption, and any plugin overlay (`ctx.ui.overlay()`). Unsubscribe also corrects the set if removed mid-hover — a real risk for overlay content a plugin can toggle while the gallery stays open, unlike static buttons. */\n private wireControlHover(el: HTMLElement): Unsubscribe {\n this.hoverableElements.add(el);\n const onEnter = (): void => {\n this.hoveringElements.add(el);\n this.onActivity();\n };\n const onLeave = (): void => {\n if (!this.hoveringElements.delete(el)) return;\n this.scheduleAutoHide();\n };\n el.addEventListener('pointerenter', onEnter);\n el.addEventListener('pointerleave', onLeave);\n return () => {\n el.removeEventListener('pointerenter', onEnter);\n el.removeEventListener('pointerleave', onLeave);\n this.hoverableElements.delete(el);\n if (this.hoveringElements.delete(el)) this.scheduleAutoHide();\n };\n }\n\n /**\n * DESIGN.md §2.8 — paused only by a real *hover*. Used to also treat a\n * *focused* control as active via `document.activeElement`, but a click\n * leaves a `<button>` focused indefinitely, permanently blocking\n * `hideControls()`. Focus still counts as activity (`focusin` →\n * `onActivity()`), it just no longer blocks the eventual hide.\n */\n private isControlActive(): boolean {\n return this.hoveringElements.size > 0;\n }\n\n /**\n * Syncs `hoveringElements` to the browser's own live `:hover` truth for\n * every registered control — both directions, not just dropping a stale\n * entry: also picks up one that's genuinely hovered but never got a\n * `pointerenter` of its own (see `hoveringElements`'s own doc comment for\n * why either direction can happen). Whichever ends up true here is what\n * `isControlActive()` reads immediately after, in the same `onActivity()`\n * call — no separate reveal step needed for a newly-added element; that\n * call already does it for any activity, hover included. Cheap in\n * practice: `hoverableElements` is normally single digits, and `:hover`\n * matching is a native, already-computed browser check, not a\n * layout-triggering one.\n */\n private reconcileHover(): void {\n for (const el of this.hoverableElements) {\n if (el.matches(':hover')) this.hoveringElements.add(el);\n else this.hoveringElements.delete(el);\n }\n }\n\n /**\n * The thumbnail for `index` — what the zoom transition animates to/from,\n * and what `activeThumbnail` marks/scrolls-to. `data-shoji-id` is an\n * explicit opt-in that works in any mode (needed for dynamic mode, which\n * has no scanned DOM); checked first so it can override selector mode's\n * default `scannedElements[index]` too, e.g. to target an inner element.\n */\n getOriginElement(index: number): HTMLElement | null {\n const item = this.itemList[index];\n if (item?.id && typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {\n const marked = document.querySelector<HTMLElement>(\n `[data-shoji-id=\"${CSS.escape(item.id)}\"]`,\n );\n if (marked) return marked;\n }\n return this.scannedElements[index] ?? null;\n }\n\n /** Lets a plugin's background-page `scrollIntoView()` survive `close()`'s scroll restore, routed through this shared instance rather than importing `bodyScrollLock` directly — required for the standalone core+plugins distribution, where a direct import would get its own disconnected module copy (DESIGN.md §4.2/§10). Same reasoning `getOriginElement`/`getActiveMedia` were made public for. */\n markIntentionalScroll(): void {\n markIntentionalScrollInternal();\n }\n\n private scheduleAutoHide(): void {\n if (this.autoHideTimer !== null) {\n clearTimeout(this.autoHideTimer);\n this.autoHideTimer = null;\n }\n if (!this.opened) return;\n if (this.autoHideDelay === false) return; // always visible — no timer to arm\n if (this.autoHideDelay === 0) {\n this.hideControls(); // 0 = hidden immediately, no reveal — see onActivity\n return;\n }\n this.autoHideTimer = setTimeout(() => this.hideControls(), this.autoHideDelay);\n }\n\n /**\n * Forces the same fade §2.8's idle timer would eventually trigger —\n * public so a plugin can hide controls on its own trigger. Same\n * `isControlActive()` guard as the timer. Also a no-op under\n * `autoHideDelay: false` — a real bug, reported from real usage: Autoplay's\n * tap-to-toggle-chrome behavior called this directly and ignored `false`\n * entirely, since only the idle timer checked it. `false` has to hold for\n * every caller, not just the timer. `forceHideControls()`/\n * `setControlsHiddenForDrag()` (close, drag-to-close) deliberately don't\n * check this — direct user actions with their own feedback, not auto-hide.\n */\n hideControls(): void {\n // A real bug, reported from real usage: an idle timer already ticking\n // down before the caption modal opened isn't cancelled by opening it\n // (DESIGN.md §2.3a) — `onActivity()`'s own `captionModalOpen` guard\n // only stops a *new* timer being armed while it's open, it doesn't stop\n // one already in flight from firing. Left unguarded here, that timer\n // could still call this mid-read, and `.shoji-controls-hidden`'s own\n // `cursor: none` (shoji.css) applies to the whole dialog including the\n // modal's own backdrop/panel — the cursor visibly vanishing over text\n // the viewer is actively reading, not idling on.\n //\n // A real bug, found testing this cross-browser: `hoveringElements` is\n // normally kept in sync by `reconcileHover()` running inside\n // `onActivity()`, on every real pointer event — but that only helps if\n // one actually fires *after* the pointer reaches wherever it's really\n // ending up. Confirmed directly: some browser pointer-simulation paths\n // (reproduced consistently under Firefox automation, though nothing\n // rules out a genuine — if rarer — real-hardware equivalent) fire their\n // last bubbling pointer event mid-transition, before the browser's own\n // `:hover` state has caught up to the pointer's actual final position —\n // reconciling *then* just recorded the wrong, stale answer, and with no\n // further pointer event ever arriving, nothing was left to correct it\n // before this timer fired. A plain counter would have the identical gap\n // (whatever event it's trusted to fire is the same one that didn't).\n // Fixed by re-reconciling right here too, immediately before the\n // decision that actually depends on the answer being fresh — this is\n // the one moment `hoveringElements` being even briefly stale actually\n // matters, so it's also the one moment worth an extra, authoritative\n // check instead of trusting whatever the last activity event happened\n // to leave behind.\n this.reconcileHover();\n if (\n !this.dom ||\n this.autoHidden ||\n this.isControlActive() ||\n this.autoHideDelay === false ||\n this.captionModalOpen ||\n // DESIGN.md §3.1a — same reasoning as `captionModalOpen` immediately\n // above: an idle timer already ticking down before the toolbar\n // overflow popover opened isn't cancelled by opening it, and the\n // popover is anchored to (visually part of) the toolbar this would\n // hide out from under it.\n this.toolbarOverflowOpen\n )\n return;\n this.autoHidden = true;\n this.dom.dialog.classList.add('shoji-controls-hidden');\n this.bus.emit('controls:hide', {});\n }\n\n private showControls(): void {\n if (!this.dom || !this.autoHidden) return;\n this.autoHidden = false;\n this.dom.dialog.classList.remove('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n this.bus.emit('controls:show', {});\n }\n\n /**\n * DESIGN.md §2.1 — `caption` is `string | HTMLElement | DangerousHtmlCaption`:\n * a plain string renders as text (`textContent`, auto-escaped, safe by\n * default); an `HTMLElement` is appended as real DOM (the host built it);\n * `{ dangerouslySetInnerHTML }` renders raw, unescaped HTML via `innerHTML`\n * — Shoji does not sanitize it, the host must, same contract as React's\n * identically-named escape hatch. Returns whether the caption element\n * should be hidden.\n */\n private renderCaption(\n el: HTMLElement,\n caption: string | HTMLElement | DangerousHtmlCaption | undefined,\n ): boolean {\n if (caption instanceof HTMLElement) {\n el.replaceChildren(caption);\n return false;\n }\n if (isDangerousHtmlCaption(caption)) {\n el.innerHTML = caption.dangerouslySetInnerHTML;\n return caption.dangerouslySetInnerHTML === '';\n }\n el.textContent = caption ?? '';\n return !caption;\n }\n\n /**\n * `.shoji-toolbar-button` only — never `.shoji-close`/`.shoji-nav`, which\n * are different classes entirely, so this can't accidentally block\n * closing or navigating away from a slow-loading slide. `tabIndex = -1`\n * (not just the CSS below) so a keyboard user tabbing through the\n * toolbar skips these entirely while disabled, not just visually dims\n * them — `pointer-events: none` alone wouldn't stop Enter/Space\n * activating an already-focused button.\n */\n private setSlideLoading(loading: boolean): void {\n if (!this.dom) return;\n this.dom.outer.classList.toggle('shoji-slide-loading', loading);\n for (const button of this.dom.outer.querySelectorAll<HTMLButtonElement>(\n '.shoji-toolbar-button',\n )) {\n button.ariaDisabled = loading ? 'true' : null;\n if (loading) button.tabIndex = -1;\n else button.removeAttribute('tabindex');\n }\n }\n\n /**\n * DESIGN.md §2.5 — the caption's disappear-then-reappear fits inside the\n * *same* `--shoji-duration` window the slide's own mode animation runs\n * in, not a separate one after it: fades out over the first half, swaps\n * content invisibly at the midpoint, fades back in over the second half\n * — timed to finish exactly when the mode animation does, not still\n * catching up a beat behind it. Self-timed off the resolved\n * `--shoji-duration` value rather than hooked to the mode animation's\n * own completion event: both are driven by the same duration either way,\n * and the fade-in's own completion is what has to line up, which a\n * \"start on completion, then animate\" hook can't give — by definition,\n * a fade started only once something else finishes hasn't finished\n * *with* it.\n */\n private transitionCaption(): void {\n const dom = this.dom;\n if (!dom) return;\n if (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n ) {\n return; // --shoji-duration is already 0ms; nothing to sequence\n }\n\n // .shoji-caption's own `transition: opacity var(--shoji-duration) ...`\n // rule transitions a single property, so the computed shorthand\n // resolves to exactly --shoji-duration's own value — same read as\n // `zoomTransition.ts`/`SlideTransition.ts` already use elsewhere,\n // rather than `getPropertyValue('--shoji-duration')` directly.\n const raw = getComputedStyle(dom.caption).transitionDuration.split(',')[0]?.trim() ?? '';\n const fullMs = raw.endsWith('ms')\n ? parseFloat(raw)\n : raw.endsWith('s')\n ? parseFloat(raw) * 1000\n : 0;\n const half = fullMs / 2;\n\n this.captionFadePending = true;\n dom.caption.style.transitionDuration = `${half}ms`;\n dom.caption.style.opacity = '0';\n\n setTimeout(() => {\n if (!this.dom) return;\n this.captionFadePending = false;\n this.updateCaptionVisibility();\n this.dom.caption.style.opacity = '';\n setTimeout(() => {\n // Only the temporary half-duration override — restores the\n // caption's normal full-duration transition (e.g. for idle\n // auto-hide) once this fade-in has actually finished with it.\n if (this.dom) this.dom.caption.style.transitionDuration = '';\n }, half);\n }, half);\n }\n\n /**\n * Content is always kept current (correct the instant loading finishes,\n * no text flash) — only `hidden` also gates on `isActiveReady()`, so a\n * caption for the *new* slide can't sit there readable while the\n * image/video it describes is still a spinner.\n */\n private updateCaptionVisibility(): void {\n if (!this.dom || !this.slides) return;\n const item = this.itemList[this.activeIndex];\n const noCaption = this.renderCaption(this.dom.caption, item?.caption);\n const isVideo = !!item?.video;\n this.dom.caption.classList.toggle('shoji-caption--video', isVideo);\n const hiddenByToggle = isVideo && !this.captionVisibleOnVideo;\n this.dom.caption.hidden = noCaption || !this.slides.isActiveReady() || hiddenByToggle;\n\n const btn = this.dom.captionToggleButton;\n btn.hidden = !isVideo || noCaption;\n if (!btn.hidden) {\n btn.setAttribute('aria-pressed', String(this.captionVisibleOnVideo));\n btn.ariaLabel = btn.title = this.captionVisibleOnVideo\n ? this.locale.hideCaption\n : this.locale.showCaption;\n }\n this.updateCaptionTruncation();\n // A real bug, reported from real usage: reopening an already-loaded\n // slide (e.g. clicking the same thumbnail twice) skips the async\n // image-decode path entirely — nothing re-runs this measurement once\n // the dialog actually finishes laying out, so the synchronous call\n // above can catch it mid-layout (still effectively 0×0 at that exact\n // point, even though `hidden` itself is already correctly false) and\n // wrongly conclude nothing overflows. A fresh *first* open happens to\n // dodge this because real image decode work is slow enough that by the\n // time it resolves, layout has already settled — not something a\n // reopen (cached, near-instant) can rely on. Re-checking one frame\n // later, after layout has actually been committed, catches the case the\n // synchronous read above can miss without regressing it (the sync call\n // already got it right whenever it can, so this is a rarely-needed\n // correction, not a routine double-measurement).\n if (this.captionTruncationFrame !== null) cancelAnimationFrame(this.captionTruncationFrame);\n this.captionTruncationFrame = requestAnimationFrame(() => {\n this.captionTruncationFrame = null;\n this.updateCaptionTruncation();\n });\n }\n\n /**\n * DESIGN.md §2.3a — the caption's own default height cap (above) already\n * keeps it clear of the toolbar, but says nothing about the vertically-\n * centered prev/next nav arrows sharing its same left edge; a long\n * enough caption could still grow up over one of those. `--shoji-*`\n * collapses it to roughly one line by default (shoji.css) regardless, so\n * this only ever needs to detect whether that collapse actually clipped\n * something — `scrollHeight > clientHeight` after layout, the same\n * technique already used elsewhere in this codebase (and its own tests)\n * to detect caption overflow. Marks it truncated/interactive only when\n * there's genuinely more to read; a caption that already fits shouldn't\n * look or behave clickable.\n *\n * A real bug, reported from real usage: the first version only capped\n * `max-height` + `overflow: hidden` — a plain pixel clip with no regard\n * for where a line of text actually ends, so the cutoff routinely sliced\n * straight through the middle of the last visible line instead of\n * stopping at a clean line boundary, reading as broken rather than\n * intentionally truncated.\n *\n * Two follow-up attempts, both also wrong, both worth recording so they\n * aren't retried: `-webkit-line-clamp` never cleanly stopped at a line\n * boundary here regardless of the line count fed into it. Replacing it\n * with `lines * lineHeight + paddingY` arithmetic (using\n * `getComputedStyle(el).lineHeight`) still left a sliver of the next\n * line visible in a real browser — confirmed by screenshot, not just\n * this sandbox. Root cause: a browser doesn't necessarily lay out N\n * stacked lines at exactly N times the CSS `line-height` value: text\n * layout does its own sub-pixel rounding per line, so arithmetic\n * multiplication drifts from the real rendered geometry by enough to\n * expose part of an extra line, and no fixed safety margin is correct\n * for every font/zoom/line-count combination.\n *\n * This version doesn't compute line boundaries at all — it reads them\n * straight from the browser's own layout via `Range.getClientRects()`,\n * which returns one rect per actual rendered line fragment (rich\n * captions with inline markup can put more than one rect on the same\n * visual row; each is handled independently below rather than grouped,\n * since only the topmost/bottommost edges per row matter here). The cap\n * is set to the bottom edge of the last line whose bottom still fits\n * inside the current (arbitrary, CSS-calc'd) height budget — a real\n * measured boundary, never an assumed one.\n *\n * A third real bug, caught after switching to this measured approach:\n * padding the box out by a full `padding-bottom` past that last line's\n * *measured* bottom still isn't safe, because line boxes butt up much\n * closer together than the padding value — the next (excluded) line's\n * own top can fall well inside that padding band, so its glyph\n * ascenders paint into what was supposed to be empty breathing room.\n * Fixed by also finding that next line's top and never letting the cap\n * reach it, regardless of how much of `padding-bottom` that leaves.\n */\n private updateCaptionTruncation(): void {\n if (!this.dom) return;\n const el = this.dom.caption;\n el.style.removeProperty('max-height');\n const truncated = !el.hidden && el.scrollHeight > el.clientHeight;\n if (truncated) {\n const paddingBottom = parseFloat(getComputedStyle(el).paddingBottom) || 0;\n const budget = el.clientHeight - paddingBottom;\n const elTop = el.getBoundingClientRect().top;\n const range = document.createRange();\n range.selectNodeContents(el);\n let lastFittingBottom = 0;\n let nextLineTop = Infinity;\n for (const rect of range.getClientRects()) {\n if (rect.height === 0) continue;\n const relTop = rect.top - elTop;\n const relBottom = rect.bottom - elTop;\n if (relBottom <= budget) {\n if (relBottom > lastFittingBottom) lastFittingBottom = relBottom;\n } else if (relTop < nextLineTop) {\n nextLineTop = relTop;\n }\n }\n const cutBottom = lastFittingBottom > 0 ? lastFittingBottom : budget;\n const desired = cutBottom + paddingBottom;\n const cap = Number.isFinite(nextLineTop) ? Math.min(desired, nextLineTop) : desired;\n el.style.maxHeight = `${Math.max(0, Math.floor(cap) - 1)}px`;\n }\n el.classList.toggle('shoji-caption--truncated', truncated);\n if (truncated) {\n el.tabIndex = 0;\n el.setAttribute('role', 'button');\n el.setAttribute('aria-haspopup', 'dialog');\n } else {\n el.removeAttribute('tabindex');\n el.removeAttribute('role');\n el.removeAttribute('aria-haspopup');\n if (this.captionModalOpen) this.closeCaptionModal();\n }\n }\n\n private readonly onCaptionActivate = (event: Event): void => {\n if (!this.dom?.caption.classList.contains('shoji-caption--truncated')) return;\n this.captionModalOpenedViaKeyboard = event instanceof KeyboardEvent;\n if (event instanceof KeyboardEvent) {\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n // A real bug, reported from real usage against Autoplay's\n // onCaptionExpand (§4.1 point 18): a *keyboard* activation here\n // (Tab+Enter/Space, the only path this branch actually runs for)\n // must not also bubble up to onKeydown's shortcut dispatch — this is\n // unambiguously \"activate this control,\" not also a global shortcut\n // key, same reasoning the caption modal's own keydown handler\n // already uses to isolate itself from onKeydown. This alone doesn't\n // cover the click path below reopening on a *later*, unrelated\n // keypress — see `captionModalOpenedViaKeyboard`'s own doc comment\n // for that half of the fix.\n event.stopPropagation();\n } else {\n // A mouse-drag that ended in a real text selection is not a click to\n // open — `.shoji-caption` is deliberately excluded from drag-to-\n // navigate (GestureController's INTERACTIVE_CONTROL_SELECTOR) so the\n // viewer can select/copy caption text; without this check, finishing\n // that selection would also toggle the modal open on every drag.\n const selection = window.getSelection();\n if (selection && !selection.isCollapsed) return;\n // A link/button inside a rich-HTML caption keeps its own click\n // behavior — this only opens the modal for a click on the caption\n // itself, not one that's actually aimed at interactive content\n // inside it.\n if (event.target instanceof Element && event.target.closest('a, button')) return;\n }\n this.openCaptionModal();\n };\n\n /**\n * DESIGN.md §2.3a — shows the full caption (re-rendered via the same\n * `renderCaption()` the truncated one already used, so a rich-HTML\n * caption's own links/formatting are identical in both places) in a\n * small nested dialog, scrollable if it's still taller than the\n * viewport allows. `FocusTrap.retarget()` narrows Tab-cycling to just\n * this modal without touching the outer trap's own focus-restore state\n * (see its own doc comment for why a second `FocusTrap` instance isn't\n * used instead). Requested directly: the modal *replaces* the truncated\n * caption rather than just visually sitting on top of it — hiding\n * `dom.caption` too, not only because the modal's own opaque backdrop\n * already covers it, but so it can't still be reached by a screen\n * reader's browse-mode cursor (unlike Tab, `FocusTrap`/`retarget()`\n * don't affect that) while a completely different dialog is the one\n * actually open.\n */\n private openCaptionModal(): void {\n if (!this.dom || this.captionModalOpen) return;\n const item = this.itemList[this.activeIndex];\n this.renderCaption(this.dom.captionModalContent, item?.caption);\n this.dom.captionModal.hidden = false;\n // Captured before hiding the caption below (a real bug, caught by e2e\n // regression: hiding the currently-focused caption blurs it immediately\n // — a hidden element can't hold focus — so reading `activeElement`\n // *after* that line ended up capturing wherever the browser's own\n // focus-loss fallback landed (the dialog), not the caption itself.\n // Escape/close-button/backdrop then \"restored\" focus to the dialog\n // instead of back to the caption that was actually focused when this\n // opened.\n this.captionModalReturnFocus = document.activeElement as HTMLElement | null;\n this.dom.caption.hidden = true;\n // A real bug, caught testing this: the click that opens the modal\n // typically leaves the pointer sitting right over the caption —\n // hiding it out from under a *stationary* cursor never fires the\n // `pointerleave` `wireControlHover()` needs to drop it from\n // `hoveringElements` (browsers only fire that on actual pointer\n // movement past an element's edge, not on the element disappearing).\n // `reconcileHover()` would eventually self-heal this on the next real\n // pointer move anyway, but nothing meaningful should still read as\n // \"hovered\" once the modal has taken over — clearing it immediately\n // here is more deterministic than waiting for that.\n this.hoveringElements.clear();\n this.captionModalOpen = true;\n this.focusTrap.retarget(this.dom.captionModalPanel);\n document.addEventListener('keydown', this.onCaptionModalKeydown, true);\n this.bus.emit('captionModalChange', { open: true });\n }\n\n /**\n * Requested directly: closing should leave the viewer looking at a fully\n * normal, fully visible gallery — not just the modal gone, but the\n * truncated caption back (via `updateCaptionVisibility()`, which\n * recomputes its real hidden state from scratch rather than blindly\n * flipping a flag back — the more robust \"recompute from source of\n * truth\" this codebase already prefers elsewhere) and any auto-hidden\n * toolbar/nav explicitly re-shown (`onActivity()`, same pairing every\n * other real interaction already uses) rather than left hidden until\n * the viewer happens to move the mouse.\n */\n private closeCaptionModal(): void {\n if (!this.dom || !this.captionModalOpen) return;\n document.removeEventListener('keydown', this.onCaptionModalKeydown, true);\n this.dom.captionModal.hidden = true;\n this.captionModalOpen = false;\n this.updateCaptionVisibility();\n this.focusTrap.retarget(this.dom.dialog);\n if (this.captionModalOpenedViaKeyboard) {\n this.captionModalReturnFocus?.focus({ preventScroll: true });\n }\n this.captionModalReturnFocus = null;\n this.captionModalOpenedViaKeyboard = false;\n this.onActivity();\n this.bus.emit('captionModalChange', { open: false });\n }\n\n private renderCurrentSlide(openPlaceholderSrc?: string): void {\n if (!this.slides || !this.dom) return;\n const dom = this.dom;\n this.slides.render(\n this.itemList,\n this.activeIndex,\n (loadedIndex) => {\n if (loadedIndex === this.activeIndex) {\n this.bus.emit('slideItemLoad', { index: loadedIndex });\n this.setSlideLoading(false);\n // captionFadePending: skip here too, not just the synchronous\n // call below — decode() resolves on a microtask, which can win\n // the race against the mode animation's own onComplete (the one\n // that's actually supposed to update it), especially for an\n // already-preloaded slide.\n if (!this.captionFadePending) this.updateCaptionVisibility();\n }\n },\n openPlaceholderSrc,\n this.loop,\n );\n this.setSlideLoading(!this.slides.isActiveReady());\n\n const item = this.itemList[this.activeIndex];\n const total = this.itemList.length;\n dom.counter.textContent = total > 0 ? `${this.activeIndex + 1} / ${total}` : '';\n dom.counter.hidden = !this.showCounter || total === 0;\n // navigate()'s animated path already faded the outgoing caption out\n // and updates content itself, once that fade (and the slide's own mode\n // transition) actually finishes — updating it here too, immediately,\n // would flash the new caption's text mid-fade instead of the outgoing\n // one.\n if (!this.captionFadePending) this.updateCaptionVisibility();\n const label = `Image ${this.activeIndex + 1} of ${total}${item?.alt ? `: ${item.alt}` : ''}`;\n this.liveRegion.announce(label);\n\n dom.prevButton.hidden = total <= 1;\n dom.nextButton.hidden = total <= 1;\n dom.prevButton.disabled = !this.loop && this.activeIndex <= 0;\n dom.nextButton.disabled = !this.loop && this.activeIndex >= total - 1;\n }\n\n open(index = this.options.index ?? 0): void {\n if (this.destroyed || this.opened) return;\n this.bus.emit('beforeOpen', { index });\n this.ensureLightbox();\n this.opened = true;\n this.activeIndex = index;\n this.captionVisibleOnVideo = !!this.options.showVideoCaption;\n lockBodyScroll();\n const origin = this.getOriginElement(index);\n // Both the open placeholder and the zoom-in animation below need a size\n // to show/grow toward before the real image has loaded — without\n // item.width/height, that size can only ever be guessed (\"probably\n // fills the dialog\"), which is exactly what visibly overshoots for a\n // genuinely small photo (§2.3/§2.3b's own real-bug history). Rather\n // than guess, skip both entirely when naturalSize is unknown: the\n // ordinary spinner shows, and the real image just appears once it's\n // ready — no animation of its own, deliberately (same \"no second,\n // disconnected transition\" reasoning the placeholder-to-real-image\n // handoff already uses elsewhere).\n const naturalSize = this.resolveNaturalSize(index);\n // The first slide's caption fades in alongside zoomIn() the same way a\n // navigated-to one fades in alongside the mode transition (§2.5) —\n // only when there's actually a zoom to sync with, same \"no second,\n // disconnected transition\" reasoning as the comment above: nothing\n // grows in from the thumbnail without known dimensions, so nothing\n // should fade in disconnected from that either.\n const fadeInOnOpen =\n !!(origin && naturalSize) &&\n !(\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n if (fadeInOnOpen && this.dom) {\n this.captionFadePending = true;\n this.dom.caption.style.opacity = '0';\n }\n // A real bug/inconsistency: a video item *does* have a known naturalSize\n // (its aspect ratio), but the low-res placeholder this unlocks is a\n // dead end — it's a static photo, immediately replaced by something\n // entirely different (an error state, or the real embed), not the same\n // image sharpening the way a photo's placeholder-to-full-res handoff\n // is. That made a fresh open() inconsistent with navigating back to an\n // already-cached video slide (no placeholder shown there at all, since\n // navigate() never passes one) — same \"no second, disconnected\n // transition\" reasoning as the naturalSize-unknown case above, just\n // triggered by content type instead of missing dimensions.\n this.renderCurrentSlide(\n naturalSize && !this.itemList[index]?.video\n ? this.resolveOpenPlaceholderSrc(this.itemList[index], origin)\n : undefined,\n );\n this.dom!.outer.classList.add('shoji-open');\n document.addEventListener('keydown', this.onKeydown);\n this.focusTrap.activate(this.dom!.dialog);\n this.scheduleAutoHide();\n\n const media = this.slides?.getActiveMedia();\n if (media && origin && naturalSize) {\n zoomIn({\n origin,\n target: media,\n aspectRatio: this.resolveAspectRatio(index, origin),\n naturalSize,\n });\n }\n if (fadeInOnOpen && this.dom) {\n // No half-duration split here, unlike transitionCaption() — there's\n // no outgoing caption to fade out first, just this one fading in\n // from nothing, over the same full --shoji-duration zoomIn() itself\n // runs on.\n this.captionFadePending = false;\n this.updateCaptionVisibility();\n this.dom.caption.style.opacity = '';\n }\n\n this.bus.emit('open', { index });\n this.bus.emit('afterOpen', { index });\n }\n\n /** DESIGN.md §2.3 — low-res open() placeholder source, checked in order: item.thumb, a live data-shoji-thumb on origin, else origin's own rendered <img>. */\n private resolveOpenPlaceholderSrc(\n item: GalleryItem | undefined,\n origin: HTMLElement | null,\n ): string | undefined {\n if (item?.thumb) return item.thumb;\n const dataThumb = origin?.getAttribute('data-shoji-thumb');\n if (dataThumb) return dataThumb;\n const img = origin?.querySelector('img');\n return img?.currentSrc || img?.src || undefined;\n }\n\n /**\n * DESIGN.md §2.2/§2.6 — navigates while open; always clamps an explicit\n * out-of-range index (this is a directed jump, not a step — `loop` only\n * affects `next()`/`prev()`, see below). No-op if not open. `animate`\n * (default `true`) runs the configured §2.5 transition; hosts that want\n * an instant jump — e.g. syncing to an external index without a visual\n * flourish — can pass `{ animate: false }`.\n */\n goTo(index: number, options?: { animate?: boolean }): void {\n if (this.destroyed || !this.opened || this.itemList.length === 0) return;\n const target = this.clampToRange(index);\n if (target === this.activeIndex) return;\n const direction: 1 | -1 = target > this.activeIndex ? 1 : -1;\n this.navigate(target, direction, options?.animate ?? true);\n }\n\n next(): void {\n this.navigate(this.nextIndex(), 1, true);\n }\n\n prev(): void {\n this.navigate(this.prevIndex(), -1, true);\n }\n\n private nextIndex(): number {\n const atEnd = this.activeIndex >= this.itemList.length - 1;\n return atEnd && this.loop ? 0 : this.activeIndex + 1;\n }\n\n private prevIndex(): number {\n const atStart = this.activeIndex <= 0;\n return atStart && this.loop ? this.itemList.length - 1 : this.activeIndex - 1;\n }\n\n /**\n * DESIGN.md §2.5 — the shared path behind `goTo()`/`next()`/`prev()`.\n * `animate` is `false` only for `GestureController`'s own host callbacks\n * (see `ensureLightbox()`): a gesture-completed swipe already played its\n * own live-drag/settle animation, so running a *second*, `mode`-based\n * transition on top of it would visibly double-animate. Every other\n * caller — buttons, keyboard, autoplay, a plugin calling `goTo()` — gets\n * the real, configured transition.\n */\n private navigate(target: number, direction: 1 | -1, animate: boolean): void {\n if (this.destroyed || !this.opened || this.itemList.length === 0) return;\n const clamped = this.clampToRange(target);\n if (clamped === this.activeIndex) return;\n // DESIGN.md §2.3a — the modal shows a specific slide's caption; leaving\n // it open across a navigation (arrow keys reach it even while the\n // gesture gate above suspends drag-navigate) would keep showing the\n // outgoing slide's text over the new slide.\n if (this.captionModalOpen) this.closeCaptionModal();\n // DESIGN.md §3.1a — the popover's own position depends on the current\n // toolbar height, which can change slide-to-slide (e.g. a video slide's\n // caption-toggle button appearing/disappearing); simplest to just close\n // it rather than reposition it mid-navigation.\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n const from = this.activeIndex;\n // beforeSlide fires first so a listener (e.g. Autoplay) can detach its\n // own 'pause' listener from the outgoing video before pauseMedia() below\n // triggers a native 'pause' event on it — otherwise that listener is\n // still attached and misreads this programmatic pause as the viewer\n // manually pausing the video, a real regression this caused once\n // (advancing past a stuck video called next(), which paused it here,\n // which the still-attached listener treated as a manual pause and\n // stopped the whole slideshow before the new slide's afterSlide handler\n // ever got a chance to run). activeIndex hasn't changed yet at this\n // point, so getActiveMedia() still resolves to the outgoing slide either\n // way — only the listener-detach ordering relative to pauseMedia matters.\n this.bus.emit('beforeSlide', { from, to: clamped });\n // A video started by the viewer keeps playing otherwise — this slide\n // stays cached (still within `preload`), and only pausing (not\n // releasing) lets it resume right where it left off if revisited.\n pauseMedia(this.slides?.getActiveMedia() ?? null);\n this.activeIndex = clamped;\n\n if (animate && this.transition) {\n // Not layered onto a gesture-completed swipe (the `else` branch) —\n // same scoping as the mode transition itself (§2.4/§2.5).\n this.transitionCaption();\n const swap = (): void => this.renderCurrentSlide();\n const modeName = this.resolveTransitionMode();\n const builtin = TRANSITION_PRESETS[modeName];\n if (builtin) {\n this.transition.animate(builtin, direction, swap);\n } else {\n this.transition.animateCustom(modeName, direction, swap);\n }\n } else {\n const swap = (): void => this.renderCurrentSlide();\n swap();\n }\n\n this.bus.emit('afterSlide', { from, to: clamped });\n }\n\n private resolveTransitionMode(): string {\n return this.options.mode ?? 'slide';\n }\n\n close(): void {\n this.beginClose();\n }\n\n /**\n * DESIGN.md §2.4/§2.6a — same effect as `close()`, from a completed\n * vertical swipe. `frozenDrag` is threaded through to `zoomOut()`'s own\n * `dragStart`, so the whole close continues as one motion from exactly\n * where the drag left off (see `GestureController.\n * takeFrozenDragTransform`).\n */\n private closeFromSwipe(frozenDrag: FrozenDragTransform): void {\n this.beginClose(frozenDrag);\n }\n\n /**\n * `frozenDrag` — see `closeFromSwipe()`'s doc comment; absent for a\n * button-close, which has no drag to continue from. Controls fade and the\n * zoom-out run concurrently, both starting the instant `forceHideControls()`\n * runs — not sequenced one after the other. (A previous version waited for\n * the controls' own fade to fully finish before starting the zoom-out, for\n * a button-close specifically — requested directly, to avoid stationary\n * chrome hovering over an already-shrinking photo. Reversed on later,\n * explicit feedback: waiting read as two distinct steps rather than one\n * motion; starting both together still avoids stationary chrome, since\n * the chrome is disappearing too, just without the pause.)\n */\n private beginClose(frozenDrag?: FrozenDragTransform): void {\n if (this.destroyed || !this.opened || this.isClosing) return;\n // DESIGN.md §2.3a — every close path (button, swipe, Escape, backdrop\n // click, destroy-while-open) funnels through here; the modal must not\n // linger past the lightbox itself closing, and its own document-level\n // keydown listener needs removing before that.\n if (this.captionModalOpen) this.closeCaptionModal();\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n // Read before beforeClose fires — the Zoom plugin's own beforeClose\n // handler resets its scale/pan back to neutral there (so zoomOut()'s\n // measurement below stays correct, same reasoning dragStart's own doc\n // comment explains), which would otherwise erase the very state this\n // is capturing.\n const zoomStart = this.zoomStartProvider?.() ?? undefined;\n this.bus.emit('beforeClose', {});\n\n // .shoji-outer must stay display:block for the zoom-out to be visible,\n // so the actual state flip (isOpen, focus restore, etc.) is deferred\n // until the animation finishes — see finishClose(). isClosing guards\n // against a second close() (e.g. a repeated Escape) re-triggering the\n // animation mid-flight while isOpen is still (deliberately) true.\n this.isClosing = true;\n\n const media = this.slides?.getActiveMedia();\n // close() never tears down the slide pool (reopening should be\n // instant), so nothing else stops a viewer-started video just because\n // the lightbox is now hidden.\n pauseMedia(media ?? null);\n\n const origin = this.getOriginElement(this.activeIndex);\n const naturalSize = this.resolveNaturalSize(this.activeIndex);\n // Real content already rendered doesn't need naturalSize at all —\n // effectiveTargetBox() (zoomTransition.ts) measures it directly, no\n // guessing involved. Only closing before it ever finished loading (no\n // real content, no naturalSize to fall back on either) would have\n // nothing but a guessed target to shrink toward — same \"don't guess\"\n // reasoning open() above already applies to its own animation.\n if (media && origin && (this.slides?.isActiveReady() || naturalSize)) {\n const aspectRatio = this.resolveAspectRatio(this.activeIndex, origin);\n this.forceHideControls();\n // Starts at the same instant as the zoom-out and the controls fade —\n // see the comment on .shoji-backdrop's own transition (shoji.css) for\n // why this can't just be left to the instant display:none cut at the\n // end of finishClose().\n if (this.dom) this.dom.backdrop.style.opacity = '0';\n zoomOut(\n { origin, target: media, aspectRatio, naturalSize, dragStart: frozenDrag, zoomStart },\n () => this.finishClose(),\n );\n } else {\n this.finishClose();\n }\n }\n\n /**\n * Forces the same fade §2.8's idle timer would eventually trigger, bypassing `hideControls()`'s own `isControlActive()` hover guard — the most common close path (clicking close) is hovering a control at this exact instant, and a deliberate close should hide regardless. No-op if already hidden.\n *\n * Also marks `.shoji-controls-hidden-for-close` alongside the ordinary\n * class — a real bug, reported from real usage: a plugin's own overlay\n * (Autoplay's progress bar, `autoplay.css`) was wired to fade on plain\n * `.shoji-controls-hidden`, the same class *ordinary idle auto-hide* also\n * applies — so it faded out and stayed gone through every idle period\n * too, not just the close animation the original request was actually\n * about. That went unnoticed for a while because until recently, tapping\n * the image toggled play/pause *and* revealed controls on the same tap,\n * papering over how often it was actually gone; once that tap-to-toggle\n * was removed (§4.1 point 15) as a separate, unrelated fix, an idle\n * slideshow now visibly loses its own progress indicator and never gets\n * it back without an unrelated interaction — surfacing this as a real\n * regression in practice, even though no code touching this class had\n * changed. This second class is the hook a plugin's CSS can key off\n * specifically for \"closing,\" without it ever matching ordinary idle-hide.\n */\n private forceHideControls(): void {\n if (!this.dom || this.autoHidden) return;\n this.autoHidden = true;\n this.dom.dialog.classList.add('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n this.bus.emit('controls:hide', {});\n }\n\n /**\n * DESIGN.md §2.4/§2.8 — `GestureController`'s live vertical-drag cue: hide\n * past the same distance a release would close, reveal again on retreat.\n * `hidden: false` only reveals if visible when *this* gesture started\n * (`controlsHiddenAtGestureStart`) — shouldn't resurrect controls already\n * separately hidden (idle, or `autoHideDelay: 0`) before the drag began.\n * `dragCloseThreshold` (bus event) fires on every crossing regardless of\n * that guard — Autoplay (§4-autoplay) needs to know about the crossing\n * itself, not just whether controls visibly moved.\n */\n private setControlsHiddenForDrag(hidden: boolean): void {\n this.controlsHiddenByDrag = hidden;\n if (hidden) this.forceHideControls();\n else if (!this.controlsHiddenAtGestureStart) this.showControls();\n // A real bug, reported from real usage: `.shoji-controls-hidden` also\n // hides the cursor (shoji.css) — fine for an idle/inactive hide, but\n // this hide happens *during* an active drag, so the cursor vanished\n // right when the viewer most needs to see it. This marker class scopes\n // a cursor override to specifically this case (see shoji.css).\n this.dom?.dialog.classList.toggle('shoji-controls-hidden-for-drag', hidden);\n this.bus.emit('dragCloseThreshold', { hidden });\n }\n\n /** `item.width`/`height`, else origin's `naturalWidth`/`naturalHeight` (accurate when `item.thumb` is unset). Feeds `computeTransform`'s letterbox-aware sizing. */\n private resolveAspectRatio(index: number, origin: HTMLElement | null): number | undefined {\n const item = this.itemList[index];\n if (item?.width && item.height) return item.width / item.height;\n const thumbImg = origin?.querySelector('img');\n if (thumbImg?.naturalWidth && thumbImg.naturalHeight) {\n return thumbImg.naturalWidth / thumbImg.naturalHeight;\n }\n return undefined;\n }\n\n /**\n * `item.width`/`height` only — deliberately never a thumbnail's own\n * `naturalWidth`/`naturalHeight` the way `resolveAspectRatio` above will:\n * that's a fine stand-in for *shape*, but using it as the real photo's\n * true pixel size would under-cap a genuinely large photo down to\n * thumbnail resolution. `undefined` here just means \"genuinely unknown,\"\n * not \"assume small\" — `zoomTransition.ts`'s `containedBox` already\n * treats it that way (no cap applied at all).\n */\n private resolveNaturalSize(index: number): { width: number; height: number } | undefined {\n const item = this.itemList[index];\n return item?.width && item.height ? { width: item.width, height: item.height } : undefined;\n }\n\n /**\n * Idempotent on purpose: a pending zoom-out's `transitionend`/fallback\n * timeout can still fire after `destroy()` has already force-finished the\n * close (§ destroy() below) — the `!this.opened` guard makes that a no-op\n * instead of a second `close`/`afterClose` emission on a torn-down gallery.\n */\n private finishClose(): void {\n if (!this.opened) return;\n this.isClosing = false;\n this.opened = false;\n unlockBodyScroll();\n document.removeEventListener('keydown', this.onKeydown);\n this.focusTrap.deactivate();\n this.dom?.outer.classList.remove('shoji-open');\n // Cleared, not left at '0' — a fresh open() must start fully opaque\n // again, not still faded out from the last close.\n if (this.dom) this.dom.backdrop.style.opacity = '';\n if (this.autoHideTimer !== null) {\n clearTimeout(this.autoHideTimer);\n this.autoHideTimer = null;\n }\n this.autoHidden = false;\n this.hoveringElements.clear();\n this.controlsHiddenByDrag = false;\n this.dom?.dialog.classList.remove('shoji-controls-hidden', 'shoji-controls-hidden-for-close');\n // A completed drag-close never calls setControlsHiddenForDrag(false)\n // (nothing left to un-hide for) — clean up the marker here instead, so\n // it can't linger into the next open().\n this.dom?.dialog.classList.remove('shoji-controls-hidden-for-drag');\n this.bus.emit('close', {});\n this.bus.emit('afterClose', {});\n }\n\n /** DESIGN.md §2.1 — diffs by id (fallback src), preserving the active slide. */\n updateSlides(items: GalleryItemInput[], currentIndex?: number): void {\n if (this.destroyed) return;\n\n const activeItem = this.itemList[this.activeIndex];\n const activeKey = activeItem ? itemKey(activeItem) : undefined;\n this.itemList = resolveDynamicVideoItems(items);\n\n let nextIndex = currentIndex;\n if (nextIndex === undefined && activeKey !== undefined) {\n const preserved = items.findIndex((item) => itemKey(item) === activeKey);\n if (preserved !== -1) nextIndex = preserved;\n }\n this.activeIndex = Math.min(\n Math.max(nextIndex ?? this.activeIndex, 0),\n Math.max(items.length - 1, 0),\n );\n\n if (this.opened) this.renderCurrentSlide();\n this.bus.emit('itemsUpdated', { items: this.itemList });\n }\n\n /**\n * Sugar over `updateSlides()` for the common \"insert some items\" case —\n * splices `items` into a copy of the current list at `atIndex` (default:\n * append at the end) and hands the result to `updateSlides()`, which\n * still does all the real work (active-item preservation, live re-render\n * if open, `itemsUpdated`). `atIndex` follows `Array.prototype.splice`'s\n * own semantics (negative counts from the end, out-of-range clamps) —\n * no extra validation on top of that.\n */\n addSlides(items: GalleryItemInput[], atIndex?: number): void {\n if (this.destroyed) return;\n const next: GalleryItemInput[] = [...this.itemList];\n next.splice(atIndex ?? next.length, 0, ...items);\n this.updateSlides(next);\n }\n\n /**\n * Sugar over `updateSlides()` for the common \"remove some items\" case.\n * Accepts a single id/index or an array mixing both: a `string` matches\n * the same `id ?? src` key `updateSlides()` already uses for active-item\n * preservation, a `number` matches that position in the *current*\n * `items` list (resolved against the list as it is now, before any\n * removal — passing `[0, 1]` removes the first two items, not \"index 0,\n * then whatever became index 1 after that\").\n */\n removeSlides(match: string | number | Array<string | number>): void {\n if (this.destroyed) return;\n const matches = Array.isArray(match) ? match : [match];\n const indices = new Set(matches.filter((m): m is number => typeof m === 'number'));\n const keys = new Set(matches.filter((m): m is string => typeof m === 'string'));\n const next = this.itemList.filter((item, i) => !indices.has(i) && !keys.has(itemKey(item)));\n this.updateSlides(next);\n }\n\n /** DESIGN.md §2.7 — selector-mode only; sugar over updateSlides() sourced from a DOM rescan. */\n refresh(): void {\n if (this.destroyed) return;\n if (this.isDynamicMode) {\n console.warn('Shoji: refresh() is a no-op in dynamic mode — call updateSlides() instead.');\n return;\n }\n const scanned = scanContainer(this.element, this.selector);\n this.scannedElements = scanned.map((s) => s.element);\n this.updateSlides(scanned.map((s) => s.item));\n }\n\n /** Shared by `destroy()`/`reinit()` (§2.7): force-close, run plugin cleanups, drop gesture/transition/slide/dialog. */\n private teardown(): void {\n if (this.opened) {\n // A real bug, caught by cross-test interference in the unit suite —\n // never reproduced as a simple direct assertion because the existing\n // \"destroy() while the modal is open\" test's `removeEventListener`\n // spy assertion was too loose to actually catch it (FocusTrap's own\n // unrelated document keydown listener removal satisfied the same\n // `expect.any(Function)` matcher). `beginClose()` closes the caption\n // modal first (DESIGN.md §2.3a) — `teardown()` calls `finishClose()`\n // directly instead, skipping `beginClose()` and its own close-path\n // entirely, so destroying a gallery while its caption modal was open\n // never removed that modal's document-level keydown listener. Left\n // unfixed, it leaks forever: a capture-phase listener bound to the\n // destroyed instance, `stopPropagation()`-ing every future keydown on\n // the page regardless of what it's for.\n if (this.captionModalOpen) this.closeCaptionModal();\n // Same gap, same fix, for the toolbar overflow popover (§3.1a) —\n // teardown() skips beginClose() entirely, so a destroy()/reinit()\n // while it happened to be open would leak its own document-level\n // keydown listener the same way.\n if (this.toolbarOverflowOpen) this.closeToolbarOverflow();\n if (!this.isClosing) this.bus.emit('beforeClose', {});\n this.finishClose();\n }\n for (const cleanup of this.pluginCleanups) cleanup();\n this.pluginCleanups = [];\n this.shortcuts.clear();\n this.pluginStorage.clear();\n this.activePluginNames.clear();\n this.videoProviders.clear();\n if (!this.isDynamicMode) {\n this.element.removeEventListener('click', this.onContainerClick);\n }\n this.gesture?.destroy();\n this.gesture = null;\n this.transition = null;\n this.toolbarHeightObserver?.disconnect();\n this.toolbarHeightObserver = null;\n if (this.toolbarHeightFrame !== null) cancelAnimationFrame(this.toolbarHeightFrame);\n this.toolbarHeightFrame = null;\n if (this.captionTruncationFrame !== null) cancelAnimationFrame(this.captionTruncationFrame);\n this.captionTruncationFrame = null;\n this.captionFadePending = false;\n this.slides?.destroy();\n this.dom?.outer.remove();\n this.slides = null;\n this.dom = null;\n // A real leak, caught by inspection: core's own `wireControlHover()`\n // calls in `ensureLightbox()` (closeButton, toolbar slots, caption,\n // counter, ...) never store/call the unsubscribe they return, since\n // there was never anywhere else that needed it before — those elements\n // were expected to just live and die with the rest of `dom` above.\n // `reinit()` routes through here too, though, and rebuilds a whole new\n // `dom` afterward (`ensureLightbox()` runs again) — without this,\n // `hoverableElements` would keep every previous reinit cycle's now-\n // detached elements forever, growing unbounded across repeated calls.\n this.hoverableElements.clear();\n this.hoveringElements.clear();\n // Same reasoning: a plugin's own `ctx.ui.toolbar()` unsubscribe not\n // being called for some reason must not leave stale, now-detached\n // elements in here across a `reinit()` cycle either.\n this.pluginToolbarButtons.length = 0;\n }\n\n destroy(): void {\n if (this.destroyed) return;\n // Guarded, not a plain delete(): if a second Gallery was constructed on\n // this same element without the first ever being destroyed, the\n // registry entry already points at that newer instance — an old,\n // stale `this` being destroyed later must not evict it.\n if (instanceRegistry.get(this.element) === this) instanceRegistry.delete(this.element);\n allInstances.delete(this);\n this.teardown();\n this.bus.emit('destroy', {});\n this.bus.clear();\n this.destroyed = true;\n }\n\n /**\n * DESIGN.md §2.7 — full teardown + reconstruction on `this`, not a new\n * object: `Shoji.getInstance(el)`/any held reference keeps working across\n * the call, unlike `destroy()` + `new Shoji(...)`. Omit `options` to\n * rebuild unchanged (a hard reset); pass options to reconfigure\n * structurally. `gallery.on(...)` listeners do NOT survive — the event\n * bus is fully cleared, same as `destroy()` — re-`on()` anything needed.\n */\n reinit(options: GalleryOptions = this.options): void {\n if (this.destroyed) return;\n this.teardown();\n this.bus.clear();\n this.applyOptions(options);\n }\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport './activeThumbnail.css';\n\nexport interface ActiveThumbnailOptions {\n /** CSS class applied to the origin thumbnail for whichever slide is currently active. Default `'shoji-thumb-active'` — Shoji ships no default styling for this class itself (the host's own thumbnail markup, or the layout plugin's tiles, define what \"active\" looks like); see `highlight` below for Shoji's own opt-in styling. */\n activeClass?: string;\n /** Scrolls the active thumbnail into view (`block: 'nearest'`) whenever it changes. Default `true`. */\n scrollIntoView?: boolean;\n /** Opt-in: also adds a second, fixed (non-renameable) class that Shoji ships real CSS for — a `borderColor` outline around the active thumbnail — instead of leaving 100% of the visual highlight to the host. Default `false`. */\n highlight?: boolean;\n /** Only visible when `highlight: true`. Sets `--shoji-active-thumbnail-border-color` on the active element. Default `'blue'`. */\n borderColor?: string;\n /** Only meaningful when `highlight: true`. Milliseconds after `close()` (i.e. after the highlight actually becomes visible, not from when the slide became active) to fade it out. Default `undefined` — persists indefinitely, moving only when a different slide becomes active. Does not touch `activeClass`, only the built-in `highlight` styling. */\n highlightDuration?: number;\n /** Only meaningful when `highlight: true` and `highlightDuration` is set — otherwise nothing ever fades, so this has no visible effect. How long the fade-to-transparent transition itself takes, in milliseconds, once `highlightDuration` elapses. Default `800`. Reported directly as \"fades too fast\" against the shared `--shoji-duration` (300ms, tuned for ordinary UI transitions, not a deliberately slow fade) this used to reuse. */\n highlightFadeDuration?: number;\n}\n\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches\n );\n}\n\n/**\n * Opt-in: keeps the host's thumbnail grid in sync with whichever slide is\n * currently open — highlighting it and, by default, scrolling it into view —\n * as the viewer moves through the lightbox by any means (arrow keys,\n * prev/next buttons, a completed swipe, autoplay ticking forward, a plugin\n * calling `goTo()`). Not core: CLAUDE.md's \"everything that can be a plugin\n * is a plugin\" — a host whose thumbnail grid is short enough to always be\n * fully visible, or who doesn't want their page scrolling out from under\n * them mid-slideshow, should be able to leave this off entirely.\n *\n * Reuses `Gallery.getOriginElement()` (the same index → thumbnail lookup the\n * zoom transition already relies on, §2.3b) rather than re-deriving it, so\n * this plugin's coverage exactly matches whatever the zoom transition\n * already zooms to/from: `scannedElements[index]` in selector mode,\n * `data-shoji-id=\"<item.id>\"` markers elsewhere (including the layout\n * plugin's own tiles, which set that attribute automatically when\n * `item.id` is present).\n */\nexport const ActiveThumbnail: ShojiPlugin = {\n name: 'activeThumbnail',\n defaults: {\n activeClass: 'shoji-thumb-active',\n scrollIntoView: true,\n highlight: false,\n borderColor: 'blue',\n } satisfies ActiveThumbnailOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const activeClass = String(ctx.options.activeClass ?? 'shoji-thumb-active');\n const scrollIntoView = ctx.options.scrollIntoView !== false;\n const highlight = ctx.options.highlight === true;\n const borderColor = String(ctx.options.borderColor ?? 'blue');\n const highlightDuration =\n typeof ctx.options.highlightDuration === 'number' ? ctx.options.highlightDuration : null;\n const highlightFadeDuration =\n typeof ctx.options.highlightFadeDuration === 'number'\n ? ctx.options.highlightFadeDuration\n : 800;\n const HIGHLIGHT_CLASS = 'shoji-thumb-active--highlight';\n\n let current: HTMLElement | null = null;\n // The Layout plugin's own `groupBy` option always fully re-renders (its\n // own doc comment: \"grouped changes always fully re-render\") on any\n // `autoMeasure` correction, not just on real `updateSlides()` calls — a\n // real bug, found via a real integration combining `groupBy` with most\n // items missing `width`/`height` (so most tiles get an `autoMeasure`\n // correction as their real image loads): each correction rebuilt every\n // tile via `createTile()` from scratch, discarding the exact DOM element\n // `current` above pointed at along with whatever class was on it — the\n // highlight simply vanished, often while the lightbox was still open on\n // the very slide it was supposed to be marking. Tracking the *index*\n // (not just the resolved element) is what lets `onLayoutRender` below\n // re-resolve and re-mark the freshly-rebuilt tile — `getOriginElement()`\n // finds it again via the same `data-shoji-id`, which `createTile()` sets\n // on every rebuilt tile regardless.\n let currentIndex: number | null = null;\n let scrollTimer: ReturnType<typeof setTimeout> | null = null;\n let fadeTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPendingScroll(): void {\n if (scrollTimer !== null) {\n clearTimeout(scrollTimer);\n scrollTimer = null;\n }\n }\n\n /** Cancels a still-pending `highlightDuration` fade — called whenever the highlight moves or is re-applied (`applyClass`), so a stale countdown from a previous close never fires against a since-changed or since-reopened element. */\n function cancelFade(): void {\n if (fadeTimer !== null) {\n clearTimeout(fadeTimer);\n fadeTimer = null;\n }\n }\n\n /** Resolves and marks the origin element for `index` — no scrolling, so a DOM rebuild that didn't actually change which slide is active (`onLayoutRender` below) doesn't also re-trigger a scroll nothing about real navigation caused. */\n function applyClass(index: number): HTMLElement | null {\n cancelFade();\n const el = gallery.getOriginElement(index);\n if (current && current !== el) {\n current.classList.remove(activeClass);\n if (highlight) current.classList.remove(HIGHLIGHT_CLASS);\n }\n if (el) {\n el.classList.add(activeClass);\n if (highlight) {\n el.classList.add(HIGHLIGHT_CLASS);\n // Always the real color, not whatever a previous highlightDuration\n // fade may have left it at (transparent) — covers both a genuinely\n // new active element and this same element being re-marked (e.g.\n // reopening at the same index) after having already faded once.\n el.style.setProperty('--shoji-active-thumbnail-border-color', borderColor);\n el.style.setProperty(\n '--shoji-active-thumbnail-fade-duration',\n `${highlightFadeDuration}ms`,\n );\n }\n }\n current = el;\n return el;\n }\n\n /** Scrolling is best-effort — whatever goes wrong with it must never take the highlight down with it (already applied by `applyClass`). */\n function performScroll(el: HTMLElement): void {\n try {\n // The lightbox that's navigating (and so triggering this scroll)\n // is also what's holding the page scroll lock — without this,\n // closing it unconditionally snaps the page back to wherever it\n // was on open, undoing every scroll this call ever made.\n //\n // Through gallery.markIntentionalScroll(), not a direct import of\n // bodyScrollLock's own function — a real bug, confirmed directly:\n // in the standalone core+plugins distribution (DESIGN.md §10),\n // dist/plugins/activeThumbnail.js is bundled completely separately\n // from dist/core/shoji-core.js, so a direct import here would call\n // a totally independent copy of that module's state, invisible to\n // the actual unlockBodyScroll() running inside core. Routing\n // through the Gallery instance itself — always the same instance\n // regardless of bundle mode — reaches whichever bodyScrollLock\n // module *that* build of core is really using.\n gallery.markIntentionalScroll();\n el.scrollIntoView({\n block: 'nearest',\n inline: 'nearest',\n behavior: prefersReducedMotion() ? 'auto' : 'smooth',\n });\n } catch {\n // no-op — see comment above\n }\n }\n\n function apply(index: number): void {\n currentIndex = index;\n cancelPendingScroll();\n const el = applyClass(index);\n if (el && scrollIntoView) {\n // Debounced, not fired on every single navigation directly: a\n // real bug, reported from real usage and confirmed via direct\n // testing — navigating faster than a single smooth scroll can\n // finish (autoplay ticking, or just clicking quickly) leaves the\n // browser with an interrupted, not-yet-settled scroll animation,\n // which can visibly resolve later, at some unrelated later point\n // (e.g. exactly when the gallery closes) rather than simply being\n // superseded. Waiting a short beat before actually scrolling — and\n // restarting that wait on every subsequent navigation — means a\n // rapid burst only ever issues one real scrollIntoView call, for\n // wherever the viewer actually lands, instead of one *per step*\n // that can never keep up and pile up interrupted animations.\n // classList.add() above is unaffected either way — the highlight\n // itself is never debounced, only the scroll. `clear()` below\n // flushes this immediately instead of waiting out the rest of the\n // 80ms if close() happens first.\n scrollTimer = setTimeout(() => {\n scrollTimer = null;\n performScroll(el);\n }, 80);\n }\n }\n\n // NOT cleared on close — a real complaint, reported from real usage:\n // an earlier version removed the highlight the instant the lightbox\n // closed, which defeats the entire point of a *visible* \"you were just\n // looking at this one\" marker — it can only ever be seen once the\n // lightbox (and its backdrop) is gone, and clearing it right then meant\n // there was never a moment a host could actually see it. The highlight\n // now stays on whichever thumbnail was last active until a *different*\n // one becomes active (the next `open()`/`afterSlide`, whenever that is,\n // possibly a whole separate visit to the gallery later) — that's what\n // \"last viewed\" means. Only `onClose` below (the pending-scroll flush)\n // and real teardown (`destroy()`, returned below) still run on close;\n // the highlight itself is untouched by it.\n function onClose(): void {\n // Flushed, not dropped: a navigation immediately followed by close()\n // still means \"this is where I ended up\" — a real complaint, reported\n // from real usage, about an earlier version of this function that\n // called cancelPendingScroll() here instead, silently discarding that\n // final navigation's scroll if close() landed inside its 80ms window\n // (routine, at normal clicking speed) rather than running it. Flushing\n // immediately (not just letting the timer run out naturally after\n // close instead) avoids the *other* failure mode this guarded against\n // originally: the page visibly scrolling on its own some tens of ms\n // after the lightbox is already gone, rather than as part of closing it.\n const pending = scrollTimer !== null ? current : null;\n cancelPendingScroll();\n if (pending && scrollIntoView) performScroll(pending);\n\n // highlightDuration counts from here, not from whenever the slide\n // became active — the highlight is hidden behind the backdrop until\n // now, so a countdown that started earlier (while still open) would\n // burn down time nobody could actually see it for.\n if (highlight && highlightDuration !== null && current) {\n const el = current;\n fadeTimer = setTimeout(() => {\n fadeTimer = null;\n el.style.setProperty('--shoji-active-thumbnail-border-color', 'transparent');\n }, highlightDuration);\n }\n }\n\n /** Real teardown, run only when the plugin itself is going away (`destroy()`) — unlike `onClose()`, this does remove the highlight, since there's no plugin left afterward to manage or move it. */\n function teardown(): void {\n cancelPendingScroll();\n cancelFade();\n current?.classList.remove(activeClass);\n if (highlight) current?.classList.remove(HIGHLIGHT_CLASS);\n current = null;\n currentIndex = null;\n }\n\n const offOpen = ctx.on('afterOpen', ({ index }) => apply(index));\n const offSlide = ctx.on('afterSlide', ({ to }) => apply(to));\n // 'beforeClose', not 'close' — a real bug, reported from real usage and\n // confirmed by reading Gallery.ts directly: 'close' fires from inside\n // finishClose(), which only runs *after* the close (zoom-out) animation\n // completes — but unlockBodyScroll() (also in finishClose(), earlier in\n // the same function) has *already* run and already decided whether to\n // restore the pre-open scroll position, based on whatever\n // markIntentionalScroll() state existed *before* this handler ever got\n // a chance to flush a still-pending scroll. If the last navigation's\n // debounce hadn't fired yet, that decision was wrong: it snapped back\n // to the original position, and only *then* did this handler's flush\n // fire — starting a second, ~1s smooth scroll back to the correct\n // image, well after the lightbox was already gone. 'beforeClose' fires\n // synchronously before any of that — the animation, unlockBodyScroll(),\n // all of it — so flushing here guarantees markIntentionalScroll() has\n // already been called by the time the core makes its restore decision,\n // with no wrong snap-back and no visible second scroll to correct it.\n const offClose = ctx.on('beforeClose', onClose);\n // Re-marks (never re-scrolls, see applyClass's own doc comment) after\n // any render pass that may have rebuilt the DOM out from under `current`\n // — the layout plugin's own real bug, see the comment on `currentIndex`\n // above. Keeps working while closed too now, since `currentIndex` is no\n // longer reset to `null` on close — a layout rebuild between visits\n // still re-marks the right (still-persisted) tile.\n const offLayoutRender = ctx.on('layoutRender', () => {\n if (currentIndex !== null) applyClass(currentIndex);\n });\n\n return () => {\n offOpen();\n offSlide();\n offClose();\n offLayoutRender();\n teardown();\n };\n },\n};\n","/**\n * DESIGN.md §9 — a toolbar button whose icon reflects live state (Fullscreen's\n * enter/exit, Autoplay's play/pause, Zoom's actual-size expand/contract) used\n * to just replace `button.innerHTML` outright — an instant cut, no\n * transition, and each plugin reimplementing the same two-icon swap\n * independently. Requested directly: make every one of these a smooth\n * cross-fade, and make them all go through one shared mechanism rather than\n * three slightly different ones. Both icons are always in the DOM at once,\n * stacked via `position: absolute` inside a fixed-size wrapper\n * (`.shoji-icon-swap`, `shoji.css`) — swapping is just toggling which one is\n * `opacity: 1` via a single modifier class, so there's nothing to actually\n * replace, no risk of a flash-of-no-icon between the old node being removed\n * and the new one's fill/stroke painting in.\n */\nexport interface IconSwap {\n /** Append this into the button — it *is* the button's visible icon content. */\n el: HTMLSpanElement;\n /** `false` shows `iconOff`, `true` shows `iconOn` — cross-fades between them via CSS, respecting `prefers-reduced-motion` the same way every other transition in this codebase does (shoji.css zeroes `--shoji-icon-swap-duration` there). */\n setState(on: boolean): void;\n}\n\nexport function createIconSwap(iconOff: string, iconOn: string): IconSwap {\n const el = document.createElement('span');\n el.className = 'shoji-icon-swap';\n\n const off = document.createElement('span');\n off.className = 'shoji-icon-swap-icon shoji-icon-swap-icon--off';\n off.innerHTML = iconOff;\n\n const on = document.createElement('span');\n on.className = 'shoji-icon-swap-icon shoji-icon-swap-icon--on';\n on.innerHTML = iconOn;\n\n el.append(off, on);\n\n return {\n el,\n setState(state: boolean): void {\n el.classList.toggle('shoji-icon-swap--on', state);\n },\n };\n}\n","/** DESIGN.md §9 — inline SVG, stroke/fill = currentColor, matches src/core/icons.ts's convention. */\n\nexport const PLAY_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"currentColor\"><path d=\"M8 5v14l11-7z\"/></svg>';\n\nexport const PAUSE_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"currentColor\"><path d=\"M7 5h4v14H7zM13 5h4v14h-4z\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { createIconSwap } from '../../core/iconSwap';\nimport { PAUSE_ICON, PLAY_ICON } from './icons';\nimport './autoplay.css';\n\n/**\n * A native `<video>` or a `.shoji-slide-provider-video` container a video\n * provider plugin (§4-video) has augmented with the same shape — Autoplay\n * never needs to know which. `play()`'s return type is technically a lie\n * for the provider case (that `.play` is a synchronous fire-and-forget, no\n * `HTMLVideoElement.play()`-style promise) — harmless, `enterSlide()`'s own\n * `typeof playResult.catch === 'function'` guard already treats a\n * non-promise `play()` result as \"nothing to await,\" same as `undefined`.\n */\ntype PlayableMedia = Pick<\n HTMLVideoElement,\n 'play' | 'pause' | 'paused' | 'ended' | 'muted' | 'addEventListener' | 'removeEventListener'\n>;\n\n/** `.shoji-slide-provider-video` only counts if it's actually been wired up as playable (§4-video's `wirePlayableContract`) — a provider still mid-async-setup, or one that never opted into Autoplay sync at all, isn't. */\nfunction findPlayable(media: HTMLElement | null): PlayableMedia | null {\n const video = media?.querySelector('video');\n if (video) return video;\n const provider = media?.querySelector<HTMLElement & Partial<PlayableMedia>>(\n '.shoji-slide-provider-video',\n );\n if (provider && typeof provider.play === 'function') return provider as PlayableMedia;\n return null;\n}\n\n/** A provider container is attached to the DOM immediately (§4-video), well before its async setup (loading an SDK, constructing a player) finishes wiring `.play` — this is what tells `enterSlide()` \"there's a video here, it's just not playable yet\" apart from \"no video at all,\" so it doesn't mistreat a still-loading video as an ordinary timed slide. */\nfunction isPendingProviderVideo(media: HTMLElement | null): boolean {\n const provider = media?.querySelector<HTMLElement & Partial<PlayableMedia>>(\n '.shoji-slide-provider-video',\n );\n return !!provider && typeof provider.play !== 'function';\n}\n\n// A provider embed's postMessage bridge (DESIGN.md §4.3) can need more real\n// time after \"ready\" before it reliably processes its first command — a\n// play() issued too soon can silently no-op with nothing to catch. Retries\n// a few times with a short delay instead of a single best-effort attempt.\nconst PROVIDER_PLAY_RETRY_MS = 400;\nconst MAX_PROVIDER_PLAY_ATTEMPTS = 8; // + the initial attempt = 9 total, ~3.6s before giving up\n\nexport interface AutoplayOptions {\n /** Milliseconds between advances for timed (photo) slides. Default `5000`. */\n interval?: number;\n /** Shows the thin progress bar (`--shoji-progress`) tracking time-to-next-advance along the dialog's bottom edge, for timed slides only — never shown during video slides, whose own runtime drives advancement instead. Default `true`. Purely presentational: turning it off doesn't change any timing, only whether it's drawn. */\n showProgress?: boolean;\n /** Starts the slideshow automatically as soon as the gallery opens — every `open()`, not just the first — instead of waiting for the toolbar button/`Space`. Default `false`. */\n autoStart?: boolean;\n /**\n * How the slideshow reacts to the viewer zooming in on the active slide\n * (Zoom plugin). `'stop'` (default): pauses immediately and stays paused\n * until Play is pressed again, even once un-zoomed back to neutral — no\n * auto-resume. `'pause'`: same immediate pause, but auto-resumes on its\n * own once genuinely disengaged (see the module-level doc comment on\n * `RESUME_DEBOUNCE_MS` for why that's debounced rather than instant).\n * `false`: a complete no-op, regardless of zoom state. A no-op either way\n * if Zoom isn't loaded. Was a plain `pauseOnZoom` boolean (`true`\n * meaning today's `'stop'`) before `'pause'` existed as an option at all.\n */\n onZoom?: 'stop' | 'pause' | false;\n /**\n * Same shape as `onZoom`, for RotateFlip: `'stop'` (default) pauses on\n * any interaction — including one that lands back on the original\n * orientation, since the click itself is still an active interruption,\n * not just its end state — and stays paused; `'pause'` does the same\n * immediate pause but auto-resumes once genuinely disengaged (debounced,\n * same as `onZoom`); `false` is a no-op. A no-op either way if\n * RotateFlip isn't loaded. Was `pauseOnRotateFlip` before `'pause'`\n * existed.\n */\n onRotateFlip?: 'stop' | 'pause' | false;\n /**\n * Same shape as `onZoom`/`onRotateFlip`, for the viewer expanding a\n * truncated caption to read the rest (core's own caption modal,\n * DESIGN.md §2.3a). `'stop'` (default) pauses and stays paused; `'pause'`\n * auto-resumes once the modal closes (debounced, same as the other two —\n * even though the modal itself makes no *further* engagement possible\n * once closed, the same short window still applies for consistency and\n * because it costs nothing here). `false` is a no-op. Was\n * `pauseOnCaptionExpand` before `'pause'` existed. Unlike `onZoom`/\n * `onRotateFlip`, no re-check on Play is needed either mode: the modal\n * traps both pointer and keyboard input while open (core blocks every\n * key, not just Escape), so Play is physically unreachable until the\n * modal is already closed.\n */\n onCaptionExpand?: 'stop' | 'pause' | false;\n /** Pauses the slideshow the moment the viewer navigates manually — arrow keys/buttons, a completed swipe, a thumbnail click, or any other `goTo()` not caused by Autoplay's own `advance()` — instead of silently re-timing itself on whatever slide they land on. Stays paused until Play is pressed again — always a hard stop, no `'pause'`-style auto-resume variant: unlike zoom/rotate-flip/caption-expand, navigating away has no \"returns to its original state\" to resume from, so there's nothing for an auto-resume to key off. Default `true`, same reasoning as `onZoom`/`onRotateFlip`/`onCaptionExpand` above — reaching for the navigation controls at all is a clear signal of active engagement, and a slideshow that keeps ticking underneath that reads as broken, not helpful. Set `false` to restore the original \"manual nav just re-times the current slide\" behavior. Was `pauseOnManualNavigate` before the other three options gained a `'pause'` mode — renamed alongside them so \"stop\" only ever means stop now, not a mix of stop and pause depending which option you're reading. */\n stopOnManualNavigate?: boolean;\n}\n\n/**\n * Only meaningful for `onZoom`/`onRotateFlip`/`onCaptionExpand`'s `'pause'`\n * mode. A real bug, reported from real usage against this exact plugin's\n * *first* attempt at auto-resume (long before `'pause'` existed as a named\n * option — that attempt just always auto-resumed the moment zoom/rotate-\n * flip reported \"back to neutral\"): un-zooming or un-rotating back to\n * exactly neutral doesn't mean the viewer is done — reaching neutral is\n * just as easily one step *through* on the way to further interaction\n * (e.g. rotating 90 -> 180 -> 270 -> 0, or zooming out then immediately\n * back in) as it is the actual end of one. Resuming instantly on that\n * first neutral reading sprung the slideshow back to life mid-interaction,\n * which reads as more broken than never auto-resuming at all — the\n * original fix for this was simply to remove auto-resume entirely (the\n * `'stop'`-only behavior every `pauseOn*` option had until now). A short\n * idle debounce after the *last* disengage is what actually distinguishes\n * \"done interacting\" from \"just passing through neutral\": each further\n * engagement (re-zooming, another rotate/flip click) cancels and restarts\n * the wait, so the slideshow only ever resumes once nothing has happened\n * for a real pause in activity, not on the instant a single event happens\n * to read as neutral. Not configurable — an internal implementation detail\n * of what \"genuinely disengaged\" means, not a knob a host needs.\n */\nconst RESUME_DEBOUNCE_MS = 1000;\n\n/**\n * DESIGN.md §4-autoplay. Advances on a fixed `interval` (default 5000ms) for\n * ordinary slides; for a video slide, plays it and waits for `ended` instead\n * — the interval never applies to video. A manual pause on that video pauses\n * the *slideshow* too (not just the video); manually resuming the video does\n * NOT resume the slideshow — that requires pressing the slideshow's own\n * play control again. See `enterSlide()`/`onVideoPause()` below for exactly\n * where each half of that rule lives.\n */\nexport const Autoplay: ShojiPlugin = {\n name: 'autoplay',\n defaults: {\n interval: 5000,\n showProgress: true,\n onZoom: 'stop',\n onRotateFlip: 'stop',\n onCaptionExpand: 'stop',\n stopOnManualNavigate: true,\n } satisfies AutoplayOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const interval = Number(ctx.options.interval ?? 5000);\n const showProgress = ctx.options.showProgress !== false;\n const autoStart = ctx.options.autoStart === true;\n const readMode = (value: unknown): 'stop' | 'pause' | false =>\n value === false || value === 'pause' ? value : 'stop';\n const onZoom = readMode(ctx.options.onZoom);\n const onRotateFlip = readMode(ctx.options.onRotateFlip);\n const onCaptionExpand = readMode(ctx.options.onCaptionExpand);\n const stopOnManualNavigate = ctx.options.stopOnManualNavigate !== false;\n const locale = ctx.options.locale as Partial<Record<'play' | 'pause', string>> | undefined;\n const playLabel = locale?.play ?? 'Play slideshow';\n const pauseLabel = locale?.pause ?? 'Pause slideshow';\n\n let playing = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let currentVideo: PlayableMedia | null = null;\n let awaitingProviderVideo = false;\n let wasPlayingBeforeDrag = false;\n // Tracks only the *current* zoom/rotate-flip state, purely for\n // toggle()'s \"was it already engaged the moment Play was pressed\"\n // check below — not reused for the pause-on-event logic itself, which\n // reacts to each zoomChange/rotateFlipChange event directly instead of\n // consulting these.\n let zoomedIn = false;\n let rotatedOrFlipped = false;\n let captionOpen = false;\n // Set only when this plugin itself stopped playback because of an\n // `onX: 'pause'` trigger — never for a manual stop, a `'stop'`-mode\n // trigger, `requestAutoplayStop`, or anything else that calls stop()\n // for an unrelated reason (video pause/end, drag-close, close()). Once\n // any of those flags is true, `maybeScheduleResume()` (below) is what's\n // waiting for the *matching* engagement flag (`zoomedIn`/\n // `rotatedOrFlipped`/`captionOpen`) to clear before it'll actually\n // queue the debounced resume — see `RESUME_DEBOUNCE_MS`'s own doc\n // comment for why that's a debounce and not instant.\n let pausedByZoom = false;\n let pausedByRotateFlip = false;\n let pausedByCaptionExpand = false;\n let resumeTimer: ReturnType<typeof setTimeout> | null = null;\n\n function cancelPendingResume(): void {\n if (resumeTimer !== null) {\n clearTimeout(resumeTimer);\n resumeTimer = null;\n }\n }\n\n /** Called on every hard stop (manual, `'stop'`-mode trigger, `requestAutoplayStop`, manual navigation, or anything else) — a hard stop always wins outright over a softer pending `'pause'`-mode resume from a *different* trigger, otherwise un-rotating after a hard zoom-stop could still spring the slideshow back to life on its own. */\n function clearPauseFlags(): void {\n pausedByZoom = false;\n pausedByRotateFlip = false;\n pausedByCaptionExpand = false;\n cancelPendingResume();\n }\n\n /**\n * Queues the actual resume once every `'pause'`-mode trigger that\n * caused the current stop has genuinely disengaged — not on the first\n * instant all three read as disengaged, but after `RESUME_DEBOUNCE_MS`\n * of that holding true, restarting the wait on every call (so\n * `zoomChange`/`rotateFlipChange`/`captionModalChange` re-engaging\n * before it fires cancels and re-arms it rather than stacking a second\n * timer). A no-op if nothing is actually pending — called from every\n * disengage point regardless of whether anything's waiting, cheaper\n * than each call site checking first.\n */\n function isEngaged(): boolean {\n return (\n (onZoom !== false && zoomedIn) ||\n (onRotateFlip !== false && rotatedOrFlipped) ||\n (onCaptionExpand !== false && captionOpen)\n );\n }\n\n function maybeScheduleResume(): void {\n if (!(pausedByZoom || pausedByRotateFlip || pausedByCaptionExpand)) return;\n if (isEngaged()) return;\n cancelPendingResume();\n resumeTimer = setTimeout(() => {\n resumeTimer = null;\n // Re-checked here, not just at the top of this function above — a\n // real bug, caught by this file's own test: a *different* trigger\n // can re-engage while this timer is already ticking down without\n // ever calling this function again (its own handler only reaches\n // maybeScheduleResume() when *it* transitions to disengaged, not\n // when it transitions to engaged) — e.g. rotating while a zoom\n // resume is already pending. Firing start() unconditionally would\n // resume playback while still visibly rotated. Leaves the pending\n // flags alone rather than clearing them: whichever trigger\n // eventually disengages next calls maybeScheduleResume() again and\n // finds them still set.\n if (isEngaged()) return;\n clearPauseFlags();\n start();\n }, RESUME_DEBOUNCE_MS);\n }\n\n // Set for the exact duration of advance()'s own gallery.next() call —\n // the afterSlide handler below fires synchronously inside it, so it can\n // tell \"this slide change is autoplay's own advance()\" apart from any\n // other navigation (arrows/buttons/swipe/goTo()) without needing the\n // event itself to carry a source. See stopOnManualNavigate above.\n let isAdvancing = false;\n\n // A real bug, regression: this used to capture gallery.getActiveMedia()\n // once here and listen on that node directly, back when a pool slot's\n // own offset never changed after construction (only its *content*\n // moved between slots) — so \"whichever slot has offset 0\" was always\n // the same physical node, safe to capture once. SlideManager's pool now\n // relabels a slot's offset in place instead (§2.3) — the node that\n // happened to be offset 0 when this plugin initialized can become a\n // neighbor after even one navigation, while a *different* node becomes\n // the active one, silently going unheard by this listener. Listening on\n // `ctx.ui.outer()` instead (the whole lightbox, never relabeled) still\n // catches a provider's own error event (§4-video's `onError`, dispatched\n // with `bubbles: true`) regardless of which slide it came from — the\n // `contains()` check below is what actually scopes it to the currently\n // active slide, re-resolved fresh on every error rather than trusting a\n // stale reference.\n const outer = ctx.ui.outer();\n function onVideoError(event: Event): void {\n if (!playing) return;\n const active = gallery.getActiveMedia();\n if (active && event.target instanceof Node && active.contains(event.target)) advance();\n }\n outer.addEventListener('error', onVideoError);\n\n const button = document.createElement('button');\n button.type = 'button';\n // shoji-autoplay-toggle: a stable hook for host code that needs to find\n // this button from outside (e.g. to pause the slideshow before opening\n // its own UI on top) — `title`/`aria-label` swap with `locale`, so\n // matching on those breaks silently the moment a host customizes it.\n button.className = 'shoji-toolbar-button shoji-autoplay-toggle';\n button.setAttribute('aria-label', playLabel);\n button.title = playLabel;\n const iconSwap = createIconSwap(PLAY_ICON, PAUSE_ICON);\n button.appendChild(iconSwap.el);\n\n const progress = document.createElement('div');\n progress.className = 'shoji-autoplay-progress';\n progress.hidden = true;\n const progressBar = document.createElement('div');\n progressBar.className = 'shoji-autoplay-progress-bar';\n progress.appendChild(progressBar);\n\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function resetProgressBar(): void {\n if (!showProgress) return;\n progress.hidden = true;\n progressBar.style.transition = 'none';\n progressBar.style.width = '0%';\n }\n\n function runProgressBar(ms: number): void {\n if (!showProgress) return;\n progress.hidden = false;\n progressBar.style.transition = 'none';\n progressBar.style.width = '0%';\n void progressBar.offsetWidth; // commit the reset before transitioning\n progressBar.style.transition = `width ${ms}ms linear`;\n progressBar.style.width = '100%';\n }\n\n /**\n * DESIGN.md §4.1 — while `onZoom`/`onRotateFlip` is holding\n * playback paused, pressing Play would otherwise just silently\n * re-pause it in the same synchronous tick (`toggle()`'s own check,\n * below) — no `transitionend`, no paint in between the two state\n * flips, so the button never visibly shows \"Pause\" at all before\n * reverting. Reported as looking broken, not just quiet. Disabling\n * the button while blocked (same `aria-disabled`/`tabIndex`/CSS\n * pattern as core's own slide-loading disable, Gallery.ts's\n * `setSlideLoading()`) makes \"you can't resume yet\" an honest, visible\n * state instead of a click that does nothing. Only while *not*\n * playing — while playing, the button always shows/means Pause, and\n * must stay clickable to stop regardless of zoom/rotate state.\n */\n function updateToggleAvailability(): void {\n const blocked =\n !playing &&\n ((onZoom !== false && zoomedIn) || (onRotateFlip !== false && rotatedOrFlipped));\n button.ariaDisabled = blocked ? 'true' : null;\n if (blocked) button.tabIndex = -1;\n else button.removeAttribute('tabindex');\n }\n\n function setButtonState(isPlaying: boolean): void {\n playing = isPlaying;\n iconSwap.setState(isPlaying);\n button.setAttribute('aria-label', isPlaying ? pauseLabel : playLabel);\n button.title = isPlaying ? pauseLabel : playLabel;\n updateToggleAvailability();\n }\n\n function onVideoEnded(): void {\n if (playing) advance();\n }\n\n // A real user pause, as opposed to the pause some browsers fire\n // immediately alongside 'ended' — `.ended` disambiguates the two.\n // Provider videos (§4.3's renderers) are responsible for holding their\n // own 'pause' dispatch back if it might just be a natural end arriving\n // slightly early — vimeo.ts's `PAUSE_DISPATCH_DELAY_MS` is why.\n function onVideoPause(): void {\n if (currentVideo?.ended) return;\n stop();\n }\n\n function detachVideo(): void {\n if (!currentVideo) return;\n currentVideo.removeEventListener('ended', onVideoEnded);\n currentVideo.removeEventListener('pause', onVideoPause);\n currentVideo = null;\n }\n\n // A provider embed (e.g. YouTube) is cross-origin — unlike native\n // <video>, its own autoplay policy requires a *direct* user gesture on\n // the embed itself, which an automatic play() arriving via this\n // timer/'ended'/slideItemLoad chain never has; it silently no-ops\n // rather than rejecting, so there's nothing to catch. Muting first is\n // what actually gets it to play — the viewer can still unmute via the\n // embed's own controls.\n //\n // A real bug, reported from real usage, found only once a second\n // promise-returning provider (Vimeo) existed to compare against:\n // re-issuing `play()`/`muted = true` on every retry — needed for\n // YouTube, whose fire-and-forget `playVideo()` can silently drop a\n // command issued before its postMessage bridge is fully settled — does\n // the opposite for a provider whose `play()` genuinely returns a\n // promise. Confirmed directly, isolated from Shoji entirely: a single,\n // uninterrupted `play()` call reliably started Vimeo playback in\n // ~1.6s, while calling it again every 400ms (this loop's original,\n // unconditional behavior) kept it stuck indefinitely — each new call\n // resets the progress the previous one had already made, so it never\n // gets an uninterrupted run long enough to actually start. (This is\n // also what point 12 below's retry-exhaustion was actually skipping\n // past: not a broken video, but this loop's own repeated calls\n // preventing it from ever finishing what the first one started.)\n // `video.play()`'s return type only *claims* to be a promise for every\n // provider (see the `PlayableMedia` doc comment above) — branching on\n // whether it genuinely is one is what lets each provider get the\n // retry behavior it actually needs from this one shared function.\n function ensureProviderPlaying(video: PlayableMedia, attemptsLeft: number): void {\n video.muted = true;\n const playResult = video.play();\n if (playResult && typeof playResult.then === 'function') {\n pollWithoutReissuing(video, attemptsLeft, playResult);\n } else {\n reissueOnEachRetry(video, attemptsLeft);\n }\n }\n\n /** Fire-and-forget `play()` (YouTube) — re-issues the command itself on every retry, per this function's own doc comment above. */\n function reissueOnEachRetry(video: PlayableMedia, attemptsLeft: number): void {\n setTimeout(() => {\n if (currentVideo !== video || !playing) return; // stale — slide changed, or already stopped\n if (!video.paused) return; // took effect\n if (attemptsLeft > 0) ensureProviderPlaying(video, attemptsLeft - 1);\n // Exhausted every retry after already muting first — muted\n // autoplay is essentially never blocked by policy, so this means\n // something is genuinely wrong with the embed, not that it's\n // waiting on a gesture. advance() (not stop()) so a slow/late\n // error report (real usage: YouTube's own error can arrive slower\n // than this retry window, e.g. Error 153) can't leave the\n // slideshow stuck if this fires first.\n else advance();\n }, PROVIDER_PLAY_RETRY_MS);\n }\n\n /** A genuine `play()` promise (e.g. Vimeo) — the command itself is only ever issued once (by the caller); this only re-checks `.paused` on the same schedule, over the same total budget, without ever calling `play()` again. */\n function pollWithoutReissuing(\n video: PlayableMedia,\n attemptsLeft: number,\n playResult: Promise<void>,\n ): void {\n // Swallowed deliberately: a rejection here isn't distinguished from\n // \"still pending\" — the .paused poll below is what actually decides\n // whether this took effect, on the same schedule regardless of how\n // the promise itself settles. An unhandled-rejection console warning\n // is the only cost, same tradeoff as the native <video> path below\n // taking a real .catch() instead when it needs to branch on *why*.\n playResult.catch(() => {});\n setTimeout(() => {\n if (currentVideo !== video || !playing) return;\n if (!video.paused) return;\n if (attemptsLeft > 0) pollWithoutReissuing(video, attemptsLeft - 1, playResult);\n else advance();\n }, PROVIDER_PLAY_RETRY_MS);\n }\n\n function enterSlide(): void {\n clearTimer();\n detachVideo();\n resetProgressBar();\n awaitingProviderVideo = false;\n if (!playing) return;\n\n const media = gallery.getActiveMedia();\n const video = findPlayable(media);\n if (video) {\n currentVideo = video;\n video.addEventListener('ended', onVideoEnded);\n video.addEventListener('pause', onVideoPause);\n if (video instanceof HTMLVideoElement) {\n const playResult = video.play();\n // A rejected play() has two different causes that look identical\n // here: the browser blocking an unmuted play() that isn't a direct\n // continuation of a user gesture (NotAllowedError — the video is\n // fine, it just needs the viewer's own click) or the video\n // genuinely being unplayable (NotSupportedError — a broken/missing\n // source, an unsupported format). Only the first pauses the\n // slideshow for the viewer to resolve by hand; anything else means\n // there's nothing to wait for, so it skips ahead instead.\n if (playResult && typeof playResult.catch === 'function') {\n playResult.catch((error: unknown) => {\n if (currentVideo !== video || !playing) return; // stale\n if (error instanceof DOMException && error.name === 'NotAllowedError') stop();\n else advance();\n });\n }\n } else {\n ensureProviderPlaying(video, MAX_PROVIDER_PLAY_ATTEMPTS);\n }\n return;\n }\n\n // A provider video (e.g. YouTube) still mid-setup isn't an ordinary\n // slide either — the slideItemLoad listener below re-enters once it's\n // actually playable. This timer is a fallback in case that never\n // happens (network failure, blocked, ...), so the slideshow can't\n // stall on it forever.\n awaitingProviderVideo = isPendingProviderVideo(media);\n runProgressBar(interval);\n timer = setTimeout(advance, interval);\n }\n\n function advance(): void {\n const before = gallery.currentIndex;\n isAdvancing = true;\n gallery.next();\n isAdvancing = false;\n // loop:false and next() was already at the last item — nothing left\n // to advance to; the 'afterSlide' handler below won't fire for a\n // no-op goTo(), so this is the only place that can catch it.\n if (gallery.currentIndex === before) stop();\n }\n\n function start(): void {\n if (playing) return;\n // A manual start succeeding makes any still-ticking 'pause'-mode\n // resume timer moot — harmless left alone (its own eventual start()\n // call would just no-op against the `if (playing) return` above), but\n // cancelling it here avoids a dangling timer doing nothing for up to\n // RESUME_DEBOUNCE_MS after this already resolved things.\n cancelPendingResume();\n setButtonState(true);\n ctx.emit('autoplayStart', {});\n enterSlide();\n }\n\n function stop(): void {\n if (!playing) return;\n setButtonState(false);\n clearTimer();\n resetProgressBar();\n if (currentVideo && !currentVideo.paused) currentVideo.pause();\n detachVideo();\n ctx.emit('autoplayStop', {});\n }\n\n // A real bug, reported from real usage: zooming in *first*, then\n // pressing Play, never paused at all — clicking Play doesn't itself\n // fire zoomChange/rotateFlipChange, and a single-step \"toggle back to\n // neutral\" action afterward (Actual size, double-tap-to-reset) only\n // ever emits the *already-neutral* event, never one crossing the\n // engaged threshold — so nothing downstream would ever have caught it\n // either. Re-checked here instead, right after a genuine manual\n // start — the one path a viewer can actually reach a non-neutral view\n // state from *before* pressing Play. `zoomedIn`/`rotatedOrFlipped`\n // (below) track only the *current* state, purely for this check —\n // deliberately not reused for the pause-on-event logic itself, which\n // reacts to each event directly. Shared by toggle()'s manual-start path\n // and requestAutoplayStart below — both are \"a genuine manual start,\"\n // just triggered from a different control.\n function reCheckEngagedAfterManualStart(): void {\n const stillZoomed = onZoom !== false && zoomedIn;\n const stillRotated = onRotateFlip !== false && rotatedOrFlipped;\n if (!stillZoomed && !stillRotated) return;\n stop();\n // Threading pause-mode tracking through *this* re-stop too (not just\n // the zoomChange/rotateFlipChange handlers below) is what avoids\n // repeating the first auto-resume attempt's other real bug: a manual\n // restart while still engaged left that design's own edge-tracker\n // permanently \"already engaged,\" silently skipping the next\n // re-pause's resume tracking. Setting the flag here, at the actual\n // moment this stop happens, means it's never missed regardless of\n // which path (button/Space, or a custom plugin's requestAutoplayStart)\n // triggered the manual start.\n if (onZoom === 'pause' && stillZoomed) pausedByZoom = true;\n if (onRotateFlip === 'pause' && stillRotated) pausedByRotateFlip = true;\n }\n\n function toggle(): void {\n if (playing) {\n clearPauseFlags(); // a real manual pause is always a hard stop, never a pending soft-resume\n stop();\n return;\n }\n start();\n reCheckEngagedAfterManualStart();\n }\n\n /**\n * Pauses the slideshow the instant a vertical drag crosses the close\n * threshold, mirroring the controls' own live hide cue\n * (`dragCloseThreshold`) — asked for directly, otherwise the\n * interval/video kept running mid-drag. Resumes only if *this*\n * crossing paused it — a manual pause (toolbar, mid-drag tap) must\n * stay paused even if the drag retreats back under the threshold.\n */\n const offDragThreshold = ctx.on('dragCloseThreshold', ({ hidden }) => {\n if (hidden) {\n wasPlayingBeforeDrag = playing;\n if (playing) {\n clearPauseFlags(); // a hard stop, unrelated to onZoom/onRotateFlip/onCaptionExpand — must not resurrect a pending soft-resume from one of those\n stop();\n }\n } else if (wasPlayingBeforeDrag) {\n wasPlayingBeforeDrag = false;\n start();\n }\n });\n\n /**\n * DESIGN.md §4.1 — a real UX gap, not a reported bug: nothing stopped\n * the slideshow from auto-advancing out from under a viewer actively\n * zoomed into a detail on the current slide. Only reacts to\n * `zoomChange`'s event *shape* (`core/types.ts`) — never imports Zoom\n * directly, so this is a no-op with it not loaded, or with `onZoom:\n * false` set explicitly (events over inheritance, CLAUDE.md).\n *\n * `'stop'` mode never auto-resumes, matching this plugin's *first*\n * attempt at this feature — see `RESUME_DEBOUNCE_MS`'s own doc comment\n * for the two real problems that attempt hit and why `'pause'` mode\n * (below) is built differently, not just re-adding the same thing\n * under a new name. `scale > 1` still gates *which* zoomChange events\n * count (an ordinary scale-1 event can also fire from an unrelated\n * slide-change reset, not a real interaction — `zoom/index.ts`'s\n * `reset()` — so it can't unconditionally pause on every event the way\n * rotateFlipChange below safely can).\n */\n const ZOOM_ENGAGED_THRESHOLD = 1.001; // matches Zoom's own ZOOM_EPSILON — \"just barely above 1\" is float residue, not a real zoom\n const offZoomChange = ctx.on('zoomChange', ({ scale }) => {\n zoomedIn = scale > ZOOM_ENGAGED_THRESHOLD;\n if (onZoom !== false && zoomedIn && playing) {\n if (onZoom === 'stop') clearPauseFlags();\n stop();\n if (onZoom === 'pause') pausedByZoom = true;\n } else {\n // stop() above already refreshes toggle availability; this branch\n // covers zooming in while already paused (stop() wouldn't touch\n // it) and zooming back out, which may have just disengaged the\n // last thing a pending 'pause'-mode resume was waiting on.\n updateToggleAvailability();\n if (!zoomedIn) maybeScheduleResume();\n }\n });\n /**\n * Same UX gap, RotateFlip's own equivalent (see `onRotateFlip`'s own\n * doc comment). Pauses on *any* `rotateFlipChange` event\n * unconditionally, including one that lands back on the original\n * orientation — confirmed directly, reported from real usage: rotate\n * four times back to 0deg still reads as an active interruption of the\n * slideshow, not \"nothing happened,\" so it must still pause too, the\n * same as landing anywhere else, in *both* modes — `'pause'` mode's\n * auto-resume is debounced specifically so this repeated-neutral case\n * doesn't spring it back to life between clicks (`RESUME_DEBOUNCE_MS`).\n * Every `rotateFlipChange` (unlike zoomChange above) only ever fires\n * from a real button/shortcut click — `rotateFlip/index.ts`'s own\n * per-slide `reset()` never emits it — so no extra state check is\n * needed here the way zoomChange's `scale > 1` gate is.\n */\n const offRotateFlipChange = ctx.on('rotateFlipChange', ({ flipH, flipV, rotation }) => {\n rotatedOrFlipped = flipH || flipV || rotation !== 0;\n if (onRotateFlip !== false && playing) {\n if (onRotateFlip === 'stop') clearPauseFlags();\n stop();\n if (onRotateFlip === 'pause') pausedByRotateFlip = true;\n } else {\n updateToggleAvailability(); // stop() above already refreshes this; covers rotating while already paused, which stop() wouldn't touch\n if (onRotateFlip !== false && !rotatedOrFlipped) maybeScheduleResume();\n }\n });\n /**\n * `onCaptionExpand`'s own doc comment above — unlike the two listeners\n * above, no `updateToggleAvailability()` companion call: the caption\n * modal already makes Play physically unreachable while `open: true`\n * (core's own focus trap + capture-phase keydown blocking, not\n * anything this plugin has to enforce), so there's no \"pressed Play\n * while still blocked\" case to disable the button for or re-check on\n * toggle() the way zoom/rotateFlip both need. `captionOpen` is still\n * tracked (unlike before `'pause'` mode existed) purely so\n * `maybeScheduleResume()` can confirm nothing else is also still\n * engaged before it queues a resume.\n */\n const offCaptionModalChange = ctx.on('captionModalChange', ({ open }) => {\n captionOpen = open;\n if (onCaptionExpand !== false && open && playing) {\n if (onCaptionExpand === 'stop') clearPauseFlags();\n stop();\n if (onCaptionExpand === 'pause') pausedByCaptionExpand = true;\n } else if (!open) {\n maybeScheduleResume();\n }\n });\n\n button.addEventListener('click', toggle);\n\n // 'right' — clusters immediately before the close button, per DESIGN.md §3.1.\n const removeButton = ctx.ui.toolbar('right', button);\n const removeProgress = showProgress ? ctx.ui.overlay(progress) : null;\n const removeShortcut = ctx.ui.registerShortcut(' ', toggle);\n // Detaches this plugin's own 'pause'/'ended' listeners from the outgoing\n // video before Gallery.navigate() pauses it (see Gallery.ts's comment on\n // this same event) — otherwise that pause is misread as the viewer\n // manually pausing, which stops the slideshow before the new slide's\n // afterSlide handler below ever runs. enterSlide() below also calls\n // detachVideo(), but by then it's too late for *this* transition; that\n // call is what handles the slide *after* this one instead.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n detachVideo();\n });\n // Any slide change — autoplay's own next(), or the viewer manually\n // navigating mid-slideshow via arrows/buttons/goTo() — re-enters here,\n // tearing down the previous slide's timer/video listeners and setting\n // up fresh ones for whatever is active now. advance() deliberately does\n // NOT call enterSlide() itself: next() already triggers this listener\n // synchronously, so calling it twice would double up the timer/video wiring.\n const offSlide = ctx.on('afterSlide', () => {\n // Zoom/RotateFlip both reset unanimated on navigation (DESIGN.md\n // §2.5) without re-emitting zoomChange/rotateFlipChange — resynced\n // here so a stale \"was engaged\" reading from the *outgoing* slide\n // can't wrongly re-pause toggle()'s next Play press on a slide\n // that's actually neutral now. Also clears any pending 'pause'-mode\n // resume outright, not just the flags it was waiting on — the slide\n // it was paused *for* isn't even the active one anymore, so whether\n // to resume here is genuinely ambiguous; `stopOnManualNavigate`\n // (default true) already decides what actually happens next.\n zoomedIn = false;\n rotatedOrFlipped = false;\n clearPauseFlags();\n updateToggleAvailability();\n if (!playing) return;\n // stopOnManualNavigate (default true, see its own doc comment) —\n // isAdvancing is only ever true for the exact duration of advance()'s\n // own gallery.next() call above, so its absence here means something\n // other than autoplay itself moved the slide.\n if (stopOnManualNavigate && !isAdvancing) stop();\n else enterSlide();\n });\n // A provider video (§4-video) that was still mid-setup when enterSlide()\n // last ran — see awaitingProviderVideo there — becomes playable some\n // time after afterSlide already fired and gave up on it for this pass.\n // Re-enter once it's genuinely ready, scoped to the still-active index\n // so a slide the viewer has already moved past doesn't retroactively\n // hijack the timer.\n const offSlideItemLoad = ctx.on('slideItemLoad', ({ index }) => {\n if (playing && awaitingProviderVideo && index === gallery.currentIndex) enterSlide();\n });\n /**\n * DESIGN.md §4.1 point 20 — a generic command surface, requested\n * directly, so a *custom* (host-authored) plugin's own toolbar button\n * can start/pause the slideshow without importing this plugin at all,\n * the same \"events over inheritance\" decoupling every other listener\n * here already uses for official plugins (`zoomChange`,\n * `rotateFlipChange`, `captionModalChange`, `dragCloseThreshold`).\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestAutoplayStop', {})` from any plugin\n * — official or custom — type-checks with zero core changes; this is\n * just the listening half. Deliberately two separate commands, not one\n * toggle — a custom plugin building its own distinct Play/Pause\n * controls (rather than one button that flips) needs to command each\n * state directly, not guess at the current one. Both no-op in the\n * already-there state (`stop()`'s own existing guard for pause;\n * `start()`'s own existing guard, plus the same manual-start re-check\n * `toggle()`'s button/Space path uses, for start).\n */\n const offRequestStop = ctx.on('requestAutoplayStop', () => {\n if (playing) {\n clearPauseFlags(); // a command from another plugin is treated like a manual pause, not a soft pending resume\n stop();\n }\n });\n const offRequestStart = ctx.on('requestAutoplayStart', () => {\n if (playing) return;\n start();\n reCheckEngagedAfterManualStart();\n });\n const offClose = ctx.on('close', () => {\n clearPauseFlags();\n stop();\n });\n const offOpen = ctx.on('afterOpen', () => {\n zoomedIn = false;\n rotatedOrFlipped = false;\n captionOpen = false;\n clearPauseFlags();\n updateToggleAvailability();\n if (autoStart) start();\n });\n\n return () => {\n cancelPendingResume(); // a pending 'pause'-mode resume must not fire start() after teardown\n stop();\n outer.removeEventListener('error', onVideoError);\n removeButton();\n removeProgress?.();\n removeShortcut();\n offBeforeSlide();\n offSlide();\n offSlideItemLoad();\n offOpen();\n offClose();\n offDragThreshold();\n offZoomChange();\n offRotateFlipChange();\n offCaptionModalChange();\n offRequestStop();\n offRequestStart();\n };\n },\n};\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. Four corner-arrow glyphs, a generic \"expand\"/\"collapse\" pair, not tied to any particular icon set. */\nexport const EXPAND_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5\"/></svg>';\n\nexport const COMPRESS_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { createIconSwap } from '../../core/iconSwap';\nimport { COMPRESS_ICON, EXPAND_ICON } from './icons';\n\n/**\n * Vendor-prefixed Fullscreen API surface (older Safari) — not in standard\n * `lib.dom.d.ts`, so this is a documented interop boundary (CLAUDE.md: `any`\n * only there). Everything else in this file uses the standard,\n * already-typed `Element.requestFullscreen`/`Document.exitFullscreen`/\n * `Document.fullscreenElement`/`Document.fullscreenEnabled`.\n */\ninterface WebkitFullscreenElement extends HTMLElement {\n webkitRequestFullscreen?: () => void;\n}\ninterface WebkitFullscreenDocument extends Document {\n webkitExitFullscreen?: () => void;\n webkitFullscreenElement?: Element | null;\n webkitFullscreenEnabled?: boolean;\n}\n\nfunction isSupported(): boolean {\n return !!(\n document.fullscreenEnabled || (document as WebkitFullscreenDocument).webkitFullscreenEnabled\n );\n}\n\nfunction currentFullscreenElement(): Element | null {\n return (\n document.fullscreenElement ??\n (document as WebkitFullscreenDocument).webkitFullscreenElement ??\n null\n );\n}\n\nfunction requestFullscreen(el: HTMLElement): void {\n const target = el as WebkitFullscreenElement;\n if (target.requestFullscreen) target.requestFullscreen().catch(() => {});\n else target.webkitRequestFullscreen?.();\n}\n\nfunction exitFullscreen(): void {\n const doc = document as WebkitFullscreenDocument;\n if (document.exitFullscreen) document.exitFullscreen().catch(() => {});\n else doc.webkitExitFullscreen?.();\n}\n\n/**\n * DESIGN.md §4 — native Fullscreen API toggle, `.shoji-outer` (`ctx.ui.outer()`,\n * the whole lightbox — backdrop, dialog, controls) is what goes fullscreen,\n * not just the slide media. No toolbar button at all — not a disabled one —\n * on a browser with no Fullscreen API support (checked once at `init()`;\n * historically Safari on iOS), rather than shipping a dead control.\n *\n * `fullscreenchange` (plus the `webkitfullscreenchange` vendor variant) is\n * the single source of truth for button state, not the click handler\n * directly — a real Fullscreen API `request`/`exit` call can be rejected\n * (permission, another element already fullscreen, etc.), and the browser's\n * own Escape-key fullscreen exit doesn't go through this plugin's click\n * handler at all. Reacting to the event instead of the request keeps the\n * button correct regardless of *why* fullscreen state changed.\n */\nexport const Fullscreen: ShojiPlugin = {\n name: 'fullscreen',\n\n init(ctx: PluginContext): (() => void) | void {\n if (!isSupported()) return;\n\n const outer = ctx.ui.outer();\n const locale = (ctx.gallery.options.locale ?? {}) as Record<string, string>;\n const enterLabel = locale.enterFullscreen ?? 'Enter fullscreen';\n const exitLabel = locale.exitFullscreen ?? 'Exit fullscreen';\n\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n const iconSwap = createIconSwap(EXPAND_ICON, COMPRESS_ICON);\n button.appendChild(iconSwap.el);\n button.setAttribute('aria-label', enterLabel);\n button.title = enterLabel;\n button.setAttribute('aria-pressed', 'false');\n\n function isActive(): boolean {\n return currentFullscreenElement() === outer;\n }\n\n function setState(active: boolean): void {\n iconSwap.setState(active);\n button.setAttribute('aria-label', active ? exitLabel : enterLabel);\n button.title = active ? exitLabel : enterLabel;\n button.setAttribute('aria-pressed', String(active));\n }\n\n /** Shared by the toolbar button and `requestFullscreenToggle` below. */\n function toggleFullscreen(): void {\n if (isActive()) exitFullscreen();\n else requestFullscreen(outer);\n }\n button.addEventListener('click', toggleFullscreen);\n\n const onChange = (): void => {\n const active = isActive();\n setState(active);\n ctx.emit('fullscreenChange', { fullscreen: active });\n };\n document.addEventListener('fullscreenchange', onChange);\n document.addEventListener('webkitfullscreenchange', onChange);\n\n // 'right' — clusters immediately before the close button (DESIGN.md §3.1).\n const removeButton = ctx.ui.toolbar('right', button);\n\n // Browser-level Escape-to-exit-fullscreen behavior is inconsistent\n // across browsers (some exit fullscreen and still deliver the page its\n // own Escape keydown, some don't) — closing the gallery explicitly\n // exits fullscreen too, rather than risking the page getting stuck\n // fullscreen-on-nothing after the lightbox itself is gone.\n const offClose = ctx.on('close', () => {\n if (isActive()) exitFullscreen();\n });\n /**\n * A generic command surface, requested directly (DESIGN.md §4.4), so a\n * *custom* (host-authored) plugin's own button can toggle fullscreen\n * without importing this plugin at all — same \"events over\n * inheritance\" decoupling `close` above already uses.\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestFullscreenToggle', {})` from any\n * plugin — official or custom — type-checks with zero core changes;\n * this is just the listening half.\n */\n const offRequestToggle = ctx.on('requestFullscreenToggle', toggleFullscreen);\n\n return () => {\n document.removeEventListener('fullscreenchange', onChange);\n document.removeEventListener('webkitfullscreenchange', onChange);\n removeButton();\n offClose();\n offRequestToggle();\n if (isActive()) exitFullscreen();\n };\n },\n};\n","/**\n * DESIGN.md §5.2 — deterministic, measure-free layout: positions come purely\n * from each tile's aspect ratio, never from measuring a loaded image (that's\n * exactly what causes the layout-jump problem most masonry libraries have).\n * Pure functions, no DOM — testable in isolation from rendering.\n */\n\nexport interface MasonryTile {\n /** Natural aspect ratio only — any unit works as long as width/height share one. */\n width: number;\n height: number;\n}\n\nexport interface MasonryPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface MasonryOptions {\n containerWidth: number;\n /** Gap *between* columns (horizontal). */\n gutterX: number;\n /** Gap *between* tiles stacked within a column (vertical). */\n gutterY: number;\n columns: number | 'auto';\n columnWidth: number;\n minColumnWidth: number;\n maxColumnWidth: number;\n fill: 'shortest' | 'ordered';\n}\n\nexport interface MasonryResult {\n positions: MasonryPosition[];\n columnCount: number;\n columnWidth: number;\n /** Per-column running height, incl. trailing gutterY — feed back in as `startHeights` to continue packing (e.g. an appended page) without relaying out earlier tiles. */\n columnHeights: number[];\n containerHeight: number;\n}\n\n/**\n * `'auto'` column count is `containerWidth / columnWidth`, floored — at odd\n * container widths that division can drift the *effective* per-column width\n * well past `columnWidth` before the count itself changes (e.g. 601px at a\n * 200px target floors to 3 columns of ~200px, but 999px floors to 4 columns\n * of ~250px). `minColumnWidth`/`maxColumnWidth` cap how far that drift goes\n * before the column count itself adjusts, so columns never go stringy-narrow\n * or stretch too wide at awkward container sizes. Only `gutterX` (the axis\n * columns are laid out along) factors into this — `gutterY` never affects\n * column count/width.\n */\nexport function computeColumnCount(options: MasonryOptions): number {\n const { containerWidth, gutterX, columns } = options;\n if (typeof columns === 'number') return Math.max(1, Math.floor(columns));\n\n const target = Math.max(\n 1,\n Math.floor((containerWidth + gutterX) / (options.columnWidth + gutterX)),\n );\n const maxAllowedByMin = Math.max(\n 1,\n Math.floor((containerWidth + gutterX) / (options.minColumnWidth + gutterX)),\n );\n const minRequiredByMax = Math.max(\n 1,\n Math.ceil((containerWidth + gutterX) / (options.maxColumnWidth + gutterX)),\n );\n // minRequiredByMax can exceed maxAllowedByMin at a pathological config\n // (minColumnWidth > maxColumnWidth) — minRequiredByMax wins rather than\n // silently violating maxColumnWidth in that case.\n return Math.max(minRequiredByMax, Math.min(target, maxAllowedByMin));\n}\n\nexport function computeColumnWidth(\n containerWidth: number,\n gutterX: number,\n columnCount: number,\n): number {\n return (containerWidth - gutterX * (columnCount - 1)) / columnCount;\n}\n\n/**\n * Packs `tiles` into columns. `startHeights` (one entry per column, from a\n * previous `MasonryResult.columnHeights`) continues packing after already-\n * placed tiles instead of relaying out from scratch — this is what makes an\n * infinite-scroll append O(new items): earlier tiles' positions never change.\n */\nexport function layoutMasonry(\n tiles: readonly MasonryTile[],\n options: MasonryOptions,\n startHeights?: readonly number[],\n): MasonryResult {\n const columnCount = computeColumnCount(options);\n const colWidth = computeColumnWidth(options.containerWidth, options.gutterX, columnCount);\n const columnHeights =\n startHeights && startHeights.length === columnCount\n ? [...startHeights]\n : new Array<number>(columnCount).fill(0);\n\n const positions: MasonryPosition[] = tiles.map((tile, i) => {\n const colIndex = options.fill === 'ordered' ? i % columnCount : indexOfShortest(columnHeights);\n const tileHeight = tile.width > 0 ? colWidth * (tile.height / tile.width) : colWidth;\n const x = colIndex * (colWidth + options.gutterX);\n const y = columnHeights[colIndex]!;\n columnHeights[colIndex] = y + tileHeight + options.gutterY;\n return { x, y, width: colWidth, height: tileHeight };\n });\n\n const containerHeight = tiles.length === 0 ? 0 : Math.max(...columnHeights) - options.gutterY;\n return { positions, columnCount, columnWidth: colWidth, columnHeights, containerHeight };\n}\n\nfunction indexOfShortest(heights: readonly number[]): number {\n let shortest = 0;\n for (let i = 1; i < heights.length; i++) {\n if (heights[i]! < heights[shortest]!) shortest = i;\n }\n return shortest;\n}\n\nexport interface MasonryHorizontalOptions {\n containerWidth: number;\n /** Gap between tiles packed rightward within a row. */\n gutterX: number;\n /** Gap *between* rows (vertical). */\n gutterY: number;\n /** Every row's exact, fixed height — never scaled/solved-for (that's what distinguishes this from `justified`, whose row heights are the free variable it adjusts to make each row's width land exactly on `containerWidth`; here, height is the fixed input and width is left wherever a row's tiles naturally end). */\n rowHeight: number;\n}\n\nexport interface MasonryHorizontalResult {\n positions: MasonryPosition[];\n rowCount: number;\n containerHeight: number;\n}\n\n/**\n * DESIGN.md §5.1 — packs tiles left-to-right into rows of `rowHeight` (each\n * tile scaled to that exact height at its own true aspect ratio, never\n * stretched/cropped), wrapping to a new row the moment the next tile would\n * push the current one past `containerWidth` — never stretching the\n * finished row to close the remaining gap. The result: every row is\n * *exactly* `rowHeight` tall (the fixed constraint), and every row's right\n * edge lands wherever its tiles' natural widths summed to (the free,\n * \"ragged\" one) — the direct masonry-family transpose of vertical masonry,\n * whose *columns* share a fixed width and whose ragged edge is the bottom.\n * `justified` (`justified.ts`) is the inverse tradeoff: width is the fixed\n * constraint (every row forced flush to `containerWidth`) and height is the\n * free variable solved per row to make that work.\n *\n * A single tile whose natural width at `rowHeight` alone already exceeds\n * `containerWidth` (a wide panorama) is still placed on its own row rather\n * than shrunk — nothing narrower to fall back to without violating the\n * fixed-height constraint, the same tradeoff `justified`'s `minRowHeight`\n * makes in its own analogous single-tile edge case.\n */\nexport function layoutMasonryHorizontal(\n tiles: readonly MasonryTile[],\n options: MasonryHorizontalOptions,\n): MasonryHorizontalResult {\n const { containerWidth, gutterX, gutterY, rowHeight } = options;\n const positions: MasonryPosition[] = new Array(tiles.length);\n let currentY = 0;\n let rowStart = 0;\n let rowWidth = 0; // cumulative width of tiles committed to the current row so far, gutters included\n let rowCount = 0;\n\n function tileWidth(tile: MasonryTile): number {\n return tile.height > 0 ? rowHeight * (tile.width / tile.height) : rowHeight;\n }\n\n function placeRow(start: number, endExclusive: number): void {\n let x = 0;\n for (let i = start; i < endExclusive; i++) {\n const w = tileWidth(tiles[i]!);\n positions[i] = { x, y: currentY, width: w, height: rowHeight };\n x += w + gutterX;\n }\n rowCount++;\n currentY += rowHeight + gutterY;\n }\n\n for (let i = 0; i < tiles.length; i++) {\n const w = tileWidth(tiles[i]!);\n const countInRow = i - rowStart;\n const widthIfIncluded = rowWidth + (countInRow > 0 ? gutterX : 0) + w;\n if (countInRow > 0 && widthIfIncluded > containerWidth) {\n placeRow(rowStart, i); // finalize the row without tile i — it starts the next one instead\n rowStart = i;\n rowWidth = w;\n } else {\n rowWidth = widthIfIncluded;\n }\n }\n if (rowStart < tiles.length) placeRow(rowStart, tiles.length);\n\n const containerHeight = tiles.length === 0 ? 0 : currentY - gutterY;\n return { positions, rowCount, containerHeight };\n}\n","/**\n * DESIGN.md §5.2 — Flickr/Google-Photos-style row filler: tiles are grouped\n * into rows, each row scaled as a whole (every tile in it keeps its own\n * aspect ratio, only the shared row height changes) until the row's total\n * width exactly matches the container — the opposite visual signature from\n * masonry: row *right edges* line up flush, row *heights* vary instead of\n * column bottoms varying. Pure, no DOM — same shape/testing pattern as\n * masonry.ts.\n */\n\nexport interface JustifiedTile {\n width: number;\n height: number;\n}\n\nexport interface JustifiedPosition {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface JustifiedOptions {\n containerWidth: number;\n /** Gap between tiles within a row (horizontal). */\n gutterX: number;\n /** Gap *between* rows (vertical). */\n gutterY: number;\n /** Target row height — rows are greedily filled until adding the next tile would exceed containerWidth at this height, then the whole row is rescaled to fit exactly (so actual row heights end up *near*, not always exactly at, this value). */\n rowHeight: number;\n /**\n * Bounds on a row's *scaled* (fill-the-container) height — an unusual mix\n * of aspect ratios (very few tiles, or very narrow/wide ones, e.g. a lone\n * portrait tile stretched to fill the container width under\n * `lastRow: 'justify'`) can otherwise scale a row to an extreme height.\n * `maxRowHeight` clamping means that row no longer exactly fills\n * `containerWidth` at its capped height — it falls short of the right\n * edge instead, the same tradeoff masonry's `maxColumnWidth` already\n * makes for the analogous reason. `minRowHeight` never causes that kind\n * of overflow, though, unlike a naive clamp would: a row that would need\n * to go below `minRowHeight` to fit exactly instead sheds tiles off its\n * end (rolled into the next row) until what's left *does* fit at\n * `minRowHeight` — rows never extend past `containerWidth`. The one\n * unavoidable exception is a single tile so wide/panoramic that even\n * alone it can't satisfy both bounds at once (`minRowHeight` at its own\n * aspect ratio is inherently wider than the container) — there,\n * `minRowHeight` itself yields rather than the row overflowing. Neither\n * bound applies to `lastRow: 'left'`, which already uses `rowHeight` as\n * a fixed, unscaled height rather than deriving one (and, being the\n * left-over *under*-full case by definition, never overflows either).\n */\n minRowHeight: number;\n maxRowHeight: number;\n /** How to handle the trailing row when there aren't enough tiles left to naturally reach containerWidth: 'justify' stretches it like any other row (Flickr-style — the default); 'left' keeps it at natural rowHeight-scaled size, left-aligned, empty space on the right; 'hide' excludes it from `positions` (returned as `null`) entirely. */\n lastRow: 'justify' | 'left' | 'hide';\n}\n\nexport interface JustifiedRow {\n /** Tile index range finalized into this row, `[start, end)`. */\n start: number;\n end: number;\n y: number;\n height: number;\n}\n\nexport interface JustifiedResult {\n /** One entry per input tile, same order — `null` only for a `lastRow: 'hide'`-excluded trailing tile. */\n positions: Array<JustifiedPosition | null>;\n containerHeight: number;\n /** One entry per finalized row, in order — lets a caller find which tiles landed on the same row (e.g. to decide where a compact section label belongs) without re-deriving it from `positions[i].y` equality. */\n rows: JustifiedRow[];\n}\n\nfunction aspectRatioOf(tile: JustifiedTile): number {\n return tile.width > 0 && tile.height > 0 ? tile.width / tile.height : 1;\n}\n\nexport function layoutJustified(\n tiles: readonly JustifiedTile[],\n options: JustifiedOptions,\n): JustifiedResult {\n const { containerWidth, gutterX, gutterY, rowHeight, minRowHeight, maxRowHeight, lastRow } =\n options;\n const positions: Array<JustifiedPosition | null> = new Array(tiles.length).fill(null);\n const rows: JustifiedRow[] = [];\n let currentY = 0;\n let rowStart = 0;\n let aspectSum = 0;\n\n function naturalHeightOf(startIndex: number, endExclusive: number, sum: number): number {\n const availableWidth = containerWidth - gutterX * (endExclusive - startIndex - 1);\n return availableWidth / sum;\n }\n\n function placeRow(startIndex: number, endExclusive: number, height: number): void {\n let x = 0;\n for (let i = startIndex; i < endExclusive; i++) {\n const width = height * aspectRatioOf(tiles[i]!);\n positions[i] = { x, y: currentY, width, height };\n x += width + gutterX;\n }\n rows.push({ start: startIndex, end: endExclusive, y: currentY, height });\n currentY += height + gutterY;\n }\n\n /**\n * Resolves `[startIndex, endExclusive)` (whose combined aspect ratio is\n * `sum`) into its final row, shedding tiles off the end — rolled into\n * whatever comes after — if honoring `minRowHeight` would otherwise push\n * this row's width past `containerWidth`. Returns the `endExclusive`\n * actually used, so the caller knows how many tiles (if any) got rolled\n * over and need to start the next row instead.\n */\n function resolveScaledRow(startIndex: number, endExclusive: number, sum: number): number {\n let end = endExclusive;\n let rowSum = sum;\n let yieldMinRowHeight = false;\n while (end - startIndex > 1 && naturalHeightOf(startIndex, end, rowSum) < minRowHeight) {\n // A real bug, reported from real usage: shedding the trailing tile\n // down to exactly one remaining tile only helps if that lone tile's\n // own natural height doesn't itself need `maxRowHeight` to clamp it\n // — otherwise shedding trades an under-`minRowHeight` row (merely a\n // bit short) for one that instead falls short of the *right edge*\n // (a visible gap, this file's own `maxRowHeight` tradeoff above) —\n // strictly worse, for nothing. Confirmed directly: a lone square\n // tile sandwiched between two wider neighbors landed exactly here.\n // Keep the wider grouping instead and let `minRowHeight` yield for\n // it too, same precedent the single-super-wide-tile case below\n // already establishes.\n if (end - startIndex === 2) {\n const soloNatural = naturalHeightOf(\n startIndex,\n startIndex + 1,\n aspectRatioOf(tiles[startIndex]!),\n );\n if (soloNatural > maxRowHeight) {\n yieldMinRowHeight = true;\n break;\n }\n }\n end--;\n rowSum -= aspectRatioOf(tiles[end]!);\n }\n const natural = naturalHeightOf(startIndex, end, rowSum);\n // Down to one tile and *still* under minRowHeight: that single tile's\n // own aspect ratio makes minRowHeight-at-full-width inherently wider\n // than the container — nothing left to shed, so minRowHeight yields\n // (the natural height keeps width exactly at containerWidth) rather\n // than ever letting the row overflow. `yieldMinRowHeight` extends the\n // same yield to the lone-tile-would-gap case just above.\n const height =\n (end - startIndex === 1 || yieldMinRowHeight) && natural < minRowHeight\n ? natural\n : Math.min(Math.max(natural, minRowHeight), maxRowHeight);\n placeRow(startIndex, end, height);\n return end;\n }\n\n for (let i = 0; i < tiles.length; i++) {\n aspectSum += aspectRatioOf(tiles[i]!);\n const count = i - rowStart + 1;\n const widthAtTargetHeight = rowHeight * aspectSum + gutterX * (count - 1);\n if (widthAtTargetHeight >= containerWidth) {\n const end = resolveScaledRow(rowStart, i + 1, aspectSum);\n rowStart = end;\n aspectSum = 0;\n for (let j = end; j <= i; j++) aspectSum += aspectRatioOf(tiles[j]!); // rolled-over tiles seed the next row\n }\n }\n\n if (rowStart < tiles.length) {\n if (lastRow === 'justify') {\n // resolveScaledRow can itself shed tiles (the same overflow-avoidance\n // as the main loop above) — unlike there, there's no \"next row\" this\n // far down for the outer loop to naturally roll them into, so keep\n // resolving whatever's left until every trailing tile lands\n // somewhere. Always makes forward progress (resolveScaledRow places\n // at least one tile per call), so this always terminates.\n let start = rowStart;\n while (start < tiles.length) {\n let sum = 0;\n for (let j = start; j < tiles.length; j++) sum += aspectRatioOf(tiles[j]!);\n start = resolveScaledRow(start, tiles.length, sum);\n }\n } else if (lastRow === 'left') {\n placeRow(rowStart, tiles.length, rowHeight);\n }\n // 'hide': positions stay null for this trailing range, currentY doesn't advance\n }\n\n const containerHeight = tiles.length === 0 ? 0 : Math.max(0, currentY - gutterY);\n return { positions, containerHeight, rows };\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport type { GalleryItem } from '../../core/types';\nimport { layoutMasonry, layoutMasonryHorizontal, type MasonryTile } from './masonry';\nimport { layoutJustified, type JustifiedOptions, type JustifiedResult } from './justified';\nimport './layout.css';\n\n/**\n * DESIGN.md §5 — `type: 'grid' | 'masonry' | 'justified'`; masonry supports\n * both `orientation`s, `breakpoints` (§5.4), and `groupBy`/headings (§5.2;\n * see that option's own doc comment for the v1 scope cuts vs. the full\n * spec, including why `groupBy` itself is excluded from `orientation:\n * 'horizontal'`). Deliberately still\n * deferred: jump-free *prepend* coordination (§5.2's scroll-anchoring\n * handoff needs the not-yet-built scroll plugin on the other end —\n * prepending today triggers a full relayout, which can shift scroll\n * position if content above the fold grew).\n */\nexport interface LayoutOptions {\n /** Default `'justified'`. */\n type?: 'grid' | 'masonry' | 'justified';\n gutter?: number | { x: number; y: number };\n /**\n * `type: 'grid'` only — every cell's shape, cropped to fit via\n * `object-fit: cover`; default 1 (square). Deliberately *not* each\n * photo's own aspect ratio: plain CSS grid sizes a row's height to its\n * tallest cell, so per-item ratios leave a visible blank gap under every\n * shorter tile sharing a row with a taller one. Masonry/justified are\n * the two types that preserve true per-photo aspect ratios instead (via\n * their own JS packing, which doesn't have this row-height problem).\n */\n aspectRatio?: number;\n /**\n * `type: 'masonry'` only. `'vertical'` (default): fixed-width columns,\n * tiles stack top-to-bottom, ragged *bottom* edge. `'horizontal'`: fixed-\n * height rows, tiles pack left-to-right, ragged *right* edge — the direct\n * transpose. Both wrap/grow within the container and scroll vertically\n * only, same as every other layout type; neither ever needs horizontal\n * scroll. See `rowHeight` for `'horizontal'`'s one fixed input, and\n * `justified` (a different `type` entirely) for the *opposite* tradeoff —\n * width forced flush, height left to solve for.\n */\n orientation?: 'vertical' | 'horizontal';\n columns?: number | 'auto';\n columnWidth?: number;\n minColumnWidth?: number;\n maxColumnWidth?: number;\n fill?: 'shortest' | 'ordered';\n /** `type: 'justified'`, or `type: 'masonry', orientation: 'horizontal'`. For horizontal masonry this is the row's exact, fixed height (see `orientation`'s doc comment) — `minRowHeight`/`maxRowHeight` don't apply there, since nothing is solved/clamped, only for justified, where it's a *target* a solved-for height converges near. */\n rowHeight?: number;\n minRowHeight?: number;\n maxRowHeight?: number;\n lastRow?: 'justify' | 'left' | 'hide';\n animate?: boolean;\n /**\n * Container-width → partial overrides, applied on top of the base options\n * above whenever the container's current width is <= that key (the\n * *narrowest* matching key wins if more than one applies). Re-evaluated on\n * every relayout, so crossing a threshold while resizing takes effect\n * live. Cannot override `type` or `orientation` — swapping the DOM\n * structure/positioning strategy live is a bigger feature than a sizing\n * tweak; use a media query + two `Shoji` instances if that's genuinely\n * needed.\n */\n breakpoints?: Record<number, Omit<LayoutOptions, 'type' | 'orientation' | 'breakpoints'>>;\n /**\n * Derives a section key per item (e.g. a formatted date) — a heading is\n * inserted whenever the key changes between consecutive items, real\n * \"Today / Yesterday / March 2024\" (Google Photos-style) sectioning.\n * Items must already be grouped consecutively; a key reappearing later\n * after a different key started a new section anyway.\n *\n * Section boundaries behave differently per `type`: `grid`'s heading is a\n * full-span (`grid-column: 1 / -1`) element, native CSS grid gives it its\n * own row for free. `masonry`'s heading is a full-width blocking element\n * too — each section is its own fresh column-packing pass, no two\n * sections ever share visual space. `justified` is the odd one out, by\n * design (this is the actual Google Photos behavior, not a simplified\n * approximation of it): sections do **not** force a row break. Row\n * *composition* ignores section boundaries entirely — one continuous\n * `layoutJustified` pass packs every item regardless of section, so a\n * section with too few items to reach a full row's target width (a\n * single lone photo, say) shares that row with whatever comes right\n * after it, instead of getting stretched into its own awkward\n * almost-empty row. A heading only marks *where* a new section starts:\n * a compact, inline label sized to its own content (not full width),\n * positioned at the x-coordinate of the tile that starts its section,\n * in a slim label-band above whichever row that tile landed on — more\n * than one label can share the same band if more than one section\n * happens to start within the same row (see `renderHeading`'s\n * `{title, subtitle}` form for exactly this — that's what the reference\n * behavior actually looks like).\n *\n * v1 scope cuts vs. DESIGN.md §5.2's full spec: (1) any items change\n * while `groupBy` is set does a full relayout, same simplification\n * justified's non-grouped path already makes for appends (§5.4) — the\n * \"merge across load boundaries\" incremental optimization is deferred;\n * (2) headings are always `<h2>`, not a configurable level; (3) not\n * supported with `orientation: 'horizontal'` (warns, ignored) —\n * DESIGN.md itself calls that pairing rare.\n */\n groupBy?: (item: GalleryItem) => string;\n /**\n * Customizes a heading's content; default renders the key as plain text.\n * Three return shapes:\n * - `string` — plain text (default behavior, just with custom content).\n * - `HTMLElement` — full control, own tag/children; the plugin adds its\n * own class/positioning on top of whatever's returned, nothing else.\n * - `{ title: string; subtitle?: string }` — the built-in structured\n * form (bold title + a smaller, muted `subtitle`, e.g. a date + a\n * location) — the only form the plugin can apply automatic overflow\n * handling to (see `headingOverflow`), since it owns the DOM structure\n * (a raw `HTMLElement` is opaque to it, no safe way to guess what's\n * droppable).\n */\n renderHeading?: (\n key: string,\n items: GalleryItem[],\n ) => string | HTMLElement | { title: string; subtitle?: string };\n /**\n * `type: 'justified'` + the `{ title, subtitle }` structured heading\n * form only — controls what happens when a compact label doesn't fit\n * its available width (the gap until the next section's label sharing\n * its row, or the container edge). Ignored otherwise: `grid`/`masonry`\n * headings are full-width and this kind of squeeze can't happen there;\n * a raw `renderHeading`-returned `HTMLElement`/`string` is left exactly\n * as returned regardless, since the plugin has no safe way to guess\n * what's droppable in an opaque element.\n * - `'show'` (default) — always render the full title + subtitle, one\n * line, however wide; a label can visually run past the next\n * section's label or the container edge if the content is long\n * enough. The simple, predictable default — nothing gets silently\n * dropped or reflowed.\n * - `'fit'` — never wraps a label's text. First the subtitle is dropped\n * if title+subtitle together don't fit; if the title *alone* still\n * doesn't fit next to whatever's sharing its row, that section is\n * pushed to start a fresh row instead, giving its label the room it\n * needs — row *composition* responds to label width, not just label\n * content. Real Google Photos behavior; opt in when labels regularly\n * need to share tight row space. The one unavoidable exception is a\n * single label wider than the entire container even alone on its own\n * row — there, nothing left to break onto, so the label is\n * ellipsis-truncated (still one line, never wrapped, never\n * overflowing).\n * - `'wrap'` — the in-between: same continuous row-packing as `'show'`\n * (row *composition* never reacts to label width, unlike `'fit'` — no\n * section is ever pushed to a fresh row), but a label that doesn't fit\n * its available width (same gap `'fit'` measures) wraps its own text\n * onto additional lines instead of running past it. Height is capped\n * at `maxRowHeight` (or its default, 360) — a label tall enough to hit\n * that cap ellipsis-truncates its last visible line rather than\n * growing the row further. Real Google Photos behavior for its date\n * headers; pick this over `'fit'` when you'd rather a label take an\n * extra line than shove a whole section onto its own row.\n */\n headingOverflow?: 'show' | 'fit' | 'wrap';\n /**\n * Pins the active section's heading via `position: sticky`. Only\n * implemented for `type: 'grid'`, where headings sit in normal document\n * flow — masonry/justified headings are absolutely positioned by JS (like\n * their tiles), and `position: sticky` doesn't do anything meaningful\n * layered onto an already explicitly-positioned element. Warns and is\n * ignored for those two types.\n */\n stickyHeadings?: boolean;\n /**\n * When an item is missing `width`/`height`, measure its tile's own `<img>`\n * once it loads (`naturalWidth`/`naturalHeight`) and correct that tile's\n * aspect ratio in place, rather than leaving it at the permanent 4:3\n * placeholder fallback. Default `true`.\n *\n * The *first* layout pass never waits on this — it always uses the 4:3\n * placeholder immediately, same as before this option existed, so opening\n * the gallery is never blocked on image loads (DESIGN.md §5.2's\n * never-measure-mid-layout-pass rule still holds for that first pass).\n * This only ever *corrects* a placeholder after the fact, once a real\n * measurement lands — the same \"async correction after an initial\n * synchronous pass\" pattern already used for a `containerWidth <= 0`\n * container (§5.4) and the zoom transition's origin-rect race (§2.3b),\n * extended to per-item dimensions. Multiple corrections landing close\n * together (e.g. several cached images resolving in the same tick) are\n * coalesced into one relayout via `requestAnimationFrame`, not one\n * relayout per image.\n *\n * Effectively does automatically, for `thumb`/`poster`/`src`, what a host\n * would otherwise have to do by hand before constructing the gallery\n * (`new Image(); img.onload = () => ...`) — set `false` to keep the old\n * behavior (permanent 4:3 fallback, no self-correction) if you'd rather\n * guarantee zero extra relayouts under any circumstance.\n */\n autoMeasure?: boolean;\n}\n\ninterface ResolvedConfig {\n gutter: { x: number; y: number };\n columns: number | 'auto';\n columnWidth: number;\n minColumnWidth: number;\n maxColumnWidth: number;\n fill: 'shortest' | 'ordered';\n rowHeight: number;\n minRowHeight: number;\n maxRowHeight: number;\n lastRow: 'justify' | 'left' | 'hide';\n}\n\nconst DEFAULT_ASPECT: MasonryTile = { width: 4, height: 3 };\n\ninterface Tile {\n index: number;\n root: HTMLAnchorElement;\n /** The tile's own thumbnail `<img>` — reused by `autoMeasure` to read `naturalWidth`/`naturalHeight` once it loads, rather than fetching the same image a second time with a separate `Image()`. */\n img: HTMLImageElement;\n}\n\ninterface HeadingEntry {\n root: HTMLElement;\n /** index into `tiles[]` (== item index) where this section's tiles start. */\n tileStart: number;\n /** Present only for the built-in `{ title, subtitle }` form — the two elements `applyJustified`'s overflow handling is allowed to hide/wrap, since the plugin itself built them (a raw `renderHeading`-returned `HTMLElement` is opaque; nothing is touched there). */\n structured: { titleEl: HTMLElement; subtitleEl: HTMLElement | null } | null;\n}\n\n/** `gutter: 8` means `{x: 8, y: 8}` — a single number applies to both axes; `{x, y}` sets them independently. */\nfunction resolveGutter(raw: unknown): { x: number; y: number } {\n if (raw && typeof raw === 'object') {\n const obj = raw as { x?: number; y?: number };\n return { x: Number(obj.x ?? 8), y: Number(obj.y ?? 8) };\n }\n const n = Number(raw ?? 8);\n return { x: n, y: n };\n}\n\nfunction keyOf(item: GalleryItem): string {\n return item.id ?? item.src;\n}\n\n/** `newItems` is a superset of `oldItems` sharing an identical prefix — i.e. purely appended, nothing reordered/removed/prepended. */\nfunction isPureAppend(oldItems: readonly GalleryItem[], newItems: readonly GalleryItem[]): boolean {\n if (newItems.length <= oldItems.length) return false;\n for (let i = 0; i < oldItems.length; i++) {\n if (keyOf(oldItems[i]!) !== keyOf(newItems[i]!)) return false;\n }\n return true;\n}\n\nexport const Layout: ShojiPlugin = {\n name: 'layout',\n defaults: {\n type: 'justified',\n gutter: 8,\n columns: 'auto',\n columnWidth: 240,\n minColumnWidth: 160,\n maxColumnWidth: 480,\n fill: 'shortest',\n animate: true,\n autoMeasure: true,\n },\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const type = (ctx.options.type as 'grid' | 'masonry' | 'justified' | undefined) ?? 'justified';\n const gutter = resolveGutter(ctx.options.gutter);\n const aspectRatio = Number(ctx.options.aspectRatio ?? 1);\n const orientation =\n (ctx.options.orientation as 'vertical' | 'horizontal' | undefined) ?? 'vertical';\n const columns = (ctx.options.columns as number | 'auto' | undefined) ?? 'auto';\n const columnWidth = Number(ctx.options.columnWidth ?? 240);\n const minColumnWidth = Number(ctx.options.minColumnWidth ?? 160);\n const maxColumnWidth = Number(ctx.options.maxColumnWidth ?? 480);\n const fill = (ctx.options.fill as 'shortest' | 'ordered' | undefined) ?? 'shortest';\n const rowHeight = Number(ctx.options.rowHeight ?? 220);\n const minRowHeight = Number(ctx.options.minRowHeight ?? 120);\n const maxRowHeight = Number(ctx.options.maxRowHeight ?? 360);\n const lastRow = (ctx.options.lastRow as 'justify' | 'left' | 'hide' | undefined) ?? 'justify';\n const animate = ctx.options.animate !== false;\n const autoMeasureEnabled = ctx.options.autoMeasure !== false;\n const horizontal = type === 'masonry' && orientation === 'horizontal';\n const groupByFn = ctx.options.groupBy as ((item: GalleryItem) => string) | undefined;\n const renderHeadingFn = ctx.options.renderHeading as\n | ((\n key: string,\n items: GalleryItem[],\n ) => string | HTMLElement | { title: string; subtitle?: string })\n | undefined;\n const headingOverflow =\n (ctx.options.headingOverflow as 'show' | 'fit' | 'wrap' | undefined) ?? 'show';\n const stickyHeadingsRaw = ctx.options.stickyHeadings === true;\n const stickyHeadings = stickyHeadingsRaw && type === 'grid';\n if (stickyHeadingsRaw && type !== 'grid') {\n console.warn(\n \"Shoji: layout plugin — stickyHeadings is only implemented for type: 'grid'; ignored (see the option's doc comment).\",\n );\n }\n if (groupByFn && horizontal) {\n console.warn(\n \"Shoji: layout plugin — groupBy isn't supported with orientation: 'horizontal'; ignored.\",\n );\n }\n const groupingEnabled = !!groupByFn && !horizontal;\n\n const baseConfig: ResolvedConfig = {\n gutter,\n columns,\n columnWidth,\n minColumnWidth,\n maxColumnWidth,\n fill,\n rowHeight,\n minRowHeight,\n maxRowHeight,\n lastRow,\n };\n\n const breakpointsRaw = ctx.options.breakpoints as\n Record<number, Partial<LayoutOptions>> | undefined;\n const sortedBreakpoints = breakpointsRaw\n ? Object.entries(breakpointsRaw)\n .map(([key, overrides]) => [Number(key), overrides] as const)\n .sort((a, b) => a[0] - b[0])\n : [];\n\n /** Re-run on every relayout — the narrowest breakpoint whose key is still >= the current width wins; falls back to `baseConfig` if none match or no breakpoints were given. */\n function resolveConfig(width: number): ResolvedConfig {\n const match = sortedBreakpoints.find(([maxWidth]) => width <= maxWidth);\n if (!match) return baseConfig;\n const overrides = match[1];\n return {\n gutter:\n overrides.gutter !== undefined ? resolveGutter(overrides.gutter) : baseConfig.gutter,\n columns: overrides.columns ?? baseConfig.columns,\n columnWidth: overrides.columnWidth ?? baseConfig.columnWidth,\n minColumnWidth: overrides.minColumnWidth ?? baseConfig.minColumnWidth,\n maxColumnWidth: overrides.maxColumnWidth ?? baseConfig.maxColumnWidth,\n fill: overrides.fill ?? baseConfig.fill,\n rowHeight: overrides.rowHeight ?? baseConfig.rowHeight,\n minRowHeight: overrides.minRowHeight ?? baseConfig.minRowHeight,\n maxRowHeight: overrides.maxRowHeight ?? baseConfig.maxRowHeight,\n lastRow: overrides.lastRow ?? baseConfig.lastRow,\n };\n }\n\n const container = gallery.element;\n container.classList.add('shoji-layout', `shoji-layout--${type}`);\n if (animate) container.classList.add('shoji-layout--animate');\n\n let tiles: Tile[] = [];\n let headings: HeadingEntry[] = [];\n let columnHeights: number[] | undefined;\n let previousItems: readonly GalleryItem[] = [];\n let warnedMissingDims = false;\n /**\n * A real bug, reported from real usage: `autoMeasureTiles()` used to\n * write its measurement straight onto `item.width`/`item.height` —\n * convenient, since `aspectOf()` already reads those first, but wrong.\n * That measurement comes from the *tile's* own `<img>`\n * (`measurableSrc()`: `item.thumb` first, then `poster`, then `src`) —\n * for layout purposes a thumbnail's aspect ratio is a fine stand-in for\n * the full photo's, close enough almost always. But `item.width`/\n * `height` aren't Layout-private state — RotateFlip's own fit-scale\n * (§4.5) and `SlideManager`'s aspect-ratio loading placeholder both\n * read the exact same fields, under the contract that they mean the\n * full photo's *true* pixel dimensions, not a thumbnail's. A thumbnail\n * genuinely smaller than the lightbox in both orientations always\n * satisfies `fitScaleFor`'s `Math.min(1, ...)` cap on its own, so\n * RotateFlip silently computed a no-op 1x scale for every such\n * item — confirmed directly against a real photo whose thumbnail\n * happened to be a separate, smaller file (an item whose thumbnail\n * happens to equal its full `src` never showed this, since then the\n * \"wrong\" measurement and the real one are simply the same numbers).\n * This cache keeps the auto-measurement entirely Layout-private —\n * `aspectOf()` below still benefits from it, but nothing outside this\n * plugin ever sees a thumbnail's dimensions mistaken for the photo's.\n */\n const measuredAspect = new WeakMap<GalleryItem, MasonryTile>();\n\n /** [startIndex, endExclusive) into `items`/`tiles` per section, split wherever `groupByFn`'s key changes. */\n function computeSections(\n items: readonly GalleryItem[],\n ): Array<{ key: string; startIndex: number; endIndex: number }> {\n const sections: Array<{ key: string; startIndex: number; endIndex: number }> = [];\n for (let i = 0; i < items.length; i++) {\n const key = groupByFn!(items[i]!);\n const current = sections[sections.length - 1];\n if (!current || current.key !== key) {\n sections.push({ key, startIndex: i, endIndex: i + 1 });\n } else {\n current.endIndex = i + 1;\n }\n }\n return sections;\n }\n\n function createHeadingRoot(\n key: string,\n sectionItems: GalleryItem[],\n ): { root: HTMLElement; structured: HeadingEntry['structured'] } {\n const rendered = renderHeadingFn ? renderHeadingFn(key, sectionItems) : key;\n let root: HTMLElement;\n let structured: HeadingEntry['structured'] = null;\n if (typeof rendered === 'string') {\n root = document.createElement('h2');\n root.textContent = rendered;\n } else if (rendered instanceof HTMLElement) {\n root = rendered;\n } else {\n root = document.createElement('h2');\n const titleEl = document.createElement('span');\n titleEl.className = 'shoji-layout-heading-title';\n titleEl.textContent = rendered.title;\n root.appendChild(titleEl);\n let subtitleEl: HTMLElement | null = null;\n if (rendered.subtitle) {\n subtitleEl = document.createElement('span');\n subtitleEl.className = 'shoji-layout-heading-subtitle';\n subtitleEl.textContent = rendered.subtitle;\n root.appendChild(subtitleEl);\n }\n structured = { titleEl, subtitleEl };\n }\n root.classList.add('shoji-layout-heading');\n if (stickyHeadings) root.classList.add('shoji-layout-heading--sticky');\n return { root, structured };\n }\n\n /** Segment boundaries derived from `headings` — `end` is the next heading's `tileStart`, or `tiles.length` for the last one. */\n function headingSegments(): Array<{ heading: HeadingEntry; start: number; end: number }> {\n return headings.map((heading, i) => ({\n heading,\n start: heading.tileStart,\n end: i + 1 < headings.length ? headings[i + 1]!.tileStart : tiles.length,\n }));\n }\n\n /** `undefined` for a video item with neither `thumb` nor `poster` — its tile `<img>` ends up pointed at the unplayable video file itself, which can never load as an image, so there's nothing `autoMeasure` could learn from it either. */\n function measurableSrc(item: GalleryItem): string | undefined {\n return item.thumb ?? item.poster ?? (item.video ? undefined : item.src);\n }\n\n function aspectOf(item: GalleryItem | undefined): MasonryTile {\n if (item?.width && item.height) return { width: item.width, height: item.height };\n const measured = item && measuredAspect.get(item);\n if (measured) return measured;\n const selfCorrecting = autoMeasureEnabled && !!item && !!measurableSrc(item);\n if (!warnedMissingDims && !selfCorrecting) {\n warnedMissingDims = true;\n console.warn(\n autoMeasureEnabled\n ? 'Shoji: layout plugin — item(s) missing width/height with no measurable thumb/poster/src to auto-measure from either; falling back to a 4:3 placeholder ratio permanently for those.'\n : 'Shoji: layout plugin — item(s) missing width/height and autoMeasure is disabled. Masonry/justified positions are computed from aspect ratios up front, never by measuring loaded images (DESIGN.md §5.2 — that causes layout-jump), so items without dimensions fall back to a 4:3 placeholder ratio instead.',\n );\n }\n return DEFAULT_ASPECT;\n }\n\n function createTile(item: GalleryItem, index: number): Tile {\n const root = document.createElement('a');\n root.className = 'shoji-layout-tile';\n if (item.id) root.dataset.shojiId = item.id;\n // Always set, unlike shojiId above (item.id is optional) — the\n // reliable element→item lookup for a `layoutRender` listener that\n // only has the element itself later (e.g. a click handler on content\n // it injected into the tile), not this render pass's own event\n // payload. `gallery.items[Number(el.dataset.shojiIndex)]` always works.\n root.dataset.shojiIndex = String(index);\n\n // item.src is the video *file* for a video item (unplayable as a tile\n // thumbnail) — item.poster is the actual image to show there, checked\n // before falling back to item.src, which is only ever correct for a\n // plain image item.\n const img = document.createElement('img');\n img.src = item.thumb ?? item.poster ?? item.src;\n img.loading = 'lazy';\n img.alt = item.alt ?? '';\n root.appendChild(img);\n\n const tile: Tile = { index, root, img };\n root.addEventListener('click', (event) => {\n event.preventDefault();\n gallery.open(tile.index);\n });\n return tile;\n }\n\n function applyGrid(target: readonly Tile[]): void {\n // Grid otherwise never reads its own size (native CSS grid reflows\n // itself) — only breakpoint resolution needs it read here.\n const containerWidth = container.getBoundingClientRect().width;\n const config = resolveConfig(containerWidth);\n container.style.setProperty('--shoji-layout-column-width', `${config.columnWidth}px`);\n // CSS gap shorthand is \"row-gap column-gap\" — y before x.\n container.style.setProperty(\n '--shoji-layout-gutter',\n `${config.gutter.y}px ${config.gutter.x}px`,\n );\n for (const tile of target) {\n tile.root.style.setProperty('--shoji-layout-tile-aspect', `${aspectRatio}`);\n }\n }\n\n /** `appendOnly`: reposition just these (new) tiles, continuing from the saved `columnHeights`; omit to relayout every tile from scratch (resize, or a non-append items change). Never called with `appendOnly` set when grouping is active — grouped changes always route through `fullRender` (see the `groupBy` option's doc comment). */\n function applyMasonry(appendOnly: readonly Tile[] | null): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet (e.g. display:none) — the resize observer's initial callback will retry once it is\n\n const config = resolveConfig(containerWidth);\n const masonryOptions = {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n columns: config.columns,\n columnWidth: config.columnWidth,\n minColumnWidth: config.minColumnWidth,\n maxColumnWidth: config.maxColumnWidth,\n fill: config.fill,\n };\n\n if (groupingEnabled && headings.length > 0) {\n const segments = headingSegments();\n // Batch-read every heading's height up front, before writing any\n // tile styles below — interleaving reads (which force a layout\n // flush) with the transform writes in the same pass measurably\n // delayed the very first paint under animate: true (each flush\n // gives the browser a \"before\" style to transition away from that\n // it otherwise wouldn't have for freshly-inserted elements).\n const headingHeights = segments.map((s) => s.heading.root.getBoundingClientRect().height);\n\n let y = 0;\n segments.forEach(({ heading, start, end }, i) => {\n const segTiles = tiles.slice(start, end);\n heading.root.style.transform = `translate(0px, ${y}px)`;\n y += headingHeights[i]! + config.gutter.y;\n const segResult = layoutMasonry(\n segTiles.map((t) => aspectOf(gallery.items[t.index])),\n masonryOptions,\n );\n segTiles.forEach((tile, j) => {\n const pos = segResult.positions[j]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${y + pos.y}px)`;\n });\n y += segResult.containerHeight + config.gutter.y;\n });\n columnHeights = undefined; // no cross-segment continuation once grouped\n container.style.height = `${Math.max(0, y - config.gutter.y)}px`;\n return;\n }\n\n const target = appendOnly ?? tiles;\n const masonryTiles = target.map((t) => aspectOf(gallery.items[t.index]));\n const startHeights = appendOnly ? columnHeights : undefined;\n const result = layoutMasonry(masonryTiles, masonryOptions, startHeights);\n\n target.forEach((tile, i) => {\n const pos = result.positions[i]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n columnHeights = result.columnHeights;\n container.style.height = `${result.containerHeight}px`;\n }\n\n /**\n * The masonry-family transpose of applyMasonry: fixed-height rows pack\n * tiles left-to-right, wrapping to a new row rather than stretching —\n * see layoutMasonryHorizontal's doc comment (masonry.ts) for the full\n * algorithm. Like applyJustified, this always relays out every tile\n * from scratch (no `appendOnly`/incremental-continuation param) — a\n * row isn't \"committed\" until enough tiles arrive to overflow it, so an\n * appended tile can extend what was the previous render's trailing row,\n * exactly the same reason applyJustified can't do incremental append.\n */\n function applyMasonryHorizontal(): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet (e.g. display:none) — the resize observer's initial callback will retry once it is\n\n const config = resolveConfig(containerWidth);\n const masonryTiles = tiles.map((t) => aspectOf(gallery.items[t.index]));\n const result = layoutMasonryHorizontal(masonryTiles, {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n rowHeight: config.rowHeight,\n });\n\n tiles.forEach((tile, i) => {\n const pos = result.positions[i]!;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n container.style.height = `${result.containerHeight}px`;\n }\n\n /**\n * The `groupBy` + `justified` combination — see that option's doc\n * comment for the full behavioral spec (sections don't force a row\n * break by default; a heading is a compact inline label, not a\n * full-width blocking element).\n *\n * `headingOverflow: 'show'` (default) and `'wrap'`: one continuous\n * `layoutJustified` pass packs every tile regardless of section — the\n * simple case, a single \"segment\" covering everything (computeSegments()\n * below only ever splits into multiple segments for `'fit'`). `'wrap'`\n * additionally constrains each label's own box afterward (see\n * applyWrapDecisions) — that's a content-level decision within a fixed\n * layout, not a row-composition one, so it doesn't need its own segment\n * handling here.\n *\n * `headingOverflow: 'fit'`: still prefers continuous packing, but a\n * section whose label (title+subtitle, or title alone once the\n * subtitle's dropped) wouldn't fit the gap to the next label sharing\n * its row gets pushed to start a fresh row instead — the label is\n * never wrapped. This means row *composition itself* has to respond to\n * label width, not just label content — computeSegments() below finds\n * the largest run of sections that can share rows without any label\n * needing to break, by growing a trial `layoutJustified` call one\n * section at a time and backing off the moment a fit check fails; each\n * final segment becomes its own independent `layoutJustified` call\n * (same mechanism as masonry's hard per-section blocks, except the\n * unit here is a dynamically-sized run of sections, not always\n * exactly one).\n */\n function applyJustifiedGrouped(\n justifiedOptions: JustifiedOptions,\n config: ResolvedConfig,\n containerWidth: number,\n ): void {\n // Batch-measure every structured heading's natural (unconstrained,\n // single-line) width up front — both with and without its subtitle —\n // before any segmentation trial runs. Needed by computeSegments()'s\n // fit checks below, and again by the final per-segment content\n // decision pass; measuring once here avoids re-measuring per trial.\n const fullWidths = new Map<number, number>();\n const titleOnlyWidths = new Map<number, number>();\n if (headingOverflow === 'fit') {\n for (const heading of headings) {\n if (!heading.structured) continue;\n const { subtitleEl } = heading.structured;\n heading.root.style.maxWidth = 'none';\n heading.root.style.whiteSpace = 'nowrap';\n if (subtitleEl) subtitleEl.hidden = false;\n fullWidths.set(heading.tileStart, heading.root.getBoundingClientRect().width);\n if (subtitleEl) {\n subtitleEl.hidden = true;\n titleOnlyWidths.set(heading.tileStart, heading.root.getBoundingClientRect().width);\n subtitleEl.hidden = false; // restored — the real decision happens per final segment, below\n } else {\n titleOnlyWidths.set(heading.tileStart, fullWidths.get(heading.tileStart)!);\n }\n }\n }\n\n /** [startSection, endSection) into `headings`, sized `tiles[]` range, and that range's own layoutJustified result. */\n type Segment = {\n startSection: number;\n endSection: number;\n tileStart: number;\n tileEnd: number;\n result: JustifiedResult;\n };\n\n function tileAspects(tileStart: number, tileEnd: number) {\n return tiles.slice(tileStart, tileEnd).map((t) => aspectOf(gallery.items[t.index]));\n }\n\n /** Runs layoutJustified on sections [startSection, endSection) and checks every label in it fits (full or title-only) its row's available width — null if any doesn't. */\n function tryFit(startSection: number, endSection: number): JustifiedResult | null {\n const tileStart = headings[startSection]!.tileStart;\n const tileEnd =\n endSection < headings.length ? headings[endSection]!.tileStart : tiles.length;\n const result = layoutJustified(tileAspects(tileStart, tileEnd), justifiedOptions);\n for (let k = startSection; k < endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue; // raw renderHeading content never triggers a break\n const pos = result.positions[heading.tileStart - tileStart];\n if (!pos) continue; // lastRow: 'hide' trailing range within this trial\n const next = k + 1 < endSection ? headings[k + 1] : undefined;\n const nextPos = next ? result.positions[next.tileStart - tileStart] : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n const bestWidth = Math.min(\n fullWidths.get(heading.tileStart) ?? Infinity,\n titleOnlyWidths.get(heading.tileStart) ?? Infinity,\n );\n if (bestWidth > available) return null;\n }\n return result;\n }\n\n function computeSegments(): Segment[] {\n if (headingOverflow !== 'fit') {\n return [\n {\n startSection: 0,\n endSection: headings.length,\n tileStart: 0,\n tileEnd: tiles.length,\n result: layoutJustified(tileAspects(0, tiles.length), justifiedOptions),\n },\n ];\n }\n const segments: Segment[] = [];\n let segStart = 0;\n while (segStart < headings.length) {\n const base = tryFit(segStart, segStart + 1);\n const tileStart = headings[segStart]!.tileStart;\n if (base === null) {\n // Doesn't fit even alone in its own row — the unavoidable case\n // (a single label wider than the container itself). Nothing\n // narrower to fall back to; take it as its own 1-section\n // segment anyway and let the content-decision pass below\n // ellipsis-truncate it rather than ever wrapping or\n // overflowing.\n const tileEnd =\n segStart + 1 < headings.length ? headings[segStart + 1]!.tileStart : tiles.length;\n segments.push({\n startSection: segStart,\n endSection: segStart + 1,\n tileStart,\n tileEnd,\n result: layoutJustified(tileAspects(tileStart, tileEnd), justifiedOptions),\n });\n segStart += 1;\n continue;\n }\n let end = segStart + 1;\n let best = base;\n while (end < headings.length) {\n const trial = tryFit(segStart, end + 1);\n if (trial === null) break;\n end += 1;\n best = trial;\n }\n const tileEnd = end < headings.length ? headings[end]!.tileStart : tiles.length;\n segments.push({\n startSection: segStart,\n endSection: end,\n tileStart,\n tileEnd,\n result: best,\n });\n segStart = end;\n }\n return segments;\n }\n\n /** Applies the real drop-subtitle/ellipsis decision for every structured heading in one finalized segment, using its actual computed positions (not a trial). */\n function applyContentDecisions(segment: Segment): void {\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (!pos) continue;\n const next = k + 1 < segment.endSection ? headings[k + 1] : undefined;\n const nextPos = next\n ? segment.result.positions[next.tileStart - segment.tileStart]\n : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n\n const { subtitleEl } = heading.structured;\n heading.root.style.whiteSpace = 'nowrap';\n heading.root.style.maxWidth = 'none';\n heading.root.style.overflow = '';\n heading.root.style.textOverflow = '';\n if (subtitleEl) subtitleEl.hidden = false;\n\n const full = fullWidths.get(heading.tileStart) ?? 0;\n if (full <= available) continue; // fits with subtitle, as-is\n\n if (subtitleEl) {\n subtitleEl.hidden = true;\n const titleOnly = titleOnlyWidths.get(heading.tileStart) ?? 0;\n if (titleOnly <= available) continue; // fits with subtitle dropped\n }\n\n // Still too wide title-only — only reachable for a 1-section\n // segment that couldn't be narrowed any further (computeSegments\n // already gave every other case its own row's worth of room).\n // Never wrap: ellipsis-truncate instead, still one line.\n heading.root.style.maxWidth = `${Math.max(0, available)}px`;\n heading.root.style.overflow = 'hidden';\n heading.root.style.textOverflow = 'ellipsis';\n }\n }\n\n /**\n * `headingOverflow: 'wrap'`'s content decision — unlike\n * applyContentDecisions above, this never drops the subtitle or\n * ellipsis-truncates a single line; it lets the label wrap onto\n * additional lines within its available width, then caps *how many*\n * lines via `-webkit-line-clamp` sized from `maxRowHeight` — a label\n * short enough to fit within that many lines is unaffected (nothing\n * for the clamp to do), a longer one ellipsis-truncates its last\n * visible line rather than growing the row past the configured cap.\n * `-webkit-line-clamp` is broadly supported cross-browser despite the\n * prefix (Chrome/Safari/Firefox all implement it) — there's no\n * unprefixed equivalent with comparable support yet.\n */\n function applyWrapDecisions(segment: Segment): void {\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n if (!heading.structured) continue;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (!pos) continue;\n const next = k + 1 < segment.endSection ? headings[k + 1] : undefined;\n const nextPos = next\n ? segment.result.positions[next.tileStart - segment.tileStart]\n : null;\n const sameRow = !!nextPos && Math.abs(nextPos.y - pos.y) < 0.5;\n const available = (sameRow ? nextPos!.x : containerWidth) - pos.x - config.gutter.x;\n\n heading.root.style.whiteSpace = 'normal';\n heading.root.style.maxWidth = `${Math.max(0, available)}px`;\n\n const style = getComputedStyle(heading.root);\n const parsedLineHeight = parseFloat(style.lineHeight);\n const lineHeight = Number.isFinite(parsedLineHeight)\n ? parsedLineHeight\n : parseFloat(style.fontSize) * 1.2;\n const maxLines = Math.max(1, Math.floor(config.maxRowHeight / lineHeight));\n\n heading.root.style.display = '-webkit-box';\n heading.root.style.overflow = 'hidden';\n heading.root.style.setProperty('-webkit-box-orient', 'vertical');\n heading.root.style.setProperty('-webkit-line-clamp', `${maxLines}`);\n }\n }\n\n const segments = computeSegments();\n let cumulativeExtra = 0;\n let headingPtr = 0;\n\n for (const segment of segments) {\n if (headingOverflow === 'fit') applyContentDecisions(segment);\n else if (headingOverflow === 'wrap') applyWrapDecisions(segment);\n\n // Batch-read this segment's heading heights up front, after content\n // decisions are final — see applyMasonry's identical pattern/comment\n // for why reads and writes shouldn't interleave in the same pass.\n const headingHeights = new Map<number, number>();\n for (let k = segment.startSection; k < segment.endSection; k++) {\n const heading = headings[k]!;\n headingHeights.set(heading.tileStart, heading.root.getBoundingClientRect().height);\n }\n\n for (const row of segment.result.rows) {\n const globalStart = row.start + segment.tileStart;\n const globalEnd = row.end + segment.tileStart;\n\n let bandHeight = 0;\n while (headingPtr < segment.endSection && headings[headingPtr]!.tileStart < globalEnd) {\n const heading = headings[headingPtr]!;\n const pos = segment.result.positions[heading.tileStart - segment.tileStart];\n if (pos) {\n heading.root.hidden = false;\n heading.root.style.transform = `translate(${pos.x}px, ${row.y + cumulativeExtra}px)`;\n bandHeight = Math.max(bandHeight, headingHeights.get(heading.tileStart) ?? 0);\n }\n headingPtr++;\n }\n if (bandHeight > 0) cumulativeExtra += bandHeight + config.gutter.y;\n\n for (let i = globalStart; i < globalEnd; i++) {\n const pos = segment.result.positions[i - segment.tileStart];\n const tile = tiles[i]!;\n tile.root.hidden = pos === null;\n if (!pos) continue;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y + cumulativeExtra}px)`;\n }\n }\n\n // Tiles beyond this segment's last finalized row (a lastRow: 'hide'\n // trailing range) never got touched above — hide them explicitly.\n const segLastCovered =\n segment.result.rows.length > 0\n ? segment.result.rows[segment.result.rows.length - 1]!.end + segment.tileStart\n : segment.tileStart;\n for (let i = segLastCovered; i < segment.tileEnd; i++) {\n tiles[i]!.root.hidden = true;\n }\n\n // Advance past this whole segment's own content height, so the\n // next segment's rows (a fresh layoutJustified call, local y\n // starting back at 0) stack directly beneath it.\n cumulativeExtra += segment.result.containerHeight + config.gutter.y;\n }\n\n // Any heading whose section starts in the very last segment's hidden\n // trailing range never got positioned above — hide it rather than\n // leaving it at its CSS default top:0/left:0.\n while (headingPtr < headings.length) {\n headings[headingPtr]!.root.hidden = true;\n headingPtr++;\n }\n\n container.style.height = `${Math.max(0, cumulativeExtra - config.gutter.y)}px`;\n }\n\n /**\n * Unlike masonry's `columnHeights`, a justified row isn't \"locked in\"\n * until enough tiles arrive to fill it — an appended tile can extend or\n * complete what was the *previous* render's trailing row. Rather than\n * build a second continuation scheme for that, justified always relays\n * out every tile on any items change (append included); see §5.4.\n */\n function applyJustified(): void {\n const containerWidth = container.getBoundingClientRect().width;\n if (containerWidth <= 0) return; // not painted yet — resize observer's initial callback retries once it is\n\n const config = resolveConfig(containerWidth);\n const justifiedOptions = {\n containerWidth,\n gutterX: config.gutter.x,\n gutterY: config.gutter.y,\n rowHeight: config.rowHeight,\n minRowHeight: config.minRowHeight,\n maxRowHeight: config.maxRowHeight,\n lastRow: config.lastRow,\n };\n\n if (groupingEnabled && headings.length > 0) {\n applyJustifiedGrouped(justifiedOptions, config, containerWidth);\n return;\n }\n\n const justifiedTiles = tiles.map((t) => aspectOf(gallery.items[t.index]));\n const result = layoutJustified(justifiedTiles, justifiedOptions);\n\n tiles.forEach((tile, i) => {\n const pos = result.positions[i];\n tile.root.hidden = pos === null; // lastRow: 'hide' on this pass's trailing tiles\n if (!pos) return;\n tile.root.style.width = `${pos.width}px`;\n tile.root.style.height = `${pos.height}px`;\n tile.root.style.visibility = 'visible';\n tile.root.style.transform = `translate(${pos.x}px, ${pos.y}px)`;\n });\n\n container.style.height = `${result.containerHeight}px`;\n }\n\n function relayoutAll(): void {\n if (horizontal) applyMasonryHorizontal();\n else if (type === 'masonry') applyMasonry(null);\n else if (type === 'justified') applyJustified();\n else applyGrid(tiles);\n }\n\n let destroyed = false;\n let measureFrame: number | null = null;\n\n /**\n * Coalesces every `autoMeasure` correction landing in the same tick (or\n * the same animation frame — several cached images resolving\n * synchronously back-to-back is the common case) into one relayout,\n * never one per image. `groupingEnabled` needs a real `fullRender()`,\n * not just a reposition pass: `groupBy` was evaluated once already\n * during the first render, using whatever `item.width`/etc. was known\n * *then* — if that's exactly the field a correction just filled in,\n * the section boundaries themselves were computed wrong and only a\n * fresh `computeSections()` call (inside `fullRender`) fixes them, not\n * `relayoutAll()`, which only ever repositions the existing tiles/headings.\n */\n function scheduleMeasureRelayout(): void {\n if (measureFrame !== null || destroyed) return;\n measureFrame = requestAnimationFrame(() => {\n measureFrame = null;\n if (destroyed) return;\n if (groupingEnabled) fullRender(gallery.items);\n else relayoutAll();\n });\n }\n\n /**\n * DESIGN.md §5's `autoMeasure` option — never blocks or delays the\n * *first* layout pass (already painted with the 4:3 placeholder by the\n * time this runs); only ever corrects it afterward, once a real\n * measurement lands. Reuses each tile's own `<img>` (already fetching\n * for display) rather than a second `new Image()`, so nothing is\n * fetched twice. A `loading=\"lazy\"` tile far off-screen may not\n * resolve for a long time (or ever, if never scrolled to) — harmless,\n * since nothing visible is waiting on it; it simply keeps its 4:3\n * placeholder until/unless it does.\n */\n function autoMeasureTiles(newTiles: readonly Tile[]): void {\n if (!autoMeasureEnabled) return;\n for (const tile of newTiles) {\n const item = gallery.items[tile.index];\n // measuredAspect.has(item): skip re-measuring (and re-attaching a\n // 'load' listener) an item this cache already has an answer for —\n // item.width/height no longer get set by this function itself\n // (see measuredAspect's own doc comment above), so that alone\n // can't short-circuit repeat work across tile rebuilds the way it\n // used to.\n if (\n !item ||\n (item.width && item.height) ||\n measuredAspect.has(item) ||\n !measurableSrc(item)\n )\n continue;\n\n const onLoad = (): void => {\n if (destroyed) return;\n if (tile.img.naturalWidth > 0 && tile.img.naturalHeight > 0) {\n measuredAspect.set(item, {\n width: tile.img.naturalWidth,\n height: tile.img.naturalHeight,\n });\n scheduleMeasureRelayout();\n }\n };\n if (tile.img.complete) onLoad();\n else tile.img.addEventListener('load', onLoad, { once: true });\n // No 'error' listener needed — aspectOf()'s 4:3 fallback already\n // covers an image that never loads; there's nothing to update.\n }\n }\n\n /** DESIGN.md §5 — fires once a render pass's tile DOM is built and appended, so a host can inject its own content into `element` (a badge, a selection checkbox, anything not itself part of layout) without re-deriving which tiles are newly built this pass. */\n function emitLayoutRender(rendered: readonly Tile[]): void {\n ctx.emit('layoutRender', {\n tiles: rendered.map((tile) => ({ index: tile.index, element: tile.root })),\n });\n }\n\n function fullRender(items: readonly GalleryItem[]): void {\n container.replaceChildren();\n tiles = items.map((item, i) => createTile(item, i));\n headings = [];\n if (groupingEnabled) {\n for (const section of computeSections(items)) {\n const sectionItems = items.slice(section.startIndex, section.endIndex);\n const { root: headingRoot, structured } = createHeadingRoot(section.key, sectionItems);\n container.appendChild(headingRoot);\n headings.push({ root: headingRoot, tileStart: section.startIndex, structured });\n for (let i = section.startIndex; i < section.endIndex; i++) {\n container.appendChild(tiles[i]!.root);\n }\n }\n } else {\n for (const tile of tiles) container.appendChild(tile.root);\n }\n columnHeights = undefined;\n relayoutAll();\n autoMeasureTiles(tiles);\n emitLayoutRender(tiles);\n }\n\n function appendRender(newItems: readonly GalleryItem[], startIndex: number): void {\n const newTiles = newItems.map((item, i) => createTile(item, startIndex + i));\n for (const tile of newTiles) container.appendChild(tile.root);\n tiles = [...tiles, ...newTiles];\n if (horizontal)\n applyMasonryHorizontal(); // full relayout — see applyMasonryHorizontal's doc comment\n else if (type === 'masonry') applyMasonry(newTiles);\n else if (type === 'justified')\n applyJustified(); // full relayout — see applyJustified's doc comment\n else applyGrid(newTiles);\n autoMeasureTiles(newTiles);\n emitLayoutRender(newTiles);\n }\n\n fullRender(gallery.items);\n previousItems = gallery.items;\n\n const offItemsUpdated = ctx.on('itemsUpdated', ({ items }) => {\n if (groupingEnabled) {\n // grouped changes always fully re-render — see the `groupBy` option's doc comment.\n fullRender(items);\n } else if (isPureAppend(previousItems, items)) {\n appendRender(items.slice(previousItems.length), previousItems.length);\n } else {\n fullRender(items);\n }\n previousItems = items;\n });\n\n // Native CSS grid already reflows its own tile positions responsively —\n // it only needs a resize-driven recompute at all when breakpoints are\n // configured (to re-check whether the container crossed a threshold).\n // Masonry/justified always need one, since they're JS-computed.\n let resizeFrame: number | null = null;\n let resizeObserver: ResizeObserver | undefined;\n if (type === 'masonry' || type === 'justified' || sortedBreakpoints.length > 0) {\n resizeObserver = new ResizeObserver(() => {\n if (resizeFrame !== null) return;\n resizeFrame = requestAnimationFrame(() => {\n resizeFrame = null;\n relayoutAll();\n });\n });\n resizeObserver.observe(container);\n }\n\n return () => {\n destroyed = true;\n if (measureFrame !== null) cancelAnimationFrame(measureFrame);\n resizeObserver?.disconnect();\n if (resizeFrame !== null) cancelAnimationFrame(resizeFrame);\n offItemsUpdated();\n container.classList.remove('shoji-layout', `shoji-layout--${type}`, 'shoji-layout--animate');\n container.style.removeProperty('height');\n container.style.removeProperty('width');\n container.replaceChildren();\n };\n },\n};\n","export interface RotateFlipState {\n flipH: boolean;\n flipV: boolean;\n /** Degrees; normalized to one of 0/90/180/270 by `normalizeRotateFlip`. */\n rotation: number;\n}\n\n/**\n * DESIGN.md §8.1's flip/rotation canonicalization table, verbatim — CLAUDE.md:\n * \"Flip + rotate compose non-commutatively. Use the normalization table...\n * don't re-derive it.\" `flipH && flipV` is always visually equivalent to a\n * 180°-rotated state with neither flip set; this collapses any\n * `flipH`/`flipV`/`rotation` combination down to that canonical form, so two\n * states reached via different sequences of clicks compare equal and never\n * accumulate redundant flip+flip-again or unbounded rotation values.\n * Shared between the standalone rotate/flip *view* plugin (§4) and the\n * future Editor plugin (§8), which both need the identical composition —\n * not duplicated per-plugin.\n */\nexport function normalizeRotateFlip(state: RotateFlipState): RotateFlipState {\n const rotation = ((state.rotation % 360) + 360) % 360;\n if (state.flipH && state.flipV) {\n return { flipH: false, flipV: false, rotation: (rotation + 180) % 360 };\n }\n return { flipH: state.flipH, flipV: state.flipV, rotation };\n}\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. */\nexport const ROTATE_LEFT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 14 4 9l5-5\"/><path d=\"M4 9h10a6 6 0 1 1 0 12H9\"/></svg>';\n\nexport const ROTATE_RIGHT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 14 20 9l-5-5\"/><path d=\"M20 9H10a6 6 0 1 0 0 12h5\"/></svg>';\n\nexport const FLIP_H_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 3v18\"/><path d=\"M17 7l3 5-3 5\"/><path d=\"M7 7l-3 5 3 5\"/></svg>';\n\nexport const FLIP_V_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 12h18\"/><path d=\"M7 17l5 3 5-3\"/><path d=\"M7 7l5-3 5 3\"/></svg>';\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { normalizeRotateFlip, type RotateFlipState } from '../../core/rotateFlipNormalize';\nimport { waitForTransitionEnd } from '../../core/zoomTransition';\nimport { FLIP_H_ICON, FLIP_V_ICON, ROTATE_LEFT_ICON, ROTATE_RIGHT_ICON } from './icons';\n\nconst NEUTRAL: RotateFlipState = { flipH: false, flipV: false, rotation: 0 };\n\n/**\n * Flip axes apply to the *currently visible* (already-rotated) orientation,\n * not the original unrotated image — `scaleX`/`scaleY` listed before\n * `rotate()` in the transform string is what makes that true: CSS transform\n * functions apply right-to-left, so `rotate()` (rightmost) affects the\n * content first, and the flip (leftmost) acts on that already-rotated\n * result.\n *\n * `flipH`/`flipV`/`rotationDeg` here are the *raw, uncanonicalized* visual\n * values (see `visualFlipH`/`visualFlipV`/`visualRotation` below) — never\n * `state`'s own normalized ones. Two real bugs came from feeding the\n * normalized state directly into this animated transform instead:\n *\n * 1. `rotationDeg` must be unbounded, not wrapped to `[0, 360)`: animating\n * straight to a wrapped value (e.g. 270° → 0° after a fourth\n * rotate-right click, instead of continuing on to 360°) makes the\n * browser interpolate a 270° *decrease*, spinning backward almost a\n * full turn instead of continuing the same 90° forward step being\n * clicked through.\n * 2. `flipH`/`flipV` must stay two independent, literal booleans, never\n * collapsed the way `normalizeRotateFlip` collapses `flipH && flipV`\n * into `rotation + 180`: flipping horizontal then vertical while\n * already flipped horizontal would otherwise animate `scaleX` back to\n * 1 *and* `rotate` up to 180° simultaneously (both values are in the\n * transform-function list, so the browser interpolates each\n * independently) — a compound squish-and-spin instead of the plain\n * vertical-flip motion \"Flip vertical\" implies. Keeping the raw\n * booleans means only `scaleY` ever changes for that click, since\n * flipping both axes is algebraically identical to a 180° rotation\n * regardless of what rotation is already applied — the *end* look\n * always matches the canonical state either way, only the *animated\n * path* differs.\n *\n * `rotationDeg === 0` is still a safe, unambiguous \"truly neutral\" check\n * for the shortcut below — every rotate click adds ±90, so it only lands\n * back on exactly `0` at genuine reset/initial state, never a masked\n * multiple of 360.\n *\n * `fitScale` (see `fitScaleFor` below) is folded directly into `scaleX`/\n * `scaleY` — a single uniform factor commutes with everything else already\n * in this transform (rotate, and flip's own -1), so multiplying it in here\n * is exactly equivalent to a separate trailing `scale()` function, without\n * adding a fourth transform function for the browser to interpolate.\n */\nfunction transformFor(\n flipH: boolean,\n flipV: boolean,\n rotationDeg: number,\n fitScale: number,\n): string {\n if (!flipH && !flipV && rotationDeg === 0 && fitScale === 1) return 'none';\n const scaleX = (flipH ? -1 : 1) * fitScale;\n const scaleY = (flipV ? -1 : 1) * fitScale;\n return `scaleX(${scaleX}) scaleY(${scaleY}) rotate(${rotationDeg}deg)`;\n}\n\n/**\n * DESIGN.md §4.5 — shrinks the *visible photo* exactly as much as needed to\n * keep it from getting its edges clipped away when rotated, and grows it\n * back up to fill newly-available space on rotation, but never past its\n * own native pixel resolution.\n *\n * **A real bug in the previous version of this fix, caught from real usage\n * on the docs site itself: it assumed `.shoji-slide-img` always scales to\n * *touch* the container on at least one axis (`object-fit: contain`'s\n * usual behavior), which is wrong.** The actual CSS is `max-width: 100%;\n * max-height: 100%` — a *cap*, not a forced fill (documented in\n * `shoji.css`'s own comment: real photos are assumed bigger than the\n * slide area, so never growing past natural size is the correct default).\n * A small placeholder photo, comfortably smaller than the dialog, simply\n * renders at its own native size — untouching every edge, nothing scaled.\n * The previous formula didn't know this: it computed an imagined\n * \"as if `object-fit: contain` always scales to fill\" pre-rotation size\n * (e.g. an 800×600 photo hypothetically stretched to ~1267×950 in a\n * 1920×950 window), then shrank *from that invented size* — a real,\n * visible shrink relative to what was actually on screen a moment\n * earlier, even though nothing should have changed at all. Confirmed\n * directly: measuring the real `<img>` on the real deployed docs page\n * showed it rendered at exactly its 800×600 native size, not the\n * \"contain-fit\" size the old formula assumed.\n *\n * **The fix: compute the photo's real render scale at each orientation\n * the same way the browser's own CSS does, then compare the two —\n * instead of computing an idealized target size and separately capping\n * it.** `scaleAt0`/`scaleAt90` are each `Math.min(1, mediaWidth /\n * relevantNaturalWidth, mediaHeight / relevantNaturalHeight)` — exactly\n * mirroring `max-width/max-height: 100%`'s own \"shrink to fit, never grow\n * past native size\" rule, once for the current (unrotated) orientation\n * and once for the rotated one (natural width/height swapped). The result\n * is simply their ratio: how much *more* (or less) of its own native\n * resolution the rotated orientation can use compared to what's already\n * on screen. This single ratio does everything the old two-step\n * idealFit-then-cap formula tried to do, correctly and for free: neither\n * `scaleAt0` nor `scaleAt90` can ever exceed `1` (native resolution is\n * never exceeded, in *either* orientation, not just relative to a\n * possibly-wrong assumed starting point), and whichever one is more\n * constrained by the container — rather than by native resolution —\n * still shrinks or grows the ratio exactly as far as that constraint\n * requires.\n *\n * `1` (a no-op) for 0°/180° — a rectangle's own bounding box is unchanged\n * by a half-turn, nothing to re-fit — and whenever either media dimension\n * isn't known yet (not yet laid out) or the photo's own natural dimensions\n * aren't known at all (video, or an image that hasn't decoded) — skipped\n * entirely rather than guessing.\n */\nfunction fitScaleFor(\n mediaWidth: number,\n mediaHeight: number,\n rotationDeg: number,\n naturalWidth: number | undefined,\n naturalHeight: number | undefined,\n): number {\n if (!mediaWidth || !mediaHeight || !naturalWidth || !naturalHeight) return 1;\n if ((rotationDeg / 90) % 2 === 0) return 1;\n const scaleAt0 = Math.min(1, mediaWidth / naturalWidth, mediaHeight / naturalHeight);\n const scaleAt90 = Math.min(1, mediaWidth / naturalHeight, mediaHeight / naturalWidth);\n return scaleAt90 / scaleAt0;\n}\n\n/**\n * DESIGN.md §4 — rotate ±90°/flip H/V of the *view*: a CSS transform on the\n * active `.shoji-slide-media`, non-destructive, resets to neutral on every\n * `afterOpen`/`afterSlide` (per-slide, not per-gallery — DESIGN.md's own\n * wording). Emits `rotateFlipChange` on every change so a host that wants\n * this to persist can store it themselves and re-apply later (e.g. by\n * feeding a starting orientation back in some other way) — this plugin\n * itself has no persistence of its own, matching \"resets per slide\".\n *\n * Distinct from the (unbuilt) Editor plugin's own rotate/flip (§8), which\n * is destructive/persisted server-side via `item.edits`. Both share the\n * same composition math (`normalizeRotateFlip`, `src/core/`) rather than\n * each re-deriving flip+rotate's non-commutative composition — a real bug\n * class CLAUDE.md calls out by name.\n */\nexport const RotateFlip: ShojiPlugin = {\n name: 'rotateFlip',\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const locale = (gallery.options.locale ?? {}) as Record<string, string>;\n const rotateLeftLabel = locale.rotateLeft ?? 'Rotate left';\n const rotateRightLabel = locale.rotateRight ?? 'Rotate right';\n const flipHLabel = locale.flipHorizontal ?? 'Flip horizontal';\n const flipVLabel = locale.flipVertical ?? 'Flip vertical';\n\n let state: RotateFlipState = { ...NEUTRAL };\n /** Unbounded — never wrapped like `state.rotation` is. Drives only the CSS transform's rotate() degrees, so every rotate click continues smoothly in the same direction (90, 180, 270, 360, 450, ...) instead of snapping backward whenever the normalized state wraps past 0/360. See `transformFor`'s own doc comment for the full reasoning. */\n let visualRotation = 0;\n /** Raw, independent toggles — never collapsed into a rotation the way `state.flipH`/`state.flipV` are. See `transformFor`'s own doc comment. */\n let visualFlipH = false;\n let visualFlipV = false;\n\n /**\n * `animate` mirrors the Zoom plugin's own \"discrete jumps animate\"\n * pattern (`zoom/index.ts`'s `withTransition`) — a button click is a\n * one-shot state change, not a continuous gesture, so it eases instead\n * of snapping. `reset()` stays unanimated: the viewer never rotated the\n * new slide, so there's nothing to visibly animate *from*. The\n * transition is cleared once it ends so it doesn't linger onto the\n * open/close zoom transition's own later use of this same element's\n * `transform` (`zoomTransition.ts`, `.shoji-slide-media`).\n */\n /** `item.width`/`height` when known, else the active image's own natural dimensions — same fallback order the zoom transition (§2.3b) uses for its own aspect ratio, just sourced from the slide itself rather than the origin thumbnail, and kept as a real width/height pair (not collapsed to a ratio) since `fitScaleFor` needs the actual pixel counts for its resolution ceiling, not just their proportion. `undefined` for anything else (video, an image not yet decoded) — `fitScaleFor` treats that as nothing to fit, not a guess. */\n function resolveNaturalSize(media: HTMLElement): { width: number; height: number } | undefined {\n const item = gallery.items[gallery.currentIndex];\n if (item?.width && item.height) return { width: item.width, height: item.height };\n const img = media.querySelector('img');\n if (img?.naturalWidth && img.naturalHeight) {\n return { width: img.naturalWidth, height: img.naturalHeight };\n }\n return undefined;\n }\n\n function apply(animate: boolean): void {\n const media = gallery.getActiveMedia();\n if (!media) return;\n const natural = resolveNaturalSize(media);\n const fitScale = fitScaleFor(\n media.clientWidth,\n media.clientHeight,\n visualRotation,\n natural?.width,\n natural?.height,\n );\n const transform = transformFor(visualFlipH, visualFlipV, visualRotation, fitScale);\n if (!animate) {\n media.style.transform = transform;\n return;\n }\n media.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n media.style.transform = transform;\n waitForTransitionEnd(media, () => {\n media.style.transition = '';\n });\n }\n\n function buildButton(icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n button.innerHTML = icon;\n button.setAttribute('aria-label', label);\n button.title = label;\n return button;\n }\n\n const rotateLeftBtn = buildButton(ROTATE_LEFT_ICON, rotateLeftLabel);\n const rotateRightBtn = buildButton(ROTATE_RIGHT_ICON, rotateRightLabel);\n const flipHBtn = buildButton(FLIP_H_ICON, flipHLabel);\n const flipVBtn = buildButton(FLIP_V_ICON, flipVLabel);\n flipHBtn.setAttribute('aria-pressed', 'false');\n flipVBtn.setAttribute('aria-pressed', 'false');\n\n /**\n * `visualRotationDelta`, when given, is a rotate click's own known\n * direction (±90) — applied as-is to the unbounded `visualRotation`.\n * Flip clicks omit it entirely: `visualFlipH`/`visualFlipV` are toggled\n * directly at each call site instead, completely independent of\n * `state`'s own canonicalized rotation/flip collapse (`transformFor`'s\n * doc comment has the full reasoning for why the two must stay\n * decoupled).\n */\n function update(patch: Partial<RotateFlipState>, visualRotationDelta?: number): void {\n state = normalizeRotateFlip({ ...state, ...patch });\n if (visualRotationDelta !== undefined) visualRotation += visualRotationDelta;\n apply(true);\n flipHBtn.setAttribute('aria-pressed', String(state.flipH));\n flipVBtn.setAttribute('aria-pressed', String(state.flipV));\n ctx.emit('rotateFlipChange', { index: gallery.currentIndex, ...state });\n }\n\n /**\n * A real bug, reported from real usage: with exactly one flip axis\n * active, \"Rotate right\" visually spun the image counter-clockwise\n * instead — a `+90` raw `rotate()` delta composed with a single\n * `scaleX(-1)`/`scaleY(-1)` mirror reverses the rotation's visual\n * handedness (a mirror is a reflection — determinant -1 — so a\n * clockwise turn *inside* it reads as counter-clockwise once mirrored\n * back onto the screen). Flipping *both* axes doesn't have this problem\n * — two reflections compose back into a rotation (determinant +1, same\n * as no flip at all), which is exactly why `normalizeRotateFlip`\n * already collapses that combination into a plain 180° rotation.\n * Inverting the raw delta whenever `visualFlipH !== visualFlipV` (XOR —\n * \"exactly one axis flipped\") makes the buttons always spin the image\n * the way they're visually labeled, regardless of flip state; `state`\n * (the canonicalized, emitted value) gets the same inverted delta, so\n * it stays an accurate description of what's actually on screen.\n */\n function rotateDelta(clockwise: boolean): number {\n const flippedOnOneAxis = visualFlipH !== visualFlipV;\n return clockwise !== flippedOnOneAxis ? 90 : -90;\n }\n\n /** Shared by the rotate-left toolbar button and `requestRotateLeft` below. */\n function rotateLeft(): void {\n const delta = rotateDelta(false);\n update({ rotation: state.rotation + delta }, delta);\n }\n /** Shared by the rotate-right toolbar button and `requestRotateRight` below. */\n function rotateRight(): void {\n const delta = rotateDelta(true);\n update({ rotation: state.rotation + delta }, delta);\n }\n /** Shared by the flip-horizontal toolbar button and `requestFlipHorizontal` below. */\n function flipHorizontal(): void {\n visualFlipH = !visualFlipH;\n update({ flipH: !state.flipH });\n }\n /** Shared by the flip-vertical toolbar button and `requestFlipVertical` below. */\n function flipVertical(): void {\n visualFlipV = !visualFlipV;\n update({ flipV: !state.flipV });\n }\n\n rotateLeftBtn.addEventListener('click', rotateLeft);\n rotateRightBtn.addEventListener('click', rotateRight);\n flipHBtn.addEventListener('click', flipHorizontal);\n flipVBtn.addEventListener('click', flipVertical);\n\n function reset(): void {\n state = { ...NEUTRAL };\n visualRotation = 0;\n visualFlipH = false;\n visualFlipV = false;\n apply(false);\n flipHBtn.setAttribute('aria-pressed', 'false');\n flipVBtn.setAttribute('aria-pressed', 'false');\n }\n\n /**\n * DESIGN.md §2.5/§4.5 — a real bug: clicking next/prev on a\n * rotated/flipped slide snapped it back to neutral *before* the slide\n * transition started, instead of un-rotating as part of it.\n * `beforeSlide`'s own `reset()` (below) still has to stay unanimated and\n * still has to run before `SlideManager.render()` reparents the\n * outgoing slide (the sixth real bug above) — that constraint doesn't\n * go away. What changes: the transform about to be wiped is captured\n * here first and handed to `SlideTransition` via\n * `registerSlideLeaveDecorator()` (Zoom registers its own, for the same\n * reason) — the decorator runs once, right after the ghost clones the\n * outgoing slide (the real node's already been reset by then, so the\n * clone alone wouldn't carry it), freezes the captured transform onto\n * that clone, and animates it back to neutral over the same window the\n * ghost itself is leaving in. Only the ghost animates away from it now.\n */\n let pendingLeaveTransform: string | null = null;\n function captureLeaveTransform(): void {\n const media = gallery.getActiveMedia();\n const transform = media?.style.transform;\n pendingLeaveTransform = transform && transform !== 'none' ? transform : null;\n }\n\n // 'right' — registered in this order, so they cluster left-to-right as\n // rotateLeft, rotateRight, flipH, flipV, then whatever later plugin (or\n // the close button) follows (DESIGN.md §3.1).\n const removeButtons = [rotateLeftBtn, rotateRightBtn, flipHBtn, flipVBtn].map((button) =>\n ctx.ui.toolbar('right', button),\n );\n\n /**\n * A generic command surface, requested directly (DESIGN.md §4.5), so a\n * *custom* (host-authored) plugin's own button can rotate/flip without\n * importing this plugin at all — same \"events over inheritance\"\n * decoupling every other listener here already uses.\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestRotateLeft', {})` from any plugin —\n * official or custom — type-checks with zero core changes; this is\n * just the listening half. Each mirrors its real toolbar button\n * exactly — same functions, same behavior.\n */\n const offRequestRotateLeft = ctx.on('requestRotateLeft', rotateLeft);\n const offRequestRotateRight = ctx.on('requestRotateRight', rotateRight);\n const offRequestFlipHorizontal = ctx.on('requestFlipHorizontal', flipHorizontal);\n const offRequestFlipVertical = ctx.on('requestFlipVertical', flipVertical);\n const offOpen = ctx.on('afterOpen', reset);\n // Un-animated, and on beforeSlide rather than only afterSlide below —\n // same fix, same reasoning, as the Zoom plugin's own identical bug\n // (zoom/index.ts's own beforeSlide handler): SlideManager.render()\n // (called synchronously between the two) reuses a still-cached slide's\n // node via a plain reparent (moveIn(), no state clearing of its own)\n // into whichever pool slot its new offset needs — there is no code\n // path afterward that can still find *this* slide to reset it.\n // Reported from real usage: rotate, click next — the old, still-\n // rotated slide, now reparented into the (unclipped, per shoji.css)\n // neighboring slot, visibly bled into the new slide instead of\n // sitting invisibly off-screen the way an unrotated one always does.\n // Resetting here, while getActiveMedia() still resolves to the\n // about-to-move slide, clears it before that reparent ever happens.\n // afterSlide (below) still separately resets whichever *incoming*\n // slide becomes active — it may carry its own stale rotation from an\n // earlier visit, unrelated to whatever the outgoing slide had.\n // captureLeaveTransform() (see its own doc comment) runs first, while\n // the about-to-be-cleared transform is still readable.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n captureLeaveTransform();\n reset();\n });\n const offSlide = ctx.on('afterSlide', reset);\n const unregisterLeaveDecorator = gallery.registerSlideLeaveDecorator((clonedMedia) => {\n if (!pendingLeaveTransform) return;\n const transform = pendingLeaveTransform;\n pendingLeaveTransform = null;\n clonedMedia.style.transform = transform;\n return () => {\n clonedMedia.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n clonedMedia.style.transform = 'none';\n };\n });\n\n return () => {\n for (const remove of removeButtons) remove();\n offRequestRotateLeft();\n offRequestRotateRight();\n offRequestFlipHorizontal();\n offRequestFlipVertical();\n offOpen();\n offBeforeSlide();\n offSlide();\n unregisterLeaveDecorator();\n };\n },\n};\n","import type { VideoProviderRenderer } from '../../core/plugin';\n\n/**\n * The bits of Vimeo's Player SDK actually used here — not in `lib.dom.d.ts`\n * (a third-party global loaded on demand), so this is a documented interop\n * boundary (CLAUDE.md: `any` only there). Kept intentionally minimal, not a\n * full mirror of Vimeo's own typings. Unlike YouTube's IFrame API, every\n * method here is genuinely Promise-based — Vimeo has no synchronous\n * \"isMuted()\"-style query at all, which is why `wirePlayableContract` below\n * mirrors `muted` locally instead of reading it live (see its own comment).\n */\ninterface VimeoPlayer {\n play(): Promise<void>;\n pause(): Promise<void>;\n setMuted(muted: boolean): Promise<boolean>;\n ready(): Promise<void>;\n destroy(): Promise<void>;\n /** The video's own real native pixel dimensions — used to correct `--shoji-provider-video-aspect` (see the `player.ready()` handler below) if a host's declared `item.width`/`item.height` doesn't match. */\n getVideoWidth(): Promise<number>;\n getVideoHeight(): Promise<number>;\n on(event: 'play' | 'pause' | 'ended', callback: () => void): void;\n on(event: 'error', callback: (error: VimeoErrorEvent) => void): void;\n}\n\n/** Vimeo's own error event shape (`name`/`message`, plus an undocumented `method` sometimes) — e.g. `name: 'PrivacyError'` (embedding disabled), `'PasswordError'` (password-protected). */\ninterface VimeoErrorEvent {\n name: string;\n message: string;\n}\n\ninterface VimeoNamespace {\n Player: new (\n element: HTMLElement,\n options: { id?: number; url?: string; playsinline?: boolean },\n ) => VimeoPlayer;\n}\n\ndeclare global {\n interface Window {\n Vimeo?: VimeoNamespace;\n }\n}\n\nlet apiPromise: Promise<VimeoNamespace> | null = null;\n\n// See the 'pause'/'ended' race comment where this is used, below.\nconst PAUSE_DISPATCH_DELAY_MS = 250;\n\n/**\n * Loads `https://player.vimeo.com/api/player.js` exactly once however many\n * Vimeo slides/galleries end up on a page — `window.Vimeo` is a single\n * global. Simpler than `youtube.ts`'s `loadYouTubeApi`: Vimeo's script has\n * no global-callback side channel to compose with (nothing else could\n * already be watching for it the way `onYouTubeIframeAPIReady` can be), so\n * a plain `script.onload` is enough.\n */\nfunction loadVimeoApi(): Promise<VimeoNamespace> {\n if (window.Vimeo?.Player) return Promise.resolve(window.Vimeo);\n if (apiPromise) return apiPromise;\n\n apiPromise = new Promise((resolve) => {\n const script = document.createElement('script');\n script.src = 'https://player.vimeo.com/api/player.js';\n script.onload = () => resolve(window.Vimeo!);\n document.head.appendChild(script);\n });\n return apiPromise;\n}\n\n/**\n * DESIGN.md §4-autoplay — Autoplay looks for exactly this shape (`.play`/\n * `.pause`/`.paused`/`.ended`, plus real `play`/`pause`/`ended` DOM events)\n * on whatever's active, native `<video>` or not. Augmenting `container` this\n * way is what makes slideshow sync work without Autoplay ever having to\n * know Vimeo — or any other provider — exists. `play` genuinely returns\n * `player.play()`'s own promise (unlike `youtube.ts`'s fire-and-forget\n * `.play`) — Autoplay's own `ensureProviderPlaying` (§4.1 point 12) branches\n * its retry strategy on whether this is a real thenable at runtime.\n */\ntype PlayableElement = HTMLElement & {\n play: () => Promise<void>;\n pause: () => void;\n paused: boolean;\n ended: boolean;\n muted: boolean;\n};\n\n/**\n * `muted`'s setter genuinely forwards to `player.setMuted()` (fire-and-\n * forget, same as `youtube.ts`'s `mute()`/`unMute()` calls), but the getter\n * mirrors a locally-tracked value instead of reading the player live —\n * unlike YouTube's `isMuted()`, Vimeo's `getMuted()` is Promise-based, so\n * there's no synchronous value to read at all. Harmless here: nothing in\n * Autoplay ever reads `.muted` back, only sets it (DESIGN.md §4.1 point 8's\n * `video.muted = true` before an automatic play).\n */\nfunction wirePlayableContract(container: HTMLElement, player: VimeoPlayer): PlayableElement {\n const playable = container as PlayableElement;\n playable.paused = true;\n playable.ended = false;\n playable.play = () => player.play();\n playable.pause = () => player.pause();\n let mutedState = false;\n Object.defineProperty(playable, 'muted', {\n configurable: true,\n get: () => mutedState,\n set: (value: boolean) => {\n mutedState = value;\n player.setMuted(value);\n },\n });\n return playable;\n}\n\n/**\n * DESIGN.md §4-video — `item.poster`, if the host supplied one, is already\n * shown by the time this runs (core's own doing, `SlideManager.ts`) and\n * always wins over the fallback below. Without one, this falls back to a\n * real thumbnail fetched from Vimeo's own oEmbed endpoint — unlike\n * YouTube's predictable, request-free thumbnail URL (`youtube.ts`), Vimeo\n * has no such pattern; its thumbnails live at unpredictable, per-video\n * CDN paths only oEmbed's response actually reveals — before finally\n * falling back to the plain spinner if that request never resolves.\n */\nexport const renderVimeo: VideoProviderRenderer = (container, item, onReady, signal, setPoster) => {\n if (item.video?.provider !== 'vimeo') return;\n const { id, url } = item.video;\n if (!id && !url) {\n // A misconfigured item — scan.ts already warned about this at\n // normalization time. Same placeholder SlideManager itself uses for \"no\n // source\"/\"provider not registered\", so the spinner doesn't hang\n // forever waiting for a ready() that would never resolve otherwise.\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n container.appendChild(placeholder);\n onReady();\n return;\n }\n\n if (!item.poster) {\n // `url` (carrying an unlisted video's privacy hash, same reasoning as\n // the player construction below) is preferred over a bare numeric id\n // when both exist; oEmbed accepts either a full vimeo.com URL or one\n // built from just the id.\n const oembedTarget = url ?? `https://vimeo.com/${id}`;\n fetch(`https://vimeo.com/api/oembed.json?url=${encodeURIComponent(oembedTarget)}`)\n .then((response) => (response.ok ? response.json() : null))\n .then((data: { thumbnail_url?: unknown } | null) => {\n if (signal.aborted) return; // navigated away before the request resolved\n if (typeof data?.thumbnail_url === 'string') setPoster(data.thumbnail_url);\n })\n // Swallowed deliberately, same reasoning as youtube.ts's 404 case —\n // a failed request (network error, CORS, rate limit, a private/\n // deleted video oEmbed itself rejects) just leaves whatever's\n // already showing (the plain spinner) alone.\n .catch(() => {});\n }\n\n // shoji-video-mount (styles/shoji.css) — several real bugs, reported from\n // real usage, chased through in sequence:\n //\n // 1. Left at its own defaults, Vimeo's SDK sizes `mount` to a small fixed\n // box (its own embed default, ~640x360) via inline styles — CSS's own\n // `width/height: 100%` on the iframe only ever resolves relative to\n // that fixed-size `mount`, not the actual slide, so the embed rendered\n // small, in a corner, instead of filling the dialog.\n //\n // 2. `responsive: true` looked like the fix (and does make `mount` fill\n // its parent's *width*) but doesn't actually solve this: it computes\n // `mount`'s *height* from that width times the video's own native\n // aspect ratio via a padding-percentage trick, entirely ignoring how\n // much vertical space the slide actually has — confirmed directly at a\n // wide-but-short viewport, the resulting iframe came out taller than\n // its container, pushing the bottom of the video (and Vimeo's own\n // scrubber/controls bar, always along that same edge) below the\n // visible area.\n //\n // 3. Fully stretching `mount` to the container's own box instead (no\n // aspect-ratio at all) fixed that, but traded it for a third bug:\n // stretching regardless of the video's real 16:9 shape exposed\n // Vimeo's own internal letterbox color (white — not overridable from\n // here, that content is cross-origin) wherever the box wasn't already\n // 16:9 itself, instead of Shoji's own dark backdrop.\n //\n // `shoji-video-mount`'s CSS rules are what actually solve all three at\n // once now: contained to a real 16:9 box via container query units\n // (`!important` still doing the \"discard whatever Vimeo tries to set\n // inline\" job point 1 needed), so any leftover gap is *outside* the\n // iframe, showing this element's own transparent background — Shoji's\n // dark backdrop — rather than the provider's white. YouTube's plain\n // iframe (no such wrapper) gets the identical treatment directly, see\n // `.shoji-slide-provider-video > iframe` in shoji.css.\n const mount = document.createElement('div');\n mount.className = 'shoji-video-mount';\n container.appendChild(mount);\n\n loadVimeoApi().then((Vimeo) => {\n if (signal.aborted) return; // navigated away before the (possibly first-ever, slow) API load resolved\n\n const playable = container as PlayableElement;\n // `url` (the original data-shoji-video/video.url, when present) is\n // preferred over a bare id: it's what carries an unlisted video's\n // privacy hash (vimeo.com/{id}/{hash}) through to the player, which a\n // numeric id alone can't express. Only dynamic-mode items authored\n // without a url ever fall back to id-only.\n const player = new Vimeo.Player(mount, {\n ...(url ? { url } : { id: Number(id) }),\n playsinline: true,\n });\n\n // A real bug, reported from real usage: reaching the end of the video\n // stopped the slideshow instead of advancing it, and — the tell —\n // manually pressing play again restarted the same video from 0 instead\n // of resuming anywhere. Confirmed directly: Vimeo's own 'pause' arrives\n // as a genuinely separate postMessage event shortly *before* 'ended'\n // (~20ms apart in testing) when a video reaches its natural end, unlike\n // native `<video>`, whose `.ended` property the browser sets\n // synchronously before firing either event — Autoplay's own\n // `onVideoPause` (DESIGN.md §4.1 point 3) checks `.ended` to tell a\n // real pause from an end-adjacent one, and that check reliably lost the\n // race, reading `false` and treating a natural end as a manual pause.\n // Fixed by not dispatching 'pause' immediately: it's held for\n // `PAUSE_DISPATCH_DELAY_MS`, comfortably above the observed gap, and\n // dropped entirely if 'ended' arrives first — which is also then the\n // *only* event a natural end ever produces, matching how a single\n // native `<video>` 'pause' alongside 'ended' was already a non-issue\n // via the `.ended` check alone. A genuine manual pause (no 'ended'\n // following) still dispatches, just delayed by that same short window\n // — imperceptible for a real pause, and worth it for a correct one.\n let pendingPauseTimer: ReturnType<typeof setTimeout> | null = null;\n function clearPendingPause(): void {\n if (pendingPauseTimer !== null) {\n clearTimeout(pendingPauseTimer);\n pendingPauseTimer = null;\n }\n }\n player.on('play', () => {\n clearPendingPause();\n playable.paused = false;\n playable.dispatchEvent(new Event('play'));\n });\n player.on('pause', () => {\n playable.paused = true;\n clearPendingPause();\n pendingPauseTimer = setTimeout(() => {\n pendingPauseTimer = null;\n playable.dispatchEvent(new Event('pause'));\n }, PAUSE_DISPATCH_DELAY_MS);\n });\n player.on('ended', () => {\n clearPendingPause();\n playable.paused = true;\n playable.ended = true;\n playable.dispatchEvent(new Event('ended'));\n });\n // bubbles: true — reaches .shoji-slide-media (the pool slot, always\n // present regardless of readiness) without needing wirePlayableContract\n // to have run first; matches youtube.ts's onError — a player can error\n // out (bad id, privacy-restricted, password-protected) without ever\n // becoming ready. Autoplay (DESIGN.md §4.1) listens for this to skip to\n // the next slide instead of stalling.\n player.on('error', (error) =>\n playable.dispatchEvent(\n new CustomEvent('error', { bubbles: true, detail: { name: error.name } }),\n ),\n );\n\n player.ready().then(() => {\n wirePlayableContract(container, player);\n // A real bug, reported from real usage: a host's declared\n // `item.width`/`item.height` (what `--shoji-provider-video-aspect`,\n // shoji.css, is normally set from — SlideManager.ts's `applyAspect()`)\n // doesn't always match the video's own real shape — confirmed\n // directly against a real 2.4:1 cinematic-widescreen video declared\n // as a plain 4:3 item. Vimeo's own player fits *itself* to the real\n // shape regardless of what box it's given, so a mismatch here leaves\n // Shoji's outer box a different aspect ratio than what Vimeo actually\n // renders inside it — exposing the iframe's own default white\n // background (not overridable from here, that content is\n // cross-origin) in the gap, instead of a clean, uniform letterbox.\n // Corrected here, before `onReady()` reveals the container, using the\n // one thing that can't be wrong: the player's own real dimensions.\n // Setting this directly on `container` (`.shoji-slide-provider-video`)\n // overrides the inherited value from `applyAspect()`'s own\n // `.shoji-slide-media` — no coordination with SlideManager needed.\n // Swallowed on rejection: a declared item.width/height (if any) is a\n // fine fallback, and this must never block onReady().\n Promise.all([player.getVideoWidth(), player.getVideoHeight()])\n .then(([width, height]) => {\n if (width && height) {\n container.style.setProperty(\n '--shoji-provider-video-aspect',\n `calc(${width} / ${height})`,\n );\n }\n })\n .catch(() => {})\n .then(() => onReady());\n });\n\n signal.addEventListener(\n 'abort',\n () => {\n clearPendingPause();\n void player.destroy();\n },\n { once: true },\n );\n });\n};\n","import type { VideoProviderRenderer } from '../../core/plugin';\n\n/**\n * The bits of the YouTube IFrame Player API actually used here — not in\n * `lib.dom.d.ts` (a third-party global loaded on demand), so this is a\n * documented interop boundary (CLAUDE.md: `any` only there). Kept\n * intentionally minimal, not a full mirror of YouTube's own typings.\n */\ninterface YTPlayer {\n playVideo(): void;\n pauseVideo(): void;\n mute(): void;\n unMute(): void;\n isMuted(): boolean;\n destroy(): void;\n}\n\ninterface YTPlayerStateEvent {\n data: number;\n}\n\n/**\n * Same `{ data: number }` shape as `YTPlayerStateEvent` — `data` holds an\n * error code there (2 invalid parameter, 5 HTML5 player error, 100 video\n * not found/private, 101/150 embedding disabled by the owner; undocumented\n * codes like 153 are also reported in the wild) rather than a player state.\n * Named separately from `YTPlayerStateEvent` for readability at the call\n * site, not because the shape actually differs.\n */\ninterface YTPlayerErrorEvent {\n data: number;\n}\n\ninterface YTNamespace {\n Player: new (\n el: HTMLElement,\n opts: {\n videoId: string;\n playerVars?: { playsinline?: 0 | 1; rel?: 0 | 1 };\n events?: {\n onReady?: () => void;\n onStateChange?: (event: YTPlayerStateEvent) => void;\n onError?: (event: YTPlayerErrorEvent) => void;\n };\n },\n ) => YTPlayer;\n PlayerState: { ENDED: number; PLAYING: number; PAUSED: number };\n}\n\ndeclare global {\n interface Window {\n YT?: YTNamespace;\n onYouTubeIframeAPIReady?: () => void;\n }\n}\n\nlet apiPromise: Promise<YTNamespace> | null = null;\n\n/**\n * Loads `https://www.youtube.com/iframe_api` exactly once however many\n * YouTube slides/galleries end up on a page — the API itself is a single\n * global (`window.YT`), and re-injecting the script tag would be wasteful\n * and risks a second, conflicting `onYouTubeIframeAPIReady` firing. Composes\n * with a host's own `onYouTubeIframeAPIReady`, if one already exists\n * (e.g. the host embeds YouTube elsewhere too), instead of clobbering it.\n */\nfunction loadYouTubeApi(): Promise<YTNamespace> {\n if (window.YT?.Player) return Promise.resolve(window.YT);\n if (apiPromise) return apiPromise;\n\n apiPromise = new Promise((resolve) => {\n const previous = window.onYouTubeIframeAPIReady;\n window.onYouTubeIframeAPIReady = () => {\n previous?.();\n resolve(window.YT!);\n };\n const script = document.createElement('script');\n script.src = 'https://www.youtube.com/iframe_api';\n document.head.appendChild(script);\n });\n return apiPromise;\n}\n\n/**\n * DESIGN.md §4-autoplay — Autoplay looks for exactly this shape (`.play`/\n * `.pause`/`.paused`/`.ended`, plus real `play`/`pause`/`ended` DOM events)\n * on whatever's active, native `<video>` or not. Augmenting `container`\n * this way is what makes slideshow sync work without Autoplay ever having\n * to know YouTube — or any other provider — exists.\n */\ntype PlayableElement = HTMLElement & {\n play: () => void;\n pause: () => void;\n paused: boolean;\n ended: boolean;\n muted: boolean;\n};\n\n/**\n * `muted` is a real accessor (not a plain property) backed by the player's\n * own `mute()`/`unMute()`/`isMuted()` — DESIGN.md §4.1's autoplay-policy fix\n * sets `video.muted = true` right before an *automatic* play, the same way\n * it would for a native `<video>`; a plain property here would just be\n * inert state that never actually silences the embed.\n */\nfunction wirePlayableContract(container: HTMLElement, player: YTPlayer): PlayableElement {\n const playable = container as PlayableElement;\n playable.paused = true;\n playable.ended = false;\n playable.play = () => player.playVideo();\n playable.pause = () => player.pauseVideo();\n Object.defineProperty(playable, 'muted', {\n configurable: true,\n get: () => player.isMuted(),\n set: (value: boolean) => (value ? player.mute() : player.unMute()),\n });\n return playable;\n}\n\nfunction handleStateChange(\n event: YTPlayerStateEvent,\n YT: YTNamespace,\n playable: PlayableElement,\n): void {\n if (event.data === YT.PlayerState.PLAYING) {\n playable.paused = false;\n playable.dispatchEvent(new Event('play'));\n } else if (event.data === YT.PlayerState.PAUSED) {\n playable.paused = true;\n playable.dispatchEvent(new Event('pause'));\n } else if (event.data === YT.PlayerState.ENDED) {\n playable.paused = true;\n playable.ended = true;\n playable.dispatchEvent(new Event('ended'));\n }\n}\n\n/**\n * DESIGN.md §4-video — `item.poster`, if the host supplied one, is already\n * shown by the time this runs (core's own doing, `SlideManager.ts`) and\n * always wins over the fallback below. Without one, this falls back to\n * YouTube's own predictable, unauthenticated thumbnail URL — no API call\n * needed, unlike Vimeo's oEmbed-based equivalent (`vimeo.ts`) — before\n * finally falling back to the plain spinner if even that never resolves.\n */\nexport const renderYouTube: VideoProviderRenderer = (\n container,\n item,\n onReady,\n signal,\n setPoster,\n) => {\n if (item.video?.provider !== 'youtube') return;\n const videoId = item.video.id;\n if (!videoId) {\n // A misconfigured item — scan.ts (data-shoji-video-id / video: true /\n // video.id auto-fill) already warned about this at normalization time.\n // Same placeholder SlideManager itself uses for \"no source\"/\"provider\n // not registered\", so the spinner doesn't hang forever waiting for an\n // onReady that would never fire otherwise.\n const placeholder = document.createElement('div');\n placeholder.className = 'shoji-slide-placeholder';\n placeholder.textContent = 'Video';\n container.appendChild(placeholder);\n onReady();\n return;\n }\n\n // hqdefault.jpg exists for essentially every uploaded video (unlike\n // maxresdefault.jpg, which many older/short videos never got generated);\n // a 404 here just leaves the plain spinner showing, same as never calling\n // setPoster at all — no error handling needed for that.\n if (!item.poster) setPoster(`https://img.youtube.com/vi/${videoId}/hqdefault.jpg`);\n\n const mount = document.createElement('div');\n container.appendChild(mount);\n\n loadYouTubeApi().then((YT) => {\n if (signal.aborted) return; // navigated away before the (possibly first-ever, slow) API load resolved\n\n const playable = container as PlayableElement;\n const player = new YT.Player(mount, {\n videoId,\n playerVars: { playsinline: 1, rel: 0 },\n events: {\n // `new YT.Player()` returns before the embed's own internal bootstrap\n // (its postMessage handshake with youtube.com) finishes — calling\n // `player.mute()`/`playVideo()`/etc. before that completes can throw\n // (\"player.isMuted is not a function\") or silently no-op, even though\n // the constructor already returned an object. `onReady` is YouTube's\n // own signal that the real API surface is actually callable now, so\n // wiring the contract here — not synchronously after construction —\n // is what makes `findPlayable()`'s \"is `.play` wired?\" check in\n // Autoplay (DESIGN.md §4.1) an accurate proxy for \"is it really\n // ready?\" instead of just \"did we build the wrapper closures?\".\n onReady: () => {\n wirePlayableContract(container, player);\n onReady();\n },\n onStateChange: (event) => handleStateChange(event, YT, playable),\n // bubbles: true — reaches .shoji-slide-media (the pool slot, always\n // present regardless of readiness) without needing wirePlayableContract\n // to have run first; onError can fire instead of onReady entirely\n // (e.g. a removed/private video), so playable isn't a safe assumption\n // here the way it is in onStateChange. Autoplay (DESIGN.md §4.1)\n // listens for this to skip to the next slide instead of stalling.\n onError: (event) =>\n playable.dispatchEvent(\n new CustomEvent('error', { bubbles: true, detail: { code: event.data } }),\n ),\n },\n });\n signal.addEventListener('abort', () => player.destroy(), { once: true });\n });\n};\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { renderVimeo } from './vimeo';\nimport { renderYouTube } from './youtube';\n\n/**\n * DESIGN.md §4-video — renders `{ video: { provider: 'youtube' | 'vimeo', id } }`\n * items (produced by `scan.ts`'s `data-shoji-video` host detection, or\n * authored directly in dynamic mode) as a real embed instead of\n * `SlideManager`'s native-`<video>` fallback, which can't play either URL at\n * all. Purely a renderer: no options, no toolbar button, no poster/\n * thumbnail handling — the slide shows nothing until the embed itself is\n * ready, same as every other slide type. Autoplay (§4-autoplay) picks up\n * real play/pause/ended sync automatically; see `youtube.ts`'s/`vimeo.ts`'s\n * `wirePlayableContract`.\n */\nexport const Video: ShojiPlugin = {\n name: 'video',\n\n init(ctx: PluginContext): () => void {\n const offYouTube = ctx.ui.registerVideoProvider('youtube', renderYouTube);\n const offVimeo = ctx.ui.registerVideoProvider('vimeo', renderVimeo);\n return () => {\n offYouTube();\n offVimeo();\n };\n },\n};\n","/** DESIGN.md §9 — inline SVG, stroke = currentColor, matches src/core/icons.ts's convention. A magnifying glass with a +/− in the lens, and a plain expand-corners glyph for \"actual size\" (distinct from fullscreen's EXPAND_ICON — no diagonal corner arrows, just a frame, so the two aren't visually confusable when both plugins are enabled). */\nexport const ZOOM_IN_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"10\" cy=\"10\" r=\"7\"/><path d=\"M21 21l-5.5-5.5M10 7v6M7 10h6\"/></svg>';\n\nexport const ZOOM_OUT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"10\" cy=\"10\" r=\"7\"/><path d=\"M21 21l-5.5-5.5M7 10h6\"/></svg>';\n\n/**\n * Live state icons for the actual-size button (index.ts's icon-swap wiring)\n * — a diagonal double-arrow pair, matching the shape of Bootstrap Icons'\n * `arrows-angle-expand`/`arrows-angle-contract` (requested directly), not\n * literally that icon set's own path data. Still distinct from Fullscreen's\n * own EXPAND_ICON/COMPRESS_ICON (fullscreen/icons.ts) despite both being\n * diagonal-corner glyphs: Fullscreen draws four independent corner brackets\n * with no connecting line between them; these draw one continuous diagonal\n * shaft with an arrowhead-style bracket at each end, a different enough\n * shape that the two read as separate icons at a glance, not near-copies of\n * each other.\n */\nexport const ZOOM_ACTUAL_SIZE_EXPAND_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 9L3 3M3 8V3h5M15 15l6 6M21 16v5h-5\"/></svg>';\n\nexport const ZOOM_ACTUAL_SIZE_CONTRACT_ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 3l6 6M9 3v6H3M21 21l-6-6M15 21v-6h6\"/></svg>';\n","/** A viewport-relative rect: `{left, top, width, height}`, same shape as `DOMRect` but plain-object so it's trivial to mock in tests. */\nexport interface ZoomBox {\n left: number;\n top: number;\n width: number;\n height: number;\n}\n\nexport interface PanOffset {\n tx: number;\n ty: number;\n}\n\nexport function clampScale(scale: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, scale));\n}\n\n/** The 2x2 linear part of a CSS transform matrix — `{a, b, c, d}` from `matrix(a, b, c, d, e, f)`, translation (`e`/`f`) deliberately excluded, since everything below only ever uses this to remap a *delta* or a *local offset*, never an absolute position. */\nexport interface LinearTransform {\n a: number;\n b: number;\n c: number;\n d: number;\n}\n\n/** No parent transform — used as the default wherever a caller doesn't have (or need) one, so every function below stays backward-compatible with a pre-RotateFlip-aware caller. */\nexport const IDENTITY_TRANSFORM: LinearTransform = { a: 1, b: 0, c: 0, d: 1 };\n\n/**\n * `getComputedStyle().transform`'s own `matrix(a, b, c, d, e, f)` (or\n * `none`) string, parsed by hand rather than via the `DOMMatrix`\n * constructor — jsdom (`tests/unit/`) doesn't implement it, so relying on\n * it broke every unit test that exercises a pan drag; a plain regex needs\n * nothing environment-specific and works identically in a real browser.\n * RotateFlip only ever emits a 2D `matrix(...)` (never `matrix3d(...)`),\n * so that's the only form handled — `none` and anything unparseable both\n * fall back to the identity matrix.\n */\nexport function parseLinearTransform(transform: string): LinearTransform {\n const match = /^matrix\\(\\s*([^,]+),\\s*([^,]+),\\s*([^,]+),\\s*([^,]+),/.exec(transform);\n if (!match) return { ...IDENTITY_TRANSFORM };\n return { a: Number(match[1]), b: Number(match[2]), c: Number(match[3]), d: Number(match[4]) };\n}\n\n/**\n * DESIGN.md §4.6 — a real bug, reported from real usage: dragging to pan a\n * zoomed photo that RotateFlip (§4.5) had also rotated moved it in the\n * *wrong* direction (e.g. dragging down moved the image sideways instead)\n * — `onPointerMove`'s raw `event.clientX/Y` delta (screen space) was being\n * applied directly as `pan.tx`/`ty` (the `<img>`'s own *local* space,\n * nested inside `.shoji-slide-media`), with nothing correcting for\n * whatever transform that parent has — RotateFlip's rotation, in this\n * case, but this doesn't need to know that specifically: it corrects for\n * *any* linear transform on the parent, read live off its own computed\n * style, not by reaching into RotateFlip.\n *\n * Standard 2x2 matrix inversion: for `M = [[a, c], [b, d]]`, `M⁻¹ =\n * 1/det * [[d, -c], [-b, a]]` — applying `M⁻¹` to a screen-space delta\n * converts it into the local space `M` itself maps *from*, which is\n * exactly what a child nested inside that transformed parent needs to\n * move by to track the pointer 1:1 on screen regardless of the parent's\n * own rotation/scale/flip. `det === 0` is a degenerate parent transform\n * (zero scale on some axis) that can't be un-done at all — returns the\n * raw delta unchanged rather than dividing by zero into `NaN`.\n */\nexport function screenDeltaToLocal(dx: number, dy: number, m: LinearTransform): PanOffset {\n const det = m.a * m.d - m.b * m.c;\n if (det === 0) return { tx: dx, ty: dy };\n return {\n tx: (m.d * dx - m.c * dy) / det,\n ty: (m.a * dy - m.b * dx) / det,\n };\n}\n\n/** The forward companion to `screenDeltaToLocal` above: `M * [dx; dy]`, converting a *local* delta into the screen-space delta it produces once composed through the parent's current transform `m`. */\nexport function localDeltaToScreen(dx: number, dy: number, m: LinearTransform): PanOffset {\n return { tx: m.a * dx + m.c * dy, ty: m.b * dx + m.d * dy };\n}\n\n/**\n * DESIGN.md §4.6 — the img's own true, *unrotated* layout size (its\n * `offsetWidth`/`offsetHeight` — CSS `transform` is paint-only and never\n * affects these, unlike `natural`'s own `getBoundingClientRect()`, which\n * *does* reflect the parent's current rotation) as an offset from the\n * img's own local origin `(0, 0)` to its own layout center, negated:\n * `{tx: -width/2, ty: -height/2}`. See `localOriginScreen`'s own doc\n * comment for why this specific offset is what a rotated parent needs.\n * Defaults to deriving it from `natural` itself (assuming `natural` *is*\n * already the true, unrotated size) — correct whenever the parent has no\n * rotation, wrong whenever it does; real callers with a possibly-rotated\n * parent should always pass the img's real `offsetWidth`/`offsetHeight`\n * explicitly instead of relying on this default.\n */\nexport function trueOriginOffset(natural: ZoomBox): PanOffset {\n return { tx: -natural.width / 2, ty: -natural.height / 2 };\n}\n\n/**\n * DESIGN.md §4.6 — a real bug, found immediately after the pan-drag fix\n * above while testing the analogous double-click-to-zoom case: `natural`'s\n * own `left`/`top` (from `getBoundingClientRect()` on the *rotated* img)\n * is **not** the screen position of the img's local origin `(0, 0)` —\n * rotating a rectangle moves *which of its own corners* ends up at the\n * bounding box's own top-left. For a 90°-rotated landscape photo, the\n * corner that lands at `natural`'s own top-left is the photo's original\n * *bottom*-left, not its top-left — confirmed directly, by hand, against\n * real `getBoundingClientRect()` numbers: treating `natural.left + pan.tx`\n * as \"the origin's screen position\" (what `zoomTowardPoint`/`clampPan`\n * both did) was off by the img's own full width on one axis, which is\n * exactly why double-clicking to zoom toward the pointer, after a\n * rotation, zoomed toward the wrong point instead — sometimes a\n * plausible-looking wrong point, sometimes (as reported) toward an edge\n * of the image instead of the actual click.\n *\n * The one point immune to this ambiguity is the bounding box's own\n * *center* — rotating a rectangle around its own center (the default\n * `transform-origin`, and where `.shoji-slide-media`'s flex-centering\n * already puts the img) never moves that center, on screen or off. Used\n * as a pivot: the img's local origin, relative to its own *true* (layout,\n * pre-rotation) center, is a fixed offset (`originOffset`, `-width/2,\n * -height/2` in the img's own local space) — that offset plus the current\n * `pan`, mapped through the parent's rotation matrix `m` and added back to\n * the pivot's own (rotation-invariant) screen position, gives the origin's\n * *real* current screen position, correct for any axis-aligned rotation\n * RotateFlip can produce. At the default identity `m` and the default\n * `originOffset` (derived from `natural` itself, correct exactly when\n * there's no rotation to begin with), this reduces to plain\n * `natural.left + pan.tx` — the original, pre-fix formula.\n */\nexport function localOriginScreen(\n natural: ZoomBox,\n pan: PanOffset,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): { x: number; y: number } {\n const pivotX = natural.left + natural.width / 2;\n const pivotY = natural.top + natural.height / 2;\n const fromPivot = localDeltaToScreen(originOffset.tx + pan.tx, originOffset.ty + pan.ty, m);\n return { x: pivotX + fromPivot.tx, y: pivotY + fromPivot.ty };\n}\n\n/** One axis of `clampEdgeToContainer` below — see `clampPan`'s own doc comment for the geometry. Keeps the scaled content's edge from retreating inside the container's edge (no empty gap beyond the image); when the content is already smaller than the container on this axis, no position can avoid a gap on *both* sides at once, so centered is the only sensible answer. */\nfunction clampEdge(\n contentPos: number,\n contentSize: number,\n containerPos: number,\n containerSize: number,\n): number {\n if (contentSize <= containerSize) {\n return containerPos + (containerSize - contentSize) / 2;\n }\n const minPos = containerPos + containerSize - contentSize;\n const maxPos = containerPos;\n return Math.min(maxPos, Math.max(minPos, contentPos));\n}\n\n/**\n * The content's own current screen-space bounding box, for `clampPan`\n * below — the four corners of the img's true (unrotated) `width x height`\n * rect (from `originOffset`, negated), scaled and panned in the wrapper's\n * own unrotated frame, then each mapped to screen space individually via\n * `m` before taking the min/max. Four corners, not one edge scaled\n * directly, because `m` can swap which axis grows with which — RotateFlip\n * only ever produces axis-aligned (90°-multiple) rotations, so the result\n * is still a plain axis-aligned box, just not derivable from a single\n * corner the way an unrotated one is.\n */\nfunction contentScreenBounds(\n natural: ZoomBox,\n pan: PanOffset,\n scale: number,\n m: LinearTransform,\n originOffset: PanOffset,\n): { left: number; top: number; right: number; bottom: number } {\n const trueWidth = -originOffset.tx * 2;\n const trueHeight = -originOffset.ty * 2;\n const pivotX = natural.left + natural.width / 2;\n const pivotY = natural.top + natural.height / 2;\n const localCorners = [\n { x: 0, y: 0 },\n { x: trueWidth, y: 0 },\n { x: 0, y: trueHeight },\n { x: trueWidth, y: trueHeight },\n ];\n const screenCorners = localCorners.map(({ x, y }) => {\n const wrapperFrame = {\n x: originOffset.tx + pan.tx + x * scale,\n y: originOffset.ty + pan.ty + y * scale,\n };\n const screen = localDeltaToScreen(wrapperFrame.x, wrapperFrame.y, m);\n return { x: pivotX + screen.tx, y: pivotY + screen.ty };\n });\n const xs = screenCorners.map((p) => p.x);\n const ys = screenCorners.map((p) => p.y);\n return {\n left: Math.min(...xs),\n top: Math.min(...ys),\n right: Math.max(...xs),\n bottom: Math.max(...ys),\n };\n}\n\n/**\n * Keeps the scaled+panned content's edges from retreating inside\n * `container`'s edges (no empty gap beyond the image), on both screen axes\n * independently.\n *\n * `m`/`originOffset` (default identity / derived from `natural`, DESIGN.md\n * §4.6) — same real bug and same root cause as `localOriginScreen`'s own\n * doc comment: the old per-axis formula compared `natural.left + pan.tx`\n * (mixing screen-space and, once rotated, the wrong corner entirely)\n * against the container's screen bounds. The content's actual screen\n * bounding box is computed properly via `contentScreenBounds` (which\n * itself only ever needs `m`/`originOffset` to do that correctly), each\n * edge is clamped against the container the same way as before, and the\n * *difference* — a screen-space delta — is mapped back to local space and\n * folded into `pan`. At the defaults, every step is a no-op and this\n * reduces to exactly the original per-axis formula.\n */\nexport function clampPan(\n natural: ZoomBox,\n container: ZoomBox,\n scale: number,\n pan: PanOffset,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): PanOffset {\n const bounds = contentScreenBounds(natural, pan, scale, m, originOffset);\n const clampedLeft = clampEdge(\n bounds.left,\n bounds.right - bounds.left,\n container.left,\n container.width,\n );\n const clampedTop = clampEdge(\n bounds.top,\n bounds.bottom - bounds.top,\n container.top,\n container.height,\n );\n const screenDelta = { tx: clampedLeft - bounds.left, ty: clampedTop - bounds.top };\n const localDelta = screenDeltaToLocal(screenDelta.tx, screenDelta.ty, m);\n return { tx: pan.tx + localDelta.tx, ty: pan.ty + localDelta.ty };\n}\n\n/**\n * The standard \"zoom toward a point\" formula: adjusts pan so the viewport\n * point `(anchorX, anchorY)` stays visually fixed as scale changes from\n * `oldScale` to `newScale`, given `transform-origin: 0 0` (scaling never\n * moves the img's own local origin on screen, only `pan` does). Callers\n * still need to clamp the result with `clampPan` afterward; this only\n * solves the anchor-fixed part, not boundary containment.\n *\n * `m`/`originOffset` (default identity / derived from `natural`, DESIGN.md\n * §4.6) — a real bug, reported from real usage: double-clicking to zoom\n * toward the pointer, after RotateFlip had rotated the slide, zoomed\n * toward the wrong point — sometimes badly (see `localOriginScreen`'s own\n * doc comment for the root cause and how these two parameters fix it,\n * shared with `clampPan` above). At the defaults, every step is a no-op\n * and this reduces to exactly the original formula.\n */\nexport function zoomTowardPoint(\n natural: ZoomBox,\n pan: PanOffset,\n oldScale: number,\n newScale: number,\n anchorX: number,\n anchorY: number,\n m: LinearTransform = IDENTITY_TRANSFORM,\n originOffset: PanOffset = trueOriginOffset(natural),\n): PanOffset {\n const origin = localOriginScreen(natural, pan, m, originOffset);\n const screenDx = anchorX - origin.x;\n const screenDy = anchorY - origin.y;\n const local = screenDeltaToLocal(screenDx, screenDy, m);\n const factor = 1 - newScale / oldScale;\n return {\n tx: pan.tx + local.tx * factor,\n ty: pan.ty + local.ty * factor,\n };\n}\n","import type { PluginContext, ShojiPlugin } from '../../core/plugin';\nimport { createIconSwap } from '../../core/iconSwap';\nimport { waitForTransitionEnd } from '../../core/zoomTransition';\nimport {\n ZOOM_ACTUAL_SIZE_CONTRACT_ICON,\n ZOOM_ACTUAL_SIZE_EXPAND_ICON,\n ZOOM_IN_ICON,\n ZOOM_OUT_ICON,\n} from './icons';\nimport {\n clampPan,\n clampScale,\n parseLinearTransform,\n screenDeltaToLocal,\n zoomTowardPoint,\n type PanOffset,\n type ZoomBox,\n} from './zoomMath';\nimport './zoom.css';\n\nexport interface ZoomOptions {\n /** Multiplier cap for pinch/wheel/button zoom. \"Actual size\" can exceed this deliberately — it's an explicit action, not continuous gesture zoom. Default 4. */\n maxScale?: number;\n /** Scale a double-tap/double-click jumps to; a second one while already zoomed resets to 1 instead. Default 2. */\n doubleTapScale?: number;\n /** Multiplier applied per zoom-in/zoom-out toolbar button click. Default 1.5. */\n buttonStep?: number;\n}\n\nconst ZOOM_EPSILON = 1.001; // treat \"just barely above 1\" as unzoomed — avoids float residue pinning isZoomed() true forever\n\n/** A click/drag starting on a real control shouldn't engage pan — same exclusion list GestureController's shouldIgnoreGesture uses, duplicated rather than imported since that function isn't part of core's exported surface. */\nfunction isRealControl(event: PointerEvent): boolean {\n return event\n .composedPath()\n .some(\n (node) =>\n node instanceof Element &&\n node.matches(\n 'button, video, input, select, textarea, a[href], [data-shoji-no-drag], .shoji-caption',\n ),\n );\n}\n\n/**\n * DESIGN.md §4-zoom — pinch, double-tap/click, wheel+ctrl, and three toolbar\n * buttons (zoom in/out/actual-size) all drive a single `scale`/pan state on\n * the active slide's `<img>` — never `.shoji-slide-media` itself, which the\n * rotateFlip plugin (§4) already transforms; nesting on the inner element\n * instead of fighting over the same transform string means a rotated *and*\n * zoomed photo behaves correctly for free (the outer rotate carries the\n * inner pan/scale along with it as a rigid unit, which is also the visually\n * expected result — see DESIGN.md's note on this plugin for the full\n * reasoning). Pinch/double-tap/wheel are core's own gesture relay (§2.4) —\n * scaffolding that existed specifically for this plugin to consume, not\n * reimplemented here. Pan (single-pointer drag while zoomed) is the one\n * piece core's relay doesn't cover — core's own drag-to-navigate/\n * drag-to-close would otherwise fight over the same drag — so this plugin\n * registers a zoom gate (`Gallery.registerZoomGate`, §4-zoom) that suspends\n * core's drag handling entirely while zoomed, and tracks pan with its own\n * minimal raw pointer listeners instead of reusing `GestureEngine` (whose\n * axis-locked model — pick horizontal *or* vertical per gesture — is the\n * wrong shape for a 2D pan that needs both at once).\n */\nexport const Zoom: ShojiPlugin = {\n name: 'zoom',\n defaults: {\n maxScale: 4,\n doubleTapScale: 2,\n buttonStep: 1.5,\n } satisfies ZoomOptions,\n\n init(ctx: PluginContext): () => void {\n const { gallery } = ctx;\n const maxScale = Number(ctx.options.maxScale ?? 4);\n const doubleTapScale = Number(ctx.options.doubleTapScale ?? 2);\n const buttonStep = Number(ctx.options.buttonStep ?? 1.5);\n const locale = (gallery.options.locale ?? {}) as Record<string, string>;\n const zoomInLabel = locale.zoomIn ?? 'Zoom in';\n const zoomOutLabel = locale.zoomOut ?? 'Zoom out';\n const actualSizeLabel = locale.zoomActualSize ?? 'Actual size';\n\n let scale = 1;\n let pan: PanOffset = { tx: 0, ty: 0 };\n let natural: ZoomBox | null = null;\n let container: ZoomBox | null = null;\n // The img's own true, unrotated local origin, as an offset from its\n // (rotation-invariant) layout center — see zoomTowardPoint/clampPan's\n // own doc comments (DESIGN.md §4.6) for why natural's left/top/width/\n // height alone aren't a safe stand-in for this once RotateFlip has\n // rotated the parent.\n let originOffset: PanOffset | null = null;\n let pinchStartScale = 1;\n\n function getImg(): HTMLImageElement | null {\n const media = gallery.getActiveMedia();\n const child = media?.firstElementChild;\n return child instanceof HTMLImageElement ? child : null;\n }\n\n function boxOf(el: Element): ZoomBox {\n const rect = el.getBoundingClientRect();\n return { left: rect.left, top: rect.top, width: rect.width, height: rect.height };\n }\n\n /** Only valid to measure while scale===1 (untransformed) — the very first zoom action on a slide; every subsequent action within the same slide reuses the cached box, since measuring an already-scaled element would capture the scaled size, not the natural one. */\n function ensureNatural(img: HTMLImageElement): boolean {\n if (natural && container && originOffset) return true;\n if (scale !== 1) return false; // shouldn't happen — defensive\n natural = boxOf(img);\n container = boxOf(img.parentElement ?? img);\n // offsetWidth/Height, not natural's own width/height above — CSS\n // transform (RotateFlip's rotation on the parent) is paint-only and\n // never affects layout size, unlike getBoundingClientRect(), which\n // reports the *rotated* bounding box (DESIGN.md §4.6). Falls back to\n // natural's own (unrotated-assuming) size when offsetWidth/Height\n // read 0 — real layout engines only report 0 for a genuinely\n // unrendered element, but jsdom (tests/unit/) never computes layout\n // at all and always reports 0, so this also keeps every rotation-\n // unaware unit test's mocked getBoundingClientRect() meaningful.\n originOffset = {\n tx: -(img.offsetWidth || natural.width) / 2,\n ty: -(img.offsetHeight || natural.height) / 2,\n };\n return true;\n }\n\n /**\n * A real bug: `ensureNatural`'s first measurement of a slide is only\n * trustworthy once the lightbox's own open FLIP transition (`zoomIn`,\n * `core/zoomTransition.ts`) has actually settled — that transition\n * applies its own transform directly to `.shoji-slide-media`, the exact\n * element `ensureNatural` measures as `container`. A zoom action firing\n * before it settles (any interaction within `--shoji-duration` of\n * opening — a fast click, or a test that only waits for the dialog to\n * become visible) captured a wildly wrong, mid-animation rect,\n * permanently poisoning that slide's zoom math (every later action\n * reuses the same cached, wrong box). `zoomIn` is fire-and-forget by\n * design (nothing to await when opening) and clears this exact inline\n * style once its own transition ends — the one signal available for\n * \"is it still running.\" Runs `action` immediately once settled, which\n * is right away in the overwhelming common case (any real interaction\n * more than ~300ms after open).\n */\n function whenSettled(action: () => void): void {\n const media = gallery.getActiveMedia();\n if (!media || media.style.transition === '') {\n action();\n return;\n }\n waitForTransitionEnd(media, action);\n }\n\n /**\n * `translate3d`/`scale3d`, not the 2D `translate`/`scale` this used to\n * use — a real bug, reported from real usage: evenly-spaced horizontal\n * lines visible across a zoomed photo, at certain zoom levels, on real\n * GPU hardware (not reproducible in headless/software rendering, so\n * this can't be verified here). The regular spacing matches Chromium's\n * own raster-tile boundaries — a known quirk where scaling large\n * content via a 2D `scale()` transform can show seams between GPU\n * tiles. Forcing the fully 3D compositing path instead (functionally\n * identical — `scale3d(s, s, 1)` and `scale(s)` produce the same\n * on-screen result) is the commonly effective fix, since it takes a\n * different rasterization path than the 2D one.\n */\n function apply(): void {\n const img = getImg();\n if (!img) return;\n img.style.transformOrigin = '0 0';\n img.style.transform =\n scale === 1 && pan.tx === 0 && pan.ty === 0\n ? 'none'\n : `translate3d(${pan.tx}px, ${pan.ty}px, 0) scale3d(${scale}, ${scale}, 1)`;\n img.classList.toggle('shoji-zoomed', scale > 1);\n }\n\n function emitChange(): void {\n ctx.emit('zoomChange', { index: gallery.currentIndex, scale });\n updateActualSizeIcon();\n }\n\n /**\n * The actual-size button's icon reflects live state, requested directly:\n * `arrows-angle-expand` at fit, `arrows-angle-contract` while zoomed in\n * at all — by pinch, wheel, the zoom-in/out buttons, or this button\n * itself, not just specifically at native pixel size. Matches\n * `actualSizeToggle()`'s own real click behavior exactly: it resets to\n * fit for *any* `scale > 1`, regardless of how that zoom was reached,\n * and only attempts to zoom to native size from exactly `scale === 1`\n * (a no-op there for a photo whose native resolution is at or below its\n * fitted size — `clampScale(targetScale, 1, ...)`'s own floor — which\n * this correctly still shows as expand, since scale is still 1 in that\n * case). A real bug in an earlier version of this: tracking a separate\n * \"are we exactly at native size\" cache (naturalWidth / natural.width,\n * refreshed on slideItemLoad) went stale the moment `reset()` cleared\n * it without every call site re-populating it, so only the *first*\n * actual-size press of a session ever updated the icon at all — using\n * `scale` directly instead, already the single live source of truth\n * `zoomChange` itself is built on, has no cache to go stale in the\n * first place.\n */\n function updateActualSizeIcon(): void {\n actualSizeIconSwap.setState(scale > ZOOM_EPSILON);\n }\n\n /** Wraps a transform-setting `run` in a transition, for discrete jumps (buttons, double-tap, actual-size) — never for pinch/pan/wheel, which already track the input 1:1 and would visibly lag behind it under a transition. `afterEnd`, if given, runs once the transition actually completes, not before — `reset()` uses it to clear `transformOrigin` only once it's safe to (see its own comment for why clearing it any earlier is a real bug). The transition itself is always cleared afterward, so it doesn't linger onto the next, possibly-continuous, zoom action. */\n function withTransition(img: HTMLImageElement, run: () => void, afterEnd?: () => void): void {\n img.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n run();\n waitForTransitionEnd(img, () => {\n img.style.transition = '';\n afterEnd?.();\n });\n }\n\n /** Shared by every zoom-in/out entry point (pinch, wheel, buttons, double-tap, actual-size) — anchors on (anchorX, anchorY), clamps scale to [1, ceiling] and pan to the container bounds. `ceiling` defaults to maxScale; actual-size passes its own (possibly larger) target so it isn't capped by the gesture-zoom limit. Deferred via `whenSettled` — see its doc comment — so a zoom action landing right as the lightbox opens doesn't measure mid-animation. `animate` — see `withTransition`. */\n function zoomTo(\n targetScale: number,\n anchorX: number,\n anchorY: number,\n ceiling = maxScale,\n animate = false,\n ): void {\n whenSettled(() => {\n const img = getImg();\n if (!img || !ensureNatural(img)) return;\n const clampedScale = clampScale(targetScale, 1, Math.max(ceiling, 1));\n // DESIGN.md §4.6 — zoomTowardPoint's own doc comment has the full\n // reasoning: the anchor point needs the same screen-vs-local\n // correction as onPointerMove's own pan drag, since RotateFlip may\n // have rotated/flipped `.shoji-slide-media` in the meantime.\n const media = gallery.getActiveMedia();\n const parentTransform = parseLinearTransform(\n media ? getComputedStyle(media).transform : 'none',\n );\n pan = zoomTowardPoint(\n natural!,\n pan,\n scale,\n clampedScale,\n anchorX,\n anchorY,\n parentTransform,\n originOffset!,\n );\n scale = clampedScale;\n // Same correction, same reason — clampAxis compares against the\n // container's screen bounds, so the candidate pan needs to be in\n // screen space too, or a 90/270deg rotation clamps the wrong edge\n // and can undo the anchor-preserving pan just computed above.\n pan = clampPan(natural!, container!, scale, pan, parentTransform, originOffset!);\n if (animate) withTransition(img, apply);\n else apply();\n emitChange();\n });\n }\n\n function reset(animate = false): void {\n // A real gap, found auditing this against its own documented contract\n // (\"emits zoomChange on every scale change, gesture or button-driven\",\n // DESIGN.md §4.6): resetting from an engaged scale back to 1 is a\n // scale change like any other, but every call site here (beforeSlide,\n // afterSlide, beforeClose, afterOpen, and zoomOutStep/toggleZoom\n // reaching neutral) silently skipped emitting it — a host listening\n // for zoomChange to reflect \"is this slide currently zoomed\" would\n // never learn it stopped being true unless something else zoomed in\n // again first. Only when there's an actual change: the overwhelming\n // majority of these calls fire while already at scale 1 (nothing\n // engaged to begin with), and emitting on every no-op reset would be\n // noisy against the \"on every *change*\" contract, not a fix for it.\n const wasEngaged = scale !== 1;\n scale = 1;\n pan = { tx: 0, ty: 0 };\n natural = null;\n container = null;\n originOffset = null;\n updateActualSizeIcon(); // scale is already 1 here, so this is always the expand state\n if (wasEngaged) emitChange(); // after scale is already 1, so listeners see the real new value\n const img = getImg();\n if (!img) return;\n const clearTransform = (): void => {\n img.style.transform = '';\n img.classList.remove('shoji-zoomed');\n };\n if (animate) {\n // transform-origin has to stay put (0 0) for the duration of the\n // transition — clearing it to the browser default (center) in the\n // same tick as starting the transition snaps the scale anchor\n // instantly, which visibly jumped the image before it eased down\n // to neutral. Deferred to `afterEnd`, once the transition is done\n // and transform-origin no longer affects anything visible.\n withTransition(img, clearTransform, () => {\n img.style.transformOrigin = '';\n });\n } else {\n clearTransform();\n img.style.transformOrigin = '';\n }\n }\n\n /** DESIGN.md §2.5/§4.6 — same fix, same reasoning, as RotateFlip's own equivalent (`rotateFlip/index.ts`): `beforeSlide`'s unanimated `reset()` above can't itself animate (it has to finish before `SlideManager.render()` reparents the outgoing image), so the live `transform`/`transformOrigin` about to be wiped are captured here first and handed to `SlideTransition` via `registerSlideLeaveDecorator()` below, to animate away on the leave-ghost's own clone instead of just vanishing. */\n let pendingLeaveTransform: string | null = null;\n let pendingLeaveOrigin = '';\n function captureLeaveTransform(): void {\n const img = getImg();\n const transform = img?.style.transform;\n pendingLeaveTransform = transform && transform !== 'none' ? transform : null;\n pendingLeaveOrigin = img?.style.transformOrigin || '0 0';\n }\n\n /** Each slide gets a freshly-created `<img>` (SlideManager never reuses elements across renders), so the cursor-affordance marker (`zoom.css`) needs reapplying every time the active media changes, not just once. */\n function markEnabled(): void {\n getImg()?.classList.add('shoji-zoom-enabled');\n }\n\n function toggleZoom(x: number, y: number): void {\n if (scale > ZOOM_EPSILON) reset(true);\n else zoomTo(doubleTapScale, x, y, maxScale, true);\n }\n\n // --- pinch (relayed by core, §2.4 — no built-in effect until this plugin exists) ---\n const offPinchStart = ctx.on('pinchStart', () => {\n pinchStartScale = scale;\n });\n const offPinchMove = ctx.on('pinchMove', ({ scale: relative, centerX, centerY }) => {\n zoomTo(pinchStartScale * relative, centerX, centerY);\n });\n const offPinchEnd = ctx.on('pinchEnd', () => {\n if (scale <= ZOOM_EPSILON) reset(); // snap fully back to neutral rather than leaving float residue\n });\n\n // --- double-tap / double-click (relayed by core; Pointer Events unify the two, see GestureEngine) ---\n const offDoubleTap = ctx.on('doubleTap', ({ x, y }) => toggleZoom(x, y));\n\n // --- ctrl+wheel / trackpad pinch (relayed by core) ---\n const offWheelZoom = ctx.on('wheelZoom', ({ deltaScale, x, y }) => {\n zoomTo(scale + deltaScale, x, y);\n });\n\n /**\n * A generic command surface, requested directly (DESIGN.md §4.6), so a\n * *custom* (host-authored) plugin's own button can drive zoom without\n * importing this plugin at all — same \"events over inheritance\"\n * decoupling `pinchStart`/`doubleTap`/`wheelZoom` above already use,\n * just in the opposite direction (a command in, not a gesture relay).\n * `GalleryEvents` (`core/types.ts`) already extends `Record<string,\n * unknown>`, so `ctx.emit('requestZoomIn', {})` from any plugin —\n * official or custom — type-checks with zero core changes; this is\n * just the listening half. Each mirrors its real toolbar button\n * exactly — same functions, same behavior on a video slide (a no-op,\n * `zoomInStep`/`zoomOutStep`/`actualSizeToggle` all bail via `getImg()`\n * returning null there).\n */\n const offRequestZoomIn = ctx.on('requestZoomIn', zoomInStep);\n const offRequestZoomOut = ctx.on('requestZoomOut', zoomOutStep);\n const offRequestZoomActualSize = ctx.on('requestZoomActualSize', actualSizeToggle);\n const offRequestZoomReset = ctx.on('requestZoomReset', () => reset(true));\n\n // --- pan while zoomed — the one gesture core's relay doesn't cover; see the plugin doc comment for why this can't reuse GestureEngine. ---\n let panPointerId: number | null = null;\n let lastX = 0;\n let lastY = 0;\n const outer = ctx.ui.outer();\n\n function onPointerDown(event: PointerEvent): void {\n if (scale <= ZOOM_EPSILON || isRealControl(event)) return;\n const img = getImg();\n // A real bug, reported from real usage: this listens on `outer` (the\n // whole lightbox, not just the image) so a fast pan can be tracked\n // even once the pointer leaves the image's own bounds — but with no\n // check on where the pointerdown itself landed, a click on the plain\n // backdrop (between the image and a nav arrow, say) engaged pan and\n // captured the pointer onto `img` regardless, which — see below —\n // retargets the click and makes it misread as \"on the image,\" not\n // backdrop, silently defeating click-to-close while zoomed.\n if (!img || !event.composedPath().includes(img)) return;\n panPointerId = event.pointerId;\n lastX = event.clientX;\n lastY = event.clientY;\n // Without this, a fast pan whose pointer exits `outer`'s bounds\n // stops receiving pointermove/pointerup entirely (no capture = only\n // elements actually under the cursor get events), leaving\n // panPointerId stuck non-null until the next pointerdown — the\n // gesture just goes dead mid-drag. Captured on the `<img>` itself,\n // not `outer`: capturing retargets the subsequent synthetic `click`\n // to whatever captured it, and `img` — unlike `outer` — already\n // matches isBackdropClick's own exclusion selector (Gallery.ts), so\n // a captured pan's release still can't misread as a backdrop click.\n // GestureEngine's own capture needs a separate suppressRetargetedClick\n // step for exactly this reason; this doesn't, since the retarget\n // lands somewhere already excluded.\n img.setPointerCapture(event.pointerId);\n }\n function onPointerMove(event: PointerEvent): void {\n if (panPointerId !== event.pointerId || !natural || !container || !originOffset) return;\n event.preventDefault();\n const rawDx = event.clientX - lastX;\n const rawDy = event.clientY - lastY;\n lastX = event.clientX;\n lastY = event.clientY;\n // DESIGN.md §4.6 — screenDeltaToLocal's own doc comment has the full\n // reasoning: the raw pointer delta is screen space, but pan.tx/ty are\n // local to the <img>, nested inside whatever transform (e.g.\n // RotateFlip's rotation) `.shoji-slide-media` currently has.\n const media = gallery.getActiveMedia();\n const m = parseLinearTransform(media ? getComputedStyle(media).transform : 'none');\n const { tx: dx, ty: dy } = screenDeltaToLocal(rawDx, rawDy, m);\n pan = clampPan(\n natural,\n container,\n scale,\n { tx: pan.tx + dx, ty: pan.ty + dy },\n m,\n originOffset,\n );\n apply();\n }\n function onPointerUp(event: PointerEvent): void {\n if (panPointerId === event.pointerId) panPointerId = null;\n }\n\n outer.addEventListener('pointerdown', onPointerDown);\n outer.addEventListener('pointermove', onPointerMove, { passive: false });\n outer.addEventListener('pointerup', onPointerUp);\n outer.addEventListener('pointercancel', onPointerUp);\n\n // --- toolbar buttons ---\n function buildButton(icon: string, label: string): HTMLButtonElement {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'shoji-toolbar-button';\n button.innerHTML = icon;\n button.setAttribute('aria-label', label);\n button.title = label;\n return button;\n }\n\n function centerAnchor(): { x: number; y: number } {\n const media = gallery.getActiveMedia();\n const rect = media?.getBoundingClientRect();\n return rect\n ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }\n : { x: 0, y: 0 };\n }\n\n /** Shared by the zoom-in toolbar button and the `w` keyboard shortcut — same fixed `buttonStep` multiplier either way. */\n function zoomInStep(): void {\n const { x, y } = centerAnchor();\n zoomTo(scale * buttonStep, x, y, maxScale, true);\n }\n\n /** Shared by the zoom-out toolbar button and the `s` keyboard shortcut. */\n function zoomOutStep(): void {\n const { x, y } = centerAnchor();\n if (scale / buttonStep <= ZOOM_EPSILON) reset(true);\n else zoomTo(scale / buttonStep, x, y, maxScale, true);\n }\n\n /** Shared by the actual-size toolbar button and `requestZoomActualSize` below. Reads natural.width directly (unlike every other entry point, which just hands zoomTo a target and lets it call ensureNatural itself) — needs its own whenSettled wrap for that reason, not just zoomTo's. */\n function actualSizeToggle(): void {\n whenSettled(() => {\n const img = getImg();\n if (!img || !img.naturalWidth) return;\n if (!ensureNatural(img)) return;\n if (scale > ZOOM_EPSILON) {\n reset(true);\n return;\n }\n const targetScale = img.naturalWidth / natural!.width;\n const { x, y } = centerAnchor();\n zoomTo(targetScale, x, y, targetScale, true); // ceiling = targetScale — bypasses maxScale deliberately\n });\n }\n\n const zoomInBtn = buildButton(ZOOM_IN_ICON, zoomInLabel);\n const zoomOutBtn = buildButton(ZOOM_OUT_ICON, zoomOutLabel);\n\n const actualSizeBtn = document.createElement('button');\n actualSizeBtn.type = 'button';\n actualSizeBtn.className = 'shoji-toolbar-button';\n const actualSizeIconSwap = createIconSwap(\n ZOOM_ACTUAL_SIZE_EXPAND_ICON,\n ZOOM_ACTUAL_SIZE_CONTRACT_ICON,\n );\n actualSizeBtn.appendChild(actualSizeIconSwap.el);\n actualSizeBtn.setAttribute('aria-label', actualSizeLabel);\n actualSizeBtn.title = actualSizeLabel;\n\n zoomInBtn.addEventListener('click', zoomInStep);\n zoomOutBtn.addEventListener('click', zoomOutStep);\n actualSizeBtn.addEventListener('click', actualSizeToggle);\n\n // 'right' — registered in this order, so they cluster left-to-right as\n // zoomIn, zoomOut, actualSize, then whatever later plugin (or the close\n // button) follows (DESIGN.md §3.1).\n const removeButtons = [zoomInBtn, zoomOutBtn, actualSizeBtn].map((button) =>\n ctx.ui.toolbar('right', button),\n );\n\n /** All three zoom buttons are no-ops on a video slide — `getImg()` returns null, so `apply()`/`ensureNatural()` bail out immediately. Hidden rather than left clickable-but-dead. */\n function updateButtonVisibility(): void {\n const isVideo = !!gallery.items[gallery.currentIndex]?.video;\n zoomInBtn.hidden = isVideo;\n zoomOutBtn.hidden = isVideo;\n actualSizeBtn.hidden = isVideo;\n }\n\n // w/s zoom in/out, same step as the toolbar buttons — both cases\n // registered explicitly (registerShortcut matches event.key verbatim,\n // no case-insensitive matching of its own) so Shift/CapsLock still work.\n const removeShortcuts = [\n ctx.ui.registerShortcut('w', zoomInStep),\n ctx.ui.registerShortcut('W', zoomInStep),\n ctx.ui.registerShortcut('s', zoomOutStep),\n ctx.ui.registerShortcut('S', zoomOutStep),\n ];\n\n const offOpen = ctx.on('afterOpen', () => {\n reset();\n markEnabled();\n updateButtonVisibility();\n });\n // Un-animated, and on beforeSlide rather than only afterSlide below:\n // SlideManager.render() (called synchronously between the two) reuses a\n // still-cached slide's node via a plain reparent (moveIn(), no state\n // clearing of its own) into whichever pool slot its new offset needs —\n // there is no code path afterward that can still find *this* image to\n // reset it. A real bug, reported from real usage: zoom in via \"Actual\n // size\", click next — the old, still-scaled image, now reparented into\n // the (unclipped, per shoji.css) neighboring slot, visibly bled into the\n // new slide instead of being invisible off-screen like an unzoomed one\n // always is. Resetting here, while getActiveMedia() still resolves to\n // the about-to-move image, clears it before that reparent ever happens.\n // captureLeaveTransform() (see registerSlideLeaveDecorator below) reads\n // the live transform first, while it's still there to read.\n const offBeforeSlide = ctx.on('beforeSlide', () => {\n captureLeaveTransform();\n reset();\n });\n const offSlide = ctx.on('afterSlide', () => {\n reset();\n markEnabled();\n updateButtonVisibility();\n });\n // Fires synchronously, before Gallery.close() measures the active\n // media's rect to compute the zoom-out-to-thumbnail animation — reset\n // here (not just afterOpen/afterSlide) so that measurement sees the\n // image at its natural position/scale, not wherever it was left\n // zoomed/panned to. Skipping this made closing while zoomed animate\n // from the image's current (zoomed, often partly off-screen) rect\n // instead of its real thumbnail-relative size, landing \"closed\" at a\n // seemingly random spot instead of visibly shrinking into the thumbnail.\n const offBeforeClose = ctx.on('beforeClose', () => reset());\n const unregisterGate = gallery.registerZoomGate(() => scale > ZOOM_EPSILON);\n // Read by Gallery.beginClose() *before* the beforeClose reset above\n // runs, so a button-close continues the zoom-out from wherever the\n // viewer was actually zoomed/panned to, instead of the reset above\n // making it (correctly, for the measurement) but also making the\n // close itself snap back to neutral first. The image's own real\n // rendered rect, not this plugin's raw scale/pan numbers — see\n // zoomTransition.ts's ZoomTransitionTarget.zoomStart for why a direct\n // scale/pan replay doesn't work once it lands on a different element.\n const unregisterZoomStart = gallery.registerZoomStartProvider(() =>\n scale > ZOOM_EPSILON ? (getImg()?.getBoundingClientRect() ?? null) : null,\n );\n const unregisterLeaveDecorator = gallery.registerSlideLeaveDecorator((clonedMedia) => {\n if (!pendingLeaveTransform) return;\n const transform = pendingLeaveTransform;\n const origin = pendingLeaveOrigin;\n pendingLeaveTransform = null;\n const clonedImg = clonedMedia.querySelector<HTMLImageElement>('img');\n if (!clonedImg) return;\n clonedImg.style.transformOrigin = origin;\n clonedImg.style.transform = transform;\n return () => {\n clonedImg.style.transition = 'transform var(--shoji-duration) var(--shoji-easing)';\n clonedImg.style.transform = 'none';\n };\n });\n markEnabled(); // covers the (unusual but possible) case of the gallery already being open when this plugin initializes\n updateButtonVisibility();\n\n return () => {\n for (const remove of removeButtons) remove();\n for (const remove of removeShortcuts) remove();\n offOpen();\n offBeforeSlide();\n offSlide();\n offBeforeClose();\n offPinchStart();\n offPinchMove();\n offPinchEnd();\n offDoubleTap();\n offWheelZoom();\n offRequestZoomIn();\n offRequestZoomOut();\n offRequestZoomActualSize();\n offRequestZoomReset();\n outer.removeEventListener('pointerdown', onPointerDown);\n outer.removeEventListener('pointermove', onPointerMove);\n outer.removeEventListener('pointerup', onPointerUp);\n outer.removeEventListener('pointercancel', onPointerUp);\n unregisterGate();\n unregisterZoomStart();\n unregisterLeaveDecorator();\n reset();\n getImg()?.classList.remove('shoji-zoom-enabled');\n };\n },\n};\n","import { Gallery } from './core';\nimport { ActiveThumbnail } from './plugins/activeThumbnail';\nimport { Autoplay } from './plugins/autoplay';\nimport { Fullscreen } from './plugins/fullscreen';\nimport { Layout } from './plugins/layout';\nimport { RotateFlip } from './plugins/rotateFlip';\nimport { Video } from './plugins/video';\nimport { Zoom } from './plugins/zoom';\nimport { version } from '../package.json';\n\nimport './styles/shoji.css';\n\nexport type {\n GalleryItem,\n GalleryOptions,\n GalleryEvents,\n MediaSource,\n VideoDescriptor,\n Unsubscribe,\n} from './core';\nexport type { ShojiPlugin, PluginContext, VideoProviderRenderer } from './core/plugin';\n\n/**\n * `new Shoji(el, options)` — the UMD global (CLAUDE.md: \"UMD build exposes\n * exactly one global\"). The default export *is* the constructor, not a\n * namespace object, so `<script src=\"shoji.js\">` usage matches the default\n * import used by bundler/ESM consumers. Headless/tree-shaking consumers who\n * want the class as a named import can pull it from the `shoji/core`\n * subpath instead.\n *\n * Official plugins are attached as static properties (`Shoji.Autoplay`) so\n * the single-file build stays \"one global\" (CLAUDE.md) while still shipping\n * every official plugin's code — self-registering, no extra <script> tags —\n * per CLAUDE.md's single-file distribution requirement. A host opts a\n * gallery into one with `new Shoji(el, { plugins: [Shoji.Autoplay] })`.\n * Bundler users who only want to pull in specific plugins' code (tree-shaking\n * this static attachment away) should import from the `shoji/plugins/*`\n * subpath instead of this default export.\n */\nconst Shoji = Object.assign(Gallery, {\n Autoplay,\n Layout,\n ActiveThumbnail,\n Fullscreen,\n RotateFlip,\n Video,\n Zoom,\n /** `package.json`'s own version — the single source of truth, read via a named JSON import so a bundler can tree-shake away everything else in package.json (devDependencies, scripts, ...) rather than embedding the whole file. */\n version,\n});\n\nexport default Shoji;\n"],"names":["lockCount","savedHtmlOverflow","savedHtmlPaddingRight","savedHtmlPaddingLeft","savedScrollX","savedScrollY","styleObserver","intentionalScrollOccurred","LIGHTBOX_SELECTOR","markIntentionalScroll","isRtl","hasScrollableAncestor","node","el","style","touchAllowsScrollThrough","onTouchStart","event","target","onTouchMove","onStyleMutation","html","lockBodyScroll","scrollbarWidth","rtl","currentPaddingLeft","currentPaddingRight","unlockBodyScroll","EventBus","__publicField","fn","set","_a","detail","CLOSE_ICON","PREV_ICON","NEXT_ICON","CAPTION_ICON","CARET_ICON","idCounter","iconButton","className","icon","label","button","buildLightboxDom","slides","labels","labelId","outer","backdrop","dialog","toolbar","toolbarLeft","toolbarCenter","toolbarRight","closeButton","captionToggleButton","toolbarOverflowButton","toolbarOverflowPanel","counter","prevButton","nextButton","caption","captionModal","captionModalPanel","captionModalCloseButton","captionModalContent","FOCUSABLE_SELECTOR","FocusTrap","focusable","first","last","active","activeIsInside","container","DOUBLE_TAP_MAX_DELAY_MS","DOUBLE_TAP_MAX_DISTANCE","TAP_MAX_DELAY_MS","GestureEngine","callbacks","options","_b","a","b","distanceBetween","center","centerOf","_d","_c","state","distance","scale","dx","dy","absX","absY","_f","_e","delta","_h","_g","deltaScale","cancelled","elapsed","totalDelta","velocity","completed","done","cleanup","x","y","now","prefersReducedMotion","parseCssTime","value","containedBox","aspectRatio","naturalSize","containerRatio","width","height","cap","effectiveTargetBox","child","isPlaceholder","rect","containerRect","transformBetween","from","to","translateX","translateY","effectiveOriginBox","origin","img","computeTransform","originRect","targetRect","waitForTransitionEnd","cb","property","durationMs","finish","onEnd","clearInlineTransform","expectedTransform","zoomIn","transform","zoomOut","dragStart","zoomStart","onComplete","existing","jump","appliedTransform","DRAG_SETTLE_TRANSITION","DRAG_FEEDBACK_TRANSITION","VERTICAL_FEEDBACK_DISTANCE","INTERACTIVE_CONTROL_SELECTOR","GESTURE_IGNORE_SELECTOR","isInVideoControlsMargin","video","margin","suppressNextClick","isOverVideoCaption","shouldIgnoreGesture","path","GestureController","host","relay","direction","_velocity","centerX","centerY","goingNext","canMove","targetPx","onSettled","settleEl","progress","pastThreshold","animate","wasHiddenForDrag","frozen","LiveRegion","text","DEFAULT_SELECTOR","scanContainer","selector","elements","scanned","element","item","scanVideo","scanImage","attr","name","numAttr","raw","n","NO_OWN_DATA_FIELD","applyCommon","src","data","key","thumb","alt","srcset","sizes","videoIdAttr","videoEl","sources","s","poster","videoUrl","providerAttr","resolved","resolveExplicitVideo","KNOWN_VIDEO_PROVIDERS","html5Fallback","url","guessVideoType","idAttr","youtube","resolveDetectedProvider","isYouTubeUrl","detectYouTubeId","vimeo","isVimeoUrl","detectVimeoId","provider","isHost","detectId","explicit","id","YOUTUBE_HOSTS","VIMEO_HOSTS","normalizeVideoHost","hostname","parsed","match","DETECTABLE_PROVIDERS","resolveDynamicVideoItems","items","detected","p","clean","ext","SlideManager","count","_","i","offset","root","media","slot","px","transition","centerIndex","onLoad","openPlaceholderSrc","loop","canWrap","targets","rawIndex","index","windowIndices","t","entry","releaseVideoNode","claimedIndices","claimedSlots","owner","freeSlots","releaseVideo","createSpinner","reveal","createOpenPlaceholder","box","placeholder","source","renderFn","showProviderPoster","controller","providerAbortControllers","revealed","onReady","setPoster","spinner","pauseMedia","releaseProviderNode","resolveAxis","config","sign","parts","tx","ty","preset","spec","PRESET_LIST","TRANSITION_PRESETS","waitForEnd","applyEnter","opacity","applyLeave","SlideTransition","decorateLeave","swapContent","ghost","incoming","leave","enter","mode","dirAttr","kickOff","cleanupIncoming","outgoing","clonedMedia","settleLeave","itemKey","resolveElement","instanceRegistry","allInstances","DEFAULT_LOCALE","isBackdropClick","isDangerousHtmlCaption","Gallery","shortcut","selection","isZoomed","decorator","settlers","decorate","settle","dom","clamped","frozenDrag","hidden","declared","validNames","plugin","changed","missing","pluginOptions","ctx","layer","render","isRawElement","unhover","rowHeight","fitsOneRow","slotEl","pinnedCeiling","dialogRight","caretRight","paddingRight","right","columnCount","onEnter","onLeave","marked","markIntentionalScrollInternal","loading","half","noCaption","isVideo","hiddenByToggle","btn","truncated","paddingBottom","budget","elTop","range","lastFittingBottom","nextLineTop","relTop","relBottom","desired","loadedIndex","total","fadeInOnOpen","dataThumb","swap","modeName","builtin","thumbImg","currentIndex","activeItem","activeKey","nextIndex","preserved","atIndex","next","matches","indices","m","keys","ActiveThumbnail","gallery","activeClass","scrollIntoView","highlight","borderColor","highlightDuration","highlightFadeDuration","HIGHLIGHT_CLASS","current","scrollTimer","fadeTimer","cancelPendingScroll","cancelFade","applyClass","performScroll","apply","onClose","pending","teardown","offOpen","offSlide","offClose","offLayoutRender","createIconSwap","iconOff","iconOn","off","on","PLAY_ICON","PAUSE_ICON","findPlayable","isPendingProviderVideo","PROVIDER_PLAY_RETRY_MS","MAX_PROVIDER_PLAY_ATTEMPTS","RESUME_DEBOUNCE_MS","Autoplay","interval","showProgress","autoStart","readMode","onZoom","onRotateFlip","onCaptionExpand","stopOnManualNavigate","locale","playLabel","pauseLabel","playing","timer","currentVideo","awaitingProviderVideo","wasPlayingBeforeDrag","zoomedIn","rotatedOrFlipped","captionOpen","pausedByZoom","pausedByRotateFlip","pausedByCaptionExpand","resumeTimer","cancelPendingResume","clearPauseFlags","isEngaged","maybeScheduleResume","start","isAdvancing","onVideoError","advance","iconSwap","progressBar","clearTimer","resetProgressBar","runProgressBar","ms","updateToggleAvailability","blocked","setButtonState","isPlaying","onVideoEnded","onVideoPause","stop","detachVideo","ensureProviderPlaying","attemptsLeft","playResult","pollWithoutReissuing","reissueOnEachRetry","enterSlide","error","before","reCheckEngagedAfterManualStart","stillZoomed","stillRotated","toggle","offDragThreshold","ZOOM_ENGAGED_THRESHOLD","offZoomChange","offRotateFlipChange","flipH","flipV","rotation","offCaptionModalChange","open","removeButton","removeProgress","removeShortcut","offBeforeSlide","offSlideItemLoad","offRequestStop","offRequestStart","EXPAND_ICON","COMPRESS_ICON","isSupported","currentFullscreenElement","requestFullscreen","exitFullscreen","doc","Fullscreen","enterLabel","exitLabel","isActive","setState","toggleFullscreen","onChange","offRequestToggle","computeColumnCount","containerWidth","gutterX","columns","maxAllowedByMin","minRequiredByMax","computeColumnWidth","layoutMasonry","tiles","startHeights","colWidth","columnHeights","positions","tile","colIndex","indexOfShortest","tileHeight","containerHeight","heights","shortest","layoutMasonryHorizontal","gutterY","currentY","rowStart","rowWidth","rowCount","tileWidth","placeRow","endExclusive","w","countInRow","widthIfIncluded","aspectRatioOf","layoutJustified","minRowHeight","maxRowHeight","lastRow","rows","aspectSum","naturalHeightOf","startIndex","sum","resolveScaledRow","end","rowSum","yieldMinRowHeight","natural","j","DEFAULT_ASPECT","resolveGutter","obj","keyOf","isPureAppend","oldItems","newItems","Layout","type","gutter","orientation","columnWidth","minColumnWidth","maxColumnWidth","fill","autoMeasureEnabled","horizontal","groupByFn","renderHeadingFn","headingOverflow","stickyHeadingsRaw","stickyHeadings","groupingEnabled","baseConfig","breakpointsRaw","sortedBreakpoints","overrides","resolveConfig","maxWidth","headings","previousItems","warnedMissingDims","measuredAspect","computeSections","sections","createHeadingRoot","sectionItems","rendered","structured","titleEl","subtitleEl","headingSegments","heading","measurableSrc","aspectOf","measured","selfCorrecting","createTile","applyGrid","applyMasonry","appendOnly","masonryOptions","segments","headingHeights","segTiles","segResult","pos","masonryTiles","result","applyMasonryHorizontal","applyJustifiedGrouped","justifiedOptions","fullWidths","titleOnlyWidths","tileAspects","tileStart","tileEnd","tryFit","startSection","endSection","k","nextPos","available","computeSegments","segStart","base","best","trial","applyContentDecisions","segment","applyWrapDecisions","parsedLineHeight","lineHeight","maxLines","cumulativeExtra","headingPtr","row","globalStart","globalEnd","bandHeight","segLastCovered","applyJustified","justifiedTiles","relayoutAll","destroyed","measureFrame","scheduleMeasureRelayout","fullRender","autoMeasureTiles","newTiles","emitLayoutRender","section","headingRoot","appendRender","offItemsUpdated","resizeFrame","resizeObserver","normalizeRotateFlip","ROTATE_LEFT_ICON","ROTATE_RIGHT_ICON","FLIP_H_ICON","FLIP_V_ICON","NEUTRAL","transformFor","rotationDeg","fitScale","scaleX","scaleY","fitScaleFor","mediaWidth","mediaHeight","naturalWidth","naturalHeight","scaleAt0","RotateFlip","rotateLeftLabel","rotateRightLabel","flipHLabel","flipVLabel","visualRotation","visualFlipH","visualFlipV","resolveNaturalSize","buildButton","rotateLeftBtn","rotateRightBtn","flipHBtn","flipVBtn","update","patch","visualRotationDelta","rotateDelta","clockwise","rotateLeft","rotateRight","flipHorizontal","flipVertical","reset","pendingLeaveTransform","captureLeaveTransform","removeButtons","offRequestRotateLeft","offRequestRotateRight","offRequestFlipHorizontal","offRequestFlipVertical","unregisterLeaveDecorator","remove","apiPromise","PAUSE_DISPATCH_DELAY_MS","loadVimeoApi","resolve","script","wirePlayableContract","player","playable","mutedState","renderVimeo","signal","oembedTarget","response","mount","Vimeo","pendingPauseTimer","clearPendingPause","loadYouTubeApi","previous","handleStateChange","YT","renderYouTube","videoId","Video","offYouTube","offVimeo","ZOOM_IN_ICON","ZOOM_OUT_ICON","ZOOM_ACTUAL_SIZE_EXPAND_ICON","ZOOM_ACTUAL_SIZE_CONTRACT_ICON","clampScale","min","max","IDENTITY_TRANSFORM","parseLinearTransform","screenDeltaToLocal","det","localDeltaToScreen","trueOriginOffset","localOriginScreen","pan","originOffset","pivotX","pivotY","fromPivot","clampEdge","contentPos","contentSize","containerPos","containerSize","minPos","contentScreenBounds","trueWidth","trueHeight","screenCorners","wrapperFrame","screen","xs","ys","clampPan","bounds","clampedLeft","clampedTop","screenDelta","localDelta","zoomTowardPoint","oldScale","newScale","anchorX","anchorY","screenDx","screenDy","local","factor","ZOOM_EPSILON","isRealControl","maxScale","doubleTapScale","buttonStep","zoomInLabel","zoomOutLabel","actualSizeLabel","pinchStartScale","getImg","boxOf","ensureNatural","whenSettled","action","emitChange","updateActualSizeIcon","actualSizeIconSwap","withTransition","run","afterEnd","zoomTo","targetScale","ceiling","clampedScale","parentTransform","wasEngaged","clearTransform","pendingLeaveOrigin","markEnabled","toggleZoom","offPinchStart","offPinchMove","relative","offPinchEnd","offDoubleTap","offWheelZoom","offRequestZoomIn","zoomInStep","offRequestZoomOut","zoomOutStep","offRequestZoomActualSize","actualSizeToggle","offRequestZoomReset","panPointerId","lastX","lastY","onPointerDown","onPointerMove","rawDx","rawDy","onPointerUp","centerAnchor","zoomInBtn","zoomOutBtn","actualSizeBtn","updateButtonVisibility","removeShortcuts","offBeforeClose","unregisterGate","unregisterZoomStart","clonedImg"],"mappings":"0ZACA,IAAIA,GAAY,EACZC,GAAoB,GACpBC,GAAwB,GACxBC,GAAuB,GACvBC,GAAe,EACfC,GAAe,EACfC,GAAyC,KAczCC,GAA4B,GAEhC,MAAMC,GAAoB,eAGnB,SAASC,IAA8B,CAC5CF,GAA4B,EAC9B,CAEA,SAASG,IAAiB,CACxB,OAAO,iBAAiB,SAAS,eAAe,EAAE,YAAc,KAClE,CAUA,SAASC,GAAsBC,EAA4B,CACzD,IAAIC,EAAKD,aAAgB,QAAUA,GAAQA,GAAA,YAAAA,EAAM,gBAAiB,KAClE,KAAOC,GAAMA,IAAO,SAAS,iBAAiB,CAC5C,MAAMC,EAAQ,iBAAiBD,CAAE,EACjC,IACGC,EAAM,YAAc,QAAUA,EAAM,YAAc,WACnDD,EAAG,aAAeA,EAAG,aAErB,MAAO,GAETA,EAAKA,EAAG,aACV,CACA,MAAO,EACT,CASA,IAAIE,GAA2B,GAE/B,SAASC,GAAaC,EAAyB,CAC7C,MAAMC,EAASD,EAAM,OAErBF,GAA2B,EADJG,aAAkB,SAAWA,EAAO,QAAQV,EAAiB,IAAM,OAC5CG,GAAsBO,CAAqB,CAC3F,CAwBA,SAASC,GAAYF,EAAyB,CAC5C,MAAMC,EAASD,EAAM,OAEjB,EADmBC,aAAkB,SAAWA,EAAO,QAAQV,EAAiB,IAAM,OACnE,CAACO,MAAgC,eAAA,CAC1D,CAcA,SAASK,IAAwB,CAC/B,GAAIpB,KAAc,EAAG,OACrB,MAAM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