@uvalib/web-components 1.7.0 → 1.8.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.
Files changed (105) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +56 -12
  3. package/dist/base/states.d.ts +12 -0
  4. package/dist/base/states.js +33 -0
  5. package/dist/base/states.js.map +1 -0
  6. package/dist/base.css +15 -5
  7. package/dist/components/bento-box/BentoBox.js +1 -0
  8. package/dist/components/bento-box/BentoBox.js.map +1 -1
  9. package/dist/components/events-section/EventsSection.js +1 -0
  10. package/dist/components/events-section/EventsSection.js.map +1 -1
  11. package/dist/components/library-hours/hours-data.js +1 -1
  12. package/dist/components/library-hours/hours-data.js.map +1 -1
  13. package/dist/components/library-weekly-hours/LibraryWeeklyHours.js +1 -0
  14. package/dist/components/library-weekly-hours/LibraryWeeklyHours.js.map +1 -1
  15. package/dist/components/uvalib-card/UvalibCard.js +6 -0
  16. package/dist/components/uvalib-card/UvalibCard.js.map +1 -1
  17. package/dist/components/uvalib-combobox/UvalibCombobox.d.ts +27 -0
  18. package/dist/components/uvalib-combobox/UvalibCombobox.js +85 -1
  19. package/dist/components/uvalib-combobox/UvalibCombobox.js.map +1 -1
  20. package/dist/components/uvalib-contents/UvalibContents.js +5 -0
  21. package/dist/components/uvalib-contents/UvalibContents.js.map +1 -1
  22. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.d.ts +6 -0
  23. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js +10 -0
  24. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js.map +1 -1
  25. package/dist/components/uvalib-image-regions/UvalibImageRegions.js +2 -0
  26. package/dist/components/uvalib-image-regions/UvalibImageRegions.js.map +1 -1
  27. package/dist/components/uvalib-image-regions/regions.d.ts +6 -2
  28. package/dist/components/uvalib-image-regions/regions.js +6 -3
  29. package/dist/components/uvalib-image-regions/regions.js.map +1 -1
  30. package/dist/components/uvalib-lightbox/UvalibLightbox.d.ts +9 -2
  31. package/dist/components/uvalib-lightbox/UvalibLightbox.js +23 -3
  32. package/dist/components/uvalib-lightbox/UvalibLightbox.js.map +1 -1
  33. package/dist/components/uvalib-lightbox/compare.d.ts +30 -3
  34. package/dist/components/uvalib-lightbox/compare.js +98 -29
  35. package/dist/components/uvalib-lightbox/compare.js.map +1 -1
  36. package/dist/components/uvalib-map/UvalibMap.js +2 -2
  37. package/dist/components/uvalib-map/UvalibMap.js.map +1 -1
  38. package/dist/components/uvalib-metadata/UvalibMetadata.js +3 -0
  39. package/dist/components/uvalib-metadata/UvalibMetadata.js.map +1 -1
  40. package/dist/components/uvalib-pagefind-search/UvalibPagefindSearch.js +3 -1
  41. package/dist/components/uvalib-pagefind-search/UvalibPagefindSearch.js.map +1 -1
  42. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.d.ts +3 -3
  43. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.js +16 -8
  44. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.js.map +1 -1
  45. package/dist/components/uvalib-tag-list/UvalibTagList.d.ts +4 -1
  46. package/dist/components/uvalib-tag-list/UvalibTagList.js +9 -2
  47. package/dist/components/uvalib-tag-list/UvalibTagList.js.map +1 -1
  48. package/dist/custom-elements.json +1926 -1637
  49. package/dist/styles/message.js +4 -0
  50. package/dist/styles/message.js.map +1 -1
  51. package/dist/styles/result-list.js +25 -4
  52. package/dist/styles/result-list.js.map +1 -1
  53. package/dist/styles/results.js +17 -2
  54. package/dist/styles/results.js.map +1 -1
  55. package/dist-cdn/base.css +15 -5
  56. package/dist-cdn/bento-box.js +1 -0
  57. package/dist-cdn/bento-box.js.map +1 -1
  58. package/dist-cdn/chunks/{compare-DV6ltvsJ.js → compare-C0nhByn7.js} +66 -29
  59. package/dist-cdn/chunks/compare-C0nhByn7.js.map +1 -0
  60. package/dist-cdn/chunks/{hours-data-Bw6vkIw7.js → hours-data-gMu5uT7H.js} +2 -2
  61. package/dist-cdn/chunks/hours-data-gMu5uT7H.js.map +1 -0
  62. package/dist-cdn/chunks/{library-weekly-hours-CrV3TlP5.js → library-weekly-hours-BJgxAyah.js} +3 -2
  63. package/dist-cdn/chunks/library-weekly-hours-BJgxAyah.js.map +1 -0
  64. package/dist-cdn/chunks/{regions-B8ExwUGP.js → regions-B-rOwa-v.js} +15 -15
  65. package/dist-cdn/chunks/regions-B-rOwa-v.js.map +1 -0
  66. package/dist-cdn/chunks/states-DGXGzcte.js +17 -0
  67. package/dist-cdn/chunks/states-DGXGzcte.js.map +1 -0
  68. package/dist-cdn/custom-elements.json +1926 -1637
  69. package/dist-cdn/events-section.js +1 -0
  70. package/dist-cdn/events-section.js.map +1 -1
  71. package/dist-cdn/library-hours-setup.js +1 -1
  72. package/dist-cdn/library-weekly-hours.js +1 -1
  73. package/dist-cdn/manifest.json +1 -1
  74. package/dist-cdn/site-hours-section.js +1 -1
  75. package/dist-cdn/skills/uvalib-web-components/SKILL.md +5 -4
  76. package/dist-cdn/skills/uvalib-web-components/reference/components.md +33 -6
  77. package/dist-cdn/uvalib-card.js +6 -0
  78. package/dist-cdn/uvalib-card.js.map +1 -1
  79. package/dist-cdn/uvalib-combobox.js +107 -68
  80. package/dist-cdn/uvalib-combobox.js.map +1 -1
  81. package/dist-cdn/uvalib-contents.js +5 -0
  82. package/dist-cdn/uvalib-contents.js.map +1 -1
  83. package/dist-cdn/uvalib-filter-drawer.js +27 -25
  84. package/dist-cdn/uvalib-filter-drawer.js.map +1 -1
  85. package/dist-cdn/uvalib-image-regions.js +3 -1
  86. package/dist-cdn/uvalib-image-regions.js.map +1 -1
  87. package/dist-cdn/uvalib-lightbox.js +80 -69
  88. package/dist-cdn/uvalib-lightbox.js.map +1 -1
  89. package/dist-cdn/uvalib-map.js +2 -2
  90. package/dist-cdn/uvalib-map.js.map +1 -1
  91. package/dist-cdn/uvalib-metadata.js +3 -0
  92. package/dist-cdn/uvalib-metadata.js.map +1 -1
  93. package/dist-cdn/uvalib-pagefind-search.js +2 -1
  94. package/dist-cdn/uvalib-pagefind-search.js.map +1 -1
  95. package/dist-cdn/uvalib-photo-grid.js +4 -5
  96. package/dist-cdn/uvalib-photo-grid.js.map +1 -1
  97. package/dist-cdn/uvalib-tag-list.js +21 -16
  98. package/dist-cdn/uvalib-tag-list.js.map +1 -1
  99. package/package.json +1 -1
  100. package/skills/uvalib-web-components/SKILL.md +5 -4
  101. package/skills/uvalib-web-components/reference/components.md +33 -6
  102. package/dist-cdn/chunks/compare-DV6ltvsJ.js.map +0 -1
  103. package/dist-cdn/chunks/hours-data-Bw6vkIw7.js.map +0 -1
  104. package/dist-cdn/chunks/library-weekly-hours-CrV3TlP5.js.map +0 -1
  105. package/dist-cdn/chunks/regions-B8ExwUGP.js.map +0 -1
@@ -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","DETAILS_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","k","found","detailRoots","noteDetails","a","el","candidates","push","owner","unique","pos","img","alt","text","caption","index","list","regions","raw","m","value","more","ref","walk","item","options","type","already","hashMode","track","version","delta","action","was","fromUi","source","pushed","focus","reason","loc","vp","rest","now","prev","mode","observer","trigger","first","again","active","position","pool","add","f","want","key","keep","still","box","parent","slotted","rendered","target","li","lent","name","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/** The slot (shadow mode) a `data-details-id` element is lent to while its image is open. */\nconst DETAILS_SLOT = 'uvalib-details';\n\n/** Why the viewer closed, in `uvalib-lightbox-close`. */\nexport type LightboxCloseReason = 'close' | 'api' | 'history' | 'empty';\n\n/** `detail` of `uvalib-lightbox-open`. */\nexport interface LightboxOpenDetail {\n /** The item's id (as `url-param` writes it). */\n id: string;\n /** Its place in the set, from 0. */\n index: number;\n /** True when the viewer was restored from the address (a reload, Back or Forward). */\n restored: boolean;\n}\n\n/** `detail` of `uvalib-lightbox-close`. */\nexport interface LightboxCloseDetail {\n /** The item that was shown. */\n id: string;\n /** Its place in the set, from 0. */\n index: number;\n /**\n * `close` (Close, Escape or the backdrop), `api` (`close()`), `history` (Back or Forward)\n * or `empty` (the last image left the page).\n */\n reason: LightboxCloseReason;\n}\n\n/** Options for `close()`. */\nexport interface LightboxCloseOptions {\n /** Where focus goes instead of the item's link (for example the page's heading). */\n focus?: HTMLElement | null;\n}\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 exactly (same place, `hidden` and `slot`) when the viewer moves on or closes. The\n * `data-details-id` element stays in the page (in shadow mode it becomes a child of the\n * lightbox slotted into the dialog), so `getElementById`, the page's CSS (except selectors\n * through its old ancestors) and listeners keep working; nothing is cloned. Details that appear\n * while their image is open (rendered after a fetch) are shown then.\n *\n * `open(idOrIndex)` and `close({ focus })` let the page open or close the viewer itself;\n * `uvalib-lightbox-open` and `uvalib-lightbox-close` say when it did.\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). A version with a different\n * framing (an AI-expanded frame, a crop, the whole plate) gives `frame`, the original's box\n * in it (`percent:x,y,w,h`, or pixels of its `width` × `height`): the viewer draws every\n * version at the original's scale in one box, the original lined up, and regions stay on it.\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-open - The viewer opened (a click, `open()`, or restored from the address): `detail` is `{ id, index, restored }` (`index` from 0; `restored` true for the address, Back and Forward). Not fired when it moves to another image. Bubbles and is composed.\n * @fires uvalib-lightbox-close - The viewer closed: `detail` is `{ id, index, reason }`, the image shown and `reason` `close` (Close, Escape, the backdrop), `api` (`close()`), `history` (Back or Forward) or `empty` (the last image left the page). Not fired when the element is removed. Bubbles and is composed.\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 shown = 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: {\n el: HTMLElement;\n parent: Node;\n next: ChildNode | null;\n hidden: boolean;\n slot: string | null;\n /** Where the viewer put it: the details panel, or the lightbox itself (slotted). */\n at: Node;\n }[] = [];\n private parkedKey = '';\n /** Watches for the open image's `data-details-id` element while it is missing. */\n private lateDetails?: MutationObserver;\n private lateDetailsId = '';\n /** The details panel, observed (shadow mode) for `data-for` changes on details moved into it. */\n private watchedBox?: HTMLElement;\n /** The open image after its link left the page: still shown, dropped once the viewer moves on. */\n private orphan: Slide | null = null;\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.shown = 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.shown) {\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.shown) {\n if (changed.has('shown')) this.restoreDetails();\n return;\n }\n if (changed.has('shown') || 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('shown')) 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.watchedBox = undefined;\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-for',\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;\n if (!this.shown) this.slides = next;\n else {\n const at = current ? next.findIndex((s) => s.el === current.el) : -1;\n if (at >= 0 || !current) {\n this.slides = next;\n this.index = Math.max(at, 0);\n this.orphan = null;\n } else if (!next.length) {\n this.dismiss('empty');\n this.slides = next;\n this.index = 0;\n } else {\n // The open image's link left the page (the page deleted it). Keep showing it, so\n // the viewer does not jump to another image while the address names this one; it\n // drops out when the visitor moves on, and the page can call close().\n const k = Math.min(this.index, next.length);\n next.splice(k, 0, current);\n this.slides = next;\n this.index = k;\n this.orphan = current;\n }\n }\n }\n // Details added, removed or retargeted (`data-for`) while an image is open.\n if (this.shown) this.placeDetails();\n else 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\"], [slot=\"${DETAILS_SLOT}\"]`)) 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.shown)\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.shown) return;\n window.clearTimeout(this.resizeTimer);\n this.resizeTimer = window.setTimeout(() => {\n if (this.isConnected && this.shown) 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 /**\n * Opens an item as a click on its link would: `item` is its id (as `url-param` writes it)\n * or its place in the set from 0. Returns false when there is no such item. Focus goes back\n * to the item's link on close. With the viewer open it shows that item instead. Fires\n * `uvalib-lightbox-open` (when the viewer was closed), not analytics: it is the page's call.\n */\n open(item: string | number): boolean {\n if (!this.isConnected) return false;\n const slides = this.collect();\n const i =\n typeof item === 'number'\n ? Number.isInteger(item) && item >= 0 && item < slides.length\n ? item\n : -1\n : slides.findIndex((s) => s.id === item);\n if (i < 0) return false;\n this.activate(i, slides, false);\n return true;\n }\n\n /**\n * Closes the viewer as Close does, `url-param` and `version-param` included (Back when the\n * viewer pushed the entry, else they are removed). Focus goes to `focus` when given, else to\n * the item's link; when that link has left the page, to the first image link left, else to\n * the lightbox itself (made focusable with `tabindex=\"-1\"` until it loses focus). Returns\n * false when the viewer was not open.\n */\n close(options: LightboxCloseOptions = {}): boolean {\n if (!this.shown && !this.dialogEl?.open) return false;\n this.dismiss('api', options.focus ?? null);\n return true;\n }\n\n private announce(type: 'open', detail: LightboxOpenDetail): void;\n private announce(type: 'close', detail: LightboxCloseDetail): void;\n private announce(type: string, detail: unknown): void {\n this.dispatchEvent(\n new CustomEvent(`uvalib-lightbox-${type}`, { detail, bubbles: true, composed: true }),\n );\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[], track = true): void {\n const already = this.shown;\n if (already && this.index === i) return;\n this.slides = slides;\n this.index = i;\n this.orphan = null;\n this.trigger = slides[i]?.el ?? null;\n this.userClosed = false;\n this.pendingVersion = null;\n this.cmp?.reset();\n this.measure();\n this.shown = 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 if (track) trackEvent(this, ['uvalib-lightbox', 'open', `image ${i + 1}`, i + 1]);\n if (!already) this.announce('open', { id: slides[i]?.id ?? '', index: i, restored: false });\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.shown || 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.orphan = null;\n this.shown = true;\n this.announce('open', { id, index: i, restored: 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 let n = this.slides.length;\n if (n < 2) return;\n let i = (this.index + delta + n) % n;\n if (this.orphan && this.current === this.orphan) {\n // Moving on from an image whose link has gone: it leaves the set.\n const at = this.index;\n this.slides = this.slides.filter((s) => s !== this.orphan);\n this.orphan = null;\n n = this.slides.length;\n i = delta > 0 ? at % n : (at - 1 + n) % 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' | 'api' | 'pop' | 'empty', focus: HTMLElement | null = null): void {\n if (this.dismissing) return;\n const dialog = this.dialogEl;\n if (!this.shown && !dialog?.open) return;\n this.dismissing = true;\n const was = { id: this.current?.id ?? '', index: this.index };\n const fromUi = source === 'ui' || source === 'api';\n this.cmp?.reset();\n try {\n const pushed = this.historyPushed;\n this.historyPushed = false;\n this.ignoreClose = true;\n this.cancelReveal();\n this.shown = false;\n if (fromUi || source === 'empty') this.userClosed = true;\n this.restoreDetails();\n if (dialog?.open) dialog.close();\n this.focusAfterClose(focus);\n if (fromUi && 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 this.orphan = null;\n const reason = source === 'ui' ? 'close' : source === 'pop' ? 'history' : source;\n this.announce('close', { ...was, reason });\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.shown) this.shown = true;\n return;\n }\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) {\n this.historyPushed = false;\n if (this.shown) 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.shown) 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.orphan = null;\n this.measure();\n this.armReopenGuard();\n if (!this.shown) {\n this.shown = true;\n this.announce('open', { id, index: i, restored: true });\n }\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.shown) return;\n if (this.dialogEl?.open) return;\n if (this.reopenGuard) {\n const view = this.ownerDocument.defaultView;\n view?.queueMicrotask(() => {\n if (this.shown && 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 /**\n * Focus after a close: `focus` when the page gave one, else the trigger; when the trigger\n * has left the page, the first image link left, else the lightbox itself (focusable with\n * `tabindex=\"-1\"` until it loses focus), so focus is never dropped on the body.\n */\n private focusAfterClose(focus: HTMLElement | null): void {\n if (focus?.isConnected) {\n focus.focus();\n return;\n }\n const trigger = this.trigger;\n if (trigger?.isConnected && !trigger.closest('[hidden]')) {\n trigger.focus();\n return;\n }\n if (!this.isConnected) return;\n const first = this.collect()[0]?.el;\n if (first) {\n first.focus();\n return;\n }\n if (!this.hasAttribute('tabindex')) {\n this.setAttribute('tabindex', '-1');\n this.addEventListener('blur', () => this.removeAttribute('tabindex'), { once: true });\n }\n this.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.shown || !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.shown) 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 /**\n * Show the open image's details. `slot=\"details\"` children move into the details panel. A\n * `data-details-id` element stays in the page: in shadow mode it becomes a light-DOM child of\n * the lightbox slotted into the panel (so `getElementById`, the page's CSS and its listeners\n * keep working); in light DOM it moves into the panel, which is in the page too. Nothing is\n * cloned. Called again for late details; a key keeps it from moving anything twice.\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) {\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) && item.el.parentNode === item.at) 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 (still.some((item) => item.el === el)) continue;\n const parent = el.parentNode;\n if (!parent) continue;\n const slotted = !this.isLight && el.getAttribute('slot') !== 'details';\n const at: Node = slotted ? this : box;\n this.parked.push({\n el,\n parent,\n next: el.nextSibling,\n hidden: el.hidden,\n slot: el.getAttribute('slot'),\n at,\n });\n el.hidden = false;\n if (slotted) el.setAttribute('slot', DETAILS_SLOT);\n at.appendChild(el);\n }\n }\n this.parkedKey = key;\n }\n this.markDetailsBox();\n this.awaitDetails();\n }\n\n /** The panel shows only while it has something in it. */\n private markDetailsBox(): void {\n const box = this.detailsBox;\n if (!box) return;\n box.hidden = !this.parked.some((item) => item.el.parentNode === item.at);\n if (!this.isLight && box !== this.watchedBox && this.observer) {\n // Details moved into the shadow panel leave the lightbox's subtree; a change to their\n // `data-for` must still be seen.\n this.watchedBox = box;\n this.observer.observe(box, {\n attributes: true,\n attributeFilter: ['data-for', 'slot'],\n subtree: true,\n });\n }\n }\n\n /**\n * The open image names a details element that is not in the page yet (a framework renders\n * it after a fetch): watch this root, only while open and only for that id, and show it\n * when it appears.\n */\n private awaitDetails(): void {\n const id = this.shown ? (this.current?.detailsId ?? '') : '';\n const missing = !!id && !this.scope.getElementById(id);\n if (!missing) {\n this.stopAwaitingDetails();\n return;\n }\n if (this.lateDetails && this.lateDetailsId === id) return;\n this.stopAwaitingDetails();\n this.lateDetailsId = id;\n this.lateDetails = new MutationObserver(() => {\n if (!this.shown || this.current?.detailsId !== id) {\n this.stopAwaitingDetails();\n return;\n }\n if (this.scope.getElementById(id)) {\n this.stopAwaitingDetails();\n this.placeDetails();\n }\n });\n this.lateDetails.observe(this.scope, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['id'],\n });\n }\n\n private stopAwaitingDetails(): void {\n this.lateDetails?.disconnect();\n this.lateDetails = undefined;\n this.lateDetailsId = '';\n }\n\n /**\n * Put a parked element back as it was: same parent and place, same `hidden` and `slot`.\n * Restoring later siblings first keeps `next` inside `parent`; if it is not (it was parked\n * too), insert at the end instead of throwing NotFoundError. An element the page has\n * removed or moved meanwhile stays where the page put it.\n */\n private putBack(item: (typeof this.parked)[number]): void {\n const { el } = item;\n el.hidden = item.hidden;\n if (item.slot == null) el.removeAttribute('slot');\n else el.setAttribute('slot', item.slot);\n if (el.parentNode !== item.at) return;\n const next = item.next?.parentNode === item.parent ? item.next : null;\n item.parent.insertBefore(el, next);\n }\n\n private restoreDetails(): void {\n this.stopAwaitingDetails();\n for (let i = this.parked.length - 1; i >= 0; i--) this.putBack(this.parked[i]!);\n this.parked = [];\n this.parkedKey = '';\n this.markDetailsBox();\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.shown) 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.shown && 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.shown) 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 style=${cmp?.regionsStyle || nothing}\n >${img}${controls}${list}</uvalib-image-regions\n >`;\n }\n\n protected override render() {\n const slide = this.shown ? 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\" hidden>\n ${this.isLight ? nothing : html`<slot name=${DETAILS_SLOT}></slot>`}\n </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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KAAA,CAAA,GACN3D,EAAA,CAAAE,EAAM,CAAA,GAAAyD,EAAA,WAAA,QAAA,KAAA,CAAA,GAEN3D,EAAA,CAAAE,EAAM,CAAA,GAAAyD,EAAA,WAAA,eAAA,KAAA,CAAA,GC3bTpD,EAAO,mBAAmBoD,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","setState","attachStateInternals","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","DETAILS_SLOT","ENTRY_MARKS","positive","v","normalize","s","structuralRules","host","shadowStructure","nextCaption","compareModule","compareLoading","compareFailed","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","k","found","detailRoots","noteDetails","a","el","candidates","push","owner","unique","pos","img","alt","text","caption","index","list","regions","raw","m","value","more","ref","walk","item","options","type","already","hashMode","track","version","delta","action","was","fromUi","source","pushed","focus","reason","loc","vp","rest","now","prev","mode","observer","trigger","first","again","active","position","pool","add","f","want","key","keep","still","box","parent","slotted","rendered","target","li","lent","name","outlined","cmp","A","controls","waiting","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 { attachStateInternals, setState } from '../../base/states.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 /** `data-version`: the comparison it opens on (the `version-param` format), or null. */\n start: string | 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/** The slot (shadow mode) a `data-details-id` element is lent to while its image is open. */\nconst DETAILS_SLOT = 'uvalib-details';\n\n/** Why the viewer closed, in `uvalib-lightbox-close`. */\nexport type LightboxCloseReason = 'close' | 'api' | 'history' | 'empty';\n\n/** `detail` of `uvalib-lightbox-open`. */\nexport interface LightboxOpenDetail {\n /** The item's id (as `url-param` writes it). */\n id: string;\n /** Its place in the set, from 0. */\n index: number;\n /** True when the viewer was restored from the address (a reload, Back or Forward). */\n restored: boolean;\n}\n\n/** `detail` of `uvalib-lightbox-close`. */\nexport interface LightboxCloseDetail {\n /** The item that was shown. */\n id: string;\n /** Its place in the set, from 0. */\n index: number;\n /**\n * `close` (Close, Escape or the backdrop), `api` (`close()`), `history` (Back or Forward)\n * or `empty` (the last image left the page).\n */\n reason: LightboxCloseReason;\n}\n\n/** Options for `close()`. */\nexport interface LightboxCloseOptions {\n /** Where focus goes instead of the item's link (for example the page's heading). */\n focus?: HTMLElement | null;\n}\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} .stack.starting > * { visibility: hidden !important; }\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/** The comparison could not be loaded: an image opening on another version shows the original. */\nlet compareFailed = false;\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 exactly (same place, `hidden` and `slot`) when the viewer moves on or closes. The\n * `data-details-id` element stays in the page (in shadow mode it becomes a child of the\n * lightbox slotted into the dialog), so `getElementById`, the page's CSS (except selectors\n * through its old ancestors) and listeners keep working; nothing is cloned. Details that appear\n * while their image is open (rendered after a fetch) are shown then.\n *\n * `open(idOrIndex)` and `close({ focus })` let the page open or close the viewer itself;\n * `uvalib-lightbox-open` and `uvalib-lightbox-close` say when it did.\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). `data-version` on a link (the\n * same values) opens that image on that version, from a click, `open()` or Previous and\n * Next; an address with `version-param` wins. A version with a different\n * framing (an AI-expanded frame, a crop, the whole plate) gives `frame`, the original's box\n * in it (`percent:x,y,w,h`, or pixels of its `width` × `height`): the viewer draws every\n * version at the original's scale in one box, the original lined up, and regions stay on it.\n *\n * Pages can style the element while the viewer is open with `:state(open)`.\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 * @cssstate open - The viewer is open.\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-open - The viewer opened (a click, `open()`, or restored from the address): `detail` is `{ id, index, restored }` (`index` from 0; `restored` true for the address, Back and Forward). Not fired when it moves to another image. Bubbles and is composed.\n * @fires uvalib-lightbox-close - The viewer closed: `detail` is `{ id, index, reason }`, the image shown and `reason` `close` (Close, Escape, the backdrop), `api` (`close()`), `history` (Back or Forward) or `empty` (the last image left the page). Not fired when the element is removed. Bubbles and is composed.\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 text-wrap: balance;\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). The link's `data-version` still picks the\n * version it opens on.\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 shown = 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 private readonly internals = attachStateInternals(this);\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: {\n el: HTMLElement;\n parent: Node;\n next: ChildNode | null;\n hidden: boolean;\n slot: string | null;\n /** Where the viewer put it: the details panel, or the lightbox itself (slotted). */\n at: Node;\n }[] = [];\n private parkedKey = '';\n /** Watches for the open image's `data-details-id` element while it is missing. */\n private lateDetails?: MutationObserver;\n private lateDetailsId = '';\n /** The details panel, observed (shadow mode) for `data-for` changes on details moved into it. */\n private watchedBox?: HTMLElement;\n /** The open image after its link left the page: still shown, dropped once the viewer moves on. */\n private orphan: Slide | null = null;\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.shown = 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.shown) {\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('shown')) setState(this.internals, 'open', this.shown);\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.shown) {\n if (changed.has('shown')) this.restoreDetails();\n return;\n }\n if (changed.has('shown') || 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('shown')) 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.watchedBox = undefined;\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-for',\n 'data-regions',\n 'data-regions-list',\n 'data-versions',\n 'data-version',\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, s.start]) ===\n JSON.stringify([\n this.slides[i]?.regions,\n this.slides[i]?.imageWidth,\n this.slides[i]?.imageHeight,\n this.slides[i]?.versions,\n this.slides[i]?.start,\n ]),\n );\n this.noteEntries();\n if (!same) {\n const current = this.current;\n if (!this.shown) this.slides = next;\n else {\n const at = current ? next.findIndex((s) => s.el === current.el) : -1;\n if (at >= 0 || !current) {\n this.slides = next;\n this.index = Math.max(at, 0);\n this.orphan = null;\n } else if (!next.length) {\n this.dismiss('empty');\n this.slides = next;\n this.index = 0;\n } else {\n // The open image's link left the page (the page deleted it). Keep showing it, so\n // the viewer does not jump to another image while the address names this one; it\n // drops out when the visitor moves on, and the page can call close().\n const k = Math.min(this.index, next.length);\n next.splice(k, 0, current);\n this.slides = next;\n this.index = k;\n this.orphan = current;\n }\n }\n }\n // Details added, removed or retargeted (`data-for`) while an image is open.\n if (this.shown) this.placeDetails();\n else 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\"], [slot=\"${DETAILS_SLOT}\"]`)) 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 start: normalize(el.dataset.version) || null,\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 compareFailed = false;\n })\n .catch((err) => {\n compareLoading = null;\n compareFailed = true;\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.shown)\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.shown) return;\n window.clearTimeout(this.resizeTimer);\n this.resizeTimer = window.setTimeout(() => {\n if (this.isConnected && this.shown) 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 /**\n * Opens an item as a click on its link would: `item` is its id (as `url-param` writes it)\n * or its place in the set from 0. Returns false when there is no such item. Focus goes back\n * to the item's link on close. With the viewer open it shows that item instead. Fires\n * `uvalib-lightbox-open` (when the viewer was closed), not analytics: it is the page's call.\n */\n open(item: string | number): boolean {\n if (!this.isConnected) return false;\n const slides = this.collect();\n const i =\n typeof item === 'number'\n ? Number.isInteger(item) && item >= 0 && item < slides.length\n ? item\n : -1\n : slides.findIndex((s) => s.id === item);\n if (i < 0) return false;\n this.activate(i, slides, false);\n return true;\n }\n\n /**\n * Closes the viewer as Close does, `url-param` and `version-param` included (Back when the\n * viewer pushed the entry, else they are removed). Focus goes to `focus` when given, else to\n * the item's link; when that link has left the page, to the first image link left, else to\n * the lightbox itself (made focusable with `tabindex=\"-1\"` until it loses focus). Returns\n * false when the viewer was not open.\n */\n close(options: LightboxCloseOptions = {}): boolean {\n if (!this.shown && !this.dialogEl?.open) return false;\n this.dismiss('api', options.focus ?? null);\n return true;\n }\n\n private announce(type: 'open', detail: LightboxOpenDetail): void;\n private announce(type: 'close', detail: LightboxCloseDetail): void;\n private announce(type: string, detail: unknown): void {\n this.dispatchEvent(\n new CustomEvent(`uvalib-lightbox-${type}`, { detail, bubbles: true, composed: true }),\n );\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[], track = true): void {\n const already = this.shown;\n if (already && this.index === i) return;\n this.slides = slides;\n this.index = i;\n this.orphan = null;\n this.trigger = slides[i]?.el ?? null;\n this.userClosed = false;\n this.pendingVersion = null;\n this.cmp?.reset();\n this.measure();\n this.shown = 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 if (track) trackEvent(this, ['uvalib-lightbox', 'open', `image ${i + 1}`, i + 1]);\n if (!already) this.announce('open', { id: slides[i]?.id ?? '', index: i, restored: false });\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.shown || 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.orphan = null;\n this.shown = true;\n this.announce('open', { id, index: i, restored: 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 let n = this.slides.length;\n if (n < 2) return;\n let i = (this.index + delta + n) % n;\n if (this.orphan && this.current === this.orphan) {\n // Moving on from an image whose link has gone: it leaves the set.\n const at = this.index;\n this.slides = this.slides.filter((s) => s !== this.orphan);\n this.orphan = null;\n n = this.slides.length;\n i = delta > 0 ? at % n : (at - 1 + n) % 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' | 'api' | 'pop' | 'empty', focus: HTMLElement | null = null): void {\n if (this.dismissing) return;\n const dialog = this.dialogEl;\n if (!this.shown && !dialog?.open) return;\n this.dismissing = true;\n const was = { id: this.current?.id ?? '', index: this.index };\n const fromUi = source === 'ui' || source === 'api';\n this.cmp?.reset();\n try {\n const pushed = this.historyPushed;\n this.historyPushed = false;\n this.ignoreClose = true;\n this.cancelReveal();\n this.shown = false;\n if (fromUi || source === 'empty') this.userClosed = true;\n this.restoreDetails();\n if (dialog?.open) dialog.close();\n this.focusAfterClose(focus);\n if (fromUi && 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 this.orphan = null;\n const reason = source === 'ui' ? 'close' : source === 'pop' ? 'history' : source;\n this.announce('close', { ...was, reason });\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.shown) this.shown = true;\n return;\n }\n const id = paramFromLocation(this.loc(), this.urlParam);\n if (!id) {\n this.historyPushed = false;\n if (this.shown) 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.shown) 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.orphan = null;\n this.measure();\n this.armReopenGuard();\n if (!this.shown) {\n this.shown = true;\n this.announce('open', { id, index: i, restored: true });\n }\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.shown) return;\n if (this.dialogEl?.open) return;\n if (this.reopenGuard) {\n const view = this.ownerDocument.defaultView;\n view?.queueMicrotask(() => {\n if (this.shown && 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 /**\n * Focus after a close: `focus` when the page gave one, else the trigger; when the trigger\n * has left the page, the first image link left, else the lightbox itself (focusable with\n * `tabindex=\"-1\"` until it loses focus), so focus is never dropped on the body.\n */\n private focusAfterClose(focus: HTMLElement | null): void {\n if (focus?.isConnected) {\n focus.focus();\n return;\n }\n const trigger = this.trigger;\n if (trigger?.isConnected && !trigger.closest('[hidden]')) {\n trigger.focus();\n return;\n }\n if (!this.isConnected) return;\n const first = this.collect()[0]?.el;\n if (first) {\n first.focus();\n return;\n }\n if (!this.hasAttribute('tabindex')) {\n this.setAttribute('tabindex', '-1');\n this.addEventListener('blur', () => this.removeAttribute('tabindex'), { once: true });\n }\n this.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.shown || !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.shown) 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 /**\n * Show the open image's details. `slot=\"details\"` children move into the details panel. A\n * `data-details-id` element stays in the page: in shadow mode it becomes a light-DOM child of\n * the lightbox slotted into the panel (so `getElementById`, the page's CSS and its listeners\n * keep working); in light DOM it moves into the panel, which is in the page too. Nothing is\n * cloned. Called again for late details; a key keeps it from moving anything twice.\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) {\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) && item.el.parentNode === item.at) 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 (still.some((item) => item.el === el)) continue;\n const parent = el.parentNode;\n if (!parent) continue;\n const slotted = !this.isLight && el.getAttribute('slot') !== 'details';\n const at: Node = slotted ? this : box;\n this.parked.push({\n el,\n parent,\n next: el.nextSibling,\n hidden: el.hidden,\n slot: el.getAttribute('slot'),\n at,\n });\n el.hidden = false;\n if (slotted) el.setAttribute('slot', DETAILS_SLOT);\n at.appendChild(el);\n }\n }\n this.parkedKey = key;\n }\n this.markDetailsBox();\n this.awaitDetails();\n }\n\n /** The panel shows only while it has something in it. */\n private markDetailsBox(): void {\n const box = this.detailsBox;\n if (!box) return;\n box.hidden = !this.parked.some((item) => item.el.parentNode === item.at);\n if (!this.isLight && box !== this.watchedBox && this.observer) {\n // Details moved into the shadow panel leave the lightbox's subtree; a change to their\n // `data-for` must still be seen.\n this.watchedBox = box;\n this.observer.observe(box, {\n attributes: true,\n attributeFilter: ['data-for', 'slot'],\n subtree: true,\n });\n }\n }\n\n /**\n * The open image names a details element that is not in the page yet (a framework renders\n * it after a fetch): watch this root, only while open and only for that id, and show it\n * when it appears.\n */\n private awaitDetails(): void {\n const id = this.shown ? (this.current?.detailsId ?? '') : '';\n const missing = !!id && !this.scope.getElementById(id);\n if (!missing) {\n this.stopAwaitingDetails();\n return;\n }\n if (this.lateDetails && this.lateDetailsId === id) return;\n this.stopAwaitingDetails();\n this.lateDetailsId = id;\n this.lateDetails = new MutationObserver(() => {\n if (!this.shown || this.current?.detailsId !== id) {\n this.stopAwaitingDetails();\n return;\n }\n if (this.scope.getElementById(id)) {\n this.stopAwaitingDetails();\n this.placeDetails();\n }\n });\n this.lateDetails.observe(this.scope, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['id'],\n });\n }\n\n private stopAwaitingDetails(): void {\n this.lateDetails?.disconnect();\n this.lateDetails = undefined;\n this.lateDetailsId = '';\n }\n\n /**\n * Put a parked element back as it was: same parent and place, same `hidden` and `slot`.\n * Restoring later siblings first keeps `next` inside `parent`; if it is not (it was parked\n * too), insert at the end instead of throwing NotFoundError. An element the page has\n * removed or moved meanwhile stays where the page put it.\n */\n private putBack(item: (typeof this.parked)[number]): void {\n const { el } = item;\n el.hidden = item.hidden;\n if (item.slot == null) el.removeAttribute('slot');\n else el.setAttribute('slot', item.slot);\n if (el.parentNode !== item.at) return;\n const next = item.next?.parentNode === item.parent ? item.next : null;\n item.parent.insertBefore(el, next);\n }\n\n private restoreDetails(): void {\n this.stopAwaitingDetails();\n for (let i = this.parked.length - 1; i >= 0; i--) this.putBack(this.parked[i]!);\n this.parked = [];\n this.parkedKey = '';\n this.markDetailsBox();\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.shown) 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.shown && 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.shown) 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 // Opening on another version: hidden until the comparison has loaded and drawn it.\n const waiting = !this.cmp && slide.start && !compareFailed ? 'starting' : '';\n img = html`<div\n class=\"stack ${cmp?.stackClass ?? waiting}\"\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 style=${cmp?.regionsStyle || nothing}\n >${img}${controls}${list}</uvalib-image-regions\n >`;\n }\n\n protected override render() {\n const slide = this.shown ? 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\" hidden>\n ${this.isLight ? nothing : html`<slot name=${DETAILS_SLOT}></slot>`}\n </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,IAAMuB,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,SAAS;EAAG,WAAWA,EAAM,SAAS;CAAE;AAClF;AAQA,SAAgBI,EAAa,GAAc,GAAc,GAAW,GAA0B;CAC5F,IAAMC,IAAST,EAAUE,GAAMC,CAAI;CACnC,IAAI,CAACM,GAAQ,OAAO;CACpB,IAAMJ,IAAOI,EAAO,MAAMA,EAAO,MAAM,SAAS,MAAM;CACtD,IAAI,CAACX,EAAc,KAAKO,CAAI,GAAG,OAAO;CACtC,IAAMK,IAAQ,KAAK,IAAI,GAAG,KAAK,MAAMC,CAAC,CAAC,G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A,GAQvC9D,EAAA,CAAAC,EAAS,EAAE,WAAW,GAAM,CAAC,CAAA,GAAA6D,EAAA,WAAA,YAAA,KAAA,CAAA,GAO7B9D,EAAA,CAAAC,EAAS,CAAA,GAAA6D,EAAA,WAAA,WAAA,KAAA,CAAA,GAOT9D,EAAA,CAAAC,EAAS,EAAE,WAAW,gBAAgB,CAAC,CAAA,GAAA6D,EAAA,WAAA,gBAAA,KAAA,CAAA,GAEvC9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,UAAA,KAAA,CAAA,GACN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,SAAA,KAAA,CAAA,GACN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,SAAA,KAAA,CAAA,GACN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,UAAA,KAAA,CAAA,GACN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,QAAA,KAAA,CAAA,GACN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,QAAA,KAAA,CAAA,GAEN9D,EAAA,CAAAE,EAAM,CAAA,GAAA4D,EAAA,WAAA,eAAA,KAAA,CAAA,GCxcTvD,EAAO,mBAAmBuD,CAAc"}
@@ -362,7 +362,7 @@ var P = (e) => `
362
362
  let n = this.map, r = this.places, i = (e, t) => m(r[t]) - m(r[e]) || e - t, a = new Map(e.map((e) => [e, n.project([r[e].lat, r[e].lng], t)])), o = (e, t) => {
363
363
  let n = a.get(e[0]), r = a.get(t[0]), i = (this.hitOf(e) + this.hitOf(t)) / 2 + S;
364
364
  return Math.abs(n.x - r.x) < i && Math.abs(n.y - r.y) < i;
365
- }, s = [...e].sort(i), c = [], l = /* @__PURE__ */ new Set();
365
+ }, s = e.toSorted(i), c = [], l = /* @__PURE__ */ new Set();
366
366
  for (let e of s) {
367
367
  if (l.has(e)) continue;
368
368
  let t = [e];
@@ -401,7 +401,7 @@ var P = (e) => `
401
401
  this.groupOf.clear();
402
402
  for (let t of this.cluster(i, e.getZoom())) {
403
403
  if (t.length < 2) continue;
404
- let e = [...t].sort((e, t) => e - t).join(",");
404
+ let e = t.toSorted((e, t) => e - t).join(",");
405
405
  a.set(e, this.groups.get(e) ?? this.makeGroup(e, t));
406
406
  for (let n of t) this.groupOf.set(n, e);
407
407
  }