story_player 0.1.1

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.
@@ -0,0 +1,471 @@
1
+ async (call, styles, createElementPicker, createAccessibility, { chapter, surfaceAttribute, anchorAttribute }) => {
2
+ const mounted = Symbol.for("demoStage.annotations")
3
+ if (window[mounted]) return
4
+ try {
5
+ if (!(await call("active"))) return
6
+ } catch {
7
+ return
8
+ }
9
+ if (!document.body) await new Promise(resolve => document.addEventListener("DOMContentLoaded", resolve, { once: true }))
10
+
11
+ const host = document.createElement("div")
12
+ host.id = "demo-stage-annotations"
13
+ const shadow = host.attachShadow({ mode: "open" })
14
+ const stylesheet = new CSSStyleSheet()
15
+ stylesheet.replaceSync(styles)
16
+ shadow.adoptedStyleSheets = [stylesheet]
17
+ const icon = path => `<svg aria-hidden="true" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="${path}"/></svg>`
18
+ const closeIcon = icon("M6 18 18 6M6 6l12 12")
19
+ const warningIcon = icon("M12 3 2 21h20L12 3Zm0 6v5m0 3h.01")
20
+ shadow.innerHTML = `
21
+ <div class="pins" aria-label="Annotation pins"></div>
22
+ <button type="button" class="launcher" aria-label="Annotations" title="Annotations" aria-haspopup="dialog" aria-expanded="false" aria-controls="annotation-note">
23
+ ${icon("M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.845 2.1-1.977 2.193-.34.028-.681.052-1.023.072V20.25L15.75 17.25h-3.396c-1.127 0-2.073-.844-2.169-1.977m10.065-6.762a2.094 2.094 0 0 0-.476-.09 48.91 48.91 0 0 0-7.421 0c-1.13.093-1.976 1.056-1.976 2.19v4.662m9.873-6.762V6.5c0-1.622-1.151-3.025-2.76-3.234a48.29 48.29 0 0 0-12.48 0C3.401 3.475 2.25 4.878 2.25 6.5v5.25c0 1.622 1.151 3.025 2.76 3.234.329.043.659.082.99.117V18l3.024-3.024")}
24
+ </button>
25
+ <div class="picker" hidden>
26
+ <span role="status">Click an element, or focus it and press Enter.</span>
27
+ <button type="button">Cancel selection</button>
28
+ </div>
29
+ <div class="highlight" aria-hidden="true" hidden></div>
30
+ <dialog id="annotation-note" aria-labelledby="annotations-title">
31
+ <header>
32
+ <h2 id="annotations-title">Annotations</h2>
33
+ <button type="button" data-close aria-label="Close annotations" title="Close annotations">${closeIcon}</button>
34
+ </header>
35
+ <form>
36
+ <div class="reference" hidden>
37
+ <div class="reference-content">
38
+ <span class="reference-label"></span>
39
+ <div class="targeting" hidden></div>
40
+ </div>
41
+ <button type="button" data-clear aria-label="Clear selection" title="Clear selection">${closeIcon}</button>
42
+ </div>
43
+ <label class="comment-label" for="annotation-comment">Comment</label>
44
+ <textarea id="annotation-comment" rows="2" maxlength="10000" required></textarea>
45
+ <div class="actions">
46
+ <button type="button" data-select aria-label="Select element" title="Select element">
47
+ ${icon("M15 15l-2 5L9 9l11 4-5 2Zm0 0 4 4M7.188 2.688l1.087 2.897m-2.69 2.69L2.688 7.188m11.66-2.585-2.122 2.122m-5.5 5.5-2.122 2.122")}
48
+ </button>
49
+ <button type="submit" class="primary" aria-label="Save comment" title="Save comment">
50
+ ${icon("M12 4.5v15m7.5-7.5h-15")}
51
+ </button>
52
+ </div>
53
+ </form>
54
+ <p class="status" role="status"></p>
55
+ <details hidden>
56
+ <summary>Saved comments</summary>
57
+ <ol aria-label="Comments on this page"></ol>
58
+ </details>
59
+ </dialog>
60
+ `
61
+ document.documentElement.append(host)
62
+
63
+ const find = selector => shadow.querySelector(selector)
64
+ const dialog = find("dialog")
65
+ const launcher = find(".launcher")
66
+ const comment = find("textarea")
67
+ const save = find("[type=submit]")
68
+ const status = find(".status")
69
+ const pinsLayer = find(".pins")
70
+ const pinRefs = new WeakMap()
71
+ const events = new AbortController()
72
+ let page
73
+ let selected
74
+ let listed = []
75
+ let focusKey
76
+ let warningIndex = 0
77
+
78
+ const targetingHints = {
79
+ name: "Name the control with visible text, an associated label, or aria-label for an icon-only control.",
80
+ duplicate: "Give repeated controls distinct accessible names or move them into named regions.",
81
+ identifier: "Add a stable ID or data-testid to keep the pin attached after a reload.",
82
+ native: "Use a native button or link so people can activate the action with the keyboard.",
83
+ hidden: "Remove aria-hidden if people using assistive technology need this control.",
84
+ missing: "Return to the page state where you added this comment, then try Show element again."
85
+ }
86
+ const referenceKey = reference => {
87
+ const anchor = reference?.accessibility
88
+ if (anchor?.strategy === "semantic") return JSON.stringify(anchor.path)
89
+ if (anchor?.strategy === "position") return anchor.key
90
+ return reference?.selector
91
+ }
92
+
93
+ const showTargeting = (container, reference, problem) => {
94
+ const anchor = reference?.accessibility
95
+ const path = Array.isArray(anchor?.path) ? anchor.path : []
96
+ const hints = Array.isArray(anchor?.hints) ? anchor.hints : []
97
+ const warnings = [...new Set([...hints, problem])].filter(hint => Object.hasOwn(targetingHints, hint))
98
+ container.replaceChildren()
99
+ container.hidden = !path.length && !warnings.length
100
+
101
+ if (path.length) {
102
+ const breadcrumb = document.createElement("p")
103
+ breadcrumb.className = "breadcrumb"
104
+ breadcrumb.title = "Accessibility path"
105
+ breadcrumb.textContent = path.filter(segment => segment?.role)
106
+ .map(({ role, name }) => name ? `${role} "${name}"` : role).join(" › ")
107
+ container.append(breadcrumb)
108
+ }
109
+ if (!warnings.length) return
110
+
111
+ const button = document.createElement("button")
112
+ button.type = "button"
113
+ button.className = "targeting-warning"
114
+ button.title = "Targeting warnings"
115
+ button.setAttribute("aria-label", button.title)
116
+ button.setAttribute("aria-expanded", "false")
117
+ button.innerHTML = warningIcon
118
+
119
+ const list = document.createElement("ul")
120
+ list.id = `annotation-warning-${++warningIndex}`
121
+ list.hidden = true
122
+ button.setAttribute("aria-controls", list.id)
123
+ button.addEventListener("click", () => {
124
+ list.hidden = !list.hidden
125
+ button.setAttribute("aria-expanded", String(!list.hidden))
126
+ schedulePosition()
127
+ })
128
+ for (const warning of warnings) {
129
+ const item = document.createElement("li")
130
+ item.textContent = targetingHints[warning]
131
+ list.append(item)
132
+ }
133
+ container.append(button, list)
134
+ return button
135
+ }
136
+
137
+ const showReference = reference => {
138
+ selected = reference
139
+ find(".reference").hidden = !selected
140
+ const referenceLabel = find(".reference-label")
141
+ referenceLabel.hidden = !!selected?.accessibility?.path?.length
142
+ referenceLabel.textContent = selected?.label || ""
143
+ referenceLabel.title = referenceLabel.textContent
144
+ const targeting = find("form .targeting")
145
+ showTargeting(targeting, selected)
146
+ schedulePosition()
147
+ }
148
+
149
+ const currentPage = () => ({
150
+ page: location.pathname,
151
+ surface: surfaceAttribute ? document.querySelector(`[${surfaceAttribute}]`)?.getAttribute(surfaceAttribute) || null : null,
152
+ })
153
+ const pageKey = ({ page, surface }) => JSON.stringify([chapter, page, surface])
154
+ const draftKey = () => `demoStage.annotation:${pageKey(page)}`
155
+ const storeDraft = () => {
156
+ try {
157
+ if (comment.value || selected) {
158
+ sessionStorage.setItem(draftKey(), JSON.stringify({ comment: comment.value, element: selected }))
159
+ } else {
160
+ sessionStorage.removeItem(draftKey())
161
+ }
162
+ } catch {
163
+ // Browser storage can be disabled. The open form still keeps the draft.
164
+ }
165
+ }
166
+ const restoreDraft = () => {
167
+ const current = currentPage()
168
+ if (page && pageKey(page) === pageKey(current)) return
169
+ page = current
170
+ focusKey = null
171
+ listed = []
172
+ renderPins([])
173
+ let draft
174
+ try {
175
+ draft = JSON.parse(sessionStorage.getItem(draftKey()))
176
+ } catch {
177
+ draft = null
178
+ }
179
+ comment.value = draft?.comment || ""
180
+ showReference(draft?.element || null)
181
+ }
182
+
183
+ const elementPicker = createElementPicker(host, find(".picker"), find(".highlight"), events.signal, anchorAttribute, createAccessibility(), reference => {
184
+ pinsLayer.hidden = false
185
+ if (reference) {
186
+ showReference(reference)
187
+ storeDraft()
188
+ }
189
+ showNote()
190
+ schedulePosition()
191
+ })
192
+
193
+ let positionFrame
194
+ function schedulePosition() {
195
+ if (positionFrame === undefined) positionFrame = requestAnimationFrame(positionChrome)
196
+ }
197
+ function pointOn(element, reference) {
198
+ const rect = element.getBoundingClientRect()
199
+ const x = Number.isFinite(reference?.x) ? reference.x : 0.5
200
+ const y = Number.isFinite(reference?.y) ? reference.y : 0.5
201
+ return { left: rect.left + rect.width * x, top: rect.top + rect.height * y }
202
+ }
203
+ function positionChrome() {
204
+ positionFrame = undefined
205
+ const controls = document.querySelector("#demo-stage-player")?.shadowRoot?.querySelector(".pane")
206
+ const clearance = controls?.getBoundingClientRect().height || 0
207
+ host.style.setProperty("--demo-controls-height", `${clearance}px`)
208
+ for (const pin of pinsLayer.querySelectorAll(".pin")) {
209
+ const reference = pinRefs.get(pin)
210
+ const target = reference && elementPicker.locate(reference)
211
+ if (!target) {
212
+ pin.hidden = true
213
+ continue
214
+ }
215
+ const { left, top } = pointOn(target, reference)
216
+ pin.style.left = `${left}px`
217
+ pin.style.top = `${top}px`
218
+ pin.hidden = false
219
+ pin.toggleAttribute("data-active", focusKey === referenceKey(reference))
220
+ }
221
+ if (!dialog.open) return
222
+
223
+ const target = selected && elementPicker.locate(selected)
224
+ const rect = target?.getBoundingClientRect()
225
+ const { clientWidth, clientHeight } = document.documentElement
226
+ const gap = 8
227
+ const bottom = clientHeight - clearance - (clearance ? 12 : 0)
228
+ if (!rect || rect.right < 0 || rect.left > clientWidth || rect.bottom < 0 || rect.top > clientHeight) {
229
+ dialog.removeAttribute("data-anchored")
230
+ return
231
+ }
232
+
233
+ const { width, height } = dialog.getBoundingClientRect()
234
+ const right = rect.right + gap
235
+ const left = rect.left - width - gap
236
+ const fitsRight = right + width + gap <= clientWidth
237
+ const fitsBeside = fitsRight || left >= gap
238
+ const below = rect.bottom + gap
239
+ const x = fitsBeside ? (fitsRight ? right : left) : rect.left
240
+ const y = fitsBeside ? rect.top : (below + height + gap <= bottom ? below : rect.top - height - gap)
241
+ dialog.style.setProperty("--note-x", `${Math.max(gap, Math.min(x, clientWidth - width - gap))}px`)
242
+ dialog.style.setProperty("--note-y", `${Math.max(gap, Math.min(y, bottom - height - gap))}px`)
243
+ dialog.setAttribute("data-anchored", "")
244
+ }
245
+
246
+ const showNote = () => {
247
+ dialog.show()
248
+ launcher.setAttribute("aria-expanded", "true")
249
+ schedulePosition()
250
+ comment.focus({ preventScroll: true })
251
+ }
252
+ const hideNote = () => {
253
+ dialog.close()
254
+ focusKey = null
255
+ launcher.setAttribute("aria-expanded", "false")
256
+ schedulePosition()
257
+ }
258
+ const resizeObserver = new ResizeObserver(schedulePosition)
259
+ resizeObserver.observe(dialog)
260
+ const controls = document.querySelector("#demo-stage-player")?.shadowRoot?.querySelector(".pane")
261
+ if (controls) resizeObserver.observe(controls)
262
+ const pageChanged = () => {
263
+ if (page && pageKey(page) !== pageKey(currentPage())) {
264
+ elementPicker.stop()
265
+ pinsLayer.hidden = false
266
+ void refresh()
267
+ }
268
+ }
269
+ const documentObserver = new MutationObserver(records => {
270
+ if (records.every(({ target }) => target === host || target.id === "demo-stage-player")) return
271
+ elementPicker.invalidate()
272
+ pageChanged()
273
+ schedulePosition()
274
+ })
275
+ const anchorAttributes = [
276
+ "id", "role", "aria-label", "aria-labelledby", "aria-hidden", "hidden", "inert", "for",
277
+ "title", "alt", "value", "type", "href", "list", "multiple", "size", "data-testid", "class", "style", surfaceAttribute, anchorAttribute
278
+ ].filter(Boolean)
279
+ documentObserver.observe(document.documentElement, {
280
+ childList: true, subtree: true, characterData: true, attributeFilter: anchorAttributes
281
+ })
282
+ window.addEventListener("resize", schedulePosition, { signal: events.signal })
283
+ window.addEventListener("scroll", schedulePosition, { capture: true, signal: events.signal })
284
+
285
+ const visibleComments = () => focusKey
286
+ ? listed.filter(annotation => referenceKey(annotation.element) === focusKey)
287
+ : listed
288
+
289
+ const render = annotations => {
290
+ find("details").hidden = annotations.length === 0
291
+ find("summary").textContent = `Saved comments (${annotations.length})`
292
+ find("ol").replaceChildren(...annotations.map(annotation => {
293
+ const item = document.createElement("li")
294
+ const time = document.createElement("time")
295
+ time.dateTime = annotation.created_at
296
+ time.textContent = new Date(annotation.created_at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "medium" })
297
+ const body = document.createElement("p")
298
+ body.textContent = annotation.comment
299
+ item.append(time, body)
300
+ if (annotation.element) {
301
+ const button = document.createElement("button")
302
+ button.type = "button"
303
+ button.textContent = `Show element: ${annotation.element.label}`
304
+ const details = document.createElement("details")
305
+ const summary = document.createElement("summary")
306
+ summary.textContent = "Element details"
307
+ const targeting = document.createElement("div")
308
+ targeting.className = "targeting"
309
+ showTargeting(targeting, annotation.element)
310
+ details.hidden = targeting.hidden
311
+ details.append(summary, targeting)
312
+ button.addEventListener("click", () => {
313
+ if (elementPicker.reveal(annotation.element, hideNote)) return
314
+
315
+ details.hidden = false
316
+ details.open = true
317
+ const problem = elementPicker.ambiguous(annotation.element) ? "duplicate" : "missing"
318
+ showTargeting(targeting, annotation.element, problem)?.focus()
319
+ schedulePosition()
320
+ })
321
+ item.append(button, details)
322
+ }
323
+ return item
324
+ }))
325
+ }
326
+
327
+ const renderPins = annotations => {
328
+ const groups = new Map()
329
+ for (const annotation of annotations) {
330
+ const reference = annotation.element
331
+ if (!reference?.selector) continue
332
+ const key = referenceKey(reference)
333
+ const group = groups.get(key) || { annotations: [], element: reference }
334
+ group.annotations.push(annotation)
335
+ if (!Number.isFinite(group.element.x) && Number.isFinite(reference.x)) group.element = reference
336
+ groups.set(key, group)
337
+ }
338
+ pinsLayer.replaceChildren(...[...groups.values()].map(group => {
339
+ const count = group.annotations.length
340
+ const pin = document.createElement("button")
341
+ pin.type = "button"
342
+ pin.className = "pin"
343
+ pin.hidden = true
344
+ pin.textContent = String(count)
345
+ pin.setAttribute("aria-label", `${count} ${count === 1 ? "comment" : "comments"} on ${group.element.label}`)
346
+ pin.title = group.element.label
347
+ pinRefs.set(pin, group.element)
348
+ pin.addEventListener("click", () => {
349
+ focusKey = referenceKey(group.element)
350
+ showReference(group.element)
351
+ render(group.annotations)
352
+ find("details").hidden = false
353
+ find("details").open = true
354
+ status.textContent = ""
355
+ showNote()
356
+ })
357
+ return pin
358
+ }))
359
+ schedulePosition()
360
+ }
361
+
362
+ const refresh = async () => {
363
+ restoreDraft()
364
+ const requestedPage = page
365
+ try {
366
+ const comments = await call("list", requestedPage)
367
+ if (page !== requestedPage) return
368
+ listed = comments
369
+ render(visibleComments())
370
+ renderPins(listed)
371
+ if (dialog.open) status.textContent = ""
372
+ } catch {
373
+ if (page !== requestedPage) return
374
+ renderPins([])
375
+ if (dialog.open) status.textContent = "Could not load comments. Reopen Annotations to try again."
376
+ }
377
+ }
378
+
379
+ launcher.addEventListener("click", async () => {
380
+ if (dialog.open) {
381
+ hideNote()
382
+ return
383
+ }
384
+ focusKey = null
385
+ find("details").hidden = true
386
+ find("details").open = false
387
+ showNote()
388
+ status.textContent = "Loading comments…"
389
+ await refresh()
390
+ })
391
+
392
+ comment.addEventListener("input", storeDraft)
393
+ const dismiss = () => {
394
+ hideNote()
395
+ launcher.focus()
396
+ }
397
+ find("[data-close]").addEventListener("click", dismiss)
398
+ dialog.addEventListener("keydown", event => {
399
+ if (event.key !== "Escape") return
400
+ event.preventDefault()
401
+ event.stopPropagation()
402
+ dismiss()
403
+ })
404
+ find("[data-clear]").addEventListener("click", () => {
405
+ showReference(null)
406
+ storeDraft()
407
+ })
408
+ find("[data-select]").addEventListener("click", () => {
409
+ hideNote()
410
+ pinsLayer.hidden = true
411
+ elementPicker.start()
412
+ })
413
+
414
+ find("form").addEventListener("submit", async event => {
415
+ event.preventDefault()
416
+ if (save.disabled) return
417
+ if (!comment.value.trim()) {
418
+ status.textContent = "Enter a comment."
419
+ comment.focus()
420
+ return
421
+ }
422
+ save.disabled = true
423
+ status.textContent = "Saving comment…"
424
+ const savedPage = page
425
+ const draft = { ...savedPage, comment: comment.value, element: selected }
426
+ try {
427
+ if (!(await call("save", draft))) throw new Error("Comment was not saved")
428
+ if (page !== savedPage) return
429
+ if (comment.value === draft.comment && selected === draft.element) {
430
+ comment.value = ""
431
+ showReference(null)
432
+ storeDraft()
433
+ }
434
+ status.textContent = "Comment saved."
435
+ focusKey = referenceKey(draft.element) || null
436
+ try {
437
+ const comments = await call("list", savedPage)
438
+ if (page !== savedPage) return
439
+ listed = comments
440
+ render(visibleComments())
441
+ renderPins(listed)
442
+ if (focusKey) find("details").open = true
443
+ } catch {
444
+ status.textContent = "Comment saved. Reopen Annotations to reload comments."
445
+ }
446
+ } catch {
447
+ status.textContent = "Could not save the comment. Try again."
448
+ } finally {
449
+ save.disabled = false
450
+ }
451
+ })
452
+
453
+ window[mounted] = () => {
454
+ elementPicker.stop()
455
+ resizeObserver.disconnect()
456
+ documentObserver.disconnect()
457
+ cancelAnimationFrame(positionFrame)
458
+ events.abort()
459
+ host.remove()
460
+ delete window[mounted]
461
+ }
462
+ document.addEventListener("turbo:before-render", () => {
463
+ if (dialog.open) hideNote()
464
+ elementPicker.stop()
465
+ pinsLayer.hidden = false
466
+ }, { signal: events.signal })
467
+ document.addEventListener("turbo:load", pageChanged, { signal: events.signal })
468
+ window.addEventListener("popstate", pageChanged, { signal: events.signal })
469
+ window.navigation?.addEventListener("currententrychange", pageChanged, { signal: events.signal })
470
+ void refresh()
471
+ }
@@ -0,0 +1,209 @@
1
+ (host, picker, highlight, signal, anchorAttribute, accessibility, onSelection) => {
2
+ let highlightTimer
3
+ let semanticMatches = new WeakMap()
4
+ const positionKeys = new WeakMap()
5
+ const selectedPositions = new Map()
6
+
7
+ const mark = element => {
8
+ clearTimeout(highlightTimer)
9
+ highlight.hidden = !element
10
+ if (!element) return
11
+ const { x, y, width, height } = element.getBoundingClientRect()
12
+ Object.assign(highlight.style, { left: `${x}px`, top: `${y}px`, width: `${width}px`, height: `${height}px` })
13
+ }
14
+
15
+ const label = element => {
16
+ const labelledBy = element.getAttribute("aria-labelledby")?.split(/\s+/)
17
+ .map(id => document.getElementById(id)?.textContent).join(" ").trim()
18
+ const name = labelledBy || element.getAttribute("aria-label") || element.labels?.[0]?.textContent ||
19
+ element.getAttribute("alt") || element.textContent || ""
20
+ return name.replace(/\s+/g, " ").trim().slice(0, 160) || element.localName
21
+ }
22
+
23
+ const selectorFor = element => {
24
+ const path = []
25
+ for (let node = element; node; node = node.parentElement) {
26
+ if (node === document.documentElement) return { selector: ["html", ...path].join(" > "), stable: false }
27
+ const testId = node.getAttribute("data-testid")
28
+ const anchorValue = anchorAttribute && node.getAttribute(anchorAttribute)
29
+ const anchors = [
30
+ testId && `[data-testid=${CSS.escape(testId)}]`,
31
+ anchorValue && `[${anchorAttribute}=${CSS.escape(anchorValue)}]`,
32
+ node.id && !/[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}/i.test(node.id) && `#${CSS.escape(node.id)}`,
33
+ ]
34
+ const unique = anchors.find(anchor => anchor && document.querySelectorAll(anchor).length === 1)
35
+ if (unique) return { selector: [unique, ...path].join(" > "), stable: path.length === 0 }
36
+ const siblings = Array.from(node.parentElement.children).filter(sibling => sibling.localName === node.localName)
37
+ path.unshift(`${CSS.escape(node.localName)}:nth-of-type(${siblings.indexOf(node) + 1})`)
38
+ }
39
+ }
40
+
41
+ const findElement = selector => {
42
+ try {
43
+ const matches = document.querySelectorAll(selector)
44
+ if (matches.length === 1) return matches[0]
45
+ } catch {
46
+ // A locator edited in the Markdown file might no longer be valid.
47
+ }
48
+ }
49
+
50
+ const offsetIn = (element, event) => {
51
+ if (!(event && Number.isFinite(event.clientX) && Number.isFinite(event.clientY))) {
52
+ return { x: 0.5, y: 0.5 }
53
+ }
54
+ const rect = element.getBoundingClientRect()
55
+ const width = Math.max(rect.width, 1)
56
+ const height = Math.max(rect.height, 1)
57
+ return {
58
+ x: Math.min(1, Math.max(0, (event.clientX - rect.left) / width)),
59
+ y: Math.min(1, Math.max(0, (event.clientY - rect.top) / height)),
60
+ }
61
+ }
62
+
63
+ const start = () => {
64
+ picker.hidden = false
65
+ picker.querySelector("button").focus()
66
+ }
67
+
68
+ const stop = () => {
69
+ picker.hidden = true
70
+ mark(null)
71
+ }
72
+
73
+ const rememberPosition = element => {
74
+ let key = positionKeys.get(element)
75
+ if (!key) {
76
+ key = Array.from(crypto.getRandomValues(new Uint8Array(12)), value => value.toString(16).padStart(2, "0")).join("")
77
+ positionKeys.set(element, key)
78
+ }
79
+ selectedPositions.set(key, new WeakRef(element))
80
+ return key
81
+ }
82
+
83
+ const referenceFor = (element, event) => {
84
+ const { selector, stable } = selectorFor(element)
85
+ const path = accessibility.path(element)
86
+ const { role, name } = path.at(-1)
87
+ const matches = stable ? [] : accessibility.matching(path)
88
+ const strategy = stable ? "identifier" : (matches.length === 1 && matches[0] === element ? "semantic" : "position")
89
+ const hints = []
90
+ if (element.closest("[aria-hidden=true]")) hints.push("hidden")
91
+ if (accessibility.controls.has(role) && !name) hints.push("name")
92
+ if (role === "generic" && (element.onclick || element.hasAttribute("onclick"))) hints.push("native")
93
+ if (matches.length > 1) hints.push("duplicate")
94
+ if (strategy === "position") hints.push("identifier")
95
+
96
+ const metadata = { path, strategy, hints }
97
+ if (strategy === "position") metadata.key = rememberPosition(element)
98
+ const targetLabel = name || (accessibility.controls.has(role) ? role : label(element))
99
+ return { selector, label: targetLabel, accessibility: metadata, ...offsetIn(element, event) }
100
+ }
101
+
102
+ const finish = (element, event) => {
103
+ stop()
104
+ if (!element) return onSelection(null)
105
+ onSelection(referenceFor(element, event))
106
+ }
107
+
108
+ const isDemoControl = event => event.composedPath().some(element => element === host || element.id === "demo-stage-player")
109
+
110
+ const candidate = event => {
111
+ if (!(event.target instanceof Element) || isDemoControl(event)) return
112
+ if (event.target === document.body || event.target === document.documentElement) return
113
+ return event.target.closest("button, a[href], summary, input, select, textarea, [role=button], [role=link], [role=checkbox], [role=switch], [role=tab]") || event.target
114
+ }
115
+
116
+ picker.querySelector("button").addEventListener("click", () => finish())
117
+ const capture = { capture: true, signal }
118
+ for (const name of ["pointerover", "focusin"]) {
119
+ document.addEventListener(name, event => {
120
+ if (!picker.hidden) mark(candidate(event))
121
+ }, capture)
122
+ }
123
+
124
+ for (const name of ["pointerdown", "pointerup", "click"]) {
125
+ window.addEventListener(name, event => {
126
+ if (picker.hidden || isDemoControl(event)) return
127
+ event.preventDefault()
128
+ event.stopImmediatePropagation()
129
+ if (name === "click") {
130
+ const element = candidate(event)
131
+ if (element) finish(element, event)
132
+ }
133
+ }, capture)
134
+ }
135
+
136
+ window.addEventListener("keydown", event => {
137
+ if (picker.hidden) return
138
+ const element = candidate(event)
139
+ if (event.key !== "Escape" && (event.key !== "Enter" || !element)) return
140
+ event.preventDefault()
141
+ event.stopImmediatePropagation()
142
+ finish(event.key === "Escape" ? null : element)
143
+ }, capture)
144
+
145
+ const resolve = reference => {
146
+ const element = findElement(reference.selector)
147
+ if (element && label(element) === reference.label && element.getClientRects().length) return element
148
+ }
149
+
150
+ const locateLegacy = reference => {
151
+ const exact = resolve(reference)
152
+ if (exact) return exact
153
+ if (reference.selector.includes(" > ")) return
154
+ const element = findElement(reference.selector)
155
+ if (element?.getClientRects().length) return element
156
+ }
157
+
158
+ const matchingPath = reference => {
159
+ if (!semanticMatches.has(reference)) {
160
+ semanticMatches.set(reference, accessibility.matching(reference.accessibility.path))
161
+ }
162
+ return semanticMatches.get(reference)
163
+ }
164
+
165
+ const locate = reference => {
166
+ const anchor = reference.accessibility
167
+ if (!anchor) return locateLegacy(reference)
168
+
169
+ let element
170
+ if (anchor.strategy === "identifier") {
171
+ element = findElement(reference.selector)
172
+ } else if (anchor.strategy === "position") {
173
+ element = selectedPositions.get(anchor.key)?.deref()
174
+ } else if (anchor.strategy === "semantic") {
175
+ const matches = matchingPath(reference)
176
+ if (matches.length === 1) element = matches[0]
177
+ }
178
+
179
+ if (element?.isConnected && element.getClientRects().length && getComputedStyle(element).visibility === "visible") return element
180
+ }
181
+
182
+ const invalidate = () => {
183
+ semanticMatches = new WeakMap()
184
+ accessibility.invalidate()
185
+ for (const [key, element] of selectedPositions) {
186
+ if (!element.deref()?.isConnected) selectedPositions.delete(key)
187
+ }
188
+ }
189
+
190
+ const reveal = (reference, closeDialog) => {
191
+ const element = locate(reference)
192
+ if (!element) return false
193
+
194
+ closeDialog()
195
+ element.scrollIntoView({ block: "center", inline: "nearest" })
196
+ if (element instanceof HTMLElement && element.tabIndex < 0 && !element.hasAttribute("tabindex")) {
197
+ element.tabIndex = -1
198
+ element.addEventListener("blur", () => element.removeAttribute("tabindex"), { once: true })
199
+ }
200
+ element.focus?.({ preventScroll: true })
201
+ mark(element)
202
+ highlightTimer = setTimeout(() => mark(null), 2000)
203
+ return true
204
+ }
205
+
206
+ const ambiguous = reference => reference.accessibility?.strategy === "semantic" && matchingPath(reference).length > 1
207
+
208
+ return { start, stop, locate, reveal, invalidate, ambiguous }
209
+ }