@aceshooting/lyra-ui 29.0.2 → 29.1.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 (521) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +19 -26
  3. package/design-tokens.json +1 -1
  4. package/dist/cli/migrate-wa.mjs +2 -0
  5. package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +5 -3
  6. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +4 -3
  7. package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +1 -1
  8. package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +21 -5
  9. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +14 -11
  10. package/dist/components/agent-tools/agent-trace/agent-trace.styles.js +1 -1
  11. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
  12. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +34 -7
  13. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +25 -11
  14. package/dist/components/agent-tools/eval-result/eval-result-source.js +1 -0
  15. package/dist/components/agent-tools/eval-result/eval-result.class.d.ts +31 -11
  16. package/dist/components/agent-tools/eval-result/eval-result.class.js +29 -15
  17. package/dist/components/agent-tools/eval-result/eval-result.styles.js +1 -1
  18. package/dist/components/agent-tools/eval-result/eval-run-result.d.ts +10 -0
  19. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.d.ts +26 -5
  20. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +16 -6
  21. package/dist/components/agent-tools/span-waterfall/span-waterfall.d.ts +1 -1
  22. package/dist/components/agent-tools/span-waterfall/span-waterfall.js +1 -1
  23. package/dist/components/agent-tools/span-waterfall/span-waterfall.styles.js +1 -1
  24. package/dist/components/agent-tools/task-list/task-list.class.d.ts +29 -6
  25. package/dist/components/agent-tools/task-list/task-list.class.js +13 -7
  26. package/dist/components/agent-tools/task-list/task-list.d.ts +1 -1
  27. package/dist/components/agent-tools/task-list/task-list.js +1 -1
  28. package/dist/components/agent-tools/task-list/task-list.styles.js +1 -1
  29. package/dist/components/agent-tools/terminal/terminal.class.d.ts +9 -5
  30. package/dist/components/agent-tools/terminal/terminal.class.js +8 -8
  31. package/dist/components/agent-tools/test-results/test-results.class.d.ts +16 -4
  32. package/dist/components/agent-tools/test-results/test-results.class.js +15 -6
  33. package/dist/components/agent-tools/test-results/test-results.d.ts +1 -0
  34. package/dist/components/agent-tools/test-results/test-results.js +1 -1
  35. package/dist/components/agent-tools/test-results/test-results.styles.js +1 -1
  36. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +7 -4
  37. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +2 -1
  38. package/dist/components/agent-tools/trace-tree/span-projection.js +1 -0
  39. package/dist/components/agent-tools/trace-tree/span-shared.d.ts +29 -0
  40. package/dist/components/agent-tools/trace-tree/span-shared.js +1 -0
  41. package/dist/components/agent-tools/trace-tree/span.d.ts +5 -35
  42. package/dist/components/agent-tools/trace-tree/span.js +1 -1
  43. package/dist/components/agent-tools/trace-tree/trace-tree.class.d.ts +27 -5
  44. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +19 -9
  45. package/dist/components/agent-tools/trace-tree/trace-tree.d.ts +1 -1
  46. package/dist/components/agent-tools/trace-tree/trace-tree.js +1 -1
  47. package/dist/components/agent-tools/trace-tree/trace-tree.styles.js +1 -1
  48. package/dist/components/charts/chart/bar-chart.class.d.ts +5 -1
  49. package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
  50. package/dist/components/charts/chart/box-plot.class.js +3 -3
  51. package/dist/components/charts/chart/bubble-chart.class.d.ts +5 -1
  52. package/dist/components/charts/chart/chart-prepared-data.d.ts +9 -0
  53. package/dist/components/charts/chart/chart-prepared-data.js +1 -0
  54. package/dist/components/charts/chart/chart-spatial-data.js +2 -0
  55. package/dist/components/charts/chart/chart-sync.js +1 -1
  56. package/dist/components/charts/chart/chart-table-sampling.js +1 -1
  57. package/dist/components/charts/chart/chart.class.d.ts +56 -6
  58. package/dist/components/charts/chart/chart.class.js +18 -8
  59. package/dist/components/charts/chart/chart.styles.js +1 -1
  60. package/dist/components/charts/chart/doughnut-chart.class.d.ts +5 -1
  61. package/dist/components/charts/chart/histogram-buckets.d.ts +1 -1
  62. package/dist/components/charts/chart/histogram-buckets.js +1 -1
  63. package/dist/components/charts/chart/histogram.class.d.ts +19 -4
  64. package/dist/components/charts/chart/histogram.class.js +1 -1
  65. package/dist/components/charts/chart/line-chart.class.d.ts +5 -1
  66. package/dist/components/charts/chart/lite-chart.class.d.ts +51 -11
  67. package/dist/components/charts/chart/lite-chart.class.js +33 -27
  68. package/dist/components/charts/chart/lite-chart.styles.js +1 -1
  69. package/dist/components/charts/chart/pie-chart.class.d.ts +5 -1
  70. package/dist/components/charts/chart/polar-area-chart.class.d.ts +5 -1
  71. package/dist/components/charts/chart/radar-chart.class.d.ts +5 -1
  72. package/dist/components/charts/chart/scatter-chart.class.d.ts +5 -1
  73. package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +6 -3
  74. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +6 -5
  75. package/dist/components/conversation/agent-workspace/agent-workspace.styles.js +1 -1
  76. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +8 -0
  77. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  78. package/dist/components/conversation/code-block/code-block-base.class.d.ts +5 -3
  79. package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
  80. package/dist/components/conversation/code-block/code-block-core.class.d.ts +4 -1
  81. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  82. package/dist/components/conversation/code-block/code-block-shared.d.ts +6 -4
  83. package/dist/components/conversation/code-block/code-block-shared.js +3 -2
  84. package/dist/components/conversation/code-block/code-block.class.d.ts +11 -4
  85. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  86. package/dist/components/conversation/code-block/code-block.d.ts +1 -1
  87. package/dist/components/conversation/code-block/code-block.styles.js +1 -1
  88. package/dist/components/conversation/code-block/shiki-types.d.ts +2 -0
  89. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  90. package/dist/components/conversation/markdown/markdown-base.class.d.ts +6 -4
  91. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  92. package/dist/components/conversation/markdown/markdown-code-header.d.ts +2 -2
  93. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  94. package/dist/components/conversation/markdown/markdown-core.class.d.ts +8 -3
  95. package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
  96. package/dist/components/conversation/markdown/markdown-shared.d.ts +5 -10
  97. package/dist/components/conversation/markdown/markdown-shared.js +5 -5
  98. package/dist/components/conversation/markdown/markdown-streaming-tail.js +1 -1
  99. package/dist/components/conversation/markdown/markdown.class.d.ts +17 -10
  100. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  101. package/dist/components/conversation/markdown/markdown.styles.js +1 -1
  102. package/dist/components/conversation/model-select/model-select.class.d.ts +4 -3
  103. package/dist/components/conversation/model-select/model-select.class.js +3 -2
  104. package/dist/components/conversation/model-select/model-select.styles.js +1 -1
  105. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.d.ts +2 -1
  106. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +2 -1
  107. package/dist/components/conversation/model-settings-panel/model-settings-panel.styles.js +1 -1
  108. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +3 -2
  109. package/dist/components/conversation/prompt-input/prompt-input.class.js +2 -1
  110. package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
  111. package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +10 -2
  112. package/dist/components/conversation/prompt-queue/prompt-queue.class.js +15 -6
  113. package/dist/components/conversation/prompt-queue/prompt-queue.styles.js +1 -1
  114. package/dist/components/conversation/realtime-session/realtime-session.class.d.ts +3 -1
  115. package/dist/components/conversation/realtime-session/realtime-session.class.js +2 -1
  116. package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
  117. package/dist/components/conversation/streaming-text/markdown-detection.d.ts +2 -0
  118. package/dist/components/conversation/streaming-text/markdown-detection.js +4 -1
  119. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +6 -2
  120. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +3 -3
  121. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -1
  122. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  123. package/dist/components/conversation/thread-list/thread-list.class.d.ts +34 -4
  124. package/dist/components/conversation/thread-list/thread-list.class.js +22 -15
  125. package/dist/components/conversation/thread-list/thread-list.d.ts +1 -1
  126. package/dist/components/conversation/thread-list/thread-list.js +1 -1
  127. package/dist/components/conversation/thread-list/thread-list.styles.js +1 -1
  128. package/dist/components/conversation/transcript-feed/transcript-feed.class.d.ts +6 -2
  129. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +3 -2
  130. package/dist/components/conversation/transcript-feed/transcript-feed.styles.js +1 -1
  131. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +3 -2
  132. package/dist/components/conversation/voice-picker/voice-picker.class.js +3 -2
  133. package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
  134. package/dist/components/data/calendar/calendar.class.d.ts +5 -2
  135. package/dist/components/data/calendar/calendar.class.js +1 -1
  136. package/dist/components/data/data-grid/data-grid-processing.js +2 -2
  137. package/dist/components/data/data-grid/data-grid.class.d.ts +22 -8
  138. package/dist/components/data/data-grid/data-grid.class.js +20 -19
  139. package/dist/components/data/data-grid/data-grid.styles.js +1 -1
  140. package/dist/components/data/document-library/document-library.class.d.ts +31 -4
  141. package/dist/components/data/document-library/document-library.class.js +25 -12
  142. package/dist/components/data/document-library/document-library.styles.js +1 -1
  143. package/dist/components/data/file-tree/file-tree.class.d.ts +30 -6
  144. package/dist/components/data/file-tree/file-tree.class.js +4 -3
  145. package/dist/components/data/file-tree/file-tree.d.ts +1 -0
  146. package/dist/components/data/file-tree/file-tree.js +1 -1
  147. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +31 -6
  148. package/dist/components/data/flow-canvas/flow-canvas.class.js +40 -19
  149. package/dist/components/data/flow-canvas/flow-canvas.styles.js +1 -1
  150. package/dist/components/data/flow-canvas/flow-model.js +1 -1
  151. package/dist/components/data/flow-canvas/flow-source.js +1 -0
  152. package/dist/components/data/flow-canvas/flow-types.d.ts +4 -2
  153. package/dist/components/data/flow-canvas/flow-viewport-index.js +1 -0
  154. package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +9 -3
  155. package/dist/components/data/flow-minimap/flow-minimap.class.js +11 -2
  156. package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
  157. package/dist/components/data/funnel/funnel.class.d.ts +7 -3
  158. package/dist/components/data/funnel/funnel.class.js +2 -2
  159. package/dist/components/data/heatmap/calendar-grid.d.ts +1 -1
  160. package/dist/components/data/heatmap/calendar-grid.js +1 -1
  161. package/dist/components/data/heatmap/heatmap-grid-navigation.js +1 -1
  162. package/dist/components/data/heatmap/heatmap-limits.d.ts +1 -1
  163. package/dist/components/data/heatmap/heatmap-matrix-source-controller.js +1 -0
  164. package/dist/components/data/heatmap/heatmap-matrix-source.d.ts +5 -0
  165. package/dist/components/data/heatmap/heatmap-matrix-source.js +1 -0
  166. package/dist/components/data/heatmap/heatmap-scale.d.ts +0 -16
  167. package/dist/components/data/heatmap/heatmap-scale.js +1 -1
  168. package/dist/components/data/heatmap/heatmap.class.d.ts +40 -11
  169. package/dist/components/data/heatmap/heatmap.class.js +26 -6
  170. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  171. package/dist/components/data/pagination/pagination.class.js +1 -1
  172. package/dist/components/data/sequence-strip/sequence-strip-item.d.ts +17 -0
  173. package/dist/components/data/sequence-strip/sequence-strip-source-controller.js +1 -0
  174. package/dist/components/data/sequence-strip/sequence-strip-source.d.ts +5 -0
  175. package/dist/components/data/sequence-strip/sequence-strip-source.js +1 -0
  176. package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +24 -19
  177. package/dist/components/data/sequence-strip/sequence-strip.class.js +23 -4
  178. package/dist/components/data/sequence-strip/sequence-strip.styles.js +1 -1
  179. package/dist/components/data/sparkline/sparkline.class.d.ts +17 -4
  180. package/dist/components/data/sparkline/sparkline.class.js +3 -3
  181. package/dist/components/data/sparkline/sparkline.styles.js +1 -1
  182. package/dist/components/data/table/table.class.d.ts +14 -10
  183. package/dist/components/data/table/table.class.js +17 -16
  184. package/dist/components/data/timeline/timeline.class.d.ts +5 -2
  185. package/dist/components/data/timeline/timeline.class.js +1 -1
  186. package/dist/components/data/tree/tree-item.class.js +1 -1
  187. package/dist/components/data/tree/tree-owner-controller.js +1 -1
  188. package/dist/components/data/tree/tree.class.d.ts +28 -6
  189. package/dist/components/data/tree/tree.class.js +3 -3
  190. package/dist/components/data/tree/tree.d.ts +1 -0
  191. package/dist/components/data/tree/tree.js +1 -1
  192. package/dist/components/data/word-cloud/word-cloud.class.d.ts +17 -7
  193. package/dist/components/data/word-cloud/word-cloud.class.js +6 -4
  194. package/dist/components/data/word-cloud/word-cloud.styles.js +1 -1
  195. package/dist/components/forms/catalog-picker-base.d.ts +1 -1
  196. package/dist/components/forms/catalog-picker-base.js +6 -6
  197. package/dist/components/forms/catalog-picker-base.styles.js +1 -1
  198. package/dist/components/forms/combobox/combobox.class.d.ts +7 -3
  199. package/dist/components/forms/combobox/combobox.class.js +1 -1
  200. package/dist/components/forms/combobox/option.class.d.ts +4 -2
  201. package/dist/components/forms/combobox/option.class.js +2 -2
  202. package/dist/components/forms/country-picker/country-picker.class.d.ts +3 -1
  203. package/dist/components/forms/country-picker/country-picker.class.js +1 -1
  204. package/dist/components/forms/currency-picker/currency-picker.class.d.ts +2 -0
  205. package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
  206. package/dist/components/forms/currency-picker/currency-presentation.js +1 -1
  207. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +6 -2
  208. package/dist/components/forms/emoji-picker/emoji-picker.class.js +3 -2
  209. package/dist/components/forms/emoji-picker/emoji-picker.styles.js +1 -1
  210. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +8 -2
  211. package/dist/components/forms/locale-picker/locale-picker.class.js +5 -4
  212. package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
  213. package/dist/components/forms/select/select.class.d.ts +11 -3
  214. package/dist/components/forms/select/select.class.js +4 -4
  215. package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +2 -0
  216. package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
  217. package/dist/components/forms/token-input/token-input.class.d.ts +6 -1
  218. package/dist/components/forms/token-input/token-input.class.js +15 -13
  219. package/dist/components/forms/unit-picker/unit-picker.class.d.ts +2 -0
  220. package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
  221. package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
  222. package/dist/components/layout/app-rail/app-rail.class.js +1 -1
  223. package/dist/components/layout/command-palette/command-palette.class.d.ts +5 -2
  224. package/dist/components/layout/command-palette/command-palette.class.js +2 -1
  225. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  226. package/dist/components/layout/menu/menu-item.class.d.ts +2 -2
  227. package/dist/components/layout/menu/menu-item.class.js +2 -2
  228. package/dist/components/layout/menu/menu.class.d.ts +1 -1
  229. package/dist/components/layout/menu/menu.class.js +1 -1
  230. package/dist/components/layout/menubar/menubar.class.d.ts +1 -1
  231. package/dist/components/layout/menubar/menubar.class.js +1 -1
  232. package/dist/components/layout/reorder-list/reorder-item.class.d.ts +2 -2
  233. package/dist/components/layout/reorder-list/reorder-item.class.js +2 -2
  234. package/dist/components/layout/reorder-list/reorder-list.class.d.ts +1 -1
  235. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  236. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +13 -9
  237. package/dist/components/layout/virtual-list/virtual-list.class.js +21 -17
  238. package/dist/components/media/av-player/av-cue-index.js +1 -0
  239. package/dist/components/media/av-player/av-cue-source.d.ts +13 -0
  240. package/dist/components/media/av-player/av-cue-source.js +1 -0
  241. package/dist/components/media/av-player/av-metadata.d.ts +2 -2
  242. package/dist/components/media/av-player/av-metadata.js +1 -1
  243. package/dist/components/media/av-player/av-player-cue-source-controller.js +1 -0
  244. package/dist/components/media/av-player/av-player.class.d.ts +34 -12
  245. package/dist/components/media/av-player/av-player.class.js +15 -10
  246. package/dist/components/media/flag/flag.class.js +1 -1
  247. package/dist/components/media/flag/language-map.js +1 -1
  248. package/dist/components/media/lightbox/lightbox-source.js +1 -0
  249. package/dist/components/media/lightbox/lightbox-types.d.ts +15 -0
  250. package/dist/components/media/lightbox/lightbox.class.d.ts +22 -21
  251. package/dist/components/media/lightbox/lightbox.class.js +6 -4
  252. package/dist/components/media/lightbox/lightbox.styles.js +1 -1
  253. package/dist/components/media/map/map-geojson-diff.d.ts +6 -6
  254. package/dist/components/media/map/map-geojson-diff.js +1 -1
  255. package/dist/components/media/map/map-loader.d.ts +5 -1
  256. package/dist/components/media/map/map.class.d.ts +24 -6
  257. package/dist/components/media/map/map.class.js +2 -2
  258. package/dist/components/media/map/map.styles.js +1 -1
  259. package/dist/components/media/video-playlist/video-playlist.class.d.ts +2 -1
  260. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  261. package/dist/components/overlays/chip/chip.class.d.ts +1 -1
  262. package/dist/components/overlays/chip/chip.class.js +1 -1
  263. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +30 -8
  264. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +22 -8
  265. package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +1 -1
  266. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  267. package/dist/components/retrieval/graph/graph-source-composition.js +1 -0
  268. package/dist/components/retrieval/graph/graph-source-controller.js +1 -0
  269. package/dist/components/retrieval/graph/graph-spatial-controller.js +2 -2
  270. package/dist/components/retrieval/graph/graph-spatial-model.js +1 -0
  271. package/dist/components/retrieval/graph/graph-spatial.js +1 -1
  272. package/dist/components/retrieval/graph/graph.class.d.ts +31 -6
  273. package/dist/components/retrieval/graph/graph.class.js +26 -5
  274. package/dist/components/retrieval/graph/graph.d.ts +1 -1
  275. package/dist/components/retrieval/graph/graph.js +1 -1
  276. package/dist/components/retrieval/graph/graph.styles.js +1 -1
  277. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +33 -4
  278. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +27 -17
  279. package/dist/components/retrieval/ingestion-queue/ingestion-queue.d.ts +1 -1
  280. package/dist/components/retrieval/ingestion-queue/ingestion-queue.js +1 -1
  281. package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
  282. package/dist/components/retrieval/knowledge-base/knowledge-base.class.d.ts +27 -4
  283. package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +29 -14
  284. package/dist/components/retrieval/knowledge-base/knowledge-base.styles.js +1 -1
  285. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.d.ts +17 -3
  286. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +15 -10
  287. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.styles.js +1 -1
  288. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +24 -5
  289. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +17 -10
  290. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.d.ts +1 -1
  291. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.js +1 -1
  292. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +1 -1
  293. package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
  294. package/dist/components/retrieval/mind-map/mind-map-model.js +1 -0
  295. package/dist/components/retrieval/mind-map/mind-map.class.d.ts +27 -4
  296. package/dist/components/retrieval/mind-map/mind-map.class.js +11 -7
  297. package/dist/components/retrieval/mind-map/mind-map.d.ts +1 -0
  298. package/dist/components/retrieval/mind-map/mind-map.js +1 -1
  299. package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
  300. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +24 -2
  301. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +17 -3
  302. package/dist/components/retrieval/neighbor-list/neighbor-list.d.ts +1 -1
  303. package/dist/components/retrieval/neighbor-list/neighbor-list.js +1 -1
  304. package/dist/components/retrieval/neighbor-list/neighbor-list.styles.js +1 -1
  305. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +8 -4
  306. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +11 -7
  307. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.styles.js +1 -1
  308. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.d.ts +12 -6
  309. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +30 -17
  310. package/dist/components/retrieval/retrieval-compare/retrieval-compare.styles.js +1 -1
  311. package/dist/components/retrieval/retrieval-results/retrieval-results-model.js +1 -0
  312. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +46 -5
  313. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +31 -9
  314. package/dist/components/retrieval/retrieval-results/retrieval-results.d.ts +1 -1
  315. package/dist/components/retrieval/retrieval-results/retrieval-results.js +1 -1
  316. package/dist/components/retrieval/retrieval-results/retrieval-results.styles.js +1 -1
  317. package/dist/components/utility/diff-view/diff-view.class.d.ts +16 -8
  318. package/dist/components/utility/diff-view/diff-view.class.js +3 -2
  319. package/dist/components/utility/diff-view/diff-view.styles.js +1 -1
  320. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +31 -3
  321. package/dist/components/utility/json-viewer/json-viewer.class.js +13 -4
  322. package/dist/components/utility/json-viewer/json-viewer.d.ts +1 -0
  323. package/dist/components/utility/json-viewer/json-viewer.js +1 -1
  324. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  325. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +6 -4
  326. package/dist/components/utility/mention-popover/mention-popover.class.js +6 -5
  327. package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +34 -7
  328. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +9 -7
  329. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +28 -4
  330. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +12 -11
  331. package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +3 -1
  332. package/dist/components/viewers/geojson-view/geojson-viewer.class.js +17 -16
  333. package/dist/components/viewers/geojson-view/geojson-viewer.d.ts +1 -1
  334. package/dist/components/viewers/geojson-view/geojson-viewer.js +1 -1
  335. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +31 -5
  336. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +11 -8
  337. package/dist/components/viewers/table-viewer-shared.js +19 -3
  338. package/dist/components/viewers/viewer-search-limits.js +1 -1
  339. package/dist/components/viewers/xml-viewer/xml-viewer.class.d.ts +35 -3
  340. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +20 -5
  341. package/dist/components/viewers/xml-viewer/xml-viewer.d.ts +1 -1
  342. package/dist/components/viewers/xml-viewer/xml-viewer.js +1 -1
  343. package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
  344. package/dist/countries.js +1 -1
  345. package/dist/data-sources.d.ts +34 -0
  346. package/dist/data-sources.js +1 -0
  347. package/dist/events.d.ts +51 -7
  348. package/dist/framework-types.d.ts +1 -1
  349. package/dist/internal/accessibility-visibility.d.ts +4 -2
  350. package/dist/internal/accessibility-visibility.js +1 -1
  351. package/dist/internal/accessible-text-controller.js +1 -1
  352. package/dist/internal/anchor-target.js +2 -2
  353. package/dist/internal/catalog-picker.d.ts +1 -7
  354. package/dist/internal/catalog-picker.js +1 -1
  355. package/dist/internal/collection-snapshot.js +1 -1
  356. package/dist/internal/default-strings/agent-tools.generated.js +1 -1
  357. package/dist/internal/default-strings/charts.generated.js +1 -1
  358. package/dist/internal/default-strings/conversation.generated.js +1 -1
  359. package/dist/internal/default-strings/data.generated.js +1 -1
  360. package/dist/internal/default-strings/forms.generated.js +1 -1
  361. package/dist/internal/default-strings/layout.generated.js +1 -1
  362. package/dist/internal/default-strings/media.generated.js +1 -1
  363. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  364. package/dist/internal/default-strings/shared.generated.js +1 -1
  365. package/dist/internal/default-strings/utility.generated.js +1 -1
  366. package/dist/internal/delimited-data.js +1 -1
  367. package/dist/internal/fixed-containing-block.js +1 -1
  368. package/dist/internal/flow-scene-envelope.js +1 -0
  369. package/dist/internal/graph-scene-controller.js +1 -0
  370. package/dist/internal/hierarchy-source-controller.js +1 -0
  371. package/dist/internal/hierarchy-source-view.js +29 -0
  372. package/dist/internal/hierarchy-source-view.styles.js +1 -0
  373. package/dist/internal/inherited-attribute-hub.d.ts +6 -0
  374. package/dist/internal/inherited-attribute-hub.js +1 -1
  375. package/dist/internal/intl-cache.js +1 -1
  376. package/dist/internal/keyed-index.js +1 -0
  377. package/dist/internal/localization-types.d.ts +1 -1
  378. package/dist/internal/localization.js +2 -2
  379. package/dist/internal/lyra-element.d.ts +2 -2
  380. package/dist/internal/lyra-element.js +3 -2
  381. package/dist/internal/native-modal-context.js +1 -1
  382. package/dist/internal/option-selection.js +1 -1
  383. package/dist/internal/package-metadata.js +1 -1
  384. package/dist/internal/positioner.js +1 -1
  385. package/dist/internal/resource-loader.d.ts +2 -0
  386. package/dist/internal/resource-loader.js +1 -1
  387. package/dist/internal/scoped-definitions.generated.js +1 -1
  388. package/dist/internal/search-haystack.js +1 -0
  389. package/dist/internal/selection-catalog.d.ts +5 -0
  390. package/dist/internal/selection-catalog.js +1 -1
  391. package/dist/internal/shiki-language-sources.js +1 -0
  392. package/dist/internal/source-page-controller.js +1 -0
  393. package/dist/internal/source-page-scope.js +1 -0
  394. package/dist/internal/source-request-controller.js +1 -0
  395. package/dist/internal/source-window-controller.js +1 -0
  396. package/dist/internal/spatial-source-controller.js +1 -0
  397. package/dist/internal/text-quote.d.ts +2 -6
  398. package/dist/internal/text-quote.js +1 -1
  399. package/dist/internal/theme-watcher.js +1 -1
  400. package/dist/internal/virtual-list-composition.js +1 -0
  401. package/dist/lyra.d.ts +1 -1
  402. package/dist/lyra.js +1 -1
  403. package/dist/testing/interaction-drivers.js +1 -1
  404. package/dist/testing/lyra-tag-event-map.js +1 -1
  405. package/dist/units.js +1 -1
  406. package/dist/utilities/data-preparation.d.ts +56 -0
  407. package/dist/utilities/data-preparation.js +1 -0
  408. package/dist/utilities/data-spatial.d.ts +26 -0
  409. package/dist/utilities/data-spatial.js +1 -0
  410. package/dist/utilities/index.d.ts +1 -1
  411. package/dist/utilities/index.js +1 -1
  412. package/llms/components/lr-activity-feed.md +7 -2
  413. package/llms/components/lr-agent-trace.md +49 -9
  414. package/llms/components/lr-agent-workspace.md +15 -8
  415. package/llms/components/lr-av-player.md +180 -10
  416. package/llms/components/lr-bar-chart.md +1 -1
  417. package/llms/components/lr-box-plot.md +8 -0
  418. package/llms/components/lr-bubble-chart.md +1 -1
  419. package/llms/components/lr-calendar.md +26 -3
  420. package/llms/components/lr-chart.md +310 -23
  421. package/llms/components/lr-chat-viewport.md +6 -0
  422. package/llms/components/lr-code-block-core.md +12 -7
  423. package/llms/components/lr-code-block.md +23 -9
  424. package/llms/components/lr-combobox.md +27 -15
  425. package/llms/components/lr-command-palette.md +16 -3
  426. package/llms/components/lr-country-picker.md +23 -6
  427. package/llms/components/lr-csv-viewer.md +95 -12
  428. package/llms/components/lr-currency-picker.md +23 -3
  429. package/llms/components/lr-data-grid.md +24 -6
  430. package/llms/components/lr-dataset-viewer.md +92 -11
  431. package/llms/components/lr-dialog.md +1 -1
  432. package/llms/components/lr-diff-view.md +19 -6
  433. package/llms/components/lr-document-library.md +60 -5
  434. package/llms/components/lr-doughnut-chart.md +1 -1
  435. package/llms/components/lr-embedding-explorer.md +89 -9
  436. package/llms/components/lr-emoji-picker.md +7 -2
  437. package/llms/components/lr-eval-dataset.md +56 -7
  438. package/llms/components/lr-eval-result.md +89 -4
  439. package/llms/components/lr-export-button.md +1 -1
  440. package/llms/components/lr-file-tree.md +60 -6
  441. package/llms/components/lr-flag.md +5 -2
  442. package/llms/components/lr-flow-canvas.md +152 -14
  443. package/llms/components/lr-flow-minimap.md +32 -4
  444. package/llms/components/lr-funnel.md +14 -0
  445. package/llms/components/lr-geojson-viewer.md +27 -10
  446. package/llms/components/lr-graph.md +43 -7
  447. package/llms/components/lr-heatmap.md +161 -5
  448. package/llms/components/lr-histogram.md +55 -9
  449. package/llms/components/lr-ingestion-queue.md +54 -3
  450. package/llms/components/lr-json-viewer.md +87 -7
  451. package/llms/components/lr-knowledge-base-admin.md +60 -4
  452. package/llms/components/lr-knowledge-base.md +121 -9
  453. package/llms/components/lr-knowledge-graph-explorer.md +106 -11
  454. package/llms/components/lr-lightbox.md +42 -6
  455. package/llms/components/lr-line-chart.md +28 -5
  456. package/llms/components/lr-lite-chart.md +96 -31
  457. package/llms/components/lr-locale-picker.md +6 -4
  458. package/llms/components/lr-map.md +67 -8
  459. package/llms/components/lr-markdown-core.md +10 -5
  460. package/llms/components/lr-markdown.md +23 -6
  461. package/llms/components/lr-mention-popover.md +11 -6
  462. package/llms/components/lr-mind-map.md +91 -10
  463. package/llms/components/lr-model-select.md +8 -4
  464. package/llms/components/lr-model-settings-panel.md +10 -2
  465. package/llms/components/lr-navigation-menu.md +1 -1
  466. package/llms/components/lr-neighbor-list.md +69 -2
  467. package/llms/components/lr-pie-chart.md +1 -1
  468. package/llms/components/lr-polar-area-chart.md +1 -1
  469. package/llms/components/lr-prompt-input.md +9 -2
  470. package/llms/components/lr-prompt-queue.md +11 -3
  471. package/llms/components/lr-radar-chart.md +1 -1
  472. package/llms/components/lr-rag-eval-dashboard.md +9 -2
  473. package/llms/components/lr-realtime-session.md +6 -2
  474. package/llms/components/lr-reorder-list.md +4 -0
  475. package/llms/components/lr-retrieval-compare.md +9 -4
  476. package/llms/components/lr-retrieval-results.md +104 -6
  477. package/llms/components/lr-scatter-chart.md +1 -1
  478. package/llms/components/lr-select.md +20 -10
  479. package/llms/components/lr-sequence-strip.md +92 -2
  480. package/llms/components/lr-span-waterfall.md +78 -8
  481. package/llms/components/lr-sparkline.md +42 -11
  482. package/llms/components/lr-spreadsheet-viewer.md +109 -14
  483. package/llms/components/lr-streaming-text-core.md +4 -2
  484. package/llms/components/lr-streaming-text.md +5 -1
  485. package/llms/components/lr-table.md +96 -115
  486. package/llms/components/lr-task-list.md +93 -9
  487. package/llms/components/lr-terminal.md +9 -0
  488. package/llms/components/lr-test-results.md +77 -3
  489. package/llms/components/lr-thread-list.md +86 -1
  490. package/llms/components/lr-time-zone-picker.md +8 -3
  491. package/llms/components/lr-timeline.md +5 -0
  492. package/llms/components/lr-token-input.md +7 -2
  493. package/llms/components/lr-tool-timeline.md +13 -4
  494. package/llms/components/lr-trace-tree.md +96 -10
  495. package/llms/components/lr-transcript-feed.md +9 -2
  496. package/llms/components/lr-tree.md +87 -15
  497. package/llms/components/lr-unit-picker.md +8 -3
  498. package/llms/components/lr-video-playlist.md +2 -0
  499. package/llms/components/lr-virtual-list.md +17 -8
  500. package/llms/components/lr-voice-picker.md +8 -3
  501. package/llms/components/lr-word-cloud.md +128 -12
  502. package/llms/components/lr-xml-viewer.md +106 -9
  503. package/llms/index.md +1 -1
  504. package/llms/peers.md +1 -1
  505. package/llms/shared/events-and-types.md +725 -264
  506. package/llms/shared/forms-and-accessibility.md +3 -17
  507. package/llms/shared/imports-and-registration.md +3 -17
  508. package/llms/shared/localization-and-rtl.md +0 -2
  509. package/llms/shared/styles-and-tokens.md +27 -36
  510. package/llms/shared/testing-and-utilities.md +4 -5
  511. package/llms/shared.md +770 -349
  512. package/llms.txt +1 -2
  513. package/locales.json +139 -139
  514. package/package.json +13 -4
  515. package/registrations.json +1 -1
  516. package/skills/compose-lyra-interfaces/SKILL.md +6 -8
  517. package/skills/lyra-ui/SKILL.md +20 -51
  518. package/skills/lyra-ui/commands/review.md +16 -33
  519. package/skills/lyra-ui/commands/update.md +6 -5
  520. package/skills/lyra-ui/online-api.md +15 -0
  521. package/skills/lyra-ui/reporting.md +2 -1
@@ -1,4 +1,4 @@
1
- import type{CustomElementUpgradeObserver}from'./custom-element-upgrade-observer.js';export{composedParentElement}from'./active-element.js';type AccessibilityTextTruncationReason='ancestors'|'characters'|'depth'|'nodes';export interface ComposedAccessibilityTextOptions{
1
+ import type{CustomElementUpgradeObserver}from'./custom-element-upgrade-observer.js';import{type InheritedAttributeRelease}from'./inherited-attribute-hub.js';export{composedParentElement}from'./active-element.js';type AccessibilityTextTruncationReason='ancestors'|'characters'|'depth'|'nodes';export interface ComposedAccessibilityTextOptions{
2
2
  /** Whether a top-level Text node starts visible. Element visibility is resolved from CSS. */
3
3
  inheritedTextVisible?:boolean;
4
4
  /** Total UTF-16 code-unit ceiling shared by every supplied root. */
@@ -55,6 +55,8 @@ export declare function isAccessibilityExcluded(element:Element):boolean;
55
55
  * next bind records the baseline. A callback that gets `false` can skip rebinding and recomputing.
56
56
  */
57
57
  export declare function accessibleTextRecordsMatter(observer:MutationObserver,records:readonly MutationRecord[]):boolean;
58
+ /** Shared ancestor subscriptions owned by an accessible-text controller. */
59
+ export interface AccessibleTextAncestors{readonly releases:InheritedAttributeRelease[];readonly enabled:boolean;readonly changed:(records:MutationRecord[])=>void;}export declare function releaseAccessibleTextAncestors(ancestors:AccessibleTextAncestors):void;
58
60
  /** Opt-in tracking of `aria-labelledby` targets: their releases and the change callback. */
59
61
  export interface AccessibleTextReferences{readonly releases:Array<()=>void>;readonly changed:()=>void;}export declare function releaseAccessibleTextReferences(references:AccessibleTextReferences):void;export declare function labelReferenceRecordsMatter(records:readonly MutationRecord[],ids:ReadonlySet<string>,referenced:ReadonlySet<Element>):boolean;
60
62
  /**
@@ -68,7 +70,7 @@ export interface AccessibleTextReferences{readonly releases:Array<()=>void>;read
68
70
  * also listen for. Components whose accessible text does not depend on slot assignment pass nothing
69
71
  * and keep the narrower filter, so widening it here changes nothing for them.
70
72
  */
71
- export declare function bindAccessibleTextObserver(observer:MutationObserver|undefined,host:Element,extraAttributes?:readonly string[],upgrades?:CustomElementUpgradeObserver,references?:AccessibleTextReferences):void;
73
+ export declare function bindAccessibleTextObserver(observer:MutationObserver|undefined,host:Element,extraAttributes?:readonly string[],upgrades?:CustomElementUpgradeObserver,references?:AccessibleTextReferences,ancestors?:AccessibleTextAncestors):void;
72
74
  /**
73
75
  * Iteratively extracts a bounded accessible name/text projection through slots and open shadow
74
76
  * roots. The result reports every ceiling it reached so authoritative-name, announcement and
@@ -1 +1 @@
1
- import{composedParentElement}from"./active-element.js";import{assignedSlotOf}from"./composed-tree.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element),ignoreSemanticExclusion=!1){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||!ignoreSemanticExclusion&&(element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden")))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}const filteringObservers=new WeakSet,ancestorVisibilityBaselines=new WeakMap,contentVisibilityBaselines=new WeakMap;function visibilityKey(element,state=accessibilityElementState(element)){return[state.subtreeExcluded,state.visibilityHidden,state.display,element.hasAttribute("open")].join("|")}function ancestorPresentationKey(element){const style=element.style,customProperties=style?Array.from(style).filter(name=>name.startsWith("--")).sort().map(name=>`${name}:${style.getPropertyValue(name)}!${style.getPropertyPriority(name)}`):[];return[element.getAttribute("class")??"",...customProperties].join("|")}function ancestorVisibilityBaseline(element,state){return{visibility:state&&element.localName!=="area"&&element.localName!=="map"?visibilityKey(element,state):visibilityKey(element),presentation:ancestorPresentationKey(element)}}function accessibleTextRecordsMatter(observer,records){const baseline=ancestorVisibilityBaselines.get(observer);if(!filteringObservers.has(observer)||!baseline)return filteringObservers.add(observer),!0;const keys=new Map,currentKey=element=>{let key=keys.get(element);return key===void 0&&keys.set(element,key=visibilityKey(element)),key};let contentChecked=!1;for(const record of records){const target=record.target;if(record.type!=="attributes"||!baseline.has(target))return!0;const previous=baseline.get(target);if(currentKey(target)!==previous.visibility)return!0;const presentation=ancestorPresentationKey(target);if(presentation!==previous.presentation){const content=contentVisibilityBaselines.get(observer);if(content?.incomplete)return!0;if(!contentChecked){for(const[element,visibility]of content?.elements??[])if(currentKey(element)!==visibility)return!0;contentChecked=!0}previous.presentation=presentation}}return!1}function releaseAccessibleTextReferences(references){for(const release of references.releases.splice(0))release()}function labelReferenceRecordsMatter(records,ids,referenced){const affects=node=>{if(node.nodeType!==1)return!1;const element=node;if(referenced.has(element)||ids.has(element.id))return!0;for(const reference of referenced)if(element.contains(reference))return!0;const pending=[element];let visited=0;for(;pending.length;){if(++visited>4096)return!0;const descendant=pending.pop();if(ids.has(descendant.id))return!0;for(const child of descendant.children){if(pending.length>4096)return!0;pending.push(child)}}return!1};return records.some(record=>record.type==="attributes"?referenced.has(record.target)||ids.has(record.target.id):[...record.addedNodes,...record.removedNodes].some(affects))}function bindAccessibleTextObserver(observer,host,extraAttributes=[],upgrades,references){if(!observer)return;observer.disconnect(),references&&releaseAccessibleTextReferences(references),observeAccessibleTextNode(observer,host,extraAttributes);const baseline=filteringObservers.has(observer)?new Map:void 0,baselineElements=[];let ancestor=composedParentElement(host);for(;ancestor;)observer.observe(ancestor,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),baseline&&baselineElements.push(ancestor),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0})){observeAccessibleTextNode(observer,assigned,extraAttributes);let ancestor2=assigned.nodeType===1?composedParentElement(assigned):assigned.parentElement;for(;ancestor2;)ancestor2!==host&&!host.contains(ancestor2)&&ancestor2.getRootNode()!==host.shadowRoot&&(observer.observe(ancestor2,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),baseline&&baselineElements.push(ancestor2)),ancestor2=composedParentElement(ancestor2)}const contentBaseline=baseline?{elements:new Map,incomplete:!1}:void 0,observationExclusions=new Map,walkStates=new Map,result=composedAccessibilityTextResult(host.childNodes,{requireRendered:!1,isSubtreeExcluded:element=>observationExclusions.get(element)??isAccessibilitySubtreeExcluded(element),onElementState:(element,state)=>{baseline&&walkStates.set(element,state);const ownedWrapper=element.getRootNode()===host.shadowRoot,excluded=ownedWrapper&&state.subtreeExcluded?accessibilityElementState(element,void 0,!0).subtreeExcluded:state.subtreeExcluded;observationExclusions.set(element,excluded),contentBaseline&&(contentBaseline.elements.set(element,visibilityKey(element,state)),excluded&&ownedWrapper&&(contentBaseline.incomplete=!0))},shouldPrune:element=>(upgrades?.observeElement(element),!1)});if(baseline){for(const element of baselineElements)baseline.set(element,ancestorVisibilityBaseline(element,walkStates.get(element)));ancestorVisibilityBaselines.set(observer,baseline)}contentBaseline&&(contentBaseline.incomplete||=result.truncated,contentVisibilityBaselines.set(observer,contentBaseline));for(const root of result.traversedShadowRoots)root!==host.shadowRoot&&observeAccessibleTextNode(observer,root,extraAttributes);if(!references)return;for(const reference of result.referencedElements)observeAccessibleTextNode(observer,reference,extraAttributes);if(!result.labelReferenceIds.size)return;const Observer=host.ownerDocument.defaultView?.MutationObserver;for(const root of result.labelReferenceRoots){const release=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:records=>{labelReferenceRecordsMatter(records,result.labelReferenceIds,result.referencedElements)&&references.changed()}});release&&references.releases.push(release)}}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state),context.onElementState?.(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){let branch=node.nodeType===1?node:assignedSlotOf(node)??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):assignedSlotOf(node)??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function inheritedVisibilityHidden(context,node){const ancestor=node.nodeType===1?composedParentElement(node):assignedSlotOf(node)??node.parentElement;return ancestor?cachedElementState(context,ancestor).visibilityHidden:!1}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,context.labelReferenceIds.add(id),!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}const OWNED_CLOSED_POPUP_SELECTOR='[part~="popup"], .submenu-surface';function hasOwnedClosedPopupAncestor(node){let current=composedParentElement(node);for(;current;){if(current.hidden&&current.matches(OWNED_CLOSED_POPUP_SELECTOR))return!0;current=composedParentElement(current)}return!1}function isAncestorBoundaryExternallyUnrendered(context){if(context.externallyUnrenderedBoundary!==void 0)return context.externallyUnrenderedBoundary;const boundary=context.ancestorBoundary;let result=!1;if(boundary&&!cachedSubtreeExcluded(context,boundary)){const candidate=boundary;if(typeof candidate.checkVisibility=="function")try{result=!candidate.checkVisibility({contentVisibilityAuto:!0})&&hasOwnedClosedPopupAncestor(boundary)}catch{result=!1}}return context.externallyUnrenderedBoundary=result,result}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})?!0:context.ignoreInheritedVisibility&&isAncestorBoundaryExternallyUnrendered(context)}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&assignedSlotOf(node)===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden||context.visibilityBaselineHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,onElementState:resolved.onElementState,ignoreInheritedVisibility:resolved.skipRootAncestorValidation===!0||resolved.ignoreInheritedVisibility===!0,labelReferenceRoots:new Set,labelReferenceIds:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visibilityBaselineHidden:!1,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,labelReferenceIds:context.labelReferenceIds,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const validated=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root);context.visibilityBaselineHidden=(root.nodeType===1||!resolved.skipRootAncestorValidation)&&context.ignoreInheritedVisibility&&inheritedVisibilityHidden(context,root);const ancestorState=context.visibilityBaselineHidden?{available:validated.available,inheritedTextVisible:!0}:validated;if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,labelReferenceIds:context.labelReferenceIds,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue,labelReferenceRecordsMatter,releaseAccessibleTextReferences};
1
+ import{composedParentElement}from"./active-element.js";import{assignedSlotOf}from"./composed-tree.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element),ignoreSemanticExclusion=!1){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||!ignoreSemanticExclusion&&(element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden")))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}const filteringObservers=new WeakSet,ancestorVisibilityBaselines=new WeakMap,contentVisibilityBaselines=new WeakMap;function visibilityKey(element,state=accessibilityElementState(element)){return[state.subtreeExcluded,state.visibilityHidden,state.display,element.hasAttribute("open")].join("|")}function ancestorPresentationKey(element){const style=element.style,customProperties=style?Array.from(style).filter(name=>name.startsWith("--")).sort().map(name=>`${name}:${style.getPropertyValue(name)}!${style.getPropertyPriority(name)}`):[];return[element.getAttribute("class")??"",...customProperties].join("|")}function ancestorVisibilityBaseline(element,state){return{visibility:state&&element.localName!=="area"&&element.localName!=="map"?visibilityKey(element,state):visibilityKey(element),presentation:ancestorPresentationKey(element)}}function accessibleTextRecordsMatter(observer,records){const baseline=ancestorVisibilityBaselines.get(observer);if(!filteringObservers.has(observer)||!baseline)return filteringObservers.add(observer),!0;const keys=new Map,currentKey=element=>{let key=keys.get(element);return key===void 0&&keys.set(element,key=visibilityKey(element)),key};let contentChecked=!1;for(const record of records){const target=record.target;if(record.type!=="attributes"||!baseline.has(target))return!0;const previous=baseline.get(target);if(currentKey(target)!==previous.visibility)return!0;const presentation=ancestorPresentationKey(target);if(presentation!==previous.presentation){const content=contentVisibilityBaselines.get(observer);if(content?.incomplete)return!0;if(!contentChecked){for(const[element,visibility]of content?.elements??[])if(currentKey(element)!==visibility)return!0;contentChecked=!0}previous.presentation=presentation}}return!1}function releaseAccessibleTextAncestors(ancestors){for(const release of ancestors.releases.splice(0))release()}function releaseAccessibleTextReferences(references){for(const release of references.releases.splice(0))release()}function labelReferenceRecordsMatter(records,ids,referenced){const affects=node=>{if(node.nodeType!==1)return!1;const element=node;if(referenced.has(element)||ids.has(element.id))return!0;for(const reference of referenced)if(element.contains(reference))return!0;const pending=[element];let visited=0;for(;pending.length;){if(++visited>4096)return!0;const descendant=pending.pop();if(ids.has(descendant.id))return!0;for(const child of descendant.children){if(pending.length>4096)return!0;pending.push(child)}}return!1};return records.some(record=>record.type==="attributes"?referenced.has(record.target)||ids.has(record.target.id):[...record.addedNodes,...record.removedNodes].some(affects))}function bindAccessibleTextObserver(observer,host,extraAttributes=[],upgrades,references,ancestors){if(!observer)return;observer.disconnect(),ancestors&&releaseAccessibleTextAncestors(ancestors),references&&releaseAccessibleTextReferences(references),observeAccessibleTextNode(observer,host,extraAttributes);const baseline=filteringObservers.has(observer)?new Map:void 0,baselineElements=[],ancestorElements=new Set,observeAncestor=ancestor2=>{ancestors&&!ancestors.enabled||ancestorElements.has(ancestor2)||(ancestorElements.add(ancestor2),ancestors||observer.observe(ancestor2,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),baseline&&baselineElements.push(ancestor2))};let ancestor=composedParentElement(host);for(;ancestor&&(!ancestors||ancestors.enabled);)observeAncestor(ancestor),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0})){observeAccessibleTextNode(observer,assigned,extraAttributes);let ancestor2=assigned.nodeType===1?composedParentElement(assigned):assigned.parentElement;for(;ancestor2;)ancestor2!==host&&!host.contains(ancestor2)&&ancestor2.getRootNode()!==host.shadowRoot&&observeAncestor(ancestor2),ancestor2=composedParentElement(ancestor2)}if(ancestors?.enabled){const roots=new Map;for(const ancestor2 of ancestorElements){const root=ancestor2.getRootNode();let elements=roots.get(root);elements||roots.set(root,elements=new Set),elements.add(ancestor2)}const Observer2=host.ownerDocument.defaultView?.MutationObserver;for(const[root,elements]of roots){const release=subscribeInheritedAttributes(root,Observer2,{attributes:ANCESTOR_ATTRIBUTES,changed:records=>{const relevant=records.filter(record=>elements.has(record.target));relevant.length&&accessibleTextRecordsMatter(observer,relevant)&&ancestors.changed(relevant)}});release&&ancestors.releases.push(release)}}const contentBaseline=baseline?{elements:new Map,incomplete:!1}:void 0,observationExclusions=new Map,walkStates=new Map,result=composedAccessibilityTextResult(host.childNodes,{requireRendered:!1,isSubtreeExcluded:element=>observationExclusions.get(element)??isAccessibilitySubtreeExcluded(element),onElementState:(element,state)=>{baseline&&walkStates.set(element,state);const ownedWrapper=element.getRootNode()===host.shadowRoot,excluded=ownedWrapper&&state.subtreeExcluded?accessibilityElementState(element,void 0,!0).subtreeExcluded:state.subtreeExcluded;observationExclusions.set(element,excluded),contentBaseline&&(contentBaseline.elements.set(element,visibilityKey(element,state)),excluded&&ownedWrapper&&(contentBaseline.incomplete=!0))},shouldPrune:element=>(upgrades?.observeElement(element),!1)});if(baseline){for(const element of baselineElements)baseline.set(element,ancestorVisibilityBaseline(element,walkStates.get(element)));ancestorVisibilityBaselines.set(observer,baseline)}contentBaseline&&(contentBaseline.incomplete||=result.truncated,contentVisibilityBaselines.set(observer,contentBaseline));for(const root of result.traversedShadowRoots)root!==host.shadowRoot&&observeAccessibleTextNode(observer,root,extraAttributes);if(!references)return;for(const reference of result.referencedElements)observeAccessibleTextNode(observer,reference,extraAttributes);if(!result.labelReferenceIds.size)return;const Observer=host.ownerDocument.defaultView?.MutationObserver;for(const root of result.labelReferenceRoots){const release=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:records=>{labelReferenceRecordsMatter(records,result.labelReferenceIds,result.referencedElements)&&references.changed()}});release&&references.releases.push(release)}}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state),context.onElementState?.(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){let branch=node.nodeType===1?node:assignedSlotOf(node)??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):assignedSlotOf(node)??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function inheritedVisibilityHidden(context,node){const ancestor=node.nodeType===1?composedParentElement(node):assignedSlotOf(node)??node.parentElement;return ancestor?cachedElementState(context,ancestor).visibilityHidden:!1}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,context.labelReferenceIds.add(id),!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}const OWNED_CLOSED_POPUP_SELECTOR='[part~="popup"], .submenu-surface';function hasOwnedClosedPopupAncestor(node){let current=composedParentElement(node);for(;current;){if(current.hidden&&current.matches(OWNED_CLOSED_POPUP_SELECTOR))return!0;current=composedParentElement(current)}return!1}function isAncestorBoundaryExternallyUnrendered(context){if(context.externallyUnrenderedBoundary!==void 0)return context.externallyUnrenderedBoundary;const boundary=context.ancestorBoundary;let result=!1;if(boundary&&!cachedSubtreeExcluded(context,boundary)){const candidate=boundary;if(typeof candidate.checkVisibility=="function")try{result=!candidate.checkVisibility({contentVisibilityAuto:!0})&&hasOwnedClosedPopupAncestor(boundary)}catch{result=!1}}return context.externallyUnrenderedBoundary=result,result}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})?!0:context.ignoreInheritedVisibility&&isAncestorBoundaryExternallyUnrendered(context)}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&assignedSlotOf(node)===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden||context.visibilityBaselineHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,onElementState:resolved.onElementState,ignoreInheritedVisibility:resolved.skipRootAncestorValidation===!0||resolved.ignoreInheritedVisibility===!0,labelReferenceRoots:new Set,labelReferenceIds:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visibilityBaselineHidden:!1,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,labelReferenceIds:context.labelReferenceIds,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const validated=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root);context.visibilityBaselineHidden=(root.nodeType===1||!resolved.skipRootAncestorValidation)&&context.ignoreInheritedVisibility&&inheritedVisibilityHidden(context,root);const ancestorState=context.visibilityBaselineHidden?{available:validated.available,inheritedTextVisible:!0}:validated;if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,labelReferenceIds:context.labelReferenceIds,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue,labelReferenceRecordsMatter,releaseAccessibleTextAncestors,releaseAccessibleTextReferences};
@@ -1 +1 @@
1
- import{accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,releaseAccessibleTextReferences}from"./accessibility-visibility.js";import{assignedSlotOf}from"./composed-tree.js";import{CustomElementUpgradeObserver}from"./custom-element-upgrade-observer.js";import{OwnedFrame,OwnedTimeout}from"./owned-timer.js";class AccessibleTextController{constructor(host,slots,onChange,extraAttributes=[],enabled=!0,trackReferences=!1){this.host=host,this.slots=slots,this.onChange=onChange,this.extraAttributes=extraAttributes,this.enabled=enabled,this.upgrades=new CustomElementUpgradeObserver(()=>this.changed()),this.active=!1,this.preserveNextBinding=!1,this.drainedRecords=!1,this.onSlotChange=event=>{const slot=event.composedPath().find(target=>target.localName==="slot"&&target.getRootNode()===this.slotRoot);!slot||!this.slots.includes(slot.name)||this.changed()},trackReferences&&(this.references={releases:[],changed:()=>this.changed()}),this.visibilityFrame=new OwnedFrame(host),this.visibilityTimer=new OwnedTimeout(host),host.addController(this)}hostConnected(){this.active=!0,this.enabled&&(this.bindSlotRoot(),this.rebuild())}hostUpdated(){const preserveBinding=this.preserveNextBinding;if(this.preserveNextBinding=!1,this.active&&this.enabled){const observer=this.observer,pending=observer?.takeRecords()??[],relevant=observer&&pending.length>0&&this.recordsMatter(pending)&&accessibleTextRecordsMatter(observer,pending),previousRoot=this.slotRoot;this.bindSlotRoot(),(!preserveBinding||pending.length>0||this.drainedRecords||previousRoot!==this.slotRoot)&&this.bind(),relevant&&queueMicrotask(()=>{this.active&&this.enabled&&this.observer===observer&&this.host.isConnected&&this.notify(pending)})}}hostDisconnected(){this.active=!1,this.preserveNextBinding=!1,this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),this.references&&releaseAccessibleTextReferences(this.references)}adopted(){this.active&&this.enabled&&this.rebuild()}setEnabled(enabled){this.enabled!==enabled&&(this.enabled=enabled,this.active&&(enabled?(this.bindSlotRoot(),this.rebuild()):(this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),this.references&&releaseAccessibleTextReferences(this.references))))}bind(){bindAccessibleTextObserver(this.observer,this.host,this.extraAttributes,this.upgrades,this.references),this.drainedRecords=!1}preserveBindingForNextUpdate(){this.preserveNextBinding=!0}takeRecords(){const records=this.observer?.takeRecords()??[];return records.length>0&&(this.drainedRecords=!0),records}hasDrainedRecords(){return this.drainedRecords}text(){const root=this.host.shadowRoot,slots=root?[...root.querySelectorAll("slot")].filter(slot=>this.slots.includes(slot.name)):[],nodes=slots.length?slots.flatMap(slot=>[...slot.assignedNodes({flatten:!0})]):[...this.host.childNodes].filter(node=>node.nodeType!==1||this.slots.includes(node.getAttribute("slot")??""));return composedAccessibilityText(nodes)}hasContent(){return this.text().trim().length>0}rebuild(){this.cancelVisibilityRefresh(),this.observer?.disconnect(),this.upgrades.disconnect(),this.references&&releaseAccessibleTextReferences(this.references);const Observer=this.host.ownerDocument.defaultView?.MutationObserver;this.observer=Observer?new Observer((records,observer)=>{this.observer===observer&&this.recordsMatter(records)&&accessibleTextRecordsMatter(observer,records)&&this.changed(records)}):void 0,this.bind()}bindSlotRoot(){const root=this.host.shadowRoot??void 0;this.slotRoot!==root&&(this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=root,root?.addEventListener("slotchange",this.onSlotChange))}recordsMatter(records){if(this.slots.length===0)return!0;const feedsSlot=start=>{const visited=new Set;let node=start;for(;node&&node!==this.host&&!visited.has(node);){if(visited.add(node),node.parentNode===this.host){const name=node.nodeType===1?node.getAttribute("slot")??"":"";return this.slots.includes(name)}node=assignedSlotOf(node)??node.parentNode??node.host??null}return!0};return records.some(record=>record.type==="attributes"&&record.attributeName==="slot"?!0:record.target===this.host&&record.type==="childList"?[...record.addedNodes,...record.removedNodes].some(node=>node.nodeType!==1?this.slots.includes(""):this.slots.includes(node.getAttribute("slot")??"")):feedsSlot(record.target))}changed(records=[]){!this.active||!this.enabled||!this.host.isConnected||(this.bind(),this.notify(records))}notify(records){this.onChange(records),records.some(record=>record.type==="attributes"&&["class","style","hidden"].includes(record.attributeName??""))&&(this.visibilityFrame.pending||this.visibilityTimer.pending||this.visibilityFrame.schedule(()=>{this.visibilityTimer.schedule(0,()=>{this.active&&this.enabled&&this.onChange([])})}))}cancelVisibilityRefresh(){this.visibilityFrame.cancel(),this.visibilityTimer.cancel()}}export{AccessibleTextController};
1
+ import{releaseAccessibleTextAncestors,accessibleTextRecordsMatter,bindAccessibleTextObserver,composedAccessibilityText,releaseAccessibleTextReferences}from"./accessibility-visibility.js";import{assignedSlotOf}from"./composed-tree.js";import{CustomElementUpgradeObserver}from"./custom-element-upgrade-observer.js";import{OwnedFrame,OwnedTimeout}from"./owned-timer.js";class AccessibleTextController{constructor(host,slots,onChange,extraAttributes=[],enabled=!0,trackReferences=!1,observeAncestors=!0){this.host=host,this.slots=slots,this.onChange=onChange,this.extraAttributes=extraAttributes,this.enabled=enabled,this.upgrades=new CustomElementUpgradeObserver(()=>this.changed()),this.active=!1,this.preserveNextBinding=!1,this.drainedRecords=!1,this.onSlotChange=event=>{const slot=event.composedPath().find(target=>target.localName==="slot"&&target.getRootNode()===this.slotRoot);!slot||!this.slots.includes(slot.name)||this.changed()},this.ancestors={releases:[],get enabled(){return typeof observeAncestors=="function"?observeAncestors():observeAncestors},changed:records=>{this.drainingAncestors?this.drainingAncestors.push(...records):this.changed(records)}},trackReferences&&(this.references={releases:[],changed:()=>this.changed()}),this.visibilityFrame=new OwnedFrame(host),this.visibilityTimer=new OwnedTimeout(host),host.addController(this)}hostConnected(){this.active=!0,this.enabled&&(this.bindSlotRoot(),this.rebuild())}hostUpdated(){const preserveBinding=this.preserveNextBinding;if(this.preserveNextBinding=!1,this.active&&this.enabled){const observer=this.observer,pending=observer?.takeRecords()??[],relevant=observer&&pending.length>0&&this.recordsMatter(pending)&&accessibleTextRecordsMatter(observer,pending),previousRoot=this.slotRoot;this.bindSlotRoot(),(!preserveBinding||pending.length>0||this.drainedRecords||previousRoot!==this.slotRoot)&&this.bind(),relevant&&queueMicrotask(()=>{this.active&&this.enabled&&this.observer===observer&&this.host.isConnected&&this.notify(pending)})}}hostDisconnected(){this.active=!1,this.preserveNextBinding=!1,this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references)}adopted(){this.active&&this.enabled&&this.rebuild()}setEnabled(enabled){this.enabled!==enabled&&(this.enabled=enabled,this.active&&(enabled?(this.bindSlotRoot(),this.rebuild()):(this.cancelVisibilityRefresh(),this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=void 0,this.observer?.disconnect(),this.observer=void 0,this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references))))}bind(){const pending=this.takeAncestorRecords();bindAccessibleTextObserver(this.observer,this.host,this.extraAttributes,this.upgrades,this.references,this.ancestors),this.drainedRecords=!1,pending.length&&this.active&&this.enabled&&this.notify(pending)}preserveBindingForNextUpdate(){this.preserveNextBinding=!0}takeAncestorRecords(){if(this.drainingAncestors||!this.active||!this.enabled)return[];const records=[];this.drainingAncestors=records;try{for(const release of[...this.ancestors.releases])release.flush()}finally{this.drainingAncestors=void 0}return records}takeRecords(){const ancestorRecords=this.takeAncestorRecords(),records=[...this.observer?.takeRecords()??[],...ancestorRecords];return ancestorRecords.length&&this.notify(ancestorRecords),records.length>0&&(this.drainedRecords=!0),records}hasDrainedRecords(){return this.drainedRecords}text(){const root=this.host.shadowRoot,slots=root?[...root.querySelectorAll("slot")].filter(slot=>this.slots.includes(slot.name)):[],nodes=slots.length?slots.flatMap(slot=>[...slot.assignedNodes({flatten:!0})]):[...this.host.childNodes].filter(node=>node.nodeType!==1||this.slots.includes(node.getAttribute("slot")??""));return composedAccessibilityText(nodes)}hasContent(){return this.text().trim().length>0}rebuild(){this.cancelVisibilityRefresh(),this.observer?.disconnect(),this.upgrades.disconnect(),releaseAccessibleTextAncestors(this.ancestors),this.references&&releaseAccessibleTextReferences(this.references);const Observer=this.host.ownerDocument.defaultView?.MutationObserver;this.observer=Observer?new Observer((records,observer)=>{this.observer===observer&&this.recordsMatter(records)&&accessibleTextRecordsMatter(observer,records)&&this.changed(records)}):void 0,this.bind()}bindSlotRoot(){const root=this.host.shadowRoot??void 0;this.slotRoot!==root&&(this.slotRoot?.removeEventListener("slotchange",this.onSlotChange),this.slotRoot=root,root?.addEventListener("slotchange",this.onSlotChange))}recordsMatter(records){if(this.slots.length===0)return!0;const feedsSlot=start=>{const visited=new Set;let node=start;for(;node&&node!==this.host&&!visited.has(node);){if(visited.add(node),node.parentNode===this.host){const name=node.nodeType===1?node.getAttribute("slot")??"":"";return this.slots.includes(name)}node=assignedSlotOf(node)??node.parentNode??node.host??null}return!0};return records.some(record=>record.type==="attributes"&&record.attributeName==="slot"?!0:record.target===this.host&&record.type==="childList"?[...record.addedNodes,...record.removedNodes].some(node=>node.nodeType!==1?this.slots.includes(""):this.slots.includes(node.getAttribute("slot")??"")):feedsSlot(record.target))}changed(records=[]){!this.active||!this.enabled||!this.host.isConnected||(this.bind(),this.notify(records))}notify(records){this.onChange(records),records.some(record=>record.type==="attributes"&&["class","style","hidden"].includes(record.attributeName??""))&&(this.visibilityFrame.pending||this.visibilityTimer.pending||this.visibilityFrame.schedule(()=>{this.visibilityTimer.schedule(0,()=>{this.active&&this.enabled&&this.onChange([])})}))}cancelVisibilityRefresh(){this.visibilityFrame.cancel(),this.visibilityTimer.cancel()}}export{AccessibleTextController};
@@ -1,5 +1,5 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"./collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"./announcer.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";import"./lyra-element.js";import{snapshotLyraHighlights}from"./highlight-collection.js";import{boundedSelectionRects,boundedSelectionText,scopeFromElement,buildQuoteAnchor}from"./text-quote.js";const ANCHOR_RETRY_INTERVAL_MS=250,ANCHOR_TIMEOUT_MS=5e3;import{HIGHLIGHT_SNAPSHOT_LIMIT}from"./highlight-collection.js";const HIGHLIGHT_CANDIDATE_LIMIT=1e3;function prioritizedHighlightCandidates(highlights,activeHighlightId){const ordinary=[];let active;for(let index=0;index<highlights.length;index++){const highlight=highlights[index];activeHighlightId!==null&&highlight.id===activeHighlightId?active??=highlight:ordinary.length<HIGHLIGHT_CANDIDATE_LIMIT&&ordinary.push(highlight)}return active&&(ordinary.length>=HIGHLIGHT_CANDIDATE_LIMIT&&(ordinary.length=HIGHLIGHT_CANDIDATE_LIMIT-1),ordinary.unshift(active)),ordinary}function selectionRange(root,shadowRoots){const document=root.ownerDocument,globalSelection=document.defaultView?.getSelection()??null;if(globalSelection?.getComposedRanges&&shadowRoots.length>0){const[composed]=globalSelection.getComposedRanges({shadowRoots:[...shadowRoots]});if(!composed||composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)return null;const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}const selection=shadowRoots.at(-1)?.getSelection?.()??globalSelection;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function DocumentAnchorTarget(Base){class DocumentAnchorTargetElement extends Base{constructor(){super(...arguments),this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchor=null,this.anchorKinds=[],this.anchorRetryIntervalMs=ANCHOR_RETRY_INTERVAL_MS,this.anchorTimeoutMs=ANCHOR_TIMEOUT_MS,this.anchorAnnouncementText="",this.anchorGeneration=0}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor"])}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get highlights(){return this._highlights}set highlights(value){if(value===this._highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlightsSource=value,this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.anchorAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&this.anchor!==null&&this.scrollToAnchor(this.anchor).catch(()=>{})}disconnectedCallback(){this.anchorGeneration++,this.cancelAnchorRetry(),this.unbindTextSelection(),this.anchorAnnouncementSink?.release(),this.anchorAnnouncementSink=void 0,super.disconnectedCallback()}async applyAnchor(_anchor){return!1}computeSelectionAnchor(range,_text){const scope=scopeFromElement(this.renderRoot);return buildQuoteAnchor(range,scope)}cancelAnchorRetry(){this.anchorRetryHandle!==void 0&&(this.anchorRetryOwner?.clearTimeout(this.anchorRetryHandle),this.anchorRetryHandle=void 0),this.anchorRetryOwner=void 0;const resolveWait=this.anchorRetryResolve;resolveWait&&(this.anchorRetryResolve=void 0,resolveWait())}async scrollToAnchor(target){const generation=++this.anchorGeneration;try{return await this.performScrollToAnchor(target,generation)}catch{return generation!==this.anchorGeneration||(this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1})),!1}}async performScrollToAnchor(target,generation=++this.anchorGeneration){if(this.cancelAnchorRetry(),await this.updateComplete,generation!==this.anchorGeneration)return!1;const highlightId=typeof target=="string"?target:void 0,anchor=typeof target=="string"?this.highlights.find(h=>h.id===target)?.anchor:target;if(!anchor)return this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1}),!1;const ok=await this.resolveWithRetry(anchor,generation);return generation!==this.anchorGeneration?!1:(ok&&highlightId&&(this.activeHighlightId=highlightId),this.announceAnchorResult(anchor,ok),this.emit("lr-anchor-result",{found:ok}),ok)}async resolveWithRetry(anchor,generation){const deadline=Date.now()+this.anchorTimeoutMs;for(;;){if(generation!==this.anchorGeneration)return!1;const ok=await this.applyAnchor(anchor);if(generation!==this.anchorGeneration)return!1;if(ok)return!0;if(Date.now()>=deadline)return!1;const view=this.ownerDocument.defaultView;if(!view)return!1;await new Promise(resolve=>{this.anchorRetryResolve=resolve,this.anchorRetryOwner=view;let handle;handle=view.setTimeout(()=>{this.anchorRetryHandle===handle&&this.anchorRetryOwner===view&&(this.anchorRetryHandle=void 0,this.anchorRetryOwner=void 0),this.anchorRetryResolve===resolve&&(this.anchorRetryResolve=void 0),resolve()},this.anchorRetryIntervalMs),this.anchorRetryHandle=handle})}}announceAnchorResult(anchor,found){if(!found||!anchor){this.announce(this.localize("anchorNotFound"));return}const page="page"in anchor?anchor.page:void 0;this.announce(page!=null?this.localize("anchorJumpedToPage",void 0,{page}):this.localize("anchorJumped"))}announce(text){isAccessibilityVisible(this)&&this.anchorAnnouncementSink?.announce(text),this.anchorAnnouncementText=text}renderAnchorLiveRegion(){return html`<div
1
+ import{__decorate}from"tslib";import{collectionSupport}from"./collection-snapshot.js";import{html}from"lit";import{property,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"./announcer.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";import"./lyra-element.js";import{snapshotLyraHighlights}from"./highlight-collection.js";import{boundedSelectionRects,boundedSelectionText,scopeFromElement,buildQuoteAnchor}from"./text-quote.js";const selectionDispatchers=new WeakMap;function subscribeSelectionEnd(document,root,shadows,notify){let dispatcher=selectionDispatchers.get(document);if(!dispatcher){const subscribers=new Set,view=document.defaultView;let selecting=!1,frame,previous=new Set;const roots=new Map,shadowCounts=new Map,deliver=()=>{const current=new Set,selection=view?.getSelection();let node=null;if(selection?.getComposedRanges&&shadowCounts.size){const owner=selectionDispatchers.get(document);owner.shadowList??=[...shadowCounts.keys()];const composed=selection.getComposedRanges({shadowRoots:owner.shadowList})[0];if(composed&&!(composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)){const range=document.createRange();range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),node=range.commonAncestorContainer}}else selection&&selection.rangeCount&&!selection.isCollapsed&&(node=selection.getRangeAt(0).commonAncestorContainer);for(;node;){const callback=roots.get(node);callback&&current.add(callback),node=node.nodeType===11&&"host"in node?node.host:node.parentNode}if(!selection?.getComposedRanges&&current.size===0)for(const shadow of shadowCounts.keys()){const local=shadow.getSelection?.();if(!local||!local.rangeCount||local.isCollapsed)continue;let selected=local.getRangeAt(0).commonAncestorContainer;for(;selected;){const callback=roots.get(selected);callback&&current.add(callback),selected=selected.nodeType===11&&"host"in selected?selected.host:selected.parentNode}}const pending=new Set([...previous,...current]);previous=current;for(const callback of pending)subscribers.has(callback)&&callback()},change=()=>{if(!selecting){if(!view){deliver();return}frame===void 0&&(frame=view.requestAnimationFrame(()=>{frame=void 0,deliver()}))}},down=event=>{event.isPrimary&&event.button===0&&(selecting=!0,frame!==void 0&&(view?.cancelAnimationFrame(frame),frame=void 0))},release=()=>{selecting&&(selecting=!1,deliver())};document.addEventListener("selectionchange",change),document.addEventListener("pointerdown",down,!0),document.addEventListener("pointerup",release,!0),document.addEventListener("pointercancel",release,!0),dispatcher={subscribers,roots,shadows:shadowCounts,cleanup(){document.removeEventListener("selectionchange",change),document.removeEventListener("pointerdown",down,!0),document.removeEventListener("pointerup",release,!0),document.removeEventListener("pointercancel",release,!0),frame!==void 0&&view?.cancelAnimationFrame(frame)}},selectionDispatchers.set(document,dispatcher)}dispatcher.subscribers.add(notify),dispatcher.roots.set(root,notify);for(const shadow of shadows)dispatcher.shadows.set(shadow,(dispatcher.shadows.get(shadow)??0)+1);dispatcher.shadowList=void 0;const owned=dispatcher;return()=>{if(owned.subscribers.delete(notify)){owned.roots.delete(root);for(const shadow of shadows){const remaining=(owned.shadows.get(shadow)??1)-1;remaining===0?owned.shadows.delete(shadow):owned.shadows.set(shadow,remaining)}owned.shadowList=void 0,owned.subscribers.size===0&&selectionDispatchers.get(document)===owned&&(selectionDispatchers.delete(document),owned.cleanup())}}}const ANCHOR_RETRY_INTERVAL_MS=250,ANCHOR_TIMEOUT_MS=5e3;import{HIGHLIGHT_SNAPSHOT_LIMIT}from"./highlight-collection.js";const HIGHLIGHT_CANDIDATE_LIMIT=1e3;function prioritizedHighlightCandidates(highlights,activeHighlightId){const ordinary=[];let active;for(let index=0;index<highlights.length;index++){const highlight=highlights[index];activeHighlightId!==null&&highlight.id===activeHighlightId?active??=highlight:ordinary.length<HIGHLIGHT_CANDIDATE_LIMIT&&ordinary.push(highlight)}return active&&(ordinary.length>=HIGHLIGHT_CANDIDATE_LIMIT&&(ordinary.length=HIGHLIGHT_CANDIDATE_LIMIT-1),ordinary.unshift(active)),ordinary}function selectionRange(root,shadowRoots){const document=root.ownerDocument,globalSelection=document.defaultView?.getSelection()??null;if(globalSelection?.getComposedRanges&&shadowRoots.length>0){const[composed]=globalSelection.getComposedRanges({shadowRoots:[...shadowRoots]});if(!composed||composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)return null;const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}const selection=shadowRoots.at(-1)?.getSelection?.()??globalSelection;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function DocumentAnchorTarget(Base){class DocumentAnchorTargetElement extends Base{constructor(){super(...arguments),this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchor=null,this.anchorKinds=[],this.anchorRetryIntervalMs=ANCHOR_RETRY_INTERVAL_MS,this.anchorTimeoutMs=ANCHOR_TIMEOUT_MS,this.anchorAnnouncementText="",this.anchorGeneration=0}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor"])}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get highlights(){return this._highlights}set highlights(value){if(value===this._highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlightsSource=value,this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.anchorAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&this.anchor!==null&&this.scrollToAnchor(this.anchor).catch(()=>{})}disconnectedCallback(){this.cancelPendingAnchor(),this.unbindTextSelection(),this.anchorAnnouncementSink?.release(),this.anchorAnnouncementSink=void 0,super.disconnectedCallback()}cancelPendingAnchor(){this.anchorGeneration++,this.cancelAnchorRetry()}async applyAnchor(_anchor){return!1}computeSelectionAnchor(range,_text){const scope=scopeFromElement(this.renderRoot);return buildQuoteAnchor(range,scope)}cancelAnchorRetry(){this.anchorRetryHandle!==void 0&&(this.anchorRetryOwner?.clearTimeout(this.anchorRetryHandle),this.anchorRetryHandle=void 0),this.anchorRetryOwner=void 0;const resolveWait=this.anchorRetryResolve;resolveWait&&(this.anchorRetryResolve=void 0,resolveWait())}async scrollToAnchor(target){const generation=++this.anchorGeneration;try{return await this.performScrollToAnchor(target,generation)}catch{return generation!==this.anchorGeneration||(this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1})),!1}}async performScrollToAnchor(target,generation=++this.anchorGeneration){if(this.cancelAnchorRetry(),await this.updateComplete,generation!==this.anchorGeneration)return!1;const highlightId=typeof target=="string"?target:void 0,anchor=typeof target=="string"?this.highlights.find(h=>h.id===target)?.anchor:target;if(!anchor)return this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1}),!1;const ok=await this.resolveWithRetry(anchor,generation);return generation!==this.anchorGeneration?!1:(ok&&highlightId&&(this.activeHighlightId=highlightId),this.announceAnchorResult(anchor,ok),this.emit("lr-anchor-result",{found:ok}),ok)}async resolveWithRetry(anchor,generation){const deadline=Date.now()+this.anchorTimeoutMs;for(;;){if(generation!==this.anchorGeneration)return!1;const ok=await this.applyAnchor(anchor);if(generation!==this.anchorGeneration)return!1;if(ok)return!0;if(Date.now()>=deadline)return!1;const view=this.ownerDocument.defaultView;if(!view)return!1;await new Promise(resolve=>{this.anchorRetryResolve=resolve,this.anchorRetryOwner=view;let handle;handle=view.setTimeout(()=>{this.anchorRetryHandle===handle&&this.anchorRetryOwner===view&&(this.anchorRetryHandle=void 0,this.anchorRetryOwner=void 0),this.anchorRetryResolve===resolve&&(this.anchorRetryResolve=void 0),resolve()},this.anchorRetryIntervalMs),this.anchorRetryHandle=handle})}}announceAnchorResult(anchor,found){if(!found||!anchor){this.announce(this.localize("anchorNotFound"));return}const page="page"in anchor?anchor.page:void 0;this.announce(page!=null?this.localize("anchorJumpedToPage",void 0,{page}):this.localize("anchorJumped"))}announce(text){isAccessibilityVisible(this)&&this.anchorAnnouncementSink?.announce(text),this.anchorAnnouncementText=text}renderAnchorLiveRegion(){return html`<div
2
2
  part="anchor-live-region"
3
3
  class="sr-only"
4
4
  aria-hidden="true"
5
- >${this.anchorAnnouncementText}</div>`}selectionShadowRoots(contentRoot){const ShadowRootCtor=contentRoot.ownerDocument.defaultView?.ShadowRoot;if(!ShadowRootCtor)return[];const roots=[this.shadowRoot,contentRoot.getRootNode()];return roots.filter((root,index)=>root instanceof ShadowRootCtor&&roots.indexOf(root)===index)}bindTextSelection(contentRoot){this.unbindTextSelection();const document=contentRoot.ownerDocument,view=document.defaultView;let pointerSelecting=!1,reported;const onSelectionEnd=()=>{const range=selectionRange(this,this.selectionShadowRoots(contentRoot));if(!range||!containsAcrossShadowBoundaries(contentRoot,range.commonAncestorContainer)){reported=void 0;return}if(reported&&reported[0]===range.startContainer&&reported[1]===range.startOffset&&reported[2]===range.endContainer&&reported[3]===range.endOffset)return;const text=boundedSelectionText(range);if(!text)return;reported=[range.startContainer,range.startOffset,range.endContainer,range.endOffset];const anchor=this.computeSelectionAnchor(range,text),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};let debounceHandle;const onSelectionChange=()=>{if(!pointerSelecting){if(!view){onSelectionEnd();return}debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle),debounceHandle=view.requestAnimationFrame(()=>{debounceHandle=void 0,onSelectionEnd()})}},onPointerDown=event=>{event.isPrimary&&event.button===0&&(pointerSelecting=!0)},onPointerRelease=()=>{pointerSelecting&&(pointerSelecting=!1,onSelectionEnd())};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd),document.addEventListener("selectionchange",onSelectionChange),document.addEventListener("pointerdown",onPointerDown,!0),document.addEventListener("pointerup",onPointerRelease,!0),document.addEventListener("pointercancel",onPointerRelease,!0),this.selectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),document.removeEventListener("selectionchange",onSelectionChange),document.removeEventListener("pointerdown",onPointerDown,!0),document.removeEventListener("pointerup",onPointerRelease,!0),document.removeEventListener("pointercancel",onPointerRelease,!0),debounceHandle!==void 0&&view?.cancelAnimationFrame(debounceHandle)}}unbindTextSelection(){this.selectionCleanup?.(),this.selectionCleanup=void 0}}return __decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],DocumentAnchorTargetElement.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"anchor",void 0),__decorate([state()],DocumentAnchorTargetElement.prototype,"anchorAnnouncementText",void 0),DocumentAnchorTargetElement}export{DocumentAnchorTarget,HIGHLIGHT_CANDIDATE_LIMIT,HIGHLIGHT_SNAPSHOT_LIMIT,prioritizedHighlightCandidates};
5
+ >${this.anchorAnnouncementText}</div>`}selectionShadowRoots(contentRoot){const ShadowRootCtor=contentRoot.ownerDocument.defaultView?.ShadowRoot;if(!ShadowRootCtor)return[];const roots=[this.shadowRoot,contentRoot.getRootNode()];return roots.filter((root,index)=>root instanceof ShadowRootCtor&&roots.indexOf(root)===index)}bindTextSelection(contentRoot){this.unbindTextSelection();const document=contentRoot.ownerDocument;let reported;const onSelectionEnd=()=>{const range=selectionRange(this,this.selectionShadowRoots(contentRoot));if(!range||!containsAcrossShadowBoundaries(contentRoot,range.commonAncestorContainer)){reported=void 0;return}if(reported&&reported[0]===range.startContainer&&reported[1]===range.startOffset&&reported[2]===range.endContainer&&reported[3]===range.endOffset)return;const text=boundedSelectionText(range);if(!text)return;reported=[range.startContainer,range.startOffset,range.endContainer,range.endOffset];const anchor=this.computeSelectionAnchor(range,text),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd);const unsubscribe=subscribeSelectionEnd(document,contentRoot,this.selectionShadowRoots(contentRoot),onSelectionEnd);this.selectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),unsubscribe()}}unbindTextSelection(){this.selectionCleanup?.(),this.selectionCleanup=void 0}}return __decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],DocumentAnchorTargetElement.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"anchor",void 0),__decorate([state()],DocumentAnchorTargetElement.prototype,"anchorAnnouncementText",void 0),DocumentAnchorTargetElement}export{DocumentAnchorTarget,HIGHLIGHT_CANDIDATE_LIMIT,HIGHLIGHT_SNAPSHOT_LIMIT,prioritizedHighlightCandidates};
@@ -40,13 +40,7 @@ export declare function withSyntheticCatalogValue<T extends LyraCatalogEntry>(ca
40
40
  * component-specific behavior stay on the host; catalog normalization, editing state, keyboard
41
41
  * transitions, popup ownership, commits, and native/prefixed event relays have one authority.
42
42
  */
43
- export declare class CatalogPickerController<T extends LyraCatalogEntry>{private readonly host;private readonly options;private readonly popupPosition;private overlay?;private readonly popupController;private _activeIndex;private revealPending;private _query;private _open;private _value;private _defaultValue;private valueDirty;private settingDefaultValue;private reflectingDefaultValue;private _listboxHidden;private listboxHideWatcher?;suppressControlEvents:boolean;private readonly typeBuffer;constructor(host:CatalogPickerHost,options:CatalogPickerControllerOptions<T>);private normalizedMemo?;private effectiveMemo?;private searchKeysMemo?;private filteredMemo?;get normalizedCatalog():T[];get closedMode():boolean;private get isReadonly();get effectiveEntries():DisplayCatalogEntry<T>[];get filteredEntries():DisplayCatalogEntry<T>[];get visibleEntries():DisplayCatalogEntry<T>[];
44
- /** The display label for a committed id, falling back to the raw id when no row claims it.
45
- * The `!id` short-circuit is behaviour-identical to letting the lookup run -- no row can carry a
46
- * blank id (see `normalizeCatalog`), so the find would miss and `?? id` would return `''` too --
47
- * and is kept only to skip the scan on the common empty-field path. It is therefore not an
48
- * instance of the `''`-as-missing-value shape corrected in `<lr-select>`/`<lr-combobox>`. */
49
- labelFor(id:string):string;get activeIndex():number;setActiveIndex(next:number):void;private revealActiveRow;get query():string;setQuery(next:string):void;get open():boolean;
43
+ export declare class CatalogPickerController<T extends LyraCatalogEntry>{private readonly host;private readonly options;private readonly popupPosition;private overlay?;private readonly popupController;private _activeIndex;private revealPending;private _query;private _open;private _value;private _defaultValue;private valueDirty;private settingDefaultValue;private reflectingDefaultValue;private _listboxHidden;private listboxHideWatcher?;suppressControlEvents:boolean;private readonly typeBuffer;constructor(host:CatalogPickerHost,options:CatalogPickerControllerOptions<T>);private normalizedMemo?;private effectiveMemo?;private searchKeysMemo?;private filteredMemo?;get normalizedCatalog():T[];get closedMode():boolean;private get isReadonly();get effectiveEntries():DisplayCatalogEntry<T>[];get filteredEntries():DisplayCatalogEntry<T>[];get visibleEntries():DisplayCatalogEntry<T>[];private readonly rowIndexes;private indexesFor;entryFor(id:string):DisplayCatalogEntry<T> |undefined;labelFor(id:string):string;get activeIndex():number;setActiveIndex(next:number):void;private revealActiveRow;get query():string;setQuery(next:string):void;get open():boolean;
50
44
  /** `false` while open or mid-close-transition, so the exit animation still has a real box to
51
45
  * animate; settles to `true` once the closed listbox's transition has visually finished (or
52
46
  * immediately, for reduced motion / a zero-duration override). Bound to `[part="listbox"]`'s
@@ -1 +1 @@
1
- import{setNativeRangeText}from"./native-text-control.js";import{waitForTransitionSettle}from"./css-motion-time.js";import{getOwnDataDescriptor}from"./data-descriptors.js";import{CATALOG_ROW_LIMIT}from"./selection-catalog.js";import{AnchoredPopoverController}from"./anchored-popover-controller.js";import{deferredPlace}from"./anchored-overlay-runtime.js";import{resolveIntlLocale}from"./intl-cache.js";import{prefersReducedMotion}from"./motion.js";import{dispatchNativeEvent,relayNativeEvent}from"./native-event-relay.js";import{activateNonmodalOverlay}from"./nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"./positioning-strategy.js";import{TypeAheadBuffer}from"./type-ahead-buffer.js";import{resolveListMove}from"./list-navigation.js";import{PopupController}from"./popup-controller.js";const normalizedCatalogs=new WeakMap;function ownDataValue(target,key){const descriptor=getOwnDataDescriptor(target,key);return typeof descriptor=="symbol"?void 0:descriptor.value}function ownDataCopy(entry){const copy={};let keys=[];try{keys=Object.keys(entry)}catch{}for(const key of keys){const descriptor=getOwnDataDescriptor(entry,key);typeof descriptor!="symbol"&&(copy[key]=descriptor.value)}return Object.freeze(copy)}function normalizeCatalog(catalog){let frozen;try{if(!Array.isArray(catalog))return[];frozen=Object.isFrozen(catalog)}catch{return[]}const known=frozen?normalizedCatalogs.get(catalog):void 0;if(known)return known;const normalized=[],seen=new Set,length=ownDataValue(catalog,"length"),count=typeof length=="number"?Math.min(length,CATALOG_ROW_LIMIT):0;for(let index=0;index<count;index+=1){const entry=ownDataValue(catalog,String(index));let record,id,label;if(typeof entry=="string")record={id:entry,label:entry},id=label=entry;else if(entry!==null&&typeof entry=="object")record=ownDataCopy(entry),id=ownDataValue(entry,"id"),label=ownDataValue(entry,"label");else continue;typeof id!="string"||id.trim()===""||typeof label!="string"||label.trim()===""||seen.has(id)||(seen.add(id),normalized.push(record))}return frozen&&normalizedCatalogs.set(catalog,Object.freeze(normalized)),normalized}function withSyntheticCatalogValue(catalog,value){const entries=catalog.map(entry=>({...entry,synthetic:!1}));return catalog.length&&value.trim()!==""&&!catalog.some(entry=>entry.id===value)&&entries.push({id:value,label:value,synthetic:!0}),entries}function filterCatalogEntries(entries,query,locale,fields){const intlLocale=resolveIntlLocale(locale),normalized=query.trim().toLocaleLowerCase(intlLocale);return normalized?entries.filter(entry=>fields(entry).some(value=>value.toLocaleLowerCase(intlLocale).includes(normalized))):[...entries]}class CatalogPickerController{constructor(host,options){this.host=host,this.options=options,this._activeIndex=-1,this.revealPending=!1,this._query="",this._open=!1,this._value="",this._defaultValue="",this.valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._listboxHidden=!0,this.suppressControlEvents=!1,this.typeBuffer=new TypeAheadBuffer(host),this.popupController=new PopupController({host,onPointer:event=>{event.composedPath().includes(host)||this.overlay?.dismissBackdrop()}}),this.popupPosition=new AnchoredPopoverController((anchor,popup)=>deferredPlace(anchor,popup,{strategy:resolveEffectivePositioningStrategy(this.host,void 0,"fixed")}))}get normalizedCatalog(){const source=this.options.catalog(),memo=this.normalizedMemo;if(memo&&memo.source===source)return memo.rows;const rows=normalizeCatalog(source);return this.normalizedMemo={source,rows},rows}get closedMode(){return this.normalizedCatalog.length>0&&!this.options.allowCustom()}get isReadonly(){return this.options.isReadonly()}get effectiveEntries(){const rows=this.normalizedCatalog,memo=this.effectiveMemo;if(memo&&memo.rows===rows&&memo.value===this._value)return memo.entries;const entries=withSyntheticCatalogValue(rows,this._value);return this.effectiveMemo={rows,value:this._value,entries},entries}get filteredEntries(){const entries=this.effectiveEntries,query=this._query,locale=this.options.locale(),memo=this.filteredMemo;if(memo&&memo.entries===entries&&memo.query===query&&memo.locale===locale)return memo.result;const intlLocale=resolveIntlLocale(locale),needle=query.trim().toLocaleLowerCase(intlLocale);let result;if(!needle)result=[...entries];else{let keys=this.searchKeysMemo;(!keys||keys.entries!==entries||keys.locale!==intlLocale)&&(keys={entries,locale:intlLocale,keys:entries.map(entry=>this.options.searchableFields(entry).map(value=>value.toLocaleLowerCase(intlLocale)))},this.searchKeysMemo=keys);const rowKeys=keys.keys;result=entries.filter((_,index)=>rowKeys[index].some(value=>value.includes(needle)))}return this.filteredMemo={entries,query,locale,result},result}get visibleEntries(){return this.closedMode?this.effectiveEntries:this.filteredEntries}labelFor(id){return id?this.effectiveEntries.find(entry=>entry.id===id)?.label??id:""}get activeIndex(){return this._activeIndex}setActiveIndex(next){if(next===this._activeIndex)return;const old=this._activeIndex;this.options.beforeActiveIndexChange?.(next,old),this._activeIndex=next,this.revealPending=!0,this.options.onStateChange("activeIndex",old)}revealActiveRow(){const listbox=this.host.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');if(!listbox||row?.offsetParent!==listbox)return;const top=row.offsetTop,bottom=top+row.offsetHeight;top<listbox.scrollTop?listbox.scrollTop=top:bottom>listbox.scrollTop+listbox.clientHeight&&(listbox.scrollTop=bottom-listbox.clientHeight)}get query(){return this._query}setQuery(next){if(next===this._query)return;const old=this._query;this._query=next,this.options.afterQueryChange?.(next,old),this.options.onStateChange("query",old)}get open(){return this._open}get listboxHidden(){return this._listboxHidden}setListboxHidden(next){if(next===this._listboxHidden)return;const old=this._listboxHidden;this._listboxHidden=next,this.options.onStateChange("listboxHidden",old)}cancelListboxHideWatch(){this.listboxHideWatcher?.(),this.listboxHideWatcher=void 0}scheduleListboxHide(){this.cancelListboxHideWatch();const listbox=this.host.renderRoot.querySelector('[part="listbox"]'),watch=waitForTransitionSettle(listbox,this.host,{reducedMotion:prefersReducedMotion(this.host)});if(!watch.pending){this.setListboxHidden(!0);return}const cancel=()=>watch.cancel();this.listboxHideWatcher=cancel,watch.finished.then(()=>{this.listboxHideWatcher===cancel&&(this.listboxHideWatcher=void 0,this.setListboxHidden(!0))})}setOpen(next){const liveDisabled=this.host.effectiveDisabled||typeof this.host.matches=="function"&&this.host.matches(":disabled"),resolved=!!next&&!liveDisabled;if(resolved===this._open){resolved||this.deactivateOverlay(!1),next&&!resolved&&this.host.hasAttribute("open")&&this.host.removeAttribute("open");return}const old=this._open;resolved||(this.setActiveIndex(-1),this.deactivateOverlay(!1)),this._open=resolved,resolved?(this.cancelListboxHideWatch(),this.setListboxHidden(!1),this.closedMode&&this.setActiveIndex(this.effectiveEntries.findIndex(entry=>entry.id===this._value&&entry.disabled!==!0))):this.host.updateComplete.then(()=>{this._open||!this.host.isConnected||this.scheduleListboxHide()}),this.options.onStateChange("open",old)}show(){!this._open&&!this.host.effectiveDisabled&&this.setOpen(!0)}hide(){this._open&&this.setOpen(!1)}get value(){return this._value}set value(next){const normalized=next??"";if(this.options.beforeValueChange?.(normalized,this._value),normalized===this._value){this.settingDefaultValue||(this.valueDirty=!0);return}const old=this._value;this.settingDefaultValue||(this.valueDirty=!0),this._value=normalized,this.options.onValueChange(normalized,old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const normalized=next??"",old=this._defaultValue;this._defaultValue=normalized,this.reflectDefaultValue(),this.valueDirty||this.restoreLiveValueFromDefault(),this.options.onDefaultValueChange(normalized,old)}resetValue(){this.restoreLiveValueFromDefault()}restoreState(state){this.value=typeof state=="string"?state:""}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this.valueDirty=!1}reflectDefaultValue(){this.reflectingDefaultValue=!0;try{this._defaultValue?this.host.setAttribute("value",this._defaultValue):this.host.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}}commitValue(next){if(this.isReadonly)return;const inCatalog=this.normalizedCatalog.some(entry=>entry.id===next);this.value=next,this.hide(),this.options.emitChange({value:next,inCatalog}),this.emitValueEvents({value:next,inCatalog})}emitValueEvents(detail={value:this._value,inCatalog:this.normalizedCatalog.some(entry=>entry.id===this._value)}){dispatchNativeEvent(this.host,"input"),this.options.emitInput(detail),dispatchNativeEvent(this.host,"change")}commitFreeText(){const active=this.filteredEntries[this._activeIndex],useActive=this._activeIndex>=0&&!!active&&active?.disabled!==!0;this.commitValue(useActive?active.id:this._query.trim())}selectEntry(entry){entry.disabled!==!0&&this.commitValue(entry.id)}reconcileRows(activeValue,rebaseQuery,clampMissing=!0){const rows=this.visibleEntries,remapped=activeValue?rows.findIndex(entry=>entry.id===activeValue):-1;this.setActiveIndex(remapped>=0?remapped:clampMissing?Math.min(this._activeIndex,Math.max(-1,rows.length-1)):-1),rebaseQuery&&this.setQuery(this.labelFor(this._value))}typeAhead(event){const{key}=event;if(!this.typeBuffer.accepts(event)||key===" "&&this.typeBuffer.text==="")return!1;key===" "&&event.preventDefault();const locale=this.options.locale();this.typeBuffer.add(key,locale);const rows=this.effectiveEntries,current=this._open?this._activeIndex:rows.findIndex(entry=>entry.id===this._value),index=this.typeBuffer.match(rows,current,row=>row.label,locale,row=>row.disabled!==!0);if(index!==null){const row=rows[index];this._open?this.setActiveIndex(index):this.selectEntry(row)}return!0}moveIndex(rows,event){return resolveListMove(event,{count:rows.length,current:this._activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first",isAvailable:index=>rows[index]?.disabled!==!0})??-1}handleTriggerKeyDown(event){if(event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey||this.typeAhead(event))return;const rows=this.effectiveEntries;switch(event.key){case"ArrowDown":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"ArrowUp":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"Enter":case" ":if(this._open){event.preventDefault();const active=rows[this._activeIndex];this._activeIndex>=0&&active?this.selectEntry(active):this.hide()}break;case"Home":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break;case"End":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break}}handleInputKeyDown(event){if(event.isComposing||event.keyCode===229)return;const rows=this.filteredEntries;switch(event.key){case"ArrowDown":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"ArrowUp":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"Enter":this._open&&(event.preventDefault(),this.commitFreeText());break;case"Home":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break;case"End":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break}}handleInput(event){const input=event.currentTarget;if(!input)return;if(this.isReadonly){input.value=this._open?this._query:this.labelFor(this._value),event.stopPropagation();return}this.setQuery(input.value),this.setActiveIndex(-1),this.show();const detail={value:this._value,inCatalog:this.normalizedCatalog.some(entry=>entry.id===this._value)};relayNativeEvent(this.host,event),this.options.emitInput(detail)}handleInputFocus(event){if(this.suppressControlEvents){event.stopPropagation();return}this._open||this.setQuery(this.labelFor(this._value)),this.show(),this.handleControlFocus(event)}handleControlFocus(event){if(this.suppressControlEvents){event.stopPropagation();return}if(this.containsFocusTarget(event.relatedTarget)){event.stopPropagation();return}this.options.onControlFocus?.(event),relayNativeEvent(this.host,event)}handleControlBlur(event){if(this.suppressControlEvents){event.stopPropagation();return}if(this.containsFocusTarget(event.relatedTarget)){event.stopPropagation();return}this.options.onControlBlur?.(event),this.hide(),relayNativeEvent(this.host,event)}handleComboMouseDown(event){this.host.effectiveDisabled||event.composedPath()[0]!==this.input&&(event.preventDefault(),this.input?.focus())}handleListboxMouseDown(event){event.target.closest('[part="option"]')&&event.preventDefault()}handleListboxClick(event){if(this.host.effectiveDisabled)return;const value=event.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const entry=this.visibleEntries.find(candidate=>candidate.id===value);entry&&this.selectEntry(entry)}get input(){return this.host.renderRoot?.querySelector('[part="combobox-input"]')??null}click(){if(this.host.effectiveDisabled)return;const trigger=this.host.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.input;this.options.forwardFreeInputClick&&input?.click(),input?.focus()}focus(options){if(this.host.effectiveDisabled)return;this.host.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.host.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}select(){this.input?.select()}setSelectionRange(start,end,direction){this.input?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.input;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.setQuery(input.value),this.setActiveIndex(-1),this.value=input.value)}connected(hasUpdated){hasUpdated&&this._open&&queueMicrotask(()=>this.syncPopup())}disconnected(){this.typeBuffer.clear(),this.popupPosition.disconnect(),this.deactivateOverlay(!1),this.cancelListboxHideWatch(),this.setListboxHidden(!0),this.setOpen(!1)}adopted(){this.typeBuffer.clear(),this.popupPosition.disconnect(),this.popupController.unbindPointer(),this.overlay?.suspend(),this._open&&queueMicrotask(()=>this.syncPopup())}updated(reposition){reposition&&this.syncPopup(),this.revealPending&&this._open&&this.revealActiveRow(),this.revealPending=!1}containsFocusTarget(target){if(this.options.containsFocusTarget)return this.options.containsFocusTarget(target);if(!target||typeof target.nodeType!="number")return!1;const node=target;return this.host.renderRoot.contains(node)||this.host.contains(node)}activatePopupOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this.host,panel:()=>this.host.renderRoot.querySelector('[part="listbox"]')??null,onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide()})}deactivateOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}dismissFromEscape(){this._open&&(this.closedMode||this.setQuery(this.labelFor(this._value)),this.deactivateOverlay(!0),this.setOpen(!1))}syncPopup(){if(this.popupPosition.disconnect(),!this._open||!this.host.isConnected){this.deactivateOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.host.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]'),listbox=this.host.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&this.popupPosition.reposition(anchor,listbox)}}export{CatalogPickerController,filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue};
1
+ import{setNativeRangeText}from"./native-text-control.js";import{waitForTransitionSettle}from"./css-motion-time.js";import{getOwnDataDescriptor}from"./data-descriptors.js";import{CATALOG_ROW_LIMIT}from"./selection-catalog.js";import{AnchoredPopoverController}from"./anchored-popover-controller.js";import{deferredPlace}from"./anchored-overlay-runtime.js";import{resolveIntlLocale}from"./intl-cache.js";import{prefersReducedMotion}from"./motion.js";import{dispatchNativeEvent,relayNativeEvent}from"./native-event-relay.js";import{activateNonmodalOverlay}from"./nonmodal-overlay-manager.js";import{resolveEffectivePositioningStrategy}from"./positioning-strategy.js";import{TypeAheadBuffer}from"./type-ahead-buffer.js";import{resolveListMove}from"./list-navigation.js";import{PopupController}from"./popup-controller.js";const normalizedCatalogs=new WeakMap;function ownDataValue(target,key){const descriptor=getOwnDataDescriptor(target,key);return typeof descriptor=="symbol"?void 0:descriptor.value}function ownDataCopy(entry){const copy={};let keys=[];try{keys=Object.keys(entry)}catch{}for(const key of keys){const descriptor=getOwnDataDescriptor(entry,key);typeof descriptor!="symbol"&&(copy[key]=descriptor.value)}return Object.freeze(copy)}function normalizeCatalog(catalog){let frozen;try{if(!Array.isArray(catalog))return[];frozen=Object.isFrozen(catalog)}catch{return[]}const known=frozen?normalizedCatalogs.get(catalog):void 0;if(known)return known;const normalized=[],seen=new Set,length=ownDataValue(catalog,"length"),count=typeof length=="number"?Math.min(length,CATALOG_ROW_LIMIT):0;for(let index=0;index<count;index+=1){const entry=ownDataValue(catalog,String(index));let record,id,label;if(typeof entry=="string")record={id:entry,label:entry},id=label=entry;else if(entry!==null&&typeof entry=="object")record=ownDataCopy(entry),id=ownDataValue(entry,"id"),label=ownDataValue(entry,"label");else continue;typeof id!="string"||id.trim()===""||typeof label!="string"||label.trim()===""||seen.has(id)||(seen.add(id),normalized.push(record))}return frozen&&normalizedCatalogs.set(catalog,Object.freeze(normalized)),normalized}function withSyntheticCatalogValue(catalog,value){const entries=catalog.map(entry=>({...entry,synthetic:!1}));return catalog.length&&value.trim()!==""&&!catalog.some(entry=>entry.id===value)&&entries.push({id:value,label:value,synthetic:!0}),entries}function filterCatalogEntries(entries,query,locale,fields){const intlLocale=resolveIntlLocale(locale),normalized=query.trim().toLocaleLowerCase(intlLocale);return normalized?entries.filter(entry=>fields(entry).some(value=>value.toLocaleLowerCase(intlLocale).includes(normalized))):[...entries]}class CatalogPickerController{constructor(host,options){this.host=host,this.options=options,this._activeIndex=-1,this.revealPending=!1,this._query="",this._open=!1,this._value="",this._defaultValue="",this.valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._listboxHidden=!0,this.suppressControlEvents=!1,this.rowIndexes=new WeakMap,this.typeBuffer=new TypeAheadBuffer(host),this.popupController=new PopupController({host,onPointer:event=>{event.composedPath().includes(host)||this.overlay?.dismissBackdrop()}}),this.popupPosition=new AnchoredPopoverController((anchor,popup)=>deferredPlace(anchor,popup,{strategy:resolveEffectivePositioningStrategy(this.host,void 0,"fixed")}))}get normalizedCatalog(){const source=this.options.catalog(),memo=this.normalizedMemo;if(memo&&memo.source===source)return memo.rows;const rows=normalizeCatalog(source);return this.normalizedMemo={source,rows},rows}get closedMode(){return this.normalizedCatalog.length>0&&!this.options.allowCustom()}get isReadonly(){return this.options.isReadonly()}get effectiveEntries(){const rows=this.normalizedCatalog,memo=this.effectiveMemo;if(memo&&memo.rows===rows&&memo.value===this._value)return memo.entries;const entries=withSyntheticCatalogValue(rows,this._value);return this.effectiveMemo={rows,value:this._value,entries},entries}get filteredEntries(){const entries=this.effectiveEntries,query=this._query,locale=this.options.locale(),memo=this.filteredMemo;if(memo&&memo.entries===entries&&memo.query===query&&memo.locale===locale)return memo.result;const intlLocale=resolveIntlLocale(locale),needle=query.trim().toLocaleLowerCase(intlLocale);let result;if(!needle)result=[...entries];else{let keys=this.searchKeysMemo;(!keys||keys.entries!==entries||keys.locale!==intlLocale)&&(keys={entries,locale:intlLocale,keys:entries.map(entry=>this.options.searchableFields(entry).map(value=>value.toLocaleLowerCase(intlLocale)))},this.searchKeysMemo=keys);const rowKeys=keys.keys;result=entries.filter((_,index)=>rowKeys[index].some(value=>value.includes(needle)))}return this.filteredMemo={entries,query,locale,result},result}get visibleEntries(){return this.closedMode?this.effectiveEntries:this.filteredEntries}indexesFor(rows){let indexes=this.rowIndexes.get(rows);return indexes||(indexes=new Map,rows.forEach((entry,index)=>{indexes.has(entry.id)||indexes.set(entry.id,index)}),this.rowIndexes.set(rows,indexes)),indexes}entryFor(id){const rows=this.effectiveEntries,index=this.indexesFor(rows).get(id);return index===void 0?void 0:rows[index]}labelFor(id){return id?this.entryFor(id)?.label??id:""}get activeIndex(){return this._activeIndex}setActiveIndex(next){if(next===this._activeIndex)return;const old=this._activeIndex;this.options.beforeActiveIndexChange?.(next,old),this._activeIndex=next,this.revealPending=!0,this.options.onStateChange("activeIndex",old)}revealActiveRow(){const listbox=this.host.renderRoot.querySelector('[part="listbox"]'),row=listbox?.querySelector('[part="option"][data-active]');if(!listbox||row?.offsetParent!==listbox)return;const top=row.offsetTop,bottom=top+row.offsetHeight;top<listbox.scrollTop?listbox.scrollTop=top:bottom>listbox.scrollTop+listbox.clientHeight&&(listbox.scrollTop=bottom-listbox.clientHeight)}get query(){return this._query}setQuery(next){if(next===this._query)return;const old=this._query;this._query=next,this.options.afterQueryChange?.(next,old),this.options.onStateChange("query",old)}get open(){return this._open}get listboxHidden(){return this._listboxHidden}setListboxHidden(next){if(next===this._listboxHidden)return;const old=this._listboxHidden;this._listboxHidden=next,this.options.onStateChange("listboxHidden",old)}cancelListboxHideWatch(){this.listboxHideWatcher?.(),this.listboxHideWatcher=void 0}scheduleListboxHide(){this.cancelListboxHideWatch();const listbox=this.host.renderRoot.querySelector('[part="listbox"]'),watch=waitForTransitionSettle(listbox,this.host,{reducedMotion:prefersReducedMotion(this.host)});if(!watch.pending){this.setListboxHidden(!0);return}const cancel=()=>watch.cancel();this.listboxHideWatcher=cancel,watch.finished.then(()=>{this.listboxHideWatcher===cancel&&(this.listboxHideWatcher=void 0,this.setListboxHidden(!0))})}setOpen(next){const liveDisabled=this.host.effectiveDisabled||typeof this.host.matches=="function"&&this.host.matches(":disabled"),resolved=!!next&&!liveDisabled;if(resolved===this._open){resolved||this.deactivateOverlay(!1),next&&!resolved&&this.host.hasAttribute("open")&&this.host.removeAttribute("open");return}const old=this._open;resolved||(this.setActiveIndex(-1),this.deactivateOverlay(!1)),this._open=resolved,resolved?(this.cancelListboxHideWatch(),this.setListboxHidden(!1),this.closedMode&&this.setActiveIndex(this.entryFor(this._value)?.disabled===!0?-1:this.indexesFor(this.effectiveEntries).get(this._value)??-1)):this.host.updateComplete.then(()=>{this._open||!this.host.isConnected||this.scheduleListboxHide()}),this.options.onStateChange("open",old)}show(){!this._open&&!this.host.effectiveDisabled&&this.setOpen(!0)}hide(){this._open&&this.setOpen(!1)}get value(){return this._value}set value(next){const normalized=next??"";if(this.options.beforeValueChange?.(normalized,this._value),normalized===this._value){this.settingDefaultValue||(this.valueDirty=!0);return}const old=this._value;this.settingDefaultValue||(this.valueDirty=!0),this._value=normalized,this.options.onValueChange(normalized,old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const normalized=next??"",old=this._defaultValue;this._defaultValue=normalized,this.reflectDefaultValue(),this.valueDirty||this.restoreLiveValueFromDefault(),this.options.onDefaultValueChange(normalized,old)}resetValue(){this.restoreLiveValueFromDefault()}restoreState(state){this.value=typeof state=="string"?state:""}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this.valueDirty=!1}reflectDefaultValue(){this.reflectingDefaultValue=!0;try{this._defaultValue?this.host.setAttribute("value",this._defaultValue):this.host.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}}commitValue(next){if(this.isReadonly)return;const inCatalog=this.indexesFor(this.normalizedCatalog).has(next);this.value=next,this.hide(),this.options.emitChange({value:next,inCatalog}),this.emitValueEvents({value:next,inCatalog})}emitValueEvents(detail={value:this._value,inCatalog:this.indexesFor(this.normalizedCatalog).has(this._value)}){dispatchNativeEvent(this.host,"input"),this.options.emitInput(detail),dispatchNativeEvent(this.host,"change")}commitFreeText(){const active=this.filteredEntries[this._activeIndex],useActive=this._activeIndex>=0&&!!active&&active?.disabled!==!0;this.commitValue(useActive?active.id:this._query.trim())}selectEntry(entry){entry.disabled!==!0&&this.commitValue(entry.id)}reconcileRows(activeValue,rebaseQuery,clampMissing=!0){const rows=this.visibleEntries,remapped=activeValue?this.indexesFor(rows).get(activeValue)??-1:-1;this.setActiveIndex(remapped>=0?remapped:clampMissing?Math.min(this._activeIndex,Math.max(-1,rows.length-1)):-1),rebaseQuery&&this.setQuery(this.labelFor(this._value))}typeAhead(event){const{key}=event;if(!this.typeBuffer.accepts(event)||key===" "&&this.typeBuffer.text==="")return!1;key===" "&&event.preventDefault();const locale=this.options.locale();this.typeBuffer.add(key,locale);const rows=this.effectiveEntries,current=this._open?this._activeIndex:this.indexesFor(rows).get(this._value)??-1,index=this.typeBuffer.match(rows,current,row=>row.label,locale,row=>row.disabled!==!0);if(index!==null){const row=rows[index];this._open?this.setActiveIndex(index):this.selectEntry(row)}return!0}moveIndex(rows,event){return resolveListMove(event,{count:rows.length,current:this._activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first",isAvailable:index=>rows[index]?.disabled!==!0})??-1}handleTriggerKeyDown(event){if(event.isComposing||event.keyCode===229||event.altKey||event.ctrlKey||event.metaKey||this.typeAhead(event))return;const rows=this.effectiveEntries;switch(event.key){case"ArrowDown":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"ArrowUp":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"Enter":case" ":if(this._open){event.preventDefault();const active=rows[this._activeIndex];this._activeIndex>=0&&active?this.selectEntry(active):this.hide()}break;case"Home":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break;case"End":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break}}handleInputKeyDown(event){if(event.isComposing||event.keyCode===229)return;const rows=this.filteredEntries;switch(event.key){case"ArrowDown":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"ArrowUp":if(event.preventDefault(),!this._open)return this.show();this.setActiveIndex(this.moveIndex(rows,event));break;case"Enter":this._open&&(event.preventDefault(),this.commitFreeText());break;case"Home":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break;case"End":this._open&&(event.preventDefault(),this.setActiveIndex(this.moveIndex(rows,event)));break}}handleInput(event){const input=event.currentTarget;if(!input)return;if(this.isReadonly){input.value=this._open?this._query:this.labelFor(this._value),event.stopPropagation();return}this.setQuery(input.value),this.setActiveIndex(-1),this.show();const detail={value:this._value,inCatalog:this.indexesFor(this.normalizedCatalog).has(this._value)};relayNativeEvent(this.host,event),this.options.emitInput(detail)}handleInputFocus(event){if(this.suppressControlEvents){event.stopPropagation();return}this._open||this.setQuery(this.labelFor(this._value)),this.show(),this.handleControlFocus(event)}handleControlFocus(event){if(this.suppressControlEvents){event.stopPropagation();return}if(this.containsFocusTarget(event.relatedTarget)){event.stopPropagation();return}this.options.onControlFocus?.(event),relayNativeEvent(this.host,event)}handleControlBlur(event){if(this.suppressControlEvents){event.stopPropagation();return}if(this.containsFocusTarget(event.relatedTarget)){event.stopPropagation();return}this.options.onControlBlur?.(event),this.hide(),relayNativeEvent(this.host,event)}handleComboMouseDown(event){this.host.effectiveDisabled||event.composedPath()[0]!==this.input&&(event.preventDefault(),this.input?.focus())}handleListboxMouseDown(event){event.target.closest('[part="option"]')&&event.preventDefault()}handleListboxClick(event){if(this.host.effectiveDisabled)return;const value=event.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const rows=this.visibleEntries,index=this.indexesFor(rows).get(value),entry=index===void 0?void 0:rows[index];entry&&this.selectEntry(entry)}get input(){return this.host.renderRoot?.querySelector('[part="combobox-input"]')??null}click(){if(this.host.effectiveDisabled)return;const trigger=this.host.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.input;this.options.forwardFreeInputClick&&input?.click(),input?.focus()}focus(options){if(this.host.effectiveDisabled)return;this.host.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.host.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}select(){this.input?.select()}setSelectionRange(start,end,direction){this.input?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.input;input&&(setNativeRangeText(input,replacement,start,end,selectMode),this.setQuery(input.value),this.setActiveIndex(-1),this.value=input.value)}connected(hasUpdated){hasUpdated&&this._open&&queueMicrotask(()=>this.syncPopup())}disconnected(){this.typeBuffer.clear(),this.popupPosition.disconnect(),this.deactivateOverlay(!1),this.cancelListboxHideWatch(),this.setListboxHidden(!0),this.setOpen(!1)}adopted(){this.typeBuffer.clear(),this.popupPosition.disconnect(),this.popupController.unbindPointer(),this.overlay?.suspend(),this._open&&queueMicrotask(()=>this.syncPopup())}updated(reposition){const previous=this.host.renderRoot.querySelector('[part="option"][data-active]'),listbox=this.host.renderRoot.querySelector('[part="listbox"]'),activeId=this._open&&this._activeIndex>=0?`${listbox?.id}-opt-${this._activeIndex}`:"";previous?.id!==activeId&&previous?.removeAttribute("data-active"),activeId&&this.host.renderRoot.querySelector(`[id="${activeId}"]`)?.setAttribute("data-active",""),reposition&&this.syncPopup(),this.revealPending&&this._open&&this.revealActiveRow(),this.revealPending=!1}containsFocusTarget(target){if(this.options.containsFocusTarget)return this.options.containsFocusTarget(target);if(!target||typeof target.nodeType!="number")return!1;const node=target;return this.host.renderRoot.contains(node)||this.host.contains(node)}activatePopupOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this.host,panel:()=>this.host.renderRoot.querySelector('[part="listbox"]')??null,onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide()})}deactivateOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}dismissFromEscape(){this._open&&(this.closedMode||this.setQuery(this.labelFor(this._value)),this.deactivateOverlay(!0),this.setOpen(!1))}syncPopup(){if(this.popupPosition.disconnect(),!this._open||!this.host.isConnected){this.deactivateOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.host.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]'),listbox=this.host.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&this.popupPosition.reposition(anchor,listbox)}}export{CatalogPickerController,filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue};
@@ -1 +1 @@
1
- import{LitElement}from"lit";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor,isPlainDataRecord as isRealmNeutralPlainRecord,readOwnArrayLength}from"./data-descriptors.js";import{devWarnOnce}from"./dev-warning.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_WORK_LIMIT=PUBLIC_COLLECTION_NODE_LIMIT*2,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value"),EXHAUSTED_COLLECTION_VALUE=Symbol("exhausted-public-collection-value"),normalizedCollectionWrites=new WeakMap,readonlySnapshotWrappers=new WeakMap;function writeNormalizedOwnedCollection(host,property,write){let active=normalizedCollectionWrites.get(host);active||normalizedCollectionWrites.set(host,active=new Set);const alreadyActive=active.has(property);active.add(property);try{write()}finally{alreadyActive||active.delete(property),active.size===0&&normalizedCollectionWrites.delete(host)}}function isCollectionSnapshotFailure(value){return value===OMIT_COLLECTION_VALUE||value===EXHAUSTED_COLLECTION_VALUE}function boundedSnapshotLimit(value,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0?Math.min(value,maximum):maximum}function recordRootLoss(budget,kept,source,retained){retained<source&&(budget.rootLoss=Object.freeze({kept,retained,source}),budget.truncated=!0)}function consumeSnapshotWork(budget){return budget.remainingWork<=0?!1:(budget.remainingWork-=1,!0)}function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){try{return ArrayBuffer.isView(value)}catch{return!1}}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){const wrapper=readonlySnapshotWrappers.get(value);if(wrapper?.kind==="date")return wrapper.time;try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return readonlySnapshotWrappers.set(snapshot,{kind:"date",time}),rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(!isCollectionSnapshotFailure(result))return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,result}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)yield key}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(prototype);rememberSnapshot(budget,value,output);try{for(const key of keys){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.invalid=!0);continue}if(budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;budget.remaining-=1;const disposition=budget.recordKey?.(key,descriptor.value,depth)??"copy";if(disposition==="omit"){budget.invalid=!0;continue}const entry=disposition==="preserve"||preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value));if(isCollectionSnapshotFailure(entry))return entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:budget.truncated=!0,entry;Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}}catch{return OMIT_COLLECTION_VALUE}return Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>budget.depthLimit||budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;if(isArrayValue(value)){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value);if(sourceLength===void 0)return budget.invalid=!0,allowPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;if(!allowPrefixTruncation&&sourceLength>budget.entryLimit)return EXHAUSTED_COLLECTION_VALUE;const length=Math.min(sourceLength,budget.entryLimit),newest=depth===0&&allowPrefixTruncation&&budget.retention==="newest",output=new budget.realm.Array;rememberSnapshot(budget,value,output);const kept=[];let walked=0,dropped=0;for(;walked<length;walked+=1){if(budget.remaining<=0||!consumeSnapshotWork(budget)){if(!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}const index=newest?sourceLength-1-walked:walked,descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value))));if(entry===OMIT_COLLECTION_VALUE){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}if(entry===EXHAUSTED_COLLECTION_VALUE){if(budget.truncated=!0,!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}kept.push(index,entry)}output.length=walked;const offset=newest?sourceLength-walked:0;for(let index=0;index<kept.length;index+=2)Object.defineProperty(output,kept[index]-offset,{value:kept[index+1],enumerable:!0,configurable:!1,writable:!1});return walked-dropped<sourceLength&&(budget.truncated=!0),allowPrefixTruncation&&depth===0&&recordRootLoss(budget,newest?"newest":"oldest",sourceLength,walked-dropped),Object.freeze(output)}if(!readonlySnapshotWrappers.has(value)&&isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth,allowPrefixTruncation);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth,allowPrefixTruncation);if(isNativeArrayBufferView(value))return budget.invalid=!0,OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:(budget.invalid=!0,OMIT_COLLECTION_VALUE)}function boundedRecordSize(value,limit=PUBLIC_COLLECTION_WORK_LIMIT){let size=0;try{for(const key in value)if(typeof key=="string"&&(size+=1),size>=limit)break}catch{return}return size}function snapshotPublicCollection(value,view,options={}){if(value===null||typeof value!="object"&&typeof value!="function")return options.onResult?.(Object.freeze({invalid:!1,truncated:!1})),value;const realm=snapshotRealm(view),nodeLimit=boundedSnapshotLimit(options.limits?.nodes,PUBLIC_COLLECTION_NODE_LIMIT),budget={remaining:nodeLimit,remainingWork:nodeLimit*2,seen:new WeakMap,additions:[],realm,entryLimit:boundedSnapshotLimit(options.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT),depthLimit:boundedSnapshotLimit(options.limits?.depth,PUBLIC_COLLECTION_DEPTH_LIMIT),nestedArrayPrefix:options.nestedArrayPrefix??!1,recordKey:options.recordKey,invalid:!1,truncated:!1,retention:options.retain??"oldest"},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(!isCollectionSnapshotFailure(snapshot))return budget.rootLoss&&options.onTruncate?.(budget.rootLoss),options.onResult?.(Object.freeze({invalid:budget.invalid,truncated:budget.truncated})),snapshot;if(options.onResult?.(Object.freeze({invalid:budget.invalid||snapshot===OMIT_COLLECTION_VALUE,truncated:budget.truncated||snapshot===EXHAUSTED_COLLECTION_VALUE})),isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const size=boundedRecordSize(value,nodeLimit*2);size&&options.onTruncate?.(Object.freeze({kept:"oldest",retained:0,source:size}));const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Map.prototype.entries.call(wrapper?.kind==="map"?wrapper.backing:value)}catch{return}}function nativeSetValues(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Set.prototype.values.call(wrapper?.kind==="set"?wrapper.backing:value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"map",backing}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"set",backing}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm(),budget){const backing=new realm.Map;for(let count=0;count<(budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT);count+=1){const next=entries.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.set(next.value[0],next.value[1])}return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm(),budget){const backing=new realm.Set;for(let count=0;count<(budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT);count+=1){const next=values.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.add(next.value)}return readonlySetFacade(backing,realm)}function nativeCollectionSize(source,kind){const wrapper=readonlySnapshotWrappers.get(source);try{const size=Object.getOwnPropertyDescriptor(kind==="map"?Map.prototype:Set.prototype,"size")?.get?.call(wrapper?.kind===kind?wrapper.backing:source);return typeof size=="number"?size:void 0}catch{return}}function recordNativeCollectionLoss(budget,source,kind,retained){const size=nativeCollectionSize(source,kind);size!==void 0&&recordRootLoss(budget,"oldest",size,retained)}function snapshotDetachedMap(source,entries,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"map",backing.size):(nativeCollectionSize(source,"map")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=entries.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(isCollectionSnapshotFailure(key))return key;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return isCollectionSnapshotFailure(entry)?entry:[key,entry]});if(pair===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;pair===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.set(pair[0],pair[1])}return settle()}function snapshotDetachedSet(source,values,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"set",backing.size):(nativeCollectionSize(source,"set")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=values.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));if(entry===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.add(entry)}return settle()}function snapshotIdentityCollection(value,view,budget,root){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value)??0,length=Math.min(sourceLength,PUBLIC_COLLECTION_ENTRY_LIMIT),kept=root?.retain??"oldest",offset=kept==="newest"?sourceLength-length:0,output=new realm.Array(length);budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,String(offset+index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||Object.defineProperty(output,index,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1})}return length<sourceLength&&root?.onTruncate?.(Object.freeze({kept,retained:length,source:sourceLength})),Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm,budget);return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"map",output.size)),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm,budget);return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"set",output.size)),output}return emptyRealmArray(realm)}function reportIdentityCollectionLoss(root,source,kind,retained){if(!root?.onTruncate)return;const size=nativeCollectionSize(source,kind);size!==void 0&&retained<size&&root.onTruncate(Object.freeze({kept:"oldest",retained,source:size}))}function snapshotEventDetail(value,view,preserveRootKeys,preserveCollectionItemKeys){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,remainingWork:PUBLIC_COLLECTION_WORK_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view),entryLimit:PUBLIC_COLLECTION_ENTRY_LIMIT,depthLimit:PUBLIC_COLLECTION_DEPTH_LIMIT,nestedArrayPrefix:!1,invalid:!1,truncated:!1},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return isCollectionSnapshotFailure(snapshot)?null:snapshot}function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}function lyraClassChain(ctor){const constructors=[];let current=ctor;for(;typeof current=="function"&&current!==LitElement;)constructors.push(current),current=Object.getPrototypeOf(current);return constructors}const collectionPolicyByConstructor=new WeakMap;function collectionPropertyPolicy(ctor,name){let policies=collectionPolicyByConstructor.get(ctor);policies||(policies=new Map,collectionPolicyByConstructor.set(ctor,policies));const cached=policies.get(name);if(cached)return cached;let owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1,retainsNewest=!1,immutableSource=!1;for(const constructor of lyraClassChain(ctor)){const declared=constructor;Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"immutableSourceCollectionProperties")&&declared.immutableSourceCollectionProperties.includes(name)&&(immutableSource=!0),Object.prototype.hasOwnProperty.call(constructor,"appendOrderedCollectionProperties")&&declared.appendOrderedCollectionProperties.includes(name)&&(retainsNewest=!0)}const policy=Object.freeze({owns,preservesItemIdentity,preservesObjectIdentity,retainsNewest,immutableSource});return policies.set(name,policy),policy}const COLLECTION_ENROLLMENT_FIELDS=["ownedCollectionProperties","identityCollectionProperties","identityCollectionObjectProperties","appendOrderedCollectionProperties","immutableSourceCollectionProperties"];function enrolledCollectionPropertyNames(ctor){const names=new Set;for(const constructor of lyraClassChain(ctor))for(const field of COLLECTION_ENROLLMENT_FIELDS){if(!Object.prototype.hasOwnProperty.call(constructor,field))continue;const declared=constructor;for(const name of declared[field])names.add(name)}return names}function inheritedPropertyDescriptor(prototype,name){let current=prototype;for(;current;){const descriptor=Object.getOwnPropertyDescriptor(current,name);if(descriptor)return descriptor;current=Object.getPrototypeOf(current)}}const installedOwnershipBoundaries=new WeakSet,ownershipBoundarySetters=new WeakMap;function samePolicy(a,b){return a.owns===b.owns&&a.preservesItemIdentity===b.preservesItemIdentity&&a.preservesObjectIdentity===b.preservesObjectIdentity&&a.retainsNewest===b.retainsNewest&&a.immutableSource===b.immutableSource}function installOwnedCollectionAccessors(ctor){if(installedOwnershipBoundaries.has(ctor))return;installedOwnershipBoundaries.add(ctor);const prototype=ctor.prototype;for(const name of enrolledCollectionPropertyNames(ctor)){const policy=collectionPropertyPolicy(ctor,name);if(!policy.owns)continue;const declaration=ctor.elementProperties.get(name);if(!declaration||declaration.noAccessor)continue;const descriptor=inheritedPropertyDescriptor(prototype,name),inheritedSet=descriptor?.set;if(!inheritedSet)continue;const installed=ownershipBoundarySetters.get(inheritedSet);if(installed&&samePolicy(installed.policy,policy))continue;const originalSet=installed?.originalSet??inheritedSet,lastAssignments=new WeakMap,set=function(value){const previous=lastAssignments.get(this);if(previous&&declaration.hasChanged===void 0&&(!policy.preservesItemIdentity||policy.immutableSource)&&!policy.preservesObjectIdentity&&(Object.is(value,previous.source)||Object.is(value,previous.retained)))return;const ownerView=this.ownerDocument?.defaultView;let truncation;const options={retain:policy.retainsNewest?"newest":"oldest",onTruncate:report=>{truncation=report}},snapshot=policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView,void 0,options):snapshotPublicCollection(value,ownerView,options);recordCollectionTruncation(this,name,truncation),originalSet.call(this,snapshot),lastAssignments.set(this,{source:normalizedCollectionWrites.get(this)?.has(name)&&previous?previous.source:value,retained:descriptor.get?.call(this)??snapshot})};ownershipBoundarySetters.set(set,{policy,originalSet}),Object.defineProperty(prototype,name,{...descriptor,set})}}const collectionTruncations=new WeakMap;function collectionTruncationWarningKey(tagName,property){return`lyra-collection-truncated:${tagName}:${String(property)}`}function recordCollectionTruncation(host,name,truncation){let byName=collectionTruncations.get(host);if(!truncation){byName?.delete(name);return}byName||(byName=new Map,collectionTruncations.set(host,byName)),byName.set(name,truncation);const tagName=host.localName,property=String(name);devWarnOnce(collectionTruncationWarningKey(tagName,property),`<${tagName}>: '${property}' kept ${truncation.retained} of ${truncation.source} entries, the ${truncation.kept}; an assignment keeps at most ${PUBLIC_COLLECTION_ENTRY_LIMIT} per array and ${PUBLIC_COLLECTION_NODE_LIMIT} values, and drops values it cannot copy.`)}function publicCollectionTruncation(host,property){return collectionTruncations.get(host)?.get(property)}function snapshotEnrolledEventDetail(host,name,detail){let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const candidate of trustedLyraConstructorChain(host)){const constructor=candidate;if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}return snapshotsDetail?snapshotEventDetail(detail,host.ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail}function declaresOwnedCollections(ctor){for(const constructor of lyraClassChain(ctor)){if(!Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties"))continue;if(constructor.ownedCollectionProperties.length>0)return!0}return!1}const collectionSupport=/* @__PURE__ */Object.freeze({installProperties:installOwnedCollectionAccessors,snapshotEvent:snapshotEnrolledEventDetail}),eventCollectionSupport=/* @__PURE__ */Object.freeze({installProperties(ctor){declaresOwnedCollections(ctor)&&devWarnOnce(`lyra-event-collection-support:${ctor.name}`,`${ctor.name} enrolls ownedCollectionProperties but declares eventCollectionSupport; declare collectionSupport so those properties cross the immutable collection boundary.`)},snapshotEvent:snapshotEnrolledEventDetail});export{collectionSupport,collectionTruncationWarningKey,eventCollectionSupport,publicCollectionTruncation,snapshotPublicCollection,writeNormalizedOwnedCollection};
1
+ import{LitElement}from"lit";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor,isPlainDataRecord as isRealmNeutralPlainRecord,readOwnArrayLength}from"./data-descriptors.js";import{devWarnOnce}from"./dev-warning.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_WORK_LIMIT=PUBLIC_COLLECTION_NODE_LIMIT*2,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value"),EXHAUSTED_COLLECTION_VALUE=Symbol("exhausted-public-collection-value"),normalizedCollectionWrites=new WeakMap,readonlySnapshotWrappers=new WeakMap;function writeNormalizedOwnedCollection(host,property,write){let active=normalizedCollectionWrites.get(host);active||normalizedCollectionWrites.set(host,active=new Set);const alreadyActive=active.has(property);active.add(property);try{write()}finally{alreadyActive||active.delete(property),active.size===0&&normalizedCollectionWrites.delete(host)}}function isCollectionSnapshotFailure(value){return value===OMIT_COLLECTION_VALUE||value===EXHAUSTED_COLLECTION_VALUE}function boundedSnapshotLimit(value,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0?Math.min(value,maximum):maximum}function recordRootLoss(budget,kept,source,retained){retained<source&&(budget.rootLoss=Object.freeze({kept,retained,source}),budget.truncated=!0)}function consumeSnapshotWork(budget){return budget.remainingWork<=0?!1:(budget.remainingWork-=1,!0)}function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){try{return ArrayBuffer.isView(value)}catch{return!1}}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){const wrapper=readonlySnapshotWrappers.get(value);if(wrapper?.kind==="date")return wrapper.time;try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return readonlySnapshotWrappers.set(snapshot,{kind:"date",time}),rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(!isCollectionSnapshotFailure(result))return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,result}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)yield key}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(null);rememberSnapshot(budget,value,output);try{for(const key of keys){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.invalid=!0);continue}if(budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;budget.remaining-=1;const disposition=budget.recordKey?.(key,descriptor.value,depth)??"copy";if(disposition==="omit"){budget.invalid=!0;continue}const entry=disposition==="preserve"||preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value));if(isCollectionSnapshotFailure(entry))return entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:budget.truncated=!0,entry;output[key]=entry}}catch{return OMIT_COLLECTION_VALUE}return Object.setPrototypeOf(output,prototype),Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>budget.depthLimit||budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;if(isArrayValue(value)){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value);if(sourceLength===void 0)return budget.invalid=!0,allowPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;if(!allowPrefixTruncation&&sourceLength>budget.entryLimit)return EXHAUSTED_COLLECTION_VALUE;const length=Math.min(sourceLength,budget.entryLimit),newest=depth===0&&allowPrefixTruncation&&budget.retention==="newest",output=new budget.realm.Array;Object.setPrototypeOf(output,null),rememberSnapshot(budget,value,output);const kept=[];let walked=0,dropped=0;for(;walked<length;walked+=1){if(budget.remaining<=0||!consumeSnapshotWork(budget)){if(!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}const index=newest?sourceLength-1-walked:walked,descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value))));if(entry===OMIT_COLLECTION_VALUE){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}if(entry===EXHAUSTED_COLLECTION_VALUE){if(budget.truncated=!0,!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}kept.push(index,entry)}output.length=walked;const offset=newest?sourceLength-walked:0;for(let index=0;index<kept.length;index+=2)output[kept[index]-offset]=kept[index+1];return Object.setPrototypeOf(output,budget.realm.Array.prototype),walked-dropped<sourceLength&&(budget.truncated=!0),allowPrefixTruncation&&depth===0&&recordRootLoss(budget,newest?"newest":"oldest",sourceLength,walked-dropped),Object.freeze(output)}if(!readonlySnapshotWrappers.has(value)&&isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth,allowPrefixTruncation);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth,allowPrefixTruncation);if(isNativeArrayBufferView(value))return budget.invalid=!0,OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:(budget.invalid=!0,OMIT_COLLECTION_VALUE)}function boundedRecordSize(value,limit=PUBLIC_COLLECTION_WORK_LIMIT){let size=0;try{for(const key in value)if(typeof key=="string"&&(size+=1),size>=limit)break}catch{return}return size}function snapshotPublicCollection(value,view,options={}){if(value===null||typeof value!="object"&&typeof value!="function")return options.onResult?.(Object.freeze({invalid:!1,truncated:!1})),value;const realm=snapshotRealm(view),nodeLimit=boundedSnapshotLimit(options.limits?.nodes,PUBLIC_COLLECTION_NODE_LIMIT),budget={remaining:nodeLimit,remainingWork:nodeLimit*2,seen:new WeakMap,additions:[],realm,entryLimit:boundedSnapshotLimit(options.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT),depthLimit:boundedSnapshotLimit(options.limits?.depth,PUBLIC_COLLECTION_DEPTH_LIMIT),nestedArrayPrefix:options.nestedArrayPrefix??!1,recordKey:options.recordKey,invalid:!1,truncated:!1,retention:options.retain??"oldest"},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(!isCollectionSnapshotFailure(snapshot))return budget.rootLoss&&options.onTruncate?.(budget.rootLoss),options.onResult?.(Object.freeze({invalid:budget.invalid,truncated:budget.truncated})),snapshot;if(options.onResult?.(Object.freeze({invalid:budget.invalid||snapshot===OMIT_COLLECTION_VALUE,truncated:budget.truncated||snapshot===EXHAUSTED_COLLECTION_VALUE})),isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const size=boundedRecordSize(value,nodeLimit*2);size&&options.onTruncate?.(Object.freeze({kept:"oldest",retained:0,source:size}));const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Map.prototype.entries.call(wrapper?.kind==="map"?wrapper.backing:value)}catch{return}}function nativeSetValues(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Set.prototype.values.call(wrapper?.kind==="set"?wrapper.backing:value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"map",backing}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"set",backing}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Map;for(let count=0;count<entryLimit;count+=1){const next=entries.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.set(next.value[0],next.value[1])}return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Set;for(let count=0;count<entryLimit;count+=1){const next=values.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.add(next.value)}return readonlySetFacade(backing,realm)}function nativeCollectionSize(source,kind){const wrapper=readonlySnapshotWrappers.get(source);try{const size=Object.getOwnPropertyDescriptor(kind==="map"?Map.prototype:Set.prototype,"size")?.get?.call(wrapper?.kind===kind?wrapper.backing:source);return typeof size=="number"?size:void 0}catch{return}}function recordNativeCollectionLoss(budget,source,kind,retained){const size=nativeCollectionSize(source,kind);size!==void 0&&recordRootLoss(budget,"oldest",size,retained)}function snapshotDetachedMap(source,entries,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"map",backing.size):(nativeCollectionSize(source,"map")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=entries.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(isCollectionSnapshotFailure(key))return key;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return isCollectionSnapshotFailure(entry)?entry:[key,entry]});if(pair===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;pair===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.set(pair[0],pair[1])}return settle()}function snapshotDetachedSet(source,values,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"set",backing.size):(nativeCollectionSize(source,"set")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=values.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));if(entry===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.add(entry)}return settle()}function snapshotIdentityCollection(value,view,budget,root){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value)??0,length=Math.min(sourceLength,boundedSnapshotLimit(root?.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT)),kept=root?.retain??"oldest",offset=kept==="newest"?sourceLength-length:0,output=new realm.Array(length);Object.setPrototypeOf(output,null),budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,String(offset+index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||(output[index]=descriptor.value)}return Object.setPrototypeOf(output,realm.Array.prototype),length<sourceLength&&root?.onTruncate?.(Object.freeze({kept,retained:length,source:sourceLength})),Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"map",output.size)),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"set",output.size)),output}return emptyRealmArray(realm)}function reportIdentityCollectionLoss(root,source,kind,retained){if(!root?.onTruncate)return;const size=nativeCollectionSize(source,kind);size!==void 0&&retained<size&&root.onTruncate(Object.freeze({kept:"oldest",retained,source:size}))}function snapshotEventDetail(value,view,preserveRootKeys=new Set,preserveCollectionItemKeys=new Set){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,remainingWork:PUBLIC_COLLECTION_WORK_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view),entryLimit:PUBLIC_COLLECTION_ENTRY_LIMIT,depthLimit:PUBLIC_COLLECTION_DEPTH_LIMIT,nestedArrayPrefix:!1,invalid:!1,truncated:!1},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return isCollectionSnapshotFailure(snapshot)?null:snapshot}function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}function lyraClassChain(ctor){const constructors=[];let current=ctor;for(;typeof current=="function"&&current!==LitElement;)constructors.push(current),current=Object.getPrototypeOf(current);return constructors}const collectionPolicyByConstructor=new WeakMap;function collectionPropertyPolicy(ctor,name){let policies=collectionPolicyByConstructor.get(ctor);policies||(policies=new Map,collectionPolicyByConstructor.set(ctor,policies));const cached=policies.get(name);if(cached)return cached;let limits,owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1,retainsNewest=!1,immutableSource=!1;for(const constructor of lyraClassChain(ctor)){const declared=constructor;!limits&&Object.hasOwn(constructor,"ownedCollectionLimits")&&declared.ownedCollectionLimits&&Object.hasOwn(declared.ownedCollectionLimits,name)&&(limits=declared.ownedCollectionLimits[name]),Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"immutableSourceCollectionProperties")&&declared.immutableSourceCollectionProperties.includes(name)&&(immutableSource=!0),Object.prototype.hasOwnProperty.call(constructor,"appendOrderedCollectionProperties")&&declared.appendOrderedCollectionProperties.includes(name)&&(retainsNewest=!0)}const policy=Object.freeze({limits,owns,preservesItemIdentity,preservesObjectIdentity,retainsNewest,immutableSource});return policies.set(name,policy),policy}const COLLECTION_ENROLLMENT_FIELDS=["ownedCollectionProperties","identityCollectionProperties","identityCollectionObjectProperties","appendOrderedCollectionProperties","immutableSourceCollectionProperties"];function enrolledCollectionPropertyNames(ctor){const names=new Set;for(const constructor of lyraClassChain(ctor))for(const field of COLLECTION_ENROLLMENT_FIELDS){if(!Object.prototype.hasOwnProperty.call(constructor,field))continue;const declared=constructor;for(const name of declared[field])names.add(name)}return names}function inheritedPropertyDescriptor(prototype,name){let current=prototype;for(;current;){const descriptor=Object.getOwnPropertyDescriptor(current,name);if(descriptor)return descriptor;current=Object.getPrototypeOf(current)}}const installedOwnershipBoundaries=new WeakSet,ownershipBoundarySetters=new WeakMap;function samePolicy(a,b){return a.limits===b.limits&&a.owns===b.owns&&a.preservesItemIdentity===b.preservesItemIdentity&&a.preservesObjectIdentity===b.preservesObjectIdentity&&a.retainsNewest===b.retainsNewest&&a.immutableSource===b.immutableSource}function installOwnedCollectionAccessors(ctor){if(installedOwnershipBoundaries.has(ctor))return;installedOwnershipBoundaries.add(ctor);const prototype=ctor.prototype;for(const name of enrolledCollectionPropertyNames(ctor)){const policy=collectionPropertyPolicy(ctor,name);if(!policy.owns)continue;const declaration=ctor.elementProperties.get(name);if(!declaration||declaration.noAccessor)continue;const descriptor=inheritedPropertyDescriptor(prototype,name),inheritedSet=descriptor?.set;if(!inheritedSet)continue;const installed=ownershipBoundarySetters.get(inheritedSet);if(installed&&samePolicy(installed.policy,policy))continue;const originalSet=installed?.originalSet??inheritedSet,lastAssignments=new WeakMap,set=function(value){const previous=lastAssignments.get(this);if(previous&&declaration.hasChanged===void 0&&(!policy.preservesItemIdentity||policy.immutableSource)&&!policy.preservesObjectIdentity&&(("primitive"in previous.source?Object.is(value,previous.source.primitive):value!==void 0&&Object.is(value,previous.source.deref()))||Object.is(value,previous.retained)))return;const retainedLoss=previous&&!policy.preservesObjectIdentity&&Object.is(value,previous.retained)?publicCollectionTruncation(this,name):void 0,ownerView=this.ownerDocument?.defaultView;let truncation;const options={limits:policy.limits,retain:policy.retainsNewest?"newest":"oldest",onTruncate:report=>{truncation=report}},snapshot=policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView,void 0,options):snapshotPublicCollection(value,ownerView,options);if(retainedLoss){const retained=truncation?.retained??(policy.preservesItemIdentity?isArrayValue(snapshot)?readOwnArrayLength(snapshot):snapshot!==null&&typeof snapshot=="object"?nativeCollectionSize(snapshot,"map")??nativeCollectionSize(snapshot,"set"):void 0:void 0)??retainedLoss.retained;truncation=Object.freeze({kept:truncation?.kept??retainedLoss.kept,retained,source:retainedLoss.source})}recordCollectionTruncation(this,name,truncation),originalSet.call(this,snapshot);const source=normalizedCollectionWrites.get(this)?.has(name)&&previous?previous.source:typeof value=="object"&&value!==null||typeof value=="function"?new WeakRef(value):{primitive:value};lastAssignments.set(this,{source,retained:descriptor.get?.call(this)??snapshot})};ownershipBoundarySetters.set(set,{policy,originalSet}),Object.defineProperty(prototype,name,{...descriptor,set})}}const collectionTruncations=new WeakMap;function collectionTruncationWarningKey(tagName,property){return`lyra-collection-truncated:${tagName}:${String(property)}`}function recordCollectionTruncation(host,name,truncation){let byName=collectionTruncations.get(host);if(!truncation){byName?.delete(name);return}byName||(byName=new Map,collectionTruncations.set(host,byName)),byName.set(name,truncation);const tagName=host.localName,property=String(name);devWarnOnce(collectionTruncationWarningKey(tagName,property),`<${tagName}>: '${property}' kept ${truncation.retained} of ${truncation.source} entries, the ${truncation.kept}; an assignment keeps at most ${PUBLIC_COLLECTION_ENTRY_LIMIT} per array and ${PUBLIC_COLLECTION_NODE_LIMIT} values, and drops values it cannot copy.`)}function publicCollectionTruncation(host,property){return collectionTruncations.get(host)?.get(property)}function snapshotEnrolledEventDetail(host,name,detail){let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const candidate of trustedLyraConstructorChain(host)){const constructor=candidate;if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}return snapshotsDetail?snapshotEventDetail(detail,host.ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail}function declaresOwnedCollections(ctor){for(const constructor of lyraClassChain(ctor)){if(!Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties"))continue;if(constructor.ownedCollectionProperties.length>0)return!0}return!1}const collectionSupport=/* @__PURE__ */Object.freeze({installProperties:installOwnedCollectionAccessors,snapshotEvent:snapshotEnrolledEventDetail}),eventCollectionSupport=/* @__PURE__ */Object.freeze({installProperties(ctor){declaresOwnedCollections(ctor)&&devWarnOnce(`lyra-event-collection-support:${ctor.name}`,`${ctor.name} enrolls ownedCollectionProperties but declares eventCollectionSupport; declare collectionSupport so those properties cross the immutable collection boundary.`)},snapshotEvent:snapshotEnrolledEventDetail});export{collectionSupport,collectionTruncationWarningKey,eventCollectionSupport,publicCollectionTruncation,snapshotEventDetail,snapshotPublicCollection,writeNormalizedOwnedCollection};