@uvalib/web-components 1.5.0 → 1.6.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"uvalib-lightbox.js","names":["unsafeCSS","nothing","_decorate","property","state","n","i","r$1","b","define","__decorate","r","installLightDomStyles","UvalibElement","trackEvent","accessible","toRegion","parseRegions","paramFromLocation","usesHashParam","hrefWithParam","REGION","ROTATION","QUALITY","BROWSER_IMAGE","DATA_IMAGE","parseIiif","url","href","base","parts","file","rotation","region","sizedIiifUrl","parsed","width","w","height","h","iiifIdentifier","viewportIiifSize","dpr","view","usableImageUrl","LIST_SLOT","ENTRY_MARKS","positive","v","normalize","s","structuralRules","host","shadowStructure","nextCaption","regionsLoading","loadRegions","err","UvalibLightbox","_args","link","slides","queued","id","rtl","back","forward","root","sheet","mount","light","dialog","src","changed","node","force","next","forced","same","current","at","found","detailRoots","noteDetails","a","el","candidates","push","owner","unique","pos","img","alt","text","caption","index","list","regions","more","ref","walk","already","hashMode","delta","action","pushed","source","prev","mode","observer","trigger","again","active","slide","position","pool","add","item","f","want","key","keep","still","box","parent","rendered","target","li","lent","name","was","A","full","shown","outlined","counter"],"sources":["../src/components/uvalib-lightbox/media.ts","../src/components/uvalib-lightbox/UvalibLightbox.ts","../src/components/uvalib-lightbox/uvalib-lightbox.ts"],"sourcesContent":["export {\n hrefWithParam,\n paramFromLocation,\n usesHashParam,\n type PageLocation,\n} from '../../base/url-param.js';\n\nconst REGION = /^(full|square|max|pct:[^/]+|\\d+,\\d+,\\d+,\\d+)$/i;\nconst ROTATION = /^!?\\d+(\\.\\d+)?$/;\nconst QUALITY = /^(default|color|gray|grey|bitonal|native)\\.(jpe?g|png|gif|webp|tiff?|jp2)$/i;\n/** Formats a browser can paint. TIFF and JPEG2000 are left unchanged. */\nconst BROWSER_IMAGE = /\\.(jpe?g|png|gif|webp)$/i;\n/** Full size may offer these `data:` images. SVG is never one: it can carry a script. */\nconst DATA_IMAGE = /^image\\/(png|jpeg|gif|webp)($|[;,])/i;\n\nexport interface IiifRequest {\n url: URL;\n /** Path segments, with a leading `''` for an absolute path. */\n parts: string[];\n regionIndex: number;\n sizeIndex: number;\n}\n\n/**\n * A IIIF Image API request, recognised from the end of the path:\n * `/{region}/{size}/{rotation}/{quality}.{format}`. The identifier may contain slashes\n * and colons (`uva-lib:286686`). Anything else, including an image that merely lives\n * under a `/full/` folder, is not one.\n */\nexport function parseIiif(href: string, base: string): IiifRequest | null {\n let url: URL;\n try {\n url = new URL(href, base);\n } catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;\n const parts = url.pathname.split('/');\n if (parts.length < 5) return null;\n const file = parts[parts.length - 1] ?? '';\n const rotation = parts[parts.length - 2] ?? '';\n const region = parts[parts.length - 4] ?? '';\n if (!QUALITY.test(file) || !ROTATION.test(rotation) || !REGION.test(region)) return null;\n return { url, parts, regionIndex: parts.length - 4, sizeIndex: parts.length - 3 };\n}\n\n/**\n * The same image with only the size segment rewritten to `!w,h`, so the server sends a size\n * that fits `w` by `h` device pixels and does not scale the original up. The region stays\n * (a crop or `square` is kept). Returns null when `href` is not IIIF, and for a TIFF or\n * JPEG2000 request, which is left exactly as written.\n */\nexport function sizedIiifUrl(href: string, base: string, w: number, h: number): string | null {\n const parsed = parseIiif(href, base);\n if (!parsed) return null;\n const file = parsed.parts[parsed.parts.length - 1] ?? '';\n if (!BROWSER_IMAGE.test(file)) return null;\n const width = Math.max(1, Math.round(w));\n const height = Math.max(1, Math.round(h));\n parsed.parts[parsed.sizeIndex] = `!${width},${height}`;\n parsed.url.pathname = parsed.parts.join('/');\n return parsed.url.toString();\n}\n\n/** The IIIF identifier (the segment before the region), for a stable deep-link id. */\nexport function iiifIdentifier(href: string, base: string): string | null {\n const parsed = parseIiif(href, base);\n if (!parsed) return null;\n const id = parsed.parts[parsed.regionIndex - 1];\n return id || null;\n}\n\n/** CSS pixels of the viewport, in device pixels, capped so a request stays reasonable. */\nexport function viewportIiifSize(\n view: Pick<Window, 'innerWidth' | 'innerHeight' | 'devicePixelRatio'>,\n): {\n w: number;\n h: number;\n} {\n const dpr = Math.min(view.devicePixelRatio || 1, 2);\n const w = Math.max(1, Math.min(2000, Math.round((view.innerWidth || 800) * dpr)));\n const h = Math.max(1, Math.min(2000, Math.round((view.innerHeight || 600) * dpr)));\n return { w, h };\n}\n\n/**\n * Whether `href` may be offered as Full size: an http(s) URL (including a relative one), or\n * a `data:` image of type PNG, JPEG, GIF or WebP. SVG and every other scheme are refused.\n */\nexport function usableImageUrl(href: string, base: string): boolean {\n try {\n const url = new URL(href, base);\n if (url.protocol === 'http:' || url.protocol === 'https:') return true;\n if (url.protocol === 'data:') return DATA_IMAGE.test(url.pathname);\n return false;\n } catch {\n return false;\n }\n}\n","import { css, html, nothing, unsafeCSS, type PropertyValues } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { trackEvent } from '../../base/analytics.js';\nimport { UvalibElement } from '../../base/UvalibElement.js';\nimport { installLightDomStyles } from '../../base/light-dom-styles.js';\nimport { accessible } from '../../styles/accessible.js';\nimport { parseRegions, toRegion, type ImageRegion } from '../uvalib-image-regions/regions.js';\nimport {\n hrefWithParam,\n iiifIdentifier,\n paramFromLocation,\n sizedIiifUrl,\n usableImageUrl,\n usesHashParam,\n viewportIiifSize,\n type PageLocation,\n} from './media.js';\n\n/** One image in the set, in document order. */\ninterface Slide {\n el: HTMLAnchorElement;\n /** Deep-link id: `data-id`, else the element's id, else the IIIF identifier, else the position. */\n id: string;\n /** The href as written. */\n href: string;\n caption: string;\n alt: string;\n /** `data-details-id`, when the slide has its own details element. */\n detailsId: string | null;\n /** Regions outlined on the image (`data-regions`, or the `regions` callback). */\n regions: ImageRegion[];\n /** The page's own region list (`data-regions-list`, or the `regionsList` callback). */\n list: RegionsListElement | null;\n /** `data-image-width` / `data-image-height`: the size pixel regions are measured in. */\n imageWidth?: number;\n imageHeight?: number;\n}\n\n/** What the `regions` callback is given for each image. */\nexport interface LightboxRegionsItem {\n /** The image link. */\n element: HTMLAnchorElement;\n /** Its deep-link id. */\n id: string;\n /** Its href as written. */\n href: string;\n /** Its place in the set, from 0. */\n index: number;\n}\n\n/** Maps an image to its regions (none: an empty array, null or undefined). */\nexport type LightboxRegions = (\n item: LightboxRegionsItem,\n) => readonly ImageRegion[] | null | undefined;\n\n/** Returns the page's own region list for an image: an `<ol>` or `<ul>` of `<li data-xywh>`. */\nexport type LightboxRegionsList = (item: LightboxRegionsItem) => Element | null | undefined;\n\ntype RegionsListElement = HTMLOListElement | HTMLUListElement;\n\n/** The slot (shadow mode) a page's region list is lent to while its image is open. */\nconst LIST_SLOT = 'uvalib-regions-list';\n\n/** Attributes `<uvalib-image-regions>` puts on a list's entries. */\nconst ENTRY_MARKS = ['data-uvalib-region', 'data-uvalib-active'];\n\nconst positive = (v: string | undefined): number | undefined => {\n const n = Number(v);\n return n > 0 ? n : undefined;\n};\n\nconst normalize = (s: unknown) =>\n String(s ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n\n/**\n * Kept with `no-style`: the triggers stay put, `[hidden]` hides, the dialog hugs its panel\n * (so a click outside it is the backdrop), controls are at least 44px, and the image stays\n * within the viewport. `host` is `:host` (shadow) or the tag (light DOM).\n */\nconst structuralRules = (host: string) => `\n ${host} { display: block; }\n ${host} .viewer { display: contents; }\n ${host} dialog {\n margin: auto;\n padding: 0;\n border: none;\n background: transparent;\n width: min(72rem, calc(100% - 2rem));\n max-height: calc(100% - 2rem);\n }\n ${host} .panel {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n max-height: calc(100dvh - 2rem);\n overflow: auto;\n overscroll-behavior: contain;\n padding: 0.75rem;\n }\n ${host} .head, ${host} .toolbar {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 0.5rem;\n }\n ${host} .head { justify-content: space-between; }\n ${host} .caption { margin: 0; min-width: 0; overflow-wrap: anywhere; }\n ${host} .figure { margin: 0; }\n ${host} dialog img { display: block; max-width: 100%; max-height: 70dvh; width: auto; height: auto; margin: auto; }\n ${host} .count, ${host} .status { margin: 0; }\n ${host} dialog button, ${host} dialog .full {\n box-sizing: border-box;\n min-width: 44px;\n min-height: 44px;\n padding: 0.5rem 0.75rem;\n font: inherit;\n }\n ${host} .regions { display: block; }\n ${host} .details:empty { display: none; }\n ${host} > [slot=\"details\"] { display: none; }\n ${host}[hidden], ${host} [hidden] { display: none !important; }\n`;\nconst shadowStructure = unsafeCSS(structuralRules(':host'));\n\nlet nextCaption = 0;\n\n/** `<uvalib-image-regions>` is loaded the first time an open image has regions. */\nlet regionsLoading: Promise<unknown> | null = null;\nfunction loadRegions(): void {\n if (regionsLoading || customElements.get('uvalib-image-regions')) return;\n regionsLoading = import('../uvalib-image-regions/uvalib-image-regions.js').catch((err) => {\n regionsLoading = null;\n console.warn('uvalib-lightbox: could not load uvalib-image-regions.', err);\n });\n}\n\n/**\n * An accessible image viewer over a set of plain links. With JavaScript a primary click opens\n * a modal dialog; without it (or with a modified click) the link opens the image as before.\n * Wrap the links, or point at them with `selector` (for example `a.pb-image` on a reading\n * page). There is no autoplay and no carousel.\n *\n * The dialog is labelled by the caption (`data-caption`, else the image alt, else the link\n * text). Focus moves to Close on open and back to the trigger on close. Escape and a click on\n * the backdrop close it. With more than one image, Previous and Next and the arrow keys move\n * through the set (wrapping), and a polite “3 of 13” counter is shown. Full size opens the\n * original image in a new tab. A IIIF Image API URL keeps its region; only the size becomes\n * `!W,H` for the viewport. TIFF and JPEG2000 URLs are left as written. `url-param` (for\n * example `photo`) keeps `?photo=<id>` in sync, including on a hash route\n * (`#/text?photo=<id>`): opening pushes a history entry, stepping replaces it, and\n * Back closes.\n *\n * Optional details: children with `slot=\"details\"` (and `data-for` equal to the item's id or\n * its position from 1; without `data-for` they show for every image), or `data-details-id` on\n * a link pointing at an element elsewhere on the page. Either is shown inside the dialog and\n * put back when the viewer moves on or closes.\n *\n * Optional regions (people, objects, inscriptions): `data-regions` on a link, a JSON array of\n * `{ label, x, y, w, h, unit? }` or `xywh` values each followed by its label, separated by\n * `;` (`percent:10,20,30,40 Person 1; percent:55,15,20,30 Sign`), or the `regions` callback.\n * The open image then shows numbered outlines (`<uvalib-image-regions>`, loaded on first use)\n * and a list of the regions beside it, with a \"Show regions\" toggle (`aria-pressed`) that\n * hides the outlines. Pixel regions are measured in `data-image-width` × `data-image-height`\n * when set (the viewer shows a resized IIIF image), else in the image's natural size.\n *\n * Or the page's own list, with its own buttons: `data-regions-list=\"<id>\"` on a link (or the\n * `regionsList` callback) names an `<ol>` or `<ul>` of `<li data-xywh>` anywhere in the page,\n * usually `hidden`. While that image is open the list (the same nodes, so the page's listeners\n * keep working) is the region list: in shadow mode it becomes a child of the lightbox slotted\n * into the viewer, not moved into the shadow root, so the page's CSS still applies to it. When\n * the image changes or the viewer closes it goes back where it was, `hidden` as before. It wins\n * over `data-regions`.\n *\n * @tagname uvalib-lightbox\n * @slot - The image links. A plain click opens the viewer; without JavaScript they open the image.\n * @slot details - Details for the open image. `data-for` selects one item by its id or position (from 1); without it the details show for every image.\n * @csspart dialog - The modal dialog.\n * @csspart panel - The surface inside the dialog.\n * @csspart caption - The caption that names the dialog.\n * @csspart image - The image.\n * @csspart controls - Previous, Next, the counter and Full size.\n * @csspart details - The details panel.\n * @csspart regions - The `<uvalib-image-regions>` around an image with regions.\n * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-lightbox', 'open'|'next'|'previous'|'full-size', 'image N', N]` (N from 1, the image's place in the set). Never the URL or the caption. Not fired for a viewer restored from the URL or from Back and Forward. Bubbles and is composed.\n * @cssprop --uva-color-surface-raised - Dark-mode role token: dialog surface (else `--uva-color-surface`, else #fff).\n * @cssprop --uva-color-surface - Dark-mode role token: the figure behind the image (else #fff).\n * @cssprop --uva-color-text - Dark-mode role token: text (else `--uva-grey-darkest`).\n * @cssprop --uva-color-shadow - Dark-mode role token: the backdrop scrim (else rgba(16, 23, 43, 0.72)).\n * @cssprop --uva-color-border - Dark-mode role token: dialog border (else `--uva-grey-100`).\n * @cssprop --uva-color-focus - Dark-mode role token: focus ring (else `--uva-brand-orange`).\n * @cssprop --uva-color-link - Dark-mode role token: Full size text when it is not the filled control (else `--uva-brand-blue`).\n * @cssprop --uva-color-accent-bg - Dark-mode role token: Close and Full size background (else `--uva-brand-blue`).\n * @cssprop --uva-color-on-accent - Text on those controls (else #fff).\n * @cssprop [--uva-brand-orange=#e57200] - Focus ring when `--uva-color-focus` is unset.\n * @cssprop [--uva-brand-blue=#232d4b] - Control background when `--uva-color-accent-bg` is unset.\n * @cssprop [--uva-grey-darkest=#2b2b2b] - Text when `--uva-color-text` is unset.\n * @cssprop [--uva-grey-100=#dadada] - Border when `--uva-color-border` is unset.\n */\nexport class UvalibLightbox extends UvalibElement {\n static styles = [\n accessible,\n shadowStructure,\n css`\n .panel {\n background: var(--uva-color-surface-raised, var(--uva-color-surface, #fff));\n color: var(--uva-color-text, var(--uva-grey-darkest, #2b2b2b));\n border: 1px solid var(--uva-color-border, var(--uva-grey-100, #dadada));\n }\n dialog::backdrop {\n background: var(--uva-color-shadow, rgba(16, 23, 43, 0.72));\n }\n .details a {\n color: var(--uva-color-link, var(--uva-brand-blue, #232d4b));\n }\n .figure {\n background: var(--uva-color-surface, #fff);\n }\n .caption {\n font-size: 1.125rem;\n line-height: 1.4;\n font-weight: 600;\n }\n .count {\n font-variant-numeric: tabular-nums;\n }\n dialog button,\n dialog .full {\n padding: 0.5rem 0.75rem;\n border: 2px solid transparent;\n text-decoration: none;\n cursor: pointer;\n color: var(--uva-color-on-accent, #fff);\n background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));\n }\n dialog button:focus-visible,\n dialog .full:focus-visible {\n outline: 3px solid var(--uva-color-focus, var(--uva-brand-orange, #e57200));\n outline-offset: 2px;\n }\n dialog button.prev,\n dialog button.next,\n dialog button.regions-toggle {\n color: var(--uva-color-link, var(--uva-brand-blue, #232d4b));\n background: var(--uva-color-surface, #fff);\n border-color: var(--uva-color-border, var(--uva-grey-100, #dadada));\n }\n .status {\n font-size: 1rem;\n }\n /* Pressed shows a check mark, so the state is not shown by colour alone. */\n button.regions-toggle {\n display: inline-flex;\n align-items: center;\n gap: 0.5rem;\n }\n button.regions-toggle::before {\n content: '';\n box-sizing: border-box;\n width: 1rem;\n height: 1rem;\n border: 2px solid currentColor;\n }\n button.regions-toggle[aria-pressed='true']::before {\n border-width: 0 3px 3px 0;\n width: 0.5rem;\n margin-inline: 0.25rem;\n transform: translateY(-0.125rem) rotate(45deg);\n }\n @media (prefers-reduced-motion: no-preference) {\n .panel {\n animation: uvalib-lightbox-in 0.15s ease;\n }\n }\n @media (prefers-reduced-motion: reduce) {\n dialog,\n dialog * {\n animation: none !important;\n transition: none !important;\n scroll-behavior: auto !important;\n }\n }\n @media (forced-colors: active) {\n .panel,\n dialog button,\n dialog .full {\n border: 1px solid CanvasText;\n }\n }\n @keyframes uvalib-lightbox-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n `,\n ];\n\n /**\n * CSS selector for image links elsewhere in this root (the page, or the shadow root the\n * component sits in). Combined with any links inside the component. Example: `a.pb-image`.\n */\n @property({ type: String }) selector = '';\n\n /**\n * Query parameter kept in sync with the open image, for example `photo` → `?photo=<id>`.\n * The id is the link's `data-id`, else its `id`, else the IIIF identifier, else its position\n * from 1. On a hash route the parameter is written inside the hash. Empty: no deep link.\n */\n @property({ attribute: 'url-param' }) urlParam = '';\n\n /**\n * Regions for each image, instead of (or as well as) `data-regions`: called with\n * `{ element, id, href, index }`, it returns region objects (`{ label, x, y, w, h, unit? }`).\n * An image with regions shows their outlines over it, a list of them beside it, and a\n * \"Show regions\" toggle.\n */\n @property({ attribute: false }) regions?: LightboxRegions;\n\n /**\n * The page's own region list for each image, instead of `data-regions-list`: called with\n * `{ element, id, href, index }`, it returns an `<ol>` or `<ul>` of `<li data-xywh>` (or\n * null). While the image is open the list is shown as its region list, with the page's own\n * buttons and listeners; it is put back where it was when the image changes or the viewer\n * closes.\n */\n @property({ attribute: false }) regionsList?: LightboxRegionsList;\n\n /** The heading of the regions list (for example `People`). */\n @property({ attribute: 'regions-label' }) regionsLabel = 'Regions';\n\n @state() private slides: Slide[] = [];\n @state() private index = 0;\n @state() private open = false;\n @state() private status: 'loading' | 'ready' | 'error' = 'loading';\n @state() private fitW = 0;\n @state() private fitH = 0;\n /** The \"Show regions\" toggle: outlines over an image that has regions. */\n @state() private showRegions = true;\n\n private readonly captionId = `uvalib-lightbox-caption-${++nextCaption}`;\n /** Where the dialog is rendered. Light DOM renders here so the author's links stay put. */\n private mount?: HTMLElement;\n private trigger: HTMLAnchorElement | null = null;\n /** The open image pushed a history entry, so Back (and Close) returns to the page. */\n private historyPushed = false;\n /** The visitor closed the viewer; a later mutation must not reopen it from the URL. */\n private userClosed = false;\n /** Disconnect (and the dialog it closes) is not a visitor action, so it must not touch history. */\n private suppressClose = false;\n private warnedSelector = false;\n private lastSrc = '';\n private observer?: MutationObserver;\n private syncQueued = false;\n private regionsChanged = false;\n private resizeTimer = 0;\n /** A close event from the dialog we just shut must not dismiss the next open. */\n private ignoreClose = false;\n private dismissing = false;\n private revealTries = 0;\n private revealFrame = 0;\n private listened = false;\n /** The root `listen` bound, so disconnect can remove the listener after leaving a shadow root. */\n private listenRoot?: Document | ShadowRoot;\n /**\n * `dialog.close()` removes `open` now and fires `close` on a later task. The attribute\n * observer runs as a microtask, which is what a caller sees after `await updateComplete`.\n */\n private dialogObserver?: MutationObserver;\n private observedDialog?: HTMLDialogElement;\n /** `history.back()` from Close has not fired `popstate` yet. */\n private pendingBack = false;\n /** Whether that entry kept the parameter in the hash. The pop leaves a hash that may not say so. */\n private backInHash = false;\n /** An image chosen while that Back is still in flight, opened once the popstate arrives. */\n private queuedOpen: { i: number; slides: Slide[] } | null = null;\n /**\n * Set while a history traversal is opening the dialog. The traversal can close the\n * dialog it just showed; that close is not the visitor, so show it again.\n */\n private reopenGuard = false;\n /** Details elements moved into the dialog, and where they go back to. */\n private parked: { el: HTMLElement; parent: Node; next: ChildNode | null; hidden: boolean }[] = [];\n private parkedKey = '';\n /** The page's region list lent to the viewer, and how to give it back as it was. */\n private lent: {\n el: RegionsListElement;\n parent: Node;\n next: ChildNode | null;\n hidden: boolean;\n slot: string | null;\n } | null = null;\n /** Each entry's own `tabindex` (null: none), so one the viewer added is removed. */\n private entryTabindex = new WeakMap<Element, string | null>();\n private warnedList = false;\n private refocus = false;\n\n /** Shadow mode follows the base class. Light mode renders into `.viewer`. */\n private get isLight(): boolean {\n return this.noShadowDom || this.hasAttribute('no-shadow-dom');\n }\n\n protected override createRenderRoot(): HTMLElement | DocumentFragment {\n if (!this.isLight) {\n const root = super.createRenderRoot();\n if (this.noStyle && root instanceof ShadowRoot) {\n const sheets = [accessible.styleSheet, shadowStructure.styleSheet].filter(\n (sheet): sheet is CSSStyleSheet => sheet != null,\n );\n root.adoptedStyleSheets = sheets;\n }\n return root;\n }\n const mount = this.ownerDocument.createElement('div');\n mount.className = 'viewer';\n this.mount = mount;\n this.append(mount);\n return mount;\n }\n\n override connectedCallback(): void {\n const light = this.isLight;\n super.connectedCallback();\n // A move in the DOM disconnects and reconnects. The disconnect guard must not stick,\n // or Escape would close the dialog and leave the viewer thinking it is still open.\n this.suppressClose = false;\n if (light) this.installLight(light);\n this.listen();\n this.slides = this.collect();\n this.watch();\n this.openFromUrl();\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.unlisten();\n this.observer?.disconnect();\n this.dialogObserver?.disconnect();\n this.dialogObserver = undefined;\n this.observedDialog = undefined;\n window.clearTimeout(this.resizeTimer);\n this.cancelReveal();\n this.restoreDetails();\n this.pendingBack = false;\n this.queuedOpen = null;\n this.reopenGuard = false;\n // Closing the dialog here fires `close` synchronously. That is not the visitor dismissing\n // it: do not run history.back(), which could leave the page. `open` goes false so a later\n // connect can open again from the URL.\n this.suppressClose = true;\n this.open = false;\n const dialog = this.dialogEl;\n if (dialog?.open) dialog.close();\n this.suppressClose = false;\n this.ignoreClose = false;\n }\n\n protected override willUpdate(): void {\n this.lendList();\n if (!this.open) {\n this.lastSrc = '';\n return;\n }\n const src = this.displaySrc;\n if (src !== this.lastSrc) {\n this.lastSrc = src;\n this.status = src ? 'loading' : 'error';\n } else if (!src && this.status !== 'error') {\n // A refused URL (javascript:) has an empty src. On the first open `lastSrc` is already\n // empty, so the change above does not run, and the status would stay \"loading\".\n this.status = 'error';\n }\n }\n\n protected override updated(changed: PropertyValues): void {\n super.updated(changed);\n if (changed.has('selector')) this.watch();\n if ((changed.has('regions') || changed.has('regionsList')) && this.isConnected)\n this.scheduleSync(true);\n if (!this.open) {\n if (changed.has('open')) this.restoreDetails();\n return;\n }\n if (changed.has('open') || changed.has('index') || changed.has('slides')) this.placeDetails();\n if (this.current?.regions.length || this.current?.list) loadRegions();\n this.lendList(true);\n if (this.refocus) {\n this.refocus = false;\n this.closeBtn?.focus();\n }\n this.bindDialogObserver();\n if (changed.has('open')) this.reveal();\n // Reading the image and writing `status` from inside `updated` makes Lit warn and schedule\n // a nested update. A microtask is still before the next paint.\n queueMicrotask(() => {\n if (this.isConnected) this.settleImage();\n });\n }\n\n private installLight(light: boolean): void {\n if (!light) return;\n const node = this.getRootNode();\n const root = node instanceof Document || node instanceof ShadowRoot ? node : undefined;\n if (this.noStyle) {\n installLightDomStyles(\n `${this.localName}::structure`,\n unsafeCSS(structuralRules(this.localName)),\n { root, scope: false },\n );\n installLightDomStyles(`${this.localName}::a11y`, accessible, { root });\n return;\n }\n installLightDomStyles(\n this.localName,\n (this.constructor as typeof UvalibElement).elementStyles,\n {\n root,\n },\n );\n }\n\n private get scope(): Document | ShadowRoot {\n const root = this.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot ? root : this.ownerDocument;\n }\n\n private get base(): string {\n return this.ownerDocument.baseURI || location.href;\n }\n\n private loc(): PageLocation {\n return { pathname: location.pathname, search: location.search, hash: location.hash };\n }\n\n private listen(): void {\n if (this.listened) return;\n this.listened = true;\n this.listenRoot = this.scope;\n this.listenRoot.addEventListener('click', this.onClick, true);\n window.addEventListener('popstate', this.onPop);\n window.addEventListener('resize', this.onResize);\n }\n\n private unlisten(): void {\n if (!this.listened) return;\n this.listened = false;\n this.listenRoot?.removeEventListener('click', this.onClick, true);\n this.listenRoot = undefined;\n window.removeEventListener('popstate', this.onPop);\n window.removeEventListener('resize', this.onResize);\n }\n\n private watch(): void {\n this.observer?.disconnect();\n this.observer = new MutationObserver(() => this.scheduleSync());\n this.observer.observe(this, {\n attributes: true,\n attributeFilter: [\n 'href',\n 'id',\n 'alt',\n 'title',\n 'data-caption',\n 'data-id',\n 'data-details-id',\n 'data-regions',\n 'data-regions-list',\n 'data-image-width',\n 'data-image-height',\n 'slot',\n ],\n childList: true,\n subtree: true,\n });\n if (this.selector) this.observer.observe(this.scope, { childList: true, subtree: true });\n }\n\n /** Ignore mutations inside the viewer (the dialog, parked details) so a render cannot loop. */\n private scheduleSync(force = false): void {\n if (force) this.regionsChanged = true;\n if (this.syncQueued) return;\n this.syncQueued = true;\n queueMicrotask(() => {\n this.syncQueued = false;\n if (!this.isConnected) return;\n const next = this.collect();\n const forced = this.regionsChanged;\n this.regionsChanged = false;\n const same =\n !forced &&\n next.length === this.slides.length &&\n next.every(\n (s, i) =>\n s.el === this.slides[i]?.el &&\n s.href === this.slides[i]?.href &&\n s.id === this.slides[i]?.id &&\n s.caption === this.slides[i]?.caption &&\n s.detailsId === this.slides[i]?.detailsId &&\n s.list === this.slides[i]?.list &&\n JSON.stringify([s.regions, s.imageWidth, s.imageHeight]) ===\n JSON.stringify([\n this.slides[i]?.regions,\n this.slides[i]?.imageWidth,\n this.slides[i]?.imageHeight,\n ]),\n );\n this.noteEntries();\n if (!same) {\n const current = this.current?.el;\n this.slides = next;\n if (this.open) {\n const at = current ? next.findIndex((s) => s.el === current) : -1;\n if (at >= 0) this.index = at;\n else if (!next.length) this.dismiss('empty');\n else this.index = Math.min(this.index, next.length - 1);\n }\n }\n if (!this.open) this.openFromUrl();\n });\n }\n\n private collect(): Slide[] {\n const found: HTMLAnchorElement[] = [];\n const detailRoots = new Set<Element>();\n const noteDetails = (a: Element) => {\n if (!(a instanceof HTMLAnchorElement)) return;\n const id = a.getAttribute('data-details-id');\n if (!id) return;\n const el = this.scope.getElementById(id);\n if (el) detailRoots.add(el);\n };\n const candidates: Element[] = [...this.querySelectorAll('a[href]')];\n if (this.selector) {\n try {\n candidates.push(...this.scope.querySelectorAll(this.selector));\n } catch {\n if (!this.warnedSelector) {\n this.warnedSelector = true;\n console.warn(\n `${this.localName}: selector ${JSON.stringify(this.selector)} is not a valid CSS selector.`,\n );\n }\n }\n }\n for (const a of candidates) noteDetails(a);\n const push = (a: Element) => {\n if (!(a instanceof HTMLAnchorElement) || !a.hasAttribute('href')) return;\n if (a.closest('[hidden]')) return;\n if (this.mount?.contains(a) || a.closest('dialog')) return;\n if (a.closest('[slot=\"details\"]')) return;\n // Links in a page's region list are its actions, not images (and it may be lent here).\n if (this.lent?.el.contains(a)) return;\n for (const root of detailRoots) {\n if (root.contains(a)) return;\n }\n const owner = a.closest('uvalib-lightbox');\n if (owner && owner !== this) return;\n found.push(a);\n };\n for (const a of candidates) push(a);\n const unique = [...new Set(found)];\n unique.sort((a, b) => {\n if (a === b) return 0;\n const pos = a.compareDocumentPosition(b);\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n if (pos & Node.DOCUMENT_POSITION_PRECEDING) return 1;\n return 0;\n });\n return unique.map((el, i) => this.slide(el, i));\n }\n\n private slide(el: HTMLAnchorElement, index: number): Slide {\n const href = el.getAttribute('href') ?? '';\n const img = el.querySelector('img');\n const alt = normalize(img?.getAttribute('data-uvalib-alt') || img?.getAttribute('alt'));\n const text = this.linkText(el);\n const caption =\n normalize(el.dataset.caption) ||\n alt ||\n text ||\n normalize(el.getAttribute('title')) ||\n 'Image';\n const id =\n normalize(el.dataset.id) || el.id || iiifIdentifier(href, this.base) || String(index + 1);\n const list = this.listOf(el, id, href, index);\n const regions = this.regionsOf(el, id, href, index);\n if (list && regions.length && !this.warnedList) {\n this.warnedList = true;\n console.warn(\n `${this.localName}: an image has both regions and a regions list; the list is used.`,\n );\n }\n return {\n el,\n id,\n href,\n caption,\n alt: alt || caption,\n detailsId: normalize(el.dataset.detailsId) || null,\n regions: list ? [] : regions,\n list,\n imageWidth: positive(el.dataset.imageWidth),\n imageHeight: positive(el.dataset.imageHeight),\n };\n }\n\n /** `data-regions`, then whatever the `regions` callback adds. */\n private regionsOf(el: HTMLAnchorElement, id: string, href: string, index: number) {\n const found = parseRegions(el.dataset.regions);\n if (typeof this.regions === 'function') {\n let more: unknown;\n try {\n more = this.regions({ element: el, id, href, index });\n } catch (err) {\n console.warn(`${this.localName}: the regions callback threw.`, err);\n }\n if (Array.isArray(more))\n for (const r of more) {\n const region = toRegion(r);\n if (region) found.push(region);\n }\n }\n return found;\n }\n\n /** `data-regions-list` (an id in this root), else the `regionsList` callback's element. */\n private listOf(\n el: HTMLAnchorElement,\n id: string,\n href: string,\n index: number,\n ): RegionsListElement | null {\n let found: unknown = null;\n const ref = normalize(el.dataset.regionsList);\n if (ref) found = this.scope.getElementById(ref);\n else if (typeof this.regionsList === 'function') {\n try {\n found = this.regionsList({ element: el, id, href, index });\n } catch (err) {\n console.warn(`${this.localName}: the regionsList callback threw.`, err);\n }\n }\n if (!(found instanceof HTMLOListElement || found instanceof HTMLUListElement)) return null;\n // Not one that holds the viewer or the image link itself.\n return found.contains(this) || found.contains(el) ? null : found;\n }\n\n /** The link's own text, not the alt of its image and not a details subtree. */\n private linkText(el: HTMLAnchorElement): string {\n const parts: string[] = [];\n const walk = (n: Node) => {\n if (n instanceof HTMLImageElement) return;\n if (\n n instanceof HTMLElement &&\n (n.hidden ||\n n.getAttribute('slot') === 'details' ||\n n.getAttribute('slot') === 'badge' ||\n n.classList.contains('badge') ||\n n.classList.contains('visually-hidden') ||\n n.hasAttribute('data-uvalib-generated-badge') ||\n n.hasAttribute('data-uvalib-badge-sep'))\n )\n return;\n if (n.nodeType === Node.TEXT_NODE) {\n parts.push(n.textContent ?? '');\n return;\n }\n n.childNodes.forEach(walk);\n };\n el.childNodes.forEach(walk);\n return normalize(parts.join(' '));\n }\n\n private get current(): Slide | undefined {\n return this.slides[this.index];\n }\n\n private get multiple(): boolean {\n return this.slides.length > 1;\n }\n\n /** The URL the `<img>` should load: a viewport-sized IIIF request, or the href itself. */\n private get displaySrc(): string {\n const href = this.current?.href ?? '';\n if (!usableImageUrl(href, this.base)) return '';\n const w = this.fitW || viewportIiifSize(window).w;\n const h = this.fitH || viewportIiifSize(window).h;\n return sizedIiifUrl(href, this.base, w, h) ?? href;\n }\n\n private measure(): void {\n const { w, h } = viewportIiifSize(window);\n if (w !== this.fitW) this.fitW = w;\n if (h !== this.fitH) this.fitH = h;\n }\n\n private readonly onResize = (): void => {\n if (!this.open) return;\n window.clearTimeout(this.resizeTimer);\n this.resizeTimer = window.setTimeout(() => {\n if (this.isConnected && this.open) this.measure();\n }, 150);\n };\n\n private readonly onClick = (e: Event): void => {\n if (\n !(e instanceof MouseEvent) ||\n e.button !== 0 ||\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey\n )\n return;\n const link = this.linkFrom(e);\n if (!link) return;\n const slides = this.collect();\n const i = slides.findIndex((s) => s.el === link);\n if (i < 0) return;\n e.preventDefault();\n this.activate(i, slides);\n };\n\n private linkFrom(e: Event): HTMLAnchorElement | null {\n for (const n of e.composedPath()) {\n if (n instanceof HTMLAnchorElement) return n;\n }\n const t = e.target;\n return t instanceof Element ? t.closest('a[href]') : null;\n }\n\n /** A visitor chose `slides[i]`. The first open pushes a history entry; a later choice replaces it. */\n private activate(i: number, slides: Slide[]): void {\n const already = this.open;\n if (already && this.index === i) return;\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.userClosed = false;\n this.measure();\n this.open = true;\n if (this.pendingBack) {\n // Close already asked for history.back(). Writing now would push on the entry that\n // popstate is about to remove, and that pop would shut the viewer again.\n this.queuedOpen = { i, slides };\n } else if (this.urlParam) {\n const id = slides[i]?.id ?? null;\n const hashMode = usesHashParam(location.hash);\n if (already) this.writeParam(id, 'replace', hashMode);\n else {\n // The address can already carry this param (a leftover entry). Replace it away\n // on the current entry, then push, so Back still closes onto this page. Both\n // writes share hashMode: stripping `?photo` from `#chapter?photo=1` leaves\n // `#chapter`, which would otherwise fall out of the hash.\n if (paramFromLocation(this.loc(), this.urlParam))\n this.writeParam(null, 'replace', hashMode);\n this.historyPushed = this.writeParam(id, 'push', hashMode);\n }\n }\n trackEvent(this, ['uvalib-lightbox', 'open', `image ${i + 1}`, i + 1]);\n }\n\n /** Restore a viewer the URL already points at. No analytics: it is not a new action. */\n private openFromUrl(): void {\n if (this.open || this.userClosed || !this.urlParam) return;\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) return;\n const slides = this.slides.length ? this.slides : this.collect();\n const i = slides.findIndex((s) => s.id === id);\n if (i < 0) return;\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.measure();\n // Make Back close the viewer onto this page instead of leaving it. Remember the hash\n // route before the first write removes the `?` that marked it.\n const hashMode = usesHashParam(location.hash);\n this.writeParam(null, 'replace', hashMode);\n this.historyPushed = this.writeParam(id, 'push', hashMode);\n this.open = true;\n }\n\n private step(delta: number): void {\n const n = this.slides.length;\n if (n < 2) return;\n const i = (this.index + delta + n) % n;\n this.index = i;\n this.trigger = this.slides[i]?.el ?? this.trigger;\n if (this.urlParam) this.writeParam(this.slides[i]?.id ?? null, 'replace');\n const action = delta < 0 ? 'previous' : 'next';\n trackEvent(this, ['uvalib-lightbox', action, `image ${i + 1}`, i + 1]);\n }\n\n /**\n * Close. `ui` is Close, Escape or the backdrop (Back when this viewer pushed, else drop the\n * param). `pop` is the browser already moving: the URL is already right. `empty` is the\n * last image leaving the page: drop the param and do not reopen from it.\n */\n private dismiss(source: 'ui' | 'pop' | 'empty'): void {\n if (this.dismissing) return;\n const dialog = this.dialogEl;\n if (!this.open && !dialog?.open) return;\n this.dismissing = true;\n try {\n const pushed = this.historyPushed;\n this.historyPushed = false;\n this.ignoreClose = true;\n this.cancelReveal();\n this.open = false;\n if (source === 'ui' || source === 'empty') this.userClosed = true;\n this.restoreDetails();\n if (dialog?.open) dialog.close();\n this.focusTrigger();\n if (source === 'ui' && this.urlParam) {\n if (pushed) {\n this.backInHash = usesHashParam(location.hash);\n this.pendingBack = true;\n history.back();\n } else this.writeParam(null, 'replace', usesHashParam(location.hash));\n } else if (source === 'empty' && this.urlParam) {\n this.pendingBack = false;\n this.queuedOpen = null;\n this.writeParam(null, 'replace', usesHashParam(location.hash));\n }\n } finally {\n // Leave `ignoreClose` set. `dialog.close()` can queue a second close event for the\n // next task; clearing the guard here lets that event dismiss a viewer that has\n // already been opened again. `reveal` clears it once `showModal` has succeeded, which\n // is still before a later Escape. A throw while restoring details must not leave the\n // viewer stuck dismissing.\n this.dismissing = false;\n }\n }\n\n /** Returns false when this document cannot change the address (for example an iframe srcdoc). */\n private writeParam(id: string | null, mode: 'push' | 'replace', hashMode?: boolean): boolean {\n if (!this.urlParam) return false;\n const next = hrefWithParam(this.loc(), this.urlParam, id, hashMode);\n const now = location.pathname + location.search + location.hash;\n if (next === now) return false;\n const prev = history.state && typeof history.state === 'object' ? history.state : {};\n try {\n history[mode === 'push' ? 'pushState' : 'replaceState'](\n { ...prev, uvalibLightbox: this.urlParam },\n '',\n next,\n );\n return true;\n } catch {\n // A sandboxed document (an iframe srcdoc) cannot take a history entry. The viewer\n // still opens; the address is left as it is.\n return false;\n }\n }\n\n private readonly onPop = (): void => {\n if (!this.urlParam) return;\n if (this.pendingBack) {\n this.pendingBack = false;\n const queued = this.queuedOpen;\n this.queuedOpen = null;\n if (!this.isConnected || !queued) return;\n this.slides = queued.slides;\n this.index = queued.i;\n this.trigger = queued.slides[queued.i]?.el ?? null;\n this.userClosed = false;\n this.measure();\n const id = queued.slides[queued.i]?.id ?? null;\n this.historyPushed = this.writeParam(id, 'push', this.backInHash);\n if (!this.open) this.open = true;\n return;\n }\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) {\n this.historyPushed = false;\n if (this.open) this.dismiss('pop');\n return;\n }\n this.userClosed = false;\n const slides = this.collect();\n const i = slides.findIndex((s) => s.id === id);\n if (i < 0) {\n if (this.open) this.dismiss('pop');\n return;\n }\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.historyPushed = true;\n this.measure();\n this.armReopenGuard();\n if (!this.open) this.open = true;\n };\n\n /** Ignore the close event a history traversal fires on the dialog it just opened. */\n private armReopenGuard(): void {\n this.reopenGuard = true;\n const view = this.ownerDocument.defaultView;\n if (!view) return;\n view.requestAnimationFrame(() => {\n this.reopenGuard = false;\n });\n }\n\n private readonly onKey = (e: KeyboardEvent): void => {\n if (!this.multiple || this.typing(e)) return;\n // Left is previous in LTR and next in RTL, so the key matches the direction of the set.\n const rtl = getComputedStyle(this).direction === 'rtl';\n const back = rtl ? 'ArrowRight' : 'ArrowLeft';\n const forward = rtl ? 'ArrowLeft' : 'ArrowRight';\n if (e.key !== back && e.key !== forward) return;\n if (e.altKey || e.metaKey || e.ctrlKey) return;\n e.preventDefault();\n this.step(e.key === forward ? 1 : -1);\n };\n\n private typing(e: KeyboardEvent): boolean {\n const t = e.target;\n if (!(t instanceof HTMLElement)) return false;\n return t.isContentEditable || !!t.closest('input, textarea, select');\n }\n\n private readonly onDialogClick = (e: MouseEvent): void => {\n if (e.target === this.dialogEl) this.dismiss('ui');\n };\n\n /** The dialog element is stable across renders. Watch `open` on whichever node is current. */\n private bindDialogObserver(): void {\n const dialog = this.dialogEl;\n if (!dialog || dialog === this.observedDialog) return;\n this.dialogObserver?.disconnect();\n this.observedDialog = dialog;\n const observer = new MutationObserver(() => this.onNativeClose());\n observer.observe(dialog, { attributes: true, attributeFilter: ['open'] });\n this.dialogObserver = observer;\n }\n\n private readonly onDialogClose = (): void => {\n this.onNativeClose();\n };\n\n /**\n * Escape, the backdrop's close, and a direct `dialog.close()` all clear `open`. The\n * event itself is a later task; the attribute change is observable on the microtask\n * that `await updateComplete` flushes. A close that leaves the dialog open (a queued\n * event after `showModal`, or a history traversal) is not the visitor dismissing it.\n */\n private onNativeClose(): void {\n if (this.ignoreClose || this.suppressClose || !this.open) return;\n if (this.dialogEl?.open) return;\n if (this.reopenGuard) {\n const view = this.ownerDocument.defaultView;\n view?.queueMicrotask(() => {\n if (this.open && this.isConnected && !this.dialogEl?.open) this.reveal();\n });\n return;\n }\n this.dismiss('ui');\n }\n\n private readonly onFullSize = (): void => {\n const i = this.index;\n trackEvent(this, ['uvalib-lightbox', 'full-size', `image ${i + 1}`, i + 1]);\n };\n\n private get dialogEl(): HTMLDialogElement | null {\n return this.renderRoot.querySelector('dialog');\n }\n\n private get closeBtn(): HTMLButtonElement | null {\n return this.renderRoot.querySelector('button.close');\n }\n\n private get detailsBox(): HTMLElement | null {\n return this.renderRoot.querySelector('.details');\n }\n\n private focusTrigger(): void {\n const trigger = this.trigger;\n if (trigger?.isConnected) trigger.focus();\n }\n\n /**\n * Open the dialog and focus Close. `showModal` can throw while a dialog is still leaving\n * the top layer (a reopen from Back/Forward, or the first paint), so try again on the next\n * frames. Those frames are queued before a test's own `nextFrame`.\n */\n /** History restore can drop the light-DOM mount or orphan a shadow root. Put it back. */\n private ensureRoot(): void {\n const root = this.renderRoot;\n if (!this.isConnected) return;\n if (root instanceof HTMLElement && !root.isConnected) this.append(root);\n if (root instanceof ShadowRoot && this.shadowRoot && root !== this.shadowRoot) {\n (this as unknown as { renderRoot: ShadowRoot }).renderRoot = this.shadowRoot;\n this.requestUpdate();\n }\n }\n\n private cancelReveal(): void {\n const view = this.ownerDocument.defaultView;\n if (this.revealFrame && view) view.cancelAnimationFrame(this.revealFrame);\n this.revealFrame = 0;\n }\n\n private reveal(): void {\n this.ensureRoot();\n const dialog = this.dialogEl;\n if (!this.open || !dialog) return;\n const again = () => {\n if (this.revealTries++ > 8) {\n this.ignoreClose = false;\n return;\n }\n const view = this.ownerDocument.defaultView;\n if (!view) return;\n this.revealFrame = view.requestAnimationFrame(() => {\n this.revealFrame = 0;\n if (this.open) this.reveal();\n });\n };\n if (!dialog.isConnected) {\n again();\n return;\n }\n if (!dialog.open) {\n try {\n dialog.showModal();\n } catch {\n again();\n return;\n }\n }\n this.revealTries = 0;\n this.cancelReveal();\n // A close event already queued by the dialog we shut must not dismiss this open.\n // Clearing the guard here is synchronous, so Escape after this update still closes.\n this.ignoreClose = false;\n // A later reveal (a retry, or the history traversal showing the dialog again) must\n // not pull focus back to Close after the visitor has moved it inside the dialog.\n const active = this.shadowRoot?.activeElement ?? this.ownerDocument.activeElement;\n if (!active || !dialog.contains(active)) this.closeBtn?.focus();\n }\n\n /** A cached image may already be complete before the load listener runs. */\n private settleImage(): void {\n const img = this.renderRoot.querySelector('img');\n if (!img || this.status !== 'loading') return;\n if (img.complete && img.naturalWidth > 0) this.status = 'ready';\n else if (img.complete && img.getAttribute('src') && img.naturalWidth === 0)\n this.status = 'error';\n }\n\n private readonly onLoad = (): void => {\n if (this.status === 'loading') this.status = 'ready';\n };\n\n private readonly onError = (): void => {\n this.status = 'error';\n };\n\n /** Stable identity for a details element, so parking it does not look like a new one. */\n private detailTokens = new WeakMap<HTMLElement, number>();\n private detailTokenSeq = 0;\n private detailToken(el: HTMLElement): string {\n let n = this.detailTokens.get(el);\n if (n === undefined) this.detailTokens.set(el, (n = ++this.detailTokenSeq));\n return String(n);\n }\n\n /**\n * Details for the open image: `slot=\"details\"` children (honouring `data-for`) and the\n * element named by `data-details-id`. Elements already parked in the dialog stay in the\n * set, so this does not move them again.\n */\n private matchingDetails(): HTMLElement[] {\n const slide = this.current;\n const id = slide?.id ?? '';\n const position = String(this.index + 1);\n const pool: HTMLElement[] = [];\n const add = (el: HTMLElement | null) => {\n if (el && el !== this && !pool.includes(el)) pool.push(el);\n };\n for (const el of this.querySelectorAll(':scope > [slot=\"details\"]')) {\n if (el instanceof HTMLElement) add(el);\n }\n for (const item of this.parked) add(item.el);\n if (slide?.detailsId) add(this.scope.getElementById(slide.detailsId));\n return pool.filter((el) => {\n if (el.getAttribute('slot') === 'details') {\n const f = el.getAttribute('data-for');\n return !f || f === id || f === position;\n }\n return !!slide?.detailsId && el.id === slide.detailsId;\n });\n }\n\n private placeDetails(): void {\n const want = this.matchingDetails();\n const key = `${want.map((el) => this.detailToken(el)).join('|')}@${this.index}`;\n if (key === this.parkedKey) return;\n const keep = new Set(want);\n const still: typeof this.parked = [];\n for (const item of this.parked) {\n if (keep.has(item.el) && this.detailsBox?.contains(item.el)) still.push(item);\n else this.putBack(item);\n }\n this.parked = still;\n const box = this.detailsBox;\n if (box) {\n for (const el of want) {\n if (box.contains(el)) continue;\n const parent = el.parentNode;\n if (!parent) continue;\n this.parked.push({ el, parent, next: el.nextSibling, hidden: el.hidden });\n el.hidden = false;\n box.append(el);\n }\n }\n this.parkedKey = key;\n }\n\n /**\n * Put a parked element back. Restoring later siblings first keeps `next` inside `parent`;\n * if it is not (it was parked too), insert at the end instead of throwing NotFoundError.\n */\n private putBack(item: (typeof this.parked)[number]): void {\n item.el.hidden = item.hidden;\n const next = item.next?.parentNode === item.parent ? item.next : null;\n item.parent.insertBefore(item.el, next);\n }\n\n private restoreDetails(): void {\n for (let i = this.parked.length - 1; i >= 0; i--) this.putBack(this.parked[i]!);\n this.parked = [];\n this.parkedKey = '';\n this.returnList();\n }\n\n /** The list the open image shows (none while its image cannot be drawn). */\n private get wantedList(): RegionsListElement | null {\n if (!this.open) return null;\n const list = this.current?.list ?? null;\n return list && this.displaySrc ? list : null;\n }\n\n /**\n * Lend the open image's list to the viewer, giving back any other. Shadow mode (before\n * render): the list becomes a light-DOM child of the lightbox with `slot`, and the viewer's\n * `<uvalib-image-regions>` slots it on, so it stays in the page (its styles and listeners\n * apply). Light DOM (`rendered`, after render): it is moved into `<uvalib-image-regions>`.\n */\n private lendList(rendered = false): void {\n const want = this.wantedList;\n if (this.lent && this.lent.el !== want) this.returnList();\n if (!want) return;\n if (this.isLight && !rendered) return;\n const target: Element | null = this.isLight\n ? this.renderRoot.querySelector('uvalib-image-regions')\n : this;\n if (!target || want.parentNode === target) return;\n if (!this.lent) {\n const parent = want.parentNode;\n if (!parent) return;\n this.lent = {\n el: want,\n parent,\n next: want.nextSibling,\n hidden: want.hidden,\n slot: want.getAttribute('slot'),\n };\n }\n this.noteEntries();\n if (this.isLight) want.removeAttribute('slot');\n else want.setAttribute('slot', LIST_SLOT);\n want.hidden = false;\n target.append(want);\n }\n\n /** Remember each entry's own tabindex before the viewer can add one. */\n private noteEntries(): void {\n const list = this.lent?.el;\n if (!list) return;\n for (const li of list.children) {\n if (!this.entryTabindex.has(li)) this.entryTabindex.set(li, li.getAttribute('tabindex'));\n }\n }\n\n /** Give the lent list back: same place, same `hidden` and `slot`, no marks of the viewer's. */\n private returnList(): void {\n const lent = this.lent;\n if (!lent) return;\n this.lent = null;\n const { el } = lent;\n const active = this.shadowRoot?.activeElement ?? this.ownerDocument.activeElement;\n // Focus in the list would be lost with it; Close takes it while the viewer stays open.\n if (this.open && active && el.contains(active)) this.refocus = true;\n for (const li of el.children) {\n for (const name of ENTRY_MARKS) li.removeAttribute(name);\n if (this.entryTabindex.has(li)) {\n const was = this.entryTabindex.get(li);\n if (was == null) li.removeAttribute('tabindex');\n else li.setAttribute('tabindex', was);\n }\n }\n this.entryTabindex = new WeakMap();\n if (lent.slot == null) el.removeAttribute('slot');\n else el.setAttribute('slot', lent.slot);\n el.hidden = lent.hidden;\n const next = lent.next?.parentNode === lent.parent ? lent.next : null;\n lent.parent.insertBefore(el, next);\n }\n\n private get statusText(): string {\n if (!this.open) return '';\n if (this.status === 'loading') return 'Loading image.';\n if (this.status === 'error') return 'This image could not be loaded.';\n return '';\n }\n\n private readonly toggleRegions = (): void => {\n this.showRegions = !this.showRegions;\n };\n\n /** The image, inside `<uvalib-image-regions>` when it has regions (or the page's list). */\n private renderImage(slide: Slide, src: string, regions: ImageRegion[] | null) {\n const img = html`<img\n part=\"image\"\n slot=${regions || slide.list ? 'image' : nothing}\n alt=${slide.alt}\n src=${src}\n aria-busy=${this.status === 'loading' ? 'true' : 'false'}\n @load=${this.onLoad}\n @error=${this.onError}\n />`;\n if (!regions && !slide.list) return img;\n // The page's list: slotted on from the lightbox's light DOM (shadow mode), or moved in\n // after render (light DOM).\n const list = slide.list && !this.isLight ? html`<slot name=${LIST_SLOT}></slot>` : nothing;\n return html`<uvalib-image-regions\n class=\"regions\"\n part=\"regions\"\n .items=${slide.list ? null : regions}\n label=${normalize(this.regionsLabel) || 'Regions'}\n image-width=${slide.imageWidth ?? nothing}\n image-height=${slide.imageHeight ?? nothing}\n ?hide-outlines=${!this.showRegions}\n ?no-style=${this.noStyle}\n >${img}${list}</uvalib-image-regions\n >`;\n }\n\n protected override render() {\n const slide = this.open ? this.current : undefined;\n const src = slide ? this.displaySrc : '';\n const full = slide && usableImageUrl(slide.href, this.base) ? slide.href : '';\n const shown = this.statusText;\n const regions = slide?.regions.length ? slide.regions : null;\n const outlined = !!(regions || slide?.list);\n const counter = this.multiple\n ? html`<p class=\"count\" aria-live=\"polite\">${this.index + 1} of ${this.slides.length}</p>`\n : nothing;\n // Shadow mode needs a slot or the author's links are not rendered and cannot take focus.\n // Light mode renders into `.viewer`; a `<slot>` there would not show the siblings.\n return html`\n ${this.isLight ? nothing : html`<slot></slot><slot name=\"details\" hidden></slot>`}\n <dialog\n part=\"dialog\"\n aria-labelledby=${this.captionId}\n @click=${this.onDialogClick}\n @close=${this.onDialogClose}\n @keydown=${this.onKey}\n >\n <div class=\"panel\" part=\"panel\">\n <div class=\"head\">\n <p class=\"caption\" part=\"caption\" id=${this.captionId}>${slide?.caption ?? 'Image'}</p>\n <button type=\"button\" class=\"close\" autofocus @click=${() => this.dismiss('ui')}>\n Close\n </button>\n </div>\n <figure class=\"figure\">${src ? this.renderImage(slide!, src, regions) : nothing}</figure>\n <p class=\"status ${shown ? '' : 'visually-hidden'}\" role=\"status\">${shown}</p>\n <div class=\"toolbar\" part=\"controls\">\n ${\n outlined && src\n ? html`<button\n type=\"button\"\n class=\"regions-toggle\"\n aria-pressed=${this.showRegions ? 'true' : 'false'}\n @click=${this.toggleRegions}\n >\n Show regions\n </button>`\n : nothing\n }\n ${\n this.multiple\n ? html`<button type=\"button\" class=\"prev\" @click=${() => this.step(-1)}>\n Previous\n </button>\n <button type=\"button\" class=\"next\" @click=${() => this.step(1)}>Next</button>\n ${counter}`\n : nothing\n }\n ${\n full\n ? html`<a\n class=\"full\"\n href=${full}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n @click=${this.onFullSize}\n >Full size<span class=\"visually-hidden\"> (opens in a new tab)</span></a\n >`\n : nothing\n }\n </div>\n <div class=\"details\" part=\"details\"></div>\n </div>\n </dialog>\n `;\n }\n}\n","import { define } from '../../base/define.js';\nimport { UvalibLightbox } from './UvalibLightbox.js';\n\ndefine('uvalib-lightbox', UvalibLightbox);\n"],"mappings":";;;;;;AAOA,IAAMqB,IAAS,kDACTC,IAAW,mBACXC,IAAU,+EAEVC,IAAgB,4BAEhBC,IAAa;AAgBnB,SAAgBC,EAAU,GAAc,GAAkC;CACxE,IAAIC;CACJ,IAAI;EACF,IAAM,IAAI,IAAIC,GAAMC,CAAI;CAC1B,QAAQ;EACN,OAAO;CACT;CACA,IAAIF,EAAI,aAAa,WAAWA,EAAI,aAAa,UAAU,OAAO;CAClE,IAAMG,IAAQH,EAAI,SAAS,MAAM,GAAG;CACpC,IAAIG,EAAM,SAAS,GAAG,OAAO;CAC7B,IAAMC,IAAOD,EAAMA,EAAM,SAAS,MAAM,IAClCE,IAAWF,EAAMA,EAAM,SAAS,MAAM,IACtCG,IAASH,EAAMA,EAAM,SAAS,MAAM;CAE1C,OADI,CAACP,EAAQ,KAAKQ,CAAI,KAAK,CAACT,EAAS,KAAKU,CAAQ,KAAK,CAACX,EAAO,KAAKY,CAAM,IAAU,OAC7E;EAAE;EAAK;EAAO,aAAaH,EAAM,SA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,EACL;cAECmI,IACI,CAAI;;2BAEKA,EAAK;;;6BAGH,KAAK,WAAW;;uBAG3BnI,EACL;;;;;;CAMX;AACF;;AA/lCGC,EAAA,CAAAC,EAAS,EAAE,MAAM,OAAO,CAAC,CAAA,GAAAuD,EAAA,WAAA,YAAA,KAAA,CAAA,GAOzBxD,EAAA,CAAAC,EAAS,EAAE,WAAW,YAAY,CAAC,CAAA,GAAAuD,EAAA,WAAA,YAAA,KAAA,CAAA,GAQnCxD,EAAA,CAAAC,EAAS,EAAE,WAAW,GAAM,CAAC,CAAA,GAAAuD,EAAA,WAAA,WAAA,KAAA,CAAA,GAS7BxD,EAAA,CAAAC,EAAS,EAAE,WAAW,GAAM,CAAC,CAAA,GAAAuD,EAAA,WAAA,eAAA,KAAA,CAAA,GAG7BxD,EAAA,CAAAC,EAAS,EAAE,WAAW,gBAAgB,CAAC,CAAA,GAAAuD,EAAA,WAAA,gBAAA,KAAA,CAAA,GAEvCxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,UAAA,KAAA,CAAA,GACNxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,SAAA,KAAA,CAAA,GACNxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,QAAA,KAAA,CAAA,GACNxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,UAAA,KAAA,CAAA,GACNxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,QAAA,KAAA,CAAA,GACNxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,QAAA,KAAA,CAAA,GAENxD,EAAA,CAAAE,EAAM,CAAA,GAAAsD,EAAA,WAAA,eAAA,KAAA,CAAA,GCnVTjD,EAAO,mBAAmBiD,CAAc"}
1
+ {"version":3,"file":"uvalib-lightbox.js","names":["unsafeCSS","nothing","_decorate","property","state","n","i","r$1","b","define","__decorate","r","installLightDomStyles","UvalibElement","trackEvent","accessible","toRegion","parseRegions","paramFromLocation","usesHashParam","hrefWithParam","REGION","ROTATION","QUALITY","BROWSER_IMAGE","DATA_IMAGE","parseIiif","url","href","base","parts","file","rotation","region","sizedIiifUrl","parsed","width","w","height","h","iiifIdentifier","viewportIiifSize","dpr","view","usableImageUrl","LIST_SLOT","ENTRY_MARKS","positive","v","normalize","s","structuralRules","host","shadowStructure","nextCaption","compareModule","compareLoading","regionsLoading","loadRegions","err","UvalibLightbox","_args","link","slides","queued","id","rtl","back","forward","root","sheet","mount","light","dialog","slide","src","changed","node","force","next","forced","same","current","at","found","detailRoots","noteDetails","a","el","candidates","push","owner","unique","pos","img","alt","text","caption","index","list","regions","raw","m","value","more","ref","walk","already","hashMode","version","delta","action","pushed","source","loc","vp","rest","now","prev","mode","observer","trigger","again","active","position","pool","add","item","f","want","key","keep","still","box","parent","rendered","target","li","lent","name","was","outlined","cmp","A","controls","full","fullLinks","shown","counter"],"sources":["../src/components/uvalib-lightbox/media.ts","../src/components/uvalib-lightbox/UvalibLightbox.ts","../src/components/uvalib-lightbox/uvalib-lightbox.ts"],"sourcesContent":["export {\n hrefWithParam,\n paramFromLocation,\n usesHashParam,\n type PageLocation,\n} from '../../base/url-param.js';\n\nconst REGION = /^(full|square|max|pct:[^/]+|\\d+,\\d+,\\d+,\\d+)$/i;\nconst ROTATION = /^!?\\d+(\\.\\d+)?$/;\nconst QUALITY = /^(default|color|gray|grey|bitonal|native)\\.(jpe?g|png|gif|webp|tiff?|jp2)$/i;\n/** Formats a browser can paint. TIFF and JPEG2000 are left unchanged. */\nconst BROWSER_IMAGE = /\\.(jpe?g|png|gif|webp)$/i;\n/** Full size may offer these `data:` images. SVG is never one: it can carry a script. */\nconst DATA_IMAGE = /^image\\/(png|jpeg|gif|webp)($|[;,])/i;\n\nexport interface IiifRequest {\n url: URL;\n /** Path segments, with a leading `''` for an absolute path. */\n parts: string[];\n regionIndex: number;\n sizeIndex: number;\n}\n\n/**\n * A IIIF Image API request, recognised from the end of the path:\n * `/{region}/{size}/{rotation}/{quality}.{format}`. The identifier may contain slashes\n * and colons (`uva-lib:286686`). Anything else, including an image that merely lives\n * under a `/full/` folder, is not one.\n */\nexport function parseIiif(href: string, base: string): IiifRequest | null {\n let url: URL;\n try {\n url = new URL(href, base);\n } catch {\n return null;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;\n const parts = url.pathname.split('/');\n if (parts.length < 5) return null;\n const file = parts[parts.length - 1] ?? '';\n const rotation = parts[parts.length - 2] ?? '';\n const region = parts[parts.length - 4] ?? '';\n if (!QUALITY.test(file) || !ROTATION.test(rotation) || !REGION.test(region)) return null;\n return { url, parts, regionIndex: parts.length - 4, sizeIndex: parts.length - 3 };\n}\n\n/**\n * The same image with only the size segment rewritten to `!w,h`, so the server sends a size\n * that fits `w` by `h` device pixels and does not scale the original up. The region stays\n * (a crop or `square` is kept). Returns null when `href` is not IIIF, and for a TIFF or\n * JPEG2000 request, which is left exactly as written.\n */\nexport function sizedIiifUrl(href: string, base: string, w: number, h: number): string | null {\n const parsed = parseIiif(href, base);\n if (!parsed) return null;\n const file = parsed.parts[parsed.parts.length - 1] ?? '';\n if (!BROWSER_IMAGE.test(file)) return null;\n const width = Math.max(1, Math.round(w));\n const height = Math.max(1, Math.round(h));\n parsed.parts[parsed.sizeIndex] = `!${width},${height}`;\n parsed.url.pathname = parsed.parts.join('/');\n return parsed.url.toString();\n}\n\n/** The IIIF identifier (the segment before the region), for a stable deep-link id. */\nexport function iiifIdentifier(href: string, base: string): string | null {\n const parsed = parseIiif(href, base);\n if (!parsed) return null;\n const id = parsed.parts[parsed.regionIndex - 1];\n return id || null;\n}\n\n/** CSS pixels of the viewport, in device pixels, capped so a request stays reasonable. */\nexport function viewportIiifSize(\n view: Pick<Window, 'innerWidth' | 'innerHeight' | 'devicePixelRatio'>,\n): {\n w: number;\n h: number;\n} {\n const dpr = Math.min(view.devicePixelRatio || 1, 2);\n const w = Math.max(1, Math.min(2000, Math.round((view.innerWidth || 800) * dpr)));\n const h = Math.max(1, Math.min(2000, Math.round((view.innerHeight || 600) * dpr)));\n return { w, h };\n}\n\n/**\n * Whether `href` may be offered as Full size: an http(s) URL (including a relative one), or\n * a `data:` image of type PNG, JPEG, GIF or WebP. SVG and every other scheme are refused.\n */\nexport function usableImageUrl(href: string, base: string): boolean {\n try {\n const url = new URL(href, base);\n if (url.protocol === 'http:' || url.protocol === 'https:') return true;\n if (url.protocol === 'data:') return DATA_IMAGE.test(url.pathname);\n return false;\n } catch {\n return false;\n }\n}\n","import { css, html, nothing, unsafeCSS, type PropertyValues } from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { trackEvent } from '../../base/analytics.js';\nimport { UvalibElement } from '../../base/UvalibElement.js';\nimport { installLightDomStyles } from '../../base/light-dom-styles.js';\nimport { accessible } from '../../styles/accessible.js';\nimport { parseRegions, toRegion, type ImageRegion } from '../uvalib-image-regions/regions.js';\nimport type { Compare } from './compare.js';\nimport {\n hrefWithParam,\n iiifIdentifier,\n paramFromLocation,\n sizedIiifUrl,\n usableImageUrl,\n usesHashParam,\n viewportIiifSize,\n type PageLocation,\n} from './media.js';\n\n/** One image in the set, in document order. */\ninterface Slide {\n el: HTMLAnchorElement;\n /** Deep-link id: `data-id`, else the element's id, else the IIIF identifier, else the position. */\n id: string;\n /** The href as written. */\n href: string;\n caption: string;\n alt: string;\n /** `data-details-id`, when the slide has its own details element. */\n detailsId: string | null;\n /** Regions outlined on the image (`data-regions`, or the `regions` callback). */\n regions: ImageRegion[];\n /** The page's own region list (`data-regions-list`, or the `regionsList` callback). */\n list: RegionsListElement | null;\n /** `data-image-width` / `data-image-height`: the size pixel regions are measured in. */\n imageWidth?: number;\n imageHeight?: number;\n /** `data-versions` as written, or what the `versions` callback returned (checked on use). */\n versions: string | unknown[] | null;\n}\n\n/** What the `regions` callback is given for each image. */\nexport interface LightboxRegionsItem {\n /** The image link. */\n element: HTMLAnchorElement;\n /** Its deep-link id. */\n id: string;\n /** Its href as written. */\n href: string;\n /** Its place in the set, from 0. */\n index: number;\n}\n\n/** Maps an image to its regions (none: an empty array, null or undefined). */\nexport type LightboxRegions = (\n item: LightboxRegionsItem,\n) => readonly ImageRegion[] | null | undefined;\n\n/** One version of an image: the first is the link's own `href` (which it may omit). */\nexport interface LightboxVersion {\n /** Its name, shown on the controls and at the end of the image's accessible name. */\n label: string;\n /** The image (http(s), relative, or a PNG, JPEG, GIF or WebP `data:` URL). */\n href?: string;\n /** Shown under the photo while this version is visible (for example how it was made). */\n note?: string;\n}\n\n/** Maps an image to its versions (none: null or undefined). */\nexport type LightboxVersions = (\n item: LightboxRegionsItem,\n) => readonly LightboxVersion[] | null | undefined;\n\n/** Returns the page's own region list for an image: an `<ol>` or `<ul>` of `<li data-xywh>`. */\nexport type LightboxRegionsList = (item: LightboxRegionsItem) => Element | null | undefined;\n\ntype RegionsListElement = HTMLOListElement | HTMLUListElement;\n\n/** The slot (shadow mode) a page's region list is lent to while its image is open. */\nconst LIST_SLOT = 'uvalib-regions-list';\n\n/** Attributes `<uvalib-image-regions>` puts on a list's entries. */\nconst ENTRY_MARKS = ['data-uvalib-region', 'data-uvalib-active'];\n\nconst positive = (v: string | undefined): number | undefined => {\n const n = Number(v);\n return n > 0 ? n : undefined;\n};\n\nconst normalize = (s: unknown) =>\n String(s ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n\n/**\n * Kept with `no-style`: the triggers stay put, `[hidden]` hides, the dialog hugs its panel\n * (so a click outside it is the backdrop), controls are at least 44px, and the image stays\n * within the viewport. `host` is `:host` (shadow) or the tag (light DOM).\n */\nconst structuralRules = (host: string) => `\n ${host} { display: block; }\n ${host} .viewer { display: contents; }\n ${host} dialog {\n margin: auto;\n padding: 0;\n border: none;\n background: transparent;\n width: min(72rem, calc(100% - 2rem));\n max-height: calc(100% - 2rem);\n }\n ${host} .panel {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n max-height: calc(100dvh - 2rem);\n overflow: auto;\n overscroll-behavior: contain;\n padding: 0.75rem;\n }\n ${host} .head, ${host} .toolbar {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 0.5rem;\n }\n ${host} .head { justify-content: space-between; }\n ${host} .caption { margin: 0; min-width: 0; overflow-wrap: anywhere; }\n ${host} .figure { margin: 0; }\n ${host} dialog img { display: block; max-width: 100%; max-height: 70dvh; width: auto; height: auto; margin: auto; }\n ${host} .count, ${host} .status { margin: 0; }\n ${host} dialog button, ${host} dialog .full {\n box-sizing: border-box;\n min-width: 44px;\n min-height: 44px;\n padding: 0.5rem 0.75rem;\n font: inherit;\n }\n ${host} .regions { display: block; }\n ${host} .stack { position: relative; width: fit-content; max-width: 100%; margin-inline: auto; }\n ${host} .details:empty { display: none; }\n ${host} > [slot=\"details\"] { display: none; }\n ${host}[hidden], ${host} [hidden] { display: none !important; }\n`;\nconst shadowStructure = unsafeCSS(structuralRules(':host'));\n\nlet nextCaption = 0;\n\n/** The comparison UI, loaded the first time an open image has versions. */\nlet compareModule: typeof import('./compare.js') | null = null;\nlet compareLoading: Promise<unknown> | null = null;\n\n/** `<uvalib-image-regions>` is loaded the first time an open image has regions. */\nlet regionsLoading: Promise<unknown> | null = null;\nfunction loadRegions(): void {\n if (regionsLoading || customElements.get('uvalib-image-regions')) return;\n regionsLoading = import('../uvalib-image-regions/uvalib-image-regions.js').catch((err) => {\n regionsLoading = null;\n console.warn('uvalib-lightbox: could not load uvalib-image-regions.', err);\n });\n}\n\n/**\n * An accessible image viewer over a set of plain links. With JavaScript a primary click opens\n * a modal dialog; without it (or with a modified click) the link opens the image as before.\n * Wrap the links, or point at them with `selector` (for example `a.pb-image` on a reading\n * page). There is no autoplay and no carousel.\n *\n * The dialog is labelled by the caption (`data-caption`, else the image alt, else the link\n * text). Focus moves to Close on open and back to the trigger on close. Escape and a click on\n * the backdrop close it. With more than one image, Previous and Next and the arrow keys move\n * through the set (wrapping), and a polite “3 of 13” counter is shown. Full size opens the\n * original image in a new tab. A IIIF Image API URL keeps its region; only the size becomes\n * `!W,H` for the viewport. TIFF and JPEG2000 URLs are left as written. `url-param` (for\n * example `photo`) keeps `?photo=<id>` in sync, including on a hash route\n * (`#/text?photo=<id>`): opening pushes a history entry, stepping replaces it, and\n * Back closes.\n *\n * Optional details: children with `slot=\"details\"` (and `data-for` equal to the item's id or\n * its position from 1; without `data-for` they show for every image), or `data-details-id` on\n * a link pointing at an element elsewhere on the page. Either is shown inside the dialog and\n * put back when the viewer moves on or closes.\n *\n * Optional regions (people, objects, inscriptions): `data-regions` on a link, a JSON array of\n * `{ label, x, y, w, h, unit? }` or `xywh` values each followed by its label, separated by\n * `;` (`percent:10,20,30,40 Person 1; percent:55,15,20,30 Sign`), or the `regions` callback.\n * The open image then shows numbered outlines (`<uvalib-image-regions>`, loaded on first use)\n * and a list of the regions beside it, with a \"Show regions\" toggle (`aria-pressed`) that\n * hides the outlines. Pixel regions are measured in `data-image-width` × `data-image-height`\n * when set (the viewer shows a resized IIIF image), else in the image's natural size.\n *\n * Or the page's own list, with its own buttons: `data-regions-list=\"<id>\"` on a link (or the\n * `regionsList` callback) names an `<ol>` or `<ul>` of `<li data-xywh>` anywhere in the page,\n * usually `hidden`. While that image is open the list (the same nodes, so the page's listeners\n * keep working) is the region list: in shadow mode it becomes a child of the lightbox slotted\n * into the viewer, not moved into the shadow root, so the page's CSS still applies to it. When\n * the image changes or the viewer closes it goes back where it was, `hidden` as before. It wins\n * over `data-regions`.\n *\n * Optional versions of an image (an original scan and an AI colorization, a restoration, an\n * infrared capture): `data-versions` on a link, a JSON array of `{ label, href?, note? }`\n * whose first entry is the link's own image, or the `versions` callback. The viewer then\n * compares them over the photo (loaded on first use): Switch (a segmented control), Reveal\n * (a divider: click or tap the photo, or use the slider) or Fade (a slider), `compare`\n * choosing the first. A version's `note` shows under the photo while it is visible, and\n * the image's accessible name ends with the label of the version shown. `version-param`\n * (with `url-param`) keeps the comparison in the address: `?version=2` (Switch, the version\n * from 0), `?version=wipe:40` or `?version=fade:60` (the percentage of the other version\n * shown; `wipe:40:2` compares the original with version 2).\n *\n * @tagname uvalib-lightbox\n * @slot - The image links. A plain click opens the viewer; without JavaScript they open the image.\n * @slot details - Details for the open image. `data-for` selects one item by its id or position (from 1); without it the details show for every image.\n * @csspart dialog - The modal dialog.\n * @csspart panel - The surface inside the dialog.\n * @csspart caption - The caption that names the dialog.\n * @csspart image - The image.\n * @csspart controls - Previous, Next, the counter and Full size.\n * @csspart details - The details panel.\n * @csspart regions - The `<uvalib-image-regions>` around an image with regions.\n * @csspart compare - The version comparison controls and notes under the photo.\n * @fires uvalib-lightbox-version - The visitor changed the comparison (mode, version or position; once a slider settles): `detail` is `{ id, mode, index, value }` (`mode` `switch`, `wipe` or `fade`; `index` the version shown or compared, from 0; `value` the percentage of it shown, null for Switch). Not fired on open or for a comparison restored from the URL. Bubbles and is composed.\n * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-lightbox', 'open'|'next'|'previous'|'full-size', 'image N', N]` (N from 1, the image's place in the set), and `['uvalib-lightbox', 'compare', 'switch'|'wipe'|'fade', N]` when the visitor changes a comparison (N the version's place from 1; once a slider settles). Never the URL, the caption or a version's label. Not fired for a viewer restored from the URL or from Back and Forward. Bubbles and is composed.\n * @cssprop --uva-color-surface-raised - Dark-mode role token: dialog surface (else `--uva-color-surface`, else #fff).\n * @cssprop --uva-color-surface - Dark-mode role token: the figure behind the image (else #fff).\n * @cssprop --uva-color-text - Dark-mode role token: text (else `--uva-grey-darkest`).\n * @cssprop --uva-color-shadow - Dark-mode role token: the backdrop scrim (else rgba(16, 23, 43, 0.72)).\n * @cssprop --uva-color-border - Dark-mode role token: dialog border (else `--uva-grey-100`).\n * @cssprop --uva-color-focus - Dark-mode role token: focus ring (else `--uva-brand-orange`).\n * @cssprop --uva-color-link - Dark-mode role token: Full size text when it is not the filled control (else `--uva-brand-blue`).\n * @cssprop --uva-color-accent-bg - Dark-mode role token: Close and Full size background (else `--uva-brand-blue`).\n * @cssprop --uva-color-on-accent - Text on those controls (else #fff).\n * @cssprop [--uva-brand-orange=#e57200] - Focus ring when `--uva-color-focus` is unset.\n * @cssprop [--uva-brand-blue=#232d4b] - Control background when `--uva-color-accent-bg` is unset.\n * @cssprop [--uva-grey-darkest=#2b2b2b] - Text when `--uva-color-text` is unset.\n * @cssprop [--uva-grey-100=#dadada] - Border when `--uva-color-border` is unset.\n */\nexport class UvalibLightbox extends UvalibElement {\n static styles = [\n accessible,\n shadowStructure,\n css`\n .panel {\n background: var(--uva-color-surface-raised, var(--uva-color-surface, #fff));\n color: var(--uva-color-text, var(--uva-grey-darkest, #2b2b2b));\n border: 1px solid var(--uva-color-border, var(--uva-grey-100, #dadada));\n }\n dialog::backdrop {\n background: var(--uva-color-shadow, rgba(16, 23, 43, 0.72));\n }\n .details a {\n color: var(--uva-color-link, var(--uva-brand-blue, #232d4b));\n }\n .figure {\n background: var(--uva-color-surface, #fff);\n }\n .caption {\n font-size: 1.125rem;\n line-height: 1.4;\n font-weight: 600;\n }\n .count {\n font-variant-numeric: tabular-nums;\n }\n dialog button,\n dialog .full {\n padding: 0.5rem 0.75rem;\n border: 2px solid transparent;\n text-decoration: none;\n cursor: pointer;\n color: var(--uva-color-on-accent, #fff);\n background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));\n }\n dialog button:focus-visible,\n dialog .full:focus-visible {\n outline: 3px solid var(--uva-color-focus, var(--uva-brand-orange, #e57200));\n outline-offset: 2px;\n }\n dialog button.prev,\n dialog button.next,\n dialog button.regions-toggle {\n color: var(--uva-color-link, var(--uva-brand-blue, #232d4b));\n background: var(--uva-color-surface, #fff);\n border-color: var(--uva-color-border, var(--uva-grey-100, #dadada));\n }\n .status {\n font-size: 1rem;\n }\n /* Pressed shows a check mark, so the state is not shown by colour alone. */\n button.regions-toggle {\n display: inline-flex;\n align-items: center;\n gap: 0.5rem;\n }\n button.regions-toggle::before {\n content: '';\n box-sizing: border-box;\n width: 1rem;\n height: 1rem;\n border: 2px solid currentColor;\n }\n button.regions-toggle[aria-pressed='true']::before {\n border-width: 0 3px 3px 0;\n width: 0.5rem;\n margin-inline: 0.25rem;\n transform: translateY(-0.125rem) rotate(45deg);\n }\n @media (prefers-reduced-motion: no-preference) {\n .panel {\n animation: uvalib-lightbox-in 0.15s ease;\n }\n }\n @media (prefers-reduced-motion: reduce) {\n dialog,\n dialog * {\n animation: none !important;\n transition: none !important;\n scroll-behavior: auto !important;\n }\n }\n @media (forced-colors: active) {\n .panel,\n dialog button,\n dialog .full {\n border: 1px solid CanvasText;\n }\n }\n @keyframes uvalib-lightbox-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n `,\n ];\n\n /**\n * CSS selector for image links elsewhere in this root (the page, or the shadow root the\n * component sits in). Combined with any links inside the component. Example: `a.pb-image`.\n */\n @property({ type: String }) selector = '';\n\n /**\n * Query parameter kept in sync with the open image, for example `photo` → `?photo=<id>`.\n * The id is the link's `data-id`, else its `id`, else the IIIF identifier, else its position\n * from 1. On a hash route the parameter is written inside the hash. Empty: no deep link.\n */\n @property({ attribute: 'url-param' }) urlParam = '';\n\n /**\n * Regions for each image, instead of (or as well as) `data-regions`: called with\n * `{ element, id, href, index }`, it returns region objects (`{ label, x, y, w, h, unit? }`).\n * An image with regions shows their outlines over it, a list of them beside it, and a\n * \"Show regions\" toggle.\n */\n @property({ attribute: false }) regions?: LightboxRegions;\n\n /**\n * The page's own region list for each image, instead of `data-regions-list`: called with\n * `{ element, id, href, index }`, it returns an `<ol>` or `<ul>` of `<li data-xywh>` (or\n * null). While the image is open the list is shown as its region list, with the page's own\n * buttons and listeners; it is put back where it was when the image changes or the viewer\n * closes.\n */\n @property({ attribute: false }) regionsList?: LightboxRegionsList;\n\n /** The heading of the regions list (for example `People`). */\n @property({ attribute: 'regions-label' }) regionsLabel = 'Regions';\n\n /**\n * Versions of each image, instead of `data-versions`: called with\n * `{ element, id, href, index }`, it returns `{ label, href?, note? }` objects, the first\n * being the link's own image (null: none).\n */\n @property({ attribute: false }) versions?: LightboxVersions;\n\n /**\n * How an image's versions are compared first: `switch` (default: one at a time, any number\n * of versions), `wipe` (a divider over the photo) or `fade` (a cross-fade). The viewer\n * offers the others.\n */\n @property() compare: 'switch' | 'wipe' | 'fade' = 'switch';\n\n /**\n * Query parameter for the comparison (with `url-param`), for example `version`:\n * `?version=1`, `?version=wipe:40`, `?version=fade:60`. Written with replaceState once the\n * visitor's change settles; read when the viewer opens from the address.\n */\n @property({ attribute: 'version-param' }) versionParam = '';\n\n @state() private slides: Slide[] = [];\n @state() private index = 0;\n @state() private open = false;\n @state() private status: 'loading' | 'ready' | 'error' = 'loading';\n @state() private fitW = 0;\n @state() private fitH = 0;\n /** The \"Show regions\" toggle: outlines over an image that has regions. */\n @state() private showRegions = true;\n\n private readonly captionId = `uvalib-lightbox-caption-${++nextCaption}`;\n /** Where the dialog is rendered. Light DOM renders here so the author's links stay put. */\n private mount?: HTMLElement;\n private trigger: HTMLAnchorElement | null = null;\n /** The open image pushed a history entry, so Back (and Close) returns to the page. */\n private historyPushed = false;\n /** The visitor closed the viewer; a later mutation must not reopen it from the URL. */\n private userClosed = false;\n /** Disconnect (and the dialog it closes) is not a visitor action, so it must not touch history. */\n private suppressClose = false;\n private warnedSelector = false;\n private lastSrc = '';\n private observer?: MutationObserver;\n private syncQueued = false;\n private regionsChanged = false;\n private resizeTimer = 0;\n /** A close event from the dialog we just shut must not dismiss the next open. */\n private ignoreClose = false;\n private dismissing = false;\n private revealTries = 0;\n private revealFrame = 0;\n private listened = false;\n /** The root `listen` bound, so disconnect can remove the listener after leaving a shadow root. */\n private listenRoot?: Document | ShadowRoot;\n /**\n * `dialog.close()` removes `open` now and fires `close` on a later task. The attribute\n * observer runs as a microtask, which is what a caller sees after `await updateComplete`.\n */\n private dialogObserver?: MutationObserver;\n private observedDialog?: HTMLDialogElement;\n /** `history.back()` from Close has not fired `popstate` yet. */\n private pendingBack = false;\n /** Whether that entry kept the parameter in the hash. The pop leaves a hash that may not say so. */\n private backInHash = false;\n /** An image chosen while that Back is still in flight, opened once the popstate arrives. */\n private queuedOpen: { i: number; slides: Slide[] } | null = null;\n /**\n * Set while a history traversal is opening the dialog. The traversal can close the\n * dialog it just showed; that close is not the visitor, so show it again.\n */\n private reopenGuard = false;\n /** Details elements moved into the dialog, and where they go back to. */\n private parked: { el: HTMLElement; parent: Node; next: ChildNode | null; hidden: boolean }[] = [];\n private parkedKey = '';\n /** The page's region list lent to the viewer, and how to give it back as it was. */\n private lent: {\n el: RegionsListElement;\n parent: Node;\n next: ChildNode | null;\n hidden: boolean;\n slot: string | null;\n } | null = null;\n /** Each entry's own `tabindex` (null: none), so one the viewer added is removed. */\n private entryTabindex = new WeakMap<Element, string | null>();\n private warnedList = false;\n private refocus = false;\n /** The comparison controller, once its module has loaded. */\n private cmp?: Compare;\n /** The comparison from the address, for the image opened from it. */\n private pendingVersion: string | null = null;\n\n /** Shadow mode follows the base class. Light mode renders into `.viewer`. */\n private get isLight(): boolean {\n return this.noShadowDom || this.hasAttribute('no-shadow-dom');\n }\n\n protected override createRenderRoot(): HTMLElement | DocumentFragment {\n if (!this.isLight) {\n const root = super.createRenderRoot();\n if (this.noStyle && root instanceof ShadowRoot) {\n const sheets = [accessible.styleSheet, shadowStructure.styleSheet].filter(\n (sheet): sheet is CSSStyleSheet => sheet != null,\n );\n root.adoptedStyleSheets = sheets;\n }\n return root;\n }\n const mount = this.ownerDocument.createElement('div');\n mount.className = 'viewer';\n this.mount = mount;\n this.append(mount);\n return mount;\n }\n\n override connectedCallback(): void {\n const light = this.isLight;\n super.connectedCallback();\n // A move in the DOM disconnects and reconnects. The disconnect guard must not stick,\n // or Escape would close the dialog and leave the viewer thinking it is still open.\n this.suppressClose = false;\n if (light) this.installLight(light);\n this.listen();\n this.slides = this.collect();\n this.watch();\n this.openFromUrl();\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.unlisten();\n this.observer?.disconnect();\n this.dialogObserver?.disconnect();\n this.dialogObserver = undefined;\n this.observedDialog = undefined;\n window.clearTimeout(this.resizeTimer);\n this.cancelReveal();\n this.restoreDetails();\n this.pendingBack = false;\n this.queuedOpen = null;\n this.reopenGuard = false;\n // Closing the dialog here fires `close` synchronously. That is not the visitor dismissing\n // it: do not run history.back(), which could leave the page. `open` goes false so a later\n // connect can open again from the URL.\n this.suppressClose = true;\n this.open = false;\n const dialog = this.dialogEl;\n if (dialog?.open) dialog.close();\n this.suppressClose = false;\n this.ignoreClose = false;\n }\n\n protected override willUpdate(): void {\n this.lendList();\n if (!this.open) {\n this.lastSrc = '';\n return;\n }\n const slide = this.current;\n if (this.cmp && slide) {\n this.cmp.sync(slide, this.index, this.pendingVersion);\n this.pendingVersion = null;\n }\n const src = this.displaySrc;\n if (src !== this.lastSrc) {\n this.lastSrc = src;\n this.status = src ? 'loading' : 'error';\n } else if (!src && this.status !== 'error') {\n // A refused URL (javascript:) has an empty src. On the first open `lastSrc` is already\n // empty, so the change above does not run, and the status would stay \"loading\".\n this.status = 'error';\n }\n }\n\n protected override updated(changed: PropertyValues): void {\n super.updated(changed);\n if (changed.has('selector')) this.watch();\n if (\n (changed.has('regions') || changed.has('regionsList') || changed.has('versions')) &&\n this.isConnected\n )\n this.scheduleSync(true);\n if (!this.open) {\n if (changed.has('open')) this.restoreDetails();\n return;\n }\n if (changed.has('open') || changed.has('index') || changed.has('slides')) this.placeDetails();\n if (this.current?.regions.length || this.current?.list) loadRegions();\n if (this.current?.versions) this.loadCompare();\n this.lendList(true);\n if (this.refocus) {\n this.refocus = false;\n this.closeBtn?.focus();\n }\n this.bindDialogObserver();\n if (changed.has('open')) this.reveal();\n // Reading the image and writing `status` from inside `updated` makes Lit warn and schedule\n // a nested update. A microtask is still before the next paint.\n queueMicrotask(() => {\n if (this.isConnected) this.settleImage();\n });\n }\n\n private installLight(light: boolean): void {\n if (!light) return;\n const node = this.getRootNode();\n const root = node instanceof Document || node instanceof ShadowRoot ? node : undefined;\n if (this.noStyle) {\n installLightDomStyles(\n `${this.localName}::structure`,\n unsafeCSS(structuralRules(this.localName)),\n { root, scope: false },\n );\n installLightDomStyles(`${this.localName}::a11y`, accessible, { root });\n return;\n }\n installLightDomStyles(\n this.localName,\n (this.constructor as typeof UvalibElement).elementStyles,\n {\n root,\n },\n );\n }\n\n private get scope(): Document | ShadowRoot {\n const root = this.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot ? root : this.ownerDocument;\n }\n\n private get base(): string {\n return this.ownerDocument.baseURI || location.href;\n }\n\n private loc(): PageLocation {\n return { pathname: location.pathname, search: location.search, hash: location.hash };\n }\n\n private listen(): void {\n if (this.listened) return;\n this.listened = true;\n this.listenRoot = this.scope;\n this.listenRoot.addEventListener('click', this.onClick, true);\n window.addEventListener('popstate', this.onPop);\n window.addEventListener('resize', this.onResize);\n }\n\n private unlisten(): void {\n if (!this.listened) return;\n this.listened = false;\n this.listenRoot?.removeEventListener('click', this.onClick, true);\n this.listenRoot = undefined;\n window.removeEventListener('popstate', this.onPop);\n window.removeEventListener('resize', this.onResize);\n }\n\n private watch(): void {\n this.observer?.disconnect();\n this.observer = new MutationObserver(() => this.scheduleSync());\n this.observer.observe(this, {\n attributes: true,\n attributeFilter: [\n 'href',\n 'id',\n 'alt',\n 'title',\n 'data-caption',\n 'data-id',\n 'data-details-id',\n 'data-regions',\n 'data-regions-list',\n 'data-versions',\n 'data-image-width',\n 'data-image-height',\n 'slot',\n ],\n childList: true,\n subtree: true,\n });\n if (this.selector) this.observer.observe(this.scope, { childList: true, subtree: true });\n }\n\n /** Ignore mutations inside the viewer (the dialog, parked details) so a render cannot loop. */\n private scheduleSync(force = false): void {\n if (force) this.regionsChanged = true;\n if (this.syncQueued) return;\n this.syncQueued = true;\n queueMicrotask(() => {\n this.syncQueued = false;\n if (!this.isConnected) return;\n const next = this.collect();\n const forced = this.regionsChanged;\n this.regionsChanged = false;\n const same =\n !forced &&\n next.length === this.slides.length &&\n next.every(\n (s, i) =>\n s.el === this.slides[i]?.el &&\n s.href === this.slides[i]?.href &&\n s.id === this.slides[i]?.id &&\n s.caption === this.slides[i]?.caption &&\n s.detailsId === this.slides[i]?.detailsId &&\n s.list === this.slides[i]?.list &&\n JSON.stringify([s.regions, s.imageWidth, s.imageHeight, s.versions]) ===\n JSON.stringify([\n this.slides[i]?.regions,\n this.slides[i]?.imageWidth,\n this.slides[i]?.imageHeight,\n this.slides[i]?.versions,\n ]),\n );\n this.noteEntries();\n if (!same) {\n const current = this.current?.el;\n this.slides = next;\n if (this.open) {\n const at = current ? next.findIndex((s) => s.el === current) : -1;\n if (at >= 0) this.index = at;\n else if (!next.length) this.dismiss('empty');\n else this.index = Math.min(this.index, next.length - 1);\n }\n }\n if (!this.open) this.openFromUrl();\n });\n }\n\n private collect(): Slide[] {\n const found: HTMLAnchorElement[] = [];\n const detailRoots = new Set<Element>();\n const noteDetails = (a: Element) => {\n if (!(a instanceof HTMLAnchorElement)) return;\n const id = a.getAttribute('data-details-id');\n if (!id) return;\n const el = this.scope.getElementById(id);\n if (el) detailRoots.add(el);\n };\n const candidates: Element[] = [...this.querySelectorAll('a[href]')];\n if (this.selector) {\n try {\n candidates.push(...this.scope.querySelectorAll(this.selector));\n } catch {\n if (!this.warnedSelector) {\n this.warnedSelector = true;\n console.warn(\n `${this.localName}: selector ${JSON.stringify(this.selector)} is not a valid CSS selector.`,\n );\n }\n }\n }\n for (const a of candidates) noteDetails(a);\n const push = (a: Element) => {\n if (!(a instanceof HTMLAnchorElement) || !a.hasAttribute('href')) return;\n if (a.closest('[hidden]')) return;\n if (this.mount?.contains(a) || a.closest('dialog')) return;\n if (a.closest('[slot=\"details\"]')) return;\n // Links in a page's region list are its actions, not images (and it may be lent here).\n if (this.lent?.el.contains(a)) return;\n for (const root of detailRoots) {\n if (root.contains(a)) return;\n }\n const owner = a.closest('uvalib-lightbox');\n if (owner && owner !== this) return;\n found.push(a);\n };\n for (const a of candidates) push(a);\n const unique = [...new Set(found)];\n unique.sort((a, b) => {\n if (a === b) return 0;\n const pos = a.compareDocumentPosition(b);\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n if (pos & Node.DOCUMENT_POSITION_PRECEDING) return 1;\n return 0;\n });\n return unique.map((el, i) => this.slide(el, i));\n }\n\n private slide(el: HTMLAnchorElement, index: number): Slide {\n const href = el.getAttribute('href') ?? '';\n const img = el.querySelector('img');\n const alt = normalize(img?.getAttribute('data-uvalib-alt') || img?.getAttribute('alt'));\n const text = this.linkText(el);\n const caption =\n normalize(el.dataset.caption) ||\n alt ||\n text ||\n normalize(el.getAttribute('title')) ||\n 'Image';\n const id =\n normalize(el.dataset.id) || el.id || iiifIdentifier(href, this.base) || String(index + 1);\n const list = this.listOf(el, id, href, index);\n const regions = this.regionsOf(el, id, href, index);\n if (list && regions.length && !this.warnedList) {\n this.warnedList = true;\n console.warn(\n `${this.localName}: an image has both regions and a regions list; the list is used.`,\n );\n }\n return {\n el,\n id,\n href,\n caption,\n alt: alt || caption,\n detailsId: normalize(el.dataset.detailsId) || null,\n regions: list ? [] : regions,\n list,\n imageWidth: positive(el.dataset.imageWidth),\n imageHeight: positive(el.dataset.imageHeight),\n versions: this.versionsOf(el, id, href, index),\n };\n }\n\n /** `data-versions` (checked by the comparison module), else the `versions` callback's list. */\n private versionsOf(el: HTMLAnchorElement, id: string, href: string, index: number) {\n const raw = el.dataset.versions?.trim();\n if (raw) return raw;\n if (typeof this.versions !== 'function') return null;\n try {\n const list = this.versions({ element: el, id, href, index });\n return Array.isArray(list) && list.length ? [...list] : null;\n } catch (err) {\n console.warn(`${this.localName}: the versions callback threw.`, err);\n return null;\n }\n }\n\n /** Load the comparison module (once per page), then make this viewer's controller. */\n private loadCompare(): void {\n if (this.cmp) return;\n if (compareModule) {\n this.cmp = new compareModule.Compare(this.compareHost());\n this.requestUpdate();\n return;\n }\n compareLoading ??= import('./compare.js')\n .then((m) => {\n compareModule = m;\n })\n .catch((err) => {\n compareLoading = null;\n console.warn('uvalib-lightbox: could not load the version comparison.', err);\n });\n void compareLoading.then(() => {\n if (compareModule && this.isConnected) this.loadCompare();\n });\n }\n\n /** What the comparison module may use of this viewer. */\n private compareHost() {\n return {\n el: this as HTMLElement,\n light: this.isLight,\n root: this.isLight ? this.scope : this.renderRoot,\n noStyle: this.noStyle,\n mode: () => this.compare,\n size: (href: string) => this.sized(href),\n write: (value: string | null) => {\n if (this.versionParam && this.open)\n this.writeParam(this.current?.id ?? null, 'replace', undefined, value);\n },\n update: () => this.requestUpdate(),\n };\n }\n /** `data-regions`, then whatever the `regions` callback adds. */\n private regionsOf(el: HTMLAnchorElement, id: string, href: string, index: number) {\n const found = parseRegions(el.dataset.regions);\n if (typeof this.regions === 'function') {\n let more: unknown;\n try {\n more = this.regions({ element: el, id, href, index });\n } catch (err) {\n console.warn(`${this.localName}: the regions callback threw.`, err);\n }\n if (Array.isArray(more))\n for (const r of more) {\n const region = toRegion(r);\n if (region) found.push(region);\n }\n }\n return found;\n }\n\n /** `data-regions-list` (an id in this root), else the `regionsList` callback's element. */\n private listOf(\n el: HTMLAnchorElement,\n id: string,\n href: string,\n index: number,\n ): RegionsListElement | null {\n let found: unknown = null;\n const ref = normalize(el.dataset.regionsList);\n if (ref) found = this.scope.getElementById(ref);\n else if (typeof this.regionsList === 'function') {\n try {\n found = this.regionsList({ element: el, id, href, index });\n } catch (err) {\n console.warn(`${this.localName}: the regionsList callback threw.`, err);\n }\n }\n if (!(found instanceof HTMLOListElement || found instanceof HTMLUListElement)) return null;\n // Not one that holds the viewer or the image link itself.\n return found.contains(this) || found.contains(el) ? null : found;\n }\n\n /** The link's own text, not the alt of its image and not a details subtree. */\n private linkText(el: HTMLAnchorElement): string {\n const parts: string[] = [];\n const walk = (n: Node) => {\n if (n instanceof HTMLImageElement) return;\n if (\n n instanceof HTMLElement &&\n (n.hidden ||\n n.getAttribute('slot') === 'details' ||\n n.getAttribute('slot') === 'badge' ||\n n.classList.contains('badge') ||\n n.classList.contains('visually-hidden') ||\n n.hasAttribute('data-uvalib-generated-badge') ||\n n.hasAttribute('data-uvalib-badge-sep'))\n )\n return;\n if (n.nodeType === Node.TEXT_NODE) {\n parts.push(n.textContent ?? '');\n return;\n }\n n.childNodes.forEach(walk);\n };\n el.childNodes.forEach(walk);\n return normalize(parts.join(' '));\n }\n\n private get current(): Slide | undefined {\n return this.slides[this.index];\n }\n\n private get multiple(): boolean {\n return this.slides.length > 1;\n }\n\n /** The URL the `<img>` should load: a viewport-sized IIIF request, or the href itself. */\n private get displaySrc(): string {\n return this.sized(this.current?.href ?? '');\n }\n\n private sized(href: string): string {\n if (!usableImageUrl(href, this.base)) return '';\n const w = this.fitW || viewportIiifSize(window).w;\n const h = this.fitH || viewportIiifSize(window).h;\n return sizedIiifUrl(href, this.base, w, h) ?? href;\n }\n\n private measure(): void {\n const { w, h } = viewportIiifSize(window);\n if (w !== this.fitW) this.fitW = w;\n if (h !== this.fitH) this.fitH = h;\n }\n\n private readonly onResize = (): void => {\n if (!this.open) return;\n window.clearTimeout(this.resizeTimer);\n this.resizeTimer = window.setTimeout(() => {\n if (this.isConnected && this.open) this.measure();\n }, 150);\n };\n\n private readonly onClick = (e: Event): void => {\n if (\n !(e instanceof MouseEvent) ||\n e.button !== 0 ||\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey\n )\n return;\n const link = this.linkFrom(e);\n if (!link) return;\n const slides = this.collect();\n const i = slides.findIndex((s) => s.el === link);\n if (i < 0) return;\n e.preventDefault();\n this.activate(i, slides);\n };\n\n private linkFrom(e: Event): HTMLAnchorElement | null {\n for (const n of e.composedPath()) {\n if (n instanceof HTMLAnchorElement) return n;\n }\n const t = e.target;\n return t instanceof Element ? t.closest('a[href]') : null;\n }\n\n /** A visitor chose `slides[i]`. The first open pushes a history entry; a later choice replaces it. */\n private activate(i: number, slides: Slide[]): void {\n const already = this.open;\n if (already && this.index === i) return;\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.userClosed = false;\n this.pendingVersion = null;\n this.cmp?.reset();\n this.measure();\n this.open = true;\n if (this.pendingBack) {\n // Close already asked for history.back(). Writing now would push on the entry that\n // popstate is about to remove, and that pop would shut the viewer again.\n this.queuedOpen = { i, slides };\n } else if (this.urlParam) {\n const id = slides[i]?.id ?? null;\n const hashMode = usesHashParam(location.hash);\n if (already) this.writeParam(id, 'replace', hashMode);\n else {\n // The address can already carry this param (a leftover entry). Replace it away\n // on the current entry, then push, so Back still closes onto this page. Both\n // writes share hashMode: stripping `?photo` from `#chapter?photo=1` leaves\n // `#chapter`, which would otherwise fall out of the hash.\n if (paramFromLocation(this.loc(), this.urlParam))\n this.writeParam(null, 'replace', hashMode);\n this.historyPushed = this.writeParam(id, 'push', hashMode);\n }\n }\n trackEvent(this, ['uvalib-lightbox', 'open', `image ${i + 1}`, i + 1]);\n }\n\n /** Restore a viewer the URL already points at. No analytics: it is not a new action. */\n private openFromUrl(): void {\n if (this.open || this.userClosed || !this.urlParam) return;\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) return;\n const slides = this.slides.length ? this.slides : this.collect();\n const i = slides.findIndex((s) => s.id === id);\n if (i < 0) return;\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.measure();\n const version = this.versionFromUrl();\n this.pendingVersion = version;\n // Make Back close the viewer onto this page instead of leaving it. Remember the hash\n // route before the first write removes the `?` that marked it.\n const hashMode = usesHashParam(location.hash);\n this.writeParam(null, 'replace', hashMode);\n this.historyPushed = this.writeParam(id, 'push', hashMode, version);\n this.open = true;\n }\n\n private versionFromUrl(): string | null {\n return this.versionParam ? paramFromLocation(this.loc(), this.versionParam) : null;\n }\n\n private step(delta: number): void {\n const n = this.slides.length;\n if (n < 2) return;\n const i = (this.index + delta + n) % n;\n this.index = i;\n this.pendingVersion = null;\n this.trigger = this.slides[i]?.el ?? this.trigger;\n if (this.urlParam) this.writeParam(this.slides[i]?.id ?? null, 'replace');\n const action = delta < 0 ? 'previous' : 'next';\n trackEvent(this, ['uvalib-lightbox', action, `image ${i + 1}`, i + 1]);\n }\n\n /**\n * Close. `ui` is Close, Escape or the backdrop (Back when this viewer pushed, else drop the\n * param). `pop` is the browser already moving: the URL is already right. `empty` is the\n * last image leaving the page: drop the param and do not reopen from it.\n */\n private dismiss(source: 'ui' | 'pop' | 'empty'): void {\n if (this.dismissing) return;\n const dialog = this.dialogEl;\n if (!this.open && !dialog?.open) return;\n this.dismissing = true;\n this.cmp?.reset();\n try {\n const pushed = this.historyPushed;\n this.historyPushed = false;\n this.ignoreClose = true;\n this.cancelReveal();\n this.open = false;\n if (source === 'ui' || source === 'empty') this.userClosed = true;\n this.restoreDetails();\n if (dialog?.open) dialog.close();\n this.focusTrigger();\n if (source === 'ui' && this.urlParam) {\n if (pushed) {\n this.backInHash = usesHashParam(location.hash);\n this.pendingBack = true;\n history.back();\n } else this.writeParam(null, 'replace', usesHashParam(location.hash));\n } else if (source === 'empty' && this.urlParam) {\n this.pendingBack = false;\n this.queuedOpen = null;\n this.writeParam(null, 'replace', usesHashParam(location.hash));\n }\n } finally {\n // Leave `ignoreClose` set. `dialog.close()` can queue a second close event for the\n // next task; clearing the guard here lets that event dismiss a viewer that has\n // already been opened again. `reveal` clears it once `showModal` has succeeded, which\n // is still before a later Escape. A throw while restoring details must not leave the\n // viewer stuck dismissing.\n this.dismissing = false;\n }\n }\n\n /**\n * Returns false when this document cannot change the address (for example an iframe\n * srcdoc). `version` is the comparison (`version-param`), dropped with the image.\n */\n private writeParam(\n id: string | null,\n mode: 'push' | 'replace',\n hashMode?: boolean,\n version: string | null = null,\n ): boolean {\n if (!this.urlParam) return false;\n const loc = this.loc();\n let next = hrefWithParam(loc, this.urlParam, id, hashMode);\n const vp = this.versionParam;\n if (vp && vp !== this.urlParam) {\n // The path is unchanged; a search string never contains `#`.\n const rest = next.slice(loc.pathname.length);\n const h = rest.indexOf('#');\n const at = {\n pathname: loc.pathname,\n search: h < 0 ? rest : rest.slice(0, h),\n hash: h < 0 ? '' : rest.slice(h),\n };\n next = hrefWithParam(at, vp, id === null ? null : version, hashMode);\n }\n const now = location.pathname + location.search + location.hash;\n if (next === now) return false;\n const prev = history.state && typeof history.state === 'object' ? history.state : {};\n try {\n history[mode === 'push' ? 'pushState' : 'replaceState'](\n { ...prev, uvalibLightbox: this.urlParam },\n '',\n next,\n );\n return true;\n } catch {\n // A sandboxed document (an iframe srcdoc) cannot take a history entry. The viewer\n // still opens; the address is left as it is.\n return false;\n }\n }\n\n private readonly onPop = (): void => {\n if (!this.urlParam) return;\n if (this.pendingBack) {\n this.pendingBack = false;\n const queued = this.queuedOpen;\n this.queuedOpen = null;\n if (!this.isConnected || !queued) return;\n this.slides = queued.slides;\n this.index = queued.i;\n this.trigger = queued.slides[queued.i]?.el ?? null;\n this.userClosed = false;\n this.measure();\n const id = queued.slides[queued.i]?.id ?? null;\n this.historyPushed = this.writeParam(id, 'push', this.backInHash);\n if (!this.open) this.open = true;\n return;\n }\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) {\n this.historyPushed = false;\n if (this.open) this.dismiss('pop');\n return;\n }\n this.userClosed = false;\n const slides = this.collect();\n const i = slides.findIndex((s) => s.id === id);\n if (i < 0) {\n if (this.open) this.dismiss('pop');\n return;\n }\n this.pendingVersion = this.versionFromUrl();\n this.slides = slides;\n this.index = i;\n this.trigger = slides[i]?.el ?? null;\n this.historyPushed = true;\n this.measure();\n this.armReopenGuard();\n if (!this.open) this.open = true;\n };\n\n /** Ignore the close event a history traversal fires on the dialog it just opened. */\n private armReopenGuard(): void {\n this.reopenGuard = true;\n const view = this.ownerDocument.defaultView;\n if (!view) return;\n view.requestAnimationFrame(() => {\n this.reopenGuard = false;\n });\n }\n\n private readonly onKey = (e: KeyboardEvent): void => {\n if (this.typing(e)) return;\n if (this.cmp?.key(e) || !this.multiple || e.type !== 'keydown') return;\n // Left is previous in LTR and next in RTL, so the key matches the direction of the set.\n const rtl = getComputedStyle(this).direction === 'rtl';\n const back = rtl ? 'ArrowRight' : 'ArrowLeft';\n const forward = rtl ? 'ArrowLeft' : 'ArrowRight';\n if (e.key !== back && e.key !== forward) return;\n if (e.altKey || e.metaKey || e.ctrlKey) return;\n e.preventDefault();\n this.step(e.key === forward ? 1 : -1);\n };\n\n private typing(e: KeyboardEvent): boolean {\n const t = e.target;\n if (!(t instanceof HTMLElement)) return false;\n return t.isContentEditable || !!t.closest('input, textarea, select');\n }\n\n private readonly onDialogClick = (e: MouseEvent): void => {\n // A drag over the photo that ends on the backdrop is not a click on it.\n if (e.target === this.dialogEl && !this.cmp?.dragged()) this.dismiss('ui');\n };\n\n private readonly onStack = (e: PointerEvent): void => {\n this.cmp?.pointer(e);\n };\n\n /** The dialog element is stable across renders. Watch `open` on whichever node is current. */\n private bindDialogObserver(): void {\n const dialog = this.dialogEl;\n if (!dialog || dialog === this.observedDialog) return;\n this.dialogObserver?.disconnect();\n this.observedDialog = dialog;\n const observer = new MutationObserver(() => this.onNativeClose());\n observer.observe(dialog, { attributes: true, attributeFilter: ['open'] });\n this.dialogObserver = observer;\n }\n\n private readonly onDialogClose = (): void => {\n this.onNativeClose();\n };\n\n /**\n * Escape, the backdrop's close, and a direct `dialog.close()` all clear `open`. The\n * event itself is a later task; the attribute change is observable on the microtask\n * that `await updateComplete` flushes. A close that leaves the dialog open (a queued\n * event after `showModal`, or a history traversal) is not the visitor dismissing it.\n */\n private onNativeClose(): void {\n if (this.ignoreClose || this.suppressClose || !this.open) return;\n if (this.dialogEl?.open) return;\n if (this.reopenGuard) {\n const view = this.ownerDocument.defaultView;\n view?.queueMicrotask(() => {\n if (this.open && this.isConnected && !this.dialogEl?.open) this.reveal();\n });\n return;\n }\n this.dismiss('ui');\n }\n\n private readonly onFullSize = (): void => {\n const i = this.index;\n trackEvent(this, ['uvalib-lightbox', 'full-size', `image ${i + 1}`, i + 1]);\n };\n\n private get dialogEl(): HTMLDialogElement | null {\n return this.renderRoot.querySelector('dialog');\n }\n\n private get closeBtn(): HTMLButtonElement | null {\n return this.renderRoot.querySelector('button.close');\n }\n\n private get detailsBox(): HTMLElement | null {\n return this.renderRoot.querySelector('.details');\n }\n\n private focusTrigger(): void {\n const trigger = this.trigger;\n if (trigger?.isConnected) trigger.focus();\n }\n\n /**\n * Open the dialog and focus Close. `showModal` can throw while a dialog is still leaving\n * the top layer (a reopen from Back/Forward, or the first paint), so try again on the next\n * frames. Those frames are queued before a test's own `nextFrame`.\n */\n /** History restore can drop the light-DOM mount or orphan a shadow root. Put it back. */\n private ensureRoot(): void {\n const root = this.renderRoot;\n if (!this.isConnected) return;\n if (root instanceof HTMLElement && !root.isConnected) this.append(root);\n if (root instanceof ShadowRoot && this.shadowRoot && root !== this.shadowRoot) {\n (this as unknown as { renderRoot: ShadowRoot }).renderRoot = this.shadowRoot;\n this.requestUpdate();\n }\n }\n\n private cancelReveal(): void {\n const view = this.ownerDocument.defaultView;\n if (this.revealFrame && view) view.cancelAnimationFrame(this.revealFrame);\n this.revealFrame = 0;\n }\n\n private reveal(): void {\n this.ensureRoot();\n const dialog = this.dialogEl;\n if (!this.open || !dialog) return;\n const again = () => {\n if (this.revealTries++ > 8) {\n this.ignoreClose = false;\n return;\n }\n const view = this.ownerDocument.defaultView;\n if (!view) return;\n this.revealFrame = view.requestAnimationFrame(() => {\n this.revealFrame = 0;\n if (this.open) this.reveal();\n });\n };\n if (!dialog.isConnected) {\n again();\n return;\n }\n if (!dialog.open) {\n try {\n dialog.showModal();\n } catch {\n again();\n return;\n }\n }\n this.revealTries = 0;\n this.cancelReveal();\n // A close event already queued by the dialog we shut must not dismiss this open.\n // Clearing the guard here is synchronous, so Escape after this update still closes.\n this.ignoreClose = false;\n // A later reveal (a retry, or the history traversal showing the dialog again) must\n // not pull focus back to Close after the visitor has moved it inside the dialog.\n const active = this.shadowRoot?.activeElement ?? this.ownerDocument.activeElement;\n if (!active || !dialog.contains(active)) this.closeBtn?.focus();\n }\n\n /** A cached image may already be complete before the load listener runs. */\n private settleImage(): void {\n const img = this.renderRoot.querySelector('img');\n if (!img || this.status !== 'loading') return;\n if (img.complete && img.naturalWidth > 0) this.status = 'ready';\n else if (img.complete && img.getAttribute('src') && img.naturalWidth === 0)\n this.status = 'error';\n }\n\n private readonly onLoad = (): void => {\n if (this.status === 'loading') this.status = 'ready';\n };\n\n private readonly onError = (): void => {\n this.status = 'error';\n };\n\n /** Stable identity for a details element, so parking it does not look like a new one. */\n private detailTokens = new WeakMap<HTMLElement, number>();\n private detailTokenSeq = 0;\n private detailToken(el: HTMLElement): string {\n let n = this.detailTokens.get(el);\n if (n === undefined) this.detailTokens.set(el, (n = ++this.detailTokenSeq));\n return String(n);\n }\n\n /**\n * Details for the open image: `slot=\"details\"` children (honouring `data-for`) and the\n * element named by `data-details-id`. Elements already parked in the dialog stay in the\n * set, so this does not move them again.\n */\n private matchingDetails(): HTMLElement[] {\n const slide = this.current;\n const id = slide?.id ?? '';\n const position = String(this.index + 1);\n const pool: HTMLElement[] = [];\n const add = (el: HTMLElement | null) => {\n if (el && el !== this && !pool.includes(el)) pool.push(el);\n };\n for (const el of this.querySelectorAll(':scope > [slot=\"details\"]')) {\n if (el instanceof HTMLElement) add(el);\n }\n for (const item of this.parked) add(item.el);\n if (slide?.detailsId) add(this.scope.getElementById(slide.detailsId));\n return pool.filter((el) => {\n if (el.getAttribute('slot') === 'details') {\n const f = el.getAttribute('data-for');\n return !f || f === id || f === position;\n }\n return !!slide?.detailsId && el.id === slide.detailsId;\n });\n }\n\n private placeDetails(): void {\n const want = this.matchingDetails();\n const key = `${want.map((el) => this.detailToken(el)).join('|')}@${this.index}`;\n if (key === this.parkedKey) return;\n const keep = new Set(want);\n const still: typeof this.parked = [];\n for (const item of this.parked) {\n if (keep.has(item.el) && this.detailsBox?.contains(item.el)) still.push(item);\n else this.putBack(item);\n }\n this.parked = still;\n const box = this.detailsBox;\n if (box) {\n for (const el of want) {\n if (box.contains(el)) continue;\n const parent = el.parentNode;\n if (!parent) continue;\n this.parked.push({ el, parent, next: el.nextSibling, hidden: el.hidden });\n el.hidden = false;\n box.append(el);\n }\n }\n this.parkedKey = key;\n }\n\n /**\n * Put a parked element back. Restoring later siblings first keeps `next` inside `parent`;\n * if it is not (it was parked too), insert at the end instead of throwing NotFoundError.\n */\n private putBack(item: (typeof this.parked)[number]): void {\n item.el.hidden = item.hidden;\n const next = item.next?.parentNode === item.parent ? item.next : null;\n item.parent.insertBefore(item.el, next);\n }\n\n private restoreDetails(): void {\n for (let i = this.parked.length - 1; i >= 0; i--) this.putBack(this.parked[i]!);\n this.parked = [];\n this.parkedKey = '';\n this.returnList();\n }\n\n /** The list the open image shows (none while its image cannot be drawn). */\n private get wantedList(): RegionsListElement | null {\n if (!this.open) return null;\n const list = this.current?.list ?? null;\n return list && this.displaySrc ? list : null;\n }\n\n /**\n * Lend the open image's list to the viewer, giving back any other. Shadow mode (before\n * render): the list becomes a light-DOM child of the lightbox with `slot`, and the viewer's\n * `<uvalib-image-regions>` slots it on, so it stays in the page (its styles and listeners\n * apply). Light DOM (`rendered`, after render): it is moved into `<uvalib-image-regions>`.\n */\n private lendList(rendered = false): void {\n const want = this.wantedList;\n if (this.lent && this.lent.el !== want) this.returnList();\n if (!want) return;\n if (this.isLight && !rendered) return;\n const target: Element | null = this.isLight\n ? this.renderRoot.querySelector('uvalib-image-regions')\n : this;\n if (!target || want.parentNode === target) return;\n if (!this.lent) {\n const parent = want.parentNode;\n if (!parent) return;\n this.lent = {\n el: want,\n parent,\n next: want.nextSibling,\n hidden: want.hidden,\n slot: want.getAttribute('slot'),\n };\n }\n this.noteEntries();\n if (this.isLight) want.removeAttribute('slot');\n else want.setAttribute('slot', LIST_SLOT);\n want.hidden = false;\n target.append(want);\n }\n\n /** Remember each entry's own tabindex before the viewer can add one. */\n private noteEntries(): void {\n const list = this.lent?.el;\n if (!list) return;\n for (const li of list.children) {\n if (!this.entryTabindex.has(li)) this.entryTabindex.set(li, li.getAttribute('tabindex'));\n }\n }\n\n /** Give the lent list back: same place, same `hidden` and `slot`, no marks of the viewer's. */\n private returnList(): void {\n const lent = this.lent;\n if (!lent) return;\n this.lent = null;\n const { el } = lent;\n const active = this.shadowRoot?.activeElement ?? this.ownerDocument.activeElement;\n // Focus in the list would be lost with it; Close takes it while the viewer stays open.\n if (this.open && active && el.contains(active)) this.refocus = true;\n for (const li of el.children) {\n for (const name of ENTRY_MARKS) li.removeAttribute(name);\n if (this.entryTabindex.has(li)) {\n const was = this.entryTabindex.get(li);\n if (was == null) li.removeAttribute('tabindex');\n else li.setAttribute('tabindex', was);\n }\n }\n this.entryTabindex = new WeakMap();\n if (lent.slot == null) el.removeAttribute('slot');\n else el.setAttribute('slot', lent.slot);\n el.hidden = lent.hidden;\n const next = lent.next?.parentNode === lent.parent ? lent.next : null;\n lent.parent.insertBefore(el, next);\n }\n\n private get statusText(): string {\n if (!this.open) return '';\n if (this.status === 'loading') return 'Loading image.';\n if (this.status === 'error') return 'This image could not be loaded.';\n return '';\n }\n\n private readonly toggleRegions = (): void => {\n this.showRegions = !this.showRegions;\n };\n\n /**\n * The image, inside `<uvalib-image-regions>` when it has regions (or the page's list). An\n * image with versions sits in a `.stack` (the same element before and after the comparison\n * loads, so the image is not loaded again), with the comparison's layers over it and its\n * controls under it.\n */\n private renderImage(slide: Slide, src: string, regions: ImageRegion[] | null) {\n const outlined = !!(regions || slide.list);\n const cmp = slide.versions && this.cmp?.active ? this.cmp : null;\n let img = html`<img\n part=\"image\"\n slot=${outlined && !slide.versions ? 'image' : nothing}\n alt=${cmp ? cmp.alt(slide.alt) : slide.alt}\n src=${src}\n aria-busy=${this.status === 'loading' ? 'true' : 'false'}\n @load=${this.onLoad}\n @error=${this.onError}\n />`;\n let controls: unknown = nothing;\n if (slide.versions) {\n img = html`<div\n class=\"stack ${cmp?.stackClass ?? ''}\"\n slot=${outlined ? 'image' : nothing}\n style=${cmp?.stackStyle ?? nothing}\n @pointerdown=${this.onStack}\n @pointermove=${this.onStack}\n @pointerup=${this.onStack}\n @pointercancel=${this.onStack}\n >\n ${img}${cmp ? cmp.layers() : nothing}\n </div>`;\n if (cmp) controls = cmp.controls(outlined ? 'controls' : '');\n }\n if (!outlined) return html`${img}${controls}`;\n // The page's list: slotted on from the lightbox's light DOM (shadow mode), or moved in\n // after render (light DOM).\n const list = slide.list && !this.isLight ? html`<slot name=${LIST_SLOT}></slot>` : nothing;\n return html`<uvalib-image-regions\n class=\"regions\"\n part=\"regions\"\n .items=${slide.list ? null : regions}\n label=${normalize(this.regionsLabel) || 'Regions'}\n image-width=${slide.imageWidth ?? nothing}\n image-height=${slide.imageHeight ?? nothing}\n ?hide-outlines=${!this.showRegions}\n ?no-style=${this.noStyle}\n >${img}${controls}${list}</uvalib-image-regions\n >`;\n }\n\n protected override render() {\n const slide = this.open ? this.current : undefined;\n const src = slide ? this.displaySrc : '';\n const full = slide && usableImageUrl(slide.href, this.base) ? slide.href : '';\n const fullLinks = full && slide?.versions && this.cmp?.active ? this.cmp.full() : null;\n const shown = this.statusText;\n const regions = slide?.regions.length ? slide.regions : null;\n const outlined = !!(regions || slide?.list);\n const counter = this.multiple\n ? html`<p class=\"count\" aria-live=\"polite\">${this.index + 1} of ${this.slides.length}</p>`\n : nothing;\n // Shadow mode needs a slot or the author's links are not rendered and cannot take focus.\n // Light mode renders into `.viewer`; a `<slot>` there would not show the siblings.\n return html`\n ${this.isLight ? nothing : html`<slot></slot><slot name=\"details\" hidden></slot>`}\n <dialog\n part=\"dialog\"\n aria-labelledby=${this.captionId}\n @click=${this.onDialogClick}\n @close=${this.onDialogClose}\n @keydown=${this.onKey}\n @keyup=${this.onKey}\n >\n <div class=\"panel\" part=\"panel\">\n <div class=\"head\">\n <p class=\"caption\" part=\"caption\" id=${this.captionId}>${slide?.caption ?? 'Image'}</p>\n <button type=\"button\" class=\"close\" autofocus @click=${() => this.dismiss('ui')}>\n Close\n </button>\n </div>\n <figure class=\"figure\">${src ? this.renderImage(slide!, src, regions) : nothing}</figure>\n <p class=\"status ${shown ? '' : 'visually-hidden'}\" role=\"status\">${shown}</p>\n <div class=\"toolbar\" part=\"controls\">\n ${\n outlined && src\n ? html`<button\n type=\"button\"\n class=\"regions-toggle\"\n aria-pressed=${this.showRegions ? 'true' : 'false'}\n @click=${this.toggleRegions}\n >\n Show regions\n </button>`\n : nothing\n }\n ${\n this.multiple\n ? html`<button type=\"button\" class=\"prev\" @click=${() => this.step(-1)}>\n Previous\n </button>\n <button type=\"button\" class=\"next\" @click=${() => this.step(1)}>Next</button>\n ${counter}`\n : nothing\n }\n ${(fullLinks ?? (full ? [{ href: full, label: '' }] : [])).map(\n (link) =>\n html`<a\n class=\"full\"\n href=${link.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n @click=${this.onFullSize}\n >Full size${link.label ? `, ${link.label}` : ''}<span class=\"visually-hidden\">\n (opens in a new tab)</span\n ></a\n >`,\n )}\n </div>\n <div class=\"details\" part=\"details\"></div>\n </div>\n </dialog>\n `;\n }\n}\n","import { define } from '../../base/define.js';\nimport { UvalibLightbox } from './UvalibLightbox.js';\n\ndefine('uvalib-lightbox', UvalibLightbox);\n"],"mappings":";;;;;;AAOA,IAAMqB,IAAS,kDACTC,IAAW,mBACXC,IAAU,+EAEVC,IAAgB,4BAEhBC,IAAa;AAgBnB,SAAgBC,EAAU,GAAc,GAAkC;CACxE,IAAIC;CACJ,IAAI;EACF,IAAM,IAAI,IAAIC,GAAMC,CAAI;CAC1B,QAAQ;EACN,OAAO;CACT;CACA,IAAIF,EAAI,aAAa,WAAWA,EAAI,aAAa,UAAU,OAAO;CAClE,IAAMG,IAAQH,EAAI,SAAS,MAAM,GAAG;CACpC,IAAIG,EAAM,SAAS,GAAG,OAAO;CAC7B,IAAMC,IAAOD,EAAMA,EAAM,SAAS,MAAM,IAClCE,IAAWF,EAAMA,EAAM,SAAS,MAAM,IACtCG,IAASH,EAAMA,EAAM,SAAS,MAAM;CAE1C,OADI,CAACP,EAAQ,KAAKQ,CAAI,KAAK,CAACT,EAAS,KAAKU,CAAQ,KAAK,CAACX,EAAO,KAAKY,CAAM,IAAU,OAC7E;EAAE;EAAK;EAAO,aAAaH,EAAM,SA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,gBAAA,KAAA,CAAA,GAOvC1D,EAAA,CAAAC,EAAS,EAAE,WAAW,GAAM,CAAC,CAAA,GAAAyD,EAAA,WAAA,YAAA,KAAA,CAAA,GAO7B1D,EAAA,CAAAC,EAAS,CAAA,GAAAyD,EAAA,WAAA,WAAA,KAAA,CAAA,GAOT1D,EAAA,CAAAC,EAAS,EAAE,WAAW,gBAAgB,CAAC,CAAA,GAAAyD,EAAA,WAAA,gBAAA,KAAA,CAAA,GAEvC1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,UAAA,KAAA,CAAA,GACN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,SAAA,KAAA,CAAA,GACN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,QAAA,KAAA,CAAA,GACN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,UAAA,KAAA,CAAA,GACN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,QAAA,KAAA,CAAA,GACN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,QAAA,KAAA,CAAA,GAEN1D,EAAA,CAAAE,EAAM,CAAA,GAAAwD,EAAA,WAAA,eAAA,KAAA,CAAA,GC5YTnD,EAAO,mBAAmBmD,CAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uvalib/web-components",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "UVA Library reusable web components",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -224,7 +224,7 @@ import '@uvalib/web-components/tokens.css'; // optional: tokens for your own CSS
224
224
 
225
225
  Analytics: only when the site needs Matomo, set `<site-page matomo-id="N">`, or add `site-analytics.js` and a `<site-analytics matomoid="N">` (add `downloads="event"`, or `matomo-downloads="event"` on `<site-page>`, when file URLs carry ids: downloads are then counted as `['download', '<extension>']` events without URLs); see the analytics page in [reference/snippets.md](reference/snippets.md). `<uvalib-analytics>` (`uvalib-analytics.js`) is the same element under its original name, for existing markup. It listens on `document` for `uvalib-analytics-*` and `site-analytics-*` events (`event`, `search`, `pageview`, `content`) and queues them for Matomo, so events fired before Matomo loads are kept, and a page never counts twice. A single-page app whose router uses `pushState` or hashes can set `spa="auto"` to have each route change counted (after the new title is set, never twice for one URL); bare `spa` means the app sends its own `uvalib-analytics-pageview` events.
226
226
 
227
- The library's components already report what visitors do with them; do not add tracking for any of it: header utility and site links, logo, skip link, Menu and colour scheme; main-nav menu opens and links; footer links; breadcrumb and contents levels, the contents disclosure, Copy citation; card clicks (the card's place in its grid, or single); pager next, previous, page numbers and Load more; tab changes (the tab's label); alerts (impressions, dismiss, links, errors); event clicks; See all hours, week changes; filter facets, scopes and See more/less; date-range changes; histogram selections (`<from>–<to>` when both ends are ISO dates, otherwise `other`); bento searches, result and See all clicks, retries; lightbox opens, next, previous and full size (the name is `image N`, never the URL or the caption); load errors; and tag-list clicks and Show all (`list N`, or the label with `track-label`, and the tag's place; never the tag text); and combobox choices and clears (the field's label and the suggestion's place; never the typed text or the suggestion); and image-region outline clicks (the list's label and the region's number; never a region's label); and map marker choices and zoom-button presses (the map's label and the place's position or the zoom level; never the place's name, coordinates or URL). `<uvalib-photo-grid>` and `<uvalib-results-count>` report nothing. The README's "Analytics" section has the full table.
227
+ The library's components already report what visitors do with them; do not add tracking for any of it: header utility and site links, logo, skip link, Menu and colour scheme; main-nav menu opens and links; footer links; breadcrumb and contents levels, the contents disclosure, Copy citation; card clicks (the card's place in its grid, or single); pager next, previous, page numbers and Load more; tab changes (the tab's label); alerts (impressions, dismiss, links, errors); event clicks; See all hours, week changes; filter facets, scopes and See more/less; date-range changes; histogram selections (`<from>–<to>` when both ends are ISO dates, otherwise `other`); bento searches, result and See all clicks, retries; lightbox opens, next, previous and full size (the name is `image N`, never the URL or the caption) and version comparisons (`compare`, the mode and the version's place, never its label); load errors; and tag-list clicks and Show all (`list N`, or the label with `track-label`, and the tag's place; never the tag text); and combobox choices and clears (the field's label and the suggestion's place; never the typed text or the suggestion); and image-region outline clicks (the list's label and the region's number; never a region's label); and map marker choices and zoom-button presses (the map's label and the place's position or the zoom level; never the place's name, coordinates or URL). `<uvalib-photo-grid>` and `<uvalib-results-count>` report nothing. The README's "Analytics" section has the full table.
228
228
 
229
229
  For the host page's own content, tag the clickable element (or a wrapper) with `data-uvalib-track="category,action[,name[,value]]"` instead of writing a listener, for example `<a href="/spaces" data-uvalib-track="home-page,banner-click,Study spaces">`: the category is your page or widget, the action a fixed kebab-case verb, the name a short fixed label, the value a number. It works inside shadow DOM too. Never put titles, URLs, search text, ids, email addresses, phone numbers or other personal data in events.
230
230
 
@@ -722,6 +722,7 @@ Use these instead of a hand-built gallery or a carousel. There is no autoplay.
722
722
  - Details: a child with `slot="details"` (`data-for` selects one item by id or position from 1; without it the details show for every image), or `data-details-id` on a link naming an element elsewhere. It is put back when the viewer moves on or closes.
723
723
  - `<uvalib-image-regions>` from `uvalib-image-regions.js`: numbered outlines on an image (people, objects, inscriptions) with a list of the same regions beside it. Write the page's own `<img width height alt>` and `<ol>` inside, each `<li data-xywh="percent:x,y,w,h">` (or pixels of the natural size, `160,120,320,240`; `image-width`/`image-height` for a IIIF derivative) holding the region's link and your own action buttons, which stay yours; or set `items` (`{ label, x, y, w, h, unit?, href?, description? }[]`). The list is the accessible route: the outlines are `aria-hidden`, not tab stops, and never the only place a name or action is; hovering or focusing an entry highlights its outline (thicker double outline and label) and back, and clicking an outline focuses its entry. `label` names the list. Listen for `uvalib-image-regions-activate` (an outline clicked, before its entry takes focus; `detail: { index, item, entry }`, `entry` the page's own `<li>`; cancelable, so the page can focus its own control in the entry, such as a "Who is this?" field) and `highlight`; never read the shadow DOM's outlines for it. Do not hand-build absolutely positioned outlines. It reports outline clicks itself (the list's label and the number, never a region's label).
724
724
  - Regions in the viewer: `data-regions` on a lightbox link (a JSON array, or `percent:10,20,30,40 Person 1; percent:55,15,20,30 Sign`), or the lightbox's `regions` callback (`({ element, id, href, index }) => regions`). The open image then shows the outlines, their list and a "Show regions" toggle; `regions-label` names the list. For your own buttons in each entry, `data-regions-list="<id>"` (or the `regionsList` callback) names a hidden `<ol>` of `<li data-xywh>` in the page: it is lent to the viewer (same nodes, your listeners and CSS keep working) and put back on close; give each action a unique name ("Confirm Tim Kaine").
725
+ - Versions in the viewer: `data-versions='[{"label":"Original"},{"label":"AI colorization","href":"color.jpg","note":"The colours are an AI model’s guess."}]'` on a lightbox link (first entry = the link's image; or the `versions` callback) compares them over the photo, the comparison loaded on first use: Switch (default), Reveal (`compare="wipe"`, a divider: click the photo or the slider) or Fade; label AI versions as such and give them a `note`; `version-param` (with `url-param`) keeps `?version=wipe:40`; `uvalib-lightbox-version` reports changes.
725
726
  - `<uvalib-photo-grid>` from `uvalib-photo-grid.js`: justified rows. Each direct `<a href>` or `<button>` is one photo and stays a real control. The row is about 220px, and 140px at 767px and below, unless `row-height` is set (a bare number is pixels). Give each image `width` and `height` so the row does not jump when it loads. An image with no visible text gets a caption from its alt, and a repeated alt is cleared (the original is kept for a lightbox). A different alt is kept. Do not set an `aria-label` that differs from the visible text; the grid will not add a caption beside one. Generated "Photo N" captions renumber when the photos change order. A `<span slot="badge">` inside the item, or `data-badge` on it (“seq”, “3 photos”), is drawn over the thumbnail and stays in the accessible name; an existing `aria-label` gains the badge text. A grid inside a lightbox opens the viewer. The grid reports no analytics.
726
727
 
727
728
  ```html snippet
@@ -1102,6 +1102,7 @@ An image with numbered region outlines (people, objects, inscriptions) and a lis
1102
1102
  |---|---|
1103
1103
  | (default) | The region list (`<ol>` with `<li data-xywh>`), shown as written. Not used with `items`. |
1104
1104
  | `image` | The image. A first `<img>` or `<picture>` child is put here by itself. |
1105
+ | `controls` | Controls for the image (a lightbox's version comparison), under the image and before the list in reading order. Not covered by the outlines. |
1105
1106
 
1106
1107
  ### CSS parts
1107
1108
 
@@ -1134,7 +1135,7 @@ An image with numbered region outlines (people, objects, inscriptions) and a lis
1134
1135
 
1135
1136
  ## `<uvalib-lightbox>`
1136
1137
 
1137
- An accessible image viewer over a set of plain links. With JavaScript a primary click opens a modal dialog; without it (or with a modified click) the link opens the image as before. Wrap the links, or point at them with `selector` (for example `a.pb-image` on a reading page). There is no autoplay and no carousel. The dialog is labelled by the caption (`data-caption`, else the image alt, else the link text). Focus moves to Close on open and back to the trigger on close. Escape and a click on the backdrop close it. With more than one image, Previous and Next and the arrow keys move through the set (wrapping), and a polite “3 of 13” counter is shown. Full size opens the original image in a new tab. A IIIF Image API URL keeps its region; only the size becomes `!W,H` for the viewport. TIFF and JPEG2000 URLs are left as written. `url-param` (for example `photo`) keeps `?photo=<id>` in sync, including on a hash route (`#/text?photo=<id>`): opening pushes a history entry, stepping replaces it, and Back closes. Optional details: children with `slot="details"` (and `data-for` equal to the item's id or its position from 1; without `data-for` they show for every image), or `data-details-id` on a link pointing at an element elsewhere on the page. Either is shown inside the dialog and put back when the viewer moves on or closes. Optional regions (people, objects, inscriptions): `data-regions` on a link, a JSON array of `{ label, x, y, w, h, unit? }` or `xywh` values each followed by its label, separated by `;` (`percent:10,20,30,40 Person 1; percent:55,15,20,30 Sign`), or the `regions` callback. The open image then shows numbered outlines (`<uvalib-image-regions>`, loaded on first use) and a list of the regions beside it, with a "Show regions" toggle (`aria-pressed`) that hides the outlines. Pixel regions are measured in `data-image-width` × `data-image-height` when set (the viewer shows a resized IIIF image), else in the image's natural size. Or the page's own list, with its own buttons: `data-regions-list="<id>"` on a link (or the `regionsList` callback) names an `<ol>` or `<ul>` of `<li data-xywh>` anywhere in the page, usually `hidden`. While that image is open the list (the same nodes, so the page's listeners keep working) is the region list: in shadow mode it becomes a child of the lightbox slotted into the viewer, not moved into the shadow root, so the page's CSS still applies to it. When the image changes or the viewer closes it goes back where it was, `hidden` as before. It wins over `data-regions`.
1138
+ An accessible image viewer over a set of plain links. With JavaScript a primary click opens a modal dialog; without it (or with a modified click) the link opens the image as before. Wrap the links, or point at them with `selector` (for example `a.pb-image` on a reading page). There is no autoplay and no carousel. The dialog is labelled by the caption (`data-caption`, else the image alt, else the link text). Focus moves to Close on open and back to the trigger on close. Escape and a click on the backdrop close it. With more than one image, Previous and Next and the arrow keys move through the set (wrapping), and a polite “3 of 13” counter is shown. Full size opens the original image in a new tab. A IIIF Image API URL keeps its region; only the size becomes `!W,H` for the viewport. TIFF and JPEG2000 URLs are left as written. `url-param` (for example `photo`) keeps `?photo=<id>` in sync, including on a hash route (`#/text?photo=<id>`): opening pushes a history entry, stepping replaces it, and Back closes. Optional details: children with `slot="details"` (and `data-for` equal to the item's id or its position from 1; without `data-for` they show for every image), or `data-details-id` on a link pointing at an element elsewhere on the page. Either is shown inside the dialog and put back when the viewer moves on or closes. Optional regions (people, objects, inscriptions): `data-regions` on a link, a JSON array of `{ label, x, y, w, h, unit? }` or `xywh` values each followed by its label, separated by `;` (`percent:10,20,30,40 Person 1; percent:55,15,20,30 Sign`), or the `regions` callback. The open image then shows numbered outlines (`<uvalib-image-regions>`, loaded on first use) and a list of the regions beside it, with a "Show regions" toggle (`aria-pressed`) that hides the outlines. Pixel regions are measured in `data-image-width` × `data-image-height` when set (the viewer shows a resized IIIF image), else in the image's natural size. Or the page's own list, with its own buttons: `data-regions-list="<id>"` on a link (or the `regionsList` callback) names an `<ol>` or `<ul>` of `<li data-xywh>` anywhere in the page, usually `hidden`. While that image is open the list (the same nodes, so the page's listeners keep working) is the region list: in shadow mode it becomes a child of the lightbox slotted into the viewer, not moved into the shadow root, so the page's CSS still applies to it. When the image changes or the viewer closes it goes back where it was, `hidden` as before. It wins over `data-regions`. Optional versions of an image (an original scan and an AI colorization, a restoration, an infrared capture): `data-versions` on a link, a JSON array of `{ label, href?, note? }` whose first entry is the link's own image, or the `versions` callback. The viewer then compares them over the photo (loaded on first use): Switch (a segmented control), Reveal (a divider: click or tap the photo, or use the slider) or Fade (a slider), `compare` choosing the first. A version's `note` shows under the photo while it is visible, and the image's accessible name ends with the label of the version shown. `version-param` (with `url-param`) keeps the comparison in the address: `?version=2` (Switch, the version from 0), `?version=wipe:40` or `?version=fade:60` (the percentage of the other version shown; `wipe:40:2` compares the original with version 2).
1138
1139
 
1139
1140
  ### Attributes
1140
1141
 
@@ -1143,6 +1144,8 @@ An accessible image viewer over a set of plain links. With JavaScript a primary
1143
1144
  | `selector` | `string` | `''` | CSS selector for image links elsewhere in this root (the page, or the shadow root the component sits in). Combined with any links inside the component. Example: `a.pb-image`. |
1144
1145
  | `url-param` | `string` | `''` | Query parameter kept in sync with the open image, for example `photo` → `?photo=<id>`. The id is the link's `data-id`, else its `id`, else the IIIF identifier, else its position from 1. On a hash route the parameter is written inside the hash. Empty: no deep link. |
1145
1146
  | `regions-label` | `string` | `'Regions'` | The heading of the regions list (for example `People`). |
1147
+ | `compare` | `'switch' \| 'wipe' \| 'fade'` | `'switch'` | How an image's versions are compared first: `switch` (default: one at a time, any number of versions), `wipe` (a divider over the photo) or `fade` (a cross-fade). The viewer offers the others. |
1148
+ | `version-param` | `string` | `''` | Query parameter for the comparison (with `url-param`), for example `version`: `?version=1`, `?version=wipe:40`, `?version=fade:60`. Written with replaceState once the visitor's change settles; read when the viewer opens from the address. |
1146
1149
  | `no-shadow-dom` | `boolean` | `false` | |
1147
1150
  | `no-style` | `boolean` | `false` | |
1148
1151
 
@@ -1164,12 +1167,14 @@ An accessible image viewer over a set of plain links. With JavaScript a primary
1164
1167
  | `controls` | Previous, Next, the counter and Full size. |
1165
1168
  | `details` | The details panel. |
1166
1169
  | `regions` | The `<uvalib-image-regions>` around an image with regions. |
1170
+ | `compare` | The version comparison controls and notes under the photo. |
1167
1171
 
1168
1172
  ### Events
1169
1173
 
1170
1174
  | Event | Description |
1171
1175
  |---|---|
1172
- | `uvalib-analytics-event` | For `<site-analytics>`: `['uvalib-lightbox', 'open'\|'next'\|'previous'\|'full-size', 'image N', N]` (N from 1, the image's place in the set). Never the URL or the caption. Not fired for a viewer restored from the URL or from Back and Forward. Bubbles and is composed. |
1176
+ | `uvalib-lightbox-version` | The visitor changed the comparison (mode, version or position; once a slider settles): `detail` is `{ id, mode, index, value }` (`mode` `switch`, `wipe` or `fade`; `index` the version shown or compared, from 0; `value` the percentage of it shown, null for Switch). Not fired on open or for a comparison restored from the URL. Bubbles and is composed. |
1177
+ | `uvalib-analytics-event` | For `<site-analytics>`: `['uvalib-lightbox', 'open'\|'next'\|'previous'\|'full-size', 'image N', N]` (N from 1, the image's place in the set), and `['uvalib-lightbox', 'compare', 'switch'\|'wipe'\|'fade', N]` when the visitor changes a comparison (N the version's place from 1; once a slider settles). Never the URL, the caption or a version's label. Not fired for a viewer restored from the URL or from Back and Forward. Bubbles and is composed. |
1173
1178
 
1174
1179
  ### CSS custom properties
1175
1180