@aceshooting/lyra-ui 29.0.2 → 29.2.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.
- package/CHANGELOG.md +55 -0
- package/README.md +20 -27
- package/design-tokens.json +1 -1
- package/dist/cli/migrate-wa.mjs +2 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +5 -3
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +4 -3
- package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +21 -5
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +14 -11
- package/dist/components/agent-tools/agent-trace/agent-trace.styles.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +34 -7
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +25 -11
- package/dist/components/agent-tools/eval-result/eval-result-source.js +1 -0
- package/dist/components/agent-tools/eval-result/eval-result.class.d.ts +31 -11
- package/dist/components/agent-tools/eval-result/eval-result.class.js +29 -15
- package/dist/components/agent-tools/eval-result/eval-result.styles.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-run-result.d.ts +10 -0
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.d.ts +26 -5
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +16 -6
- package/dist/components/agent-tools/span-waterfall/span-waterfall.d.ts +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +29 -6
- package/dist/components/agent-tools/task-list/task-list.class.js +13 -7
- package/dist/components/agent-tools/task-list/task-list.d.ts +1 -1
- package/dist/components/agent-tools/task-list/task-list.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.styles.js +1 -1
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +9 -5
- package/dist/components/agent-tools/terminal/terminal.class.js +8 -8
- package/dist/components/agent-tools/test-results/test-results.class.d.ts +16 -4
- package/dist/components/agent-tools/test-results/test-results.class.js +15 -6
- package/dist/components/agent-tools/test-results/test-results.d.ts +1 -0
- package/dist/components/agent-tools/test-results/test-results.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.styles.js +1 -1
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +7 -4
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +2 -1
- package/dist/components/agent-tools/trace-tree/span-projection.js +1 -0
- package/dist/components/agent-tools/trace-tree/span-shared.d.ts +29 -0
- package/dist/components/agent-tools/trace-tree/span-shared.js +1 -0
- package/dist/components/agent-tools/trace-tree/span.d.ts +5 -35
- package/dist/components/agent-tools/trace-tree/span.js +1 -1
- package/dist/components/agent-tools/trace-tree/trace-tree.class.d.ts +27 -5
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +19 -9
- package/dist/components/agent-tools/trace-tree/trace-tree.d.ts +1 -1
- package/dist/components/agent-tools/trace-tree/trace-tree.js +1 -1
- package/dist/components/agent-tools/trace-tree/trace-tree.styles.js +1 -1
- package/dist/components/charts/chart/bar-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
- package/dist/components/charts/chart/box-plot.class.js +3 -3
- package/dist/components/charts/chart/bubble-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/chart-prepared-data.d.ts +9 -0
- package/dist/components/charts/chart/chart-prepared-data.js +1 -0
- package/dist/components/charts/chart/chart-spatial-data.js +2 -0
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart-table-sampling.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +56 -6
- package/dist/components/charts/chart/chart.class.js +18 -8
- package/dist/components/charts/chart/chart.styles.js +1 -1
- package/dist/components/charts/chart/doughnut-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/histogram-buckets.d.ts +1 -1
- package/dist/components/charts/chart/histogram-buckets.js +1 -1
- package/dist/components/charts/chart/histogram.class.d.ts +19 -4
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/line-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +51 -11
- package/dist/components/charts/chart/lite-chart.class.js +33 -27
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/charts/chart/pie-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/polar-area-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/radar-chart.class.d.ts +5 -1
- package/dist/components/charts/chart/scatter-chart.class.d.ts +5 -1
- package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +6 -3
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +6 -5
- package/dist/components/conversation/agent-workspace/agent-workspace.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +8 -0
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.d.ts +5 -3
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +4 -1
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.d.ts +6 -4
- package/dist/components/conversation/code-block/code-block-shared.js +3 -2
- package/dist/components/conversation/code-block/code-block.class.d.ts +11 -4
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.d.ts +1 -1
- package/dist/components/conversation/code-block/code-block.styles.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -0
- package/dist/components/conversation/code-block/shiki-types.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +6 -4
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.d.ts +2 -2
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +8 -3
- package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
- package/dist/components/conversation/markdown/markdown-shared.d.ts +5 -10
- package/dist/components/conversation/markdown/markdown-shared.js +5 -5
- package/dist/components/conversation/markdown/markdown-streaming-tail.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +17 -10
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/markdown/markdown.styles.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +4 -3
- package/dist/components/conversation/model-select/model-select.class.js +3 -2
- package/dist/components/conversation/model-select/model-select.styles.js +1 -1
- package/dist/components/conversation/model-settings-panel/model-settings-panel.class.d.ts +2 -1
- package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +2 -1
- package/dist/components/conversation/model-settings-panel/model-settings-panel.styles.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +3 -2
- package/dist/components/conversation/prompt-input/prompt-input.class.js +2 -1
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
- package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +10 -2
- package/dist/components/conversation/prompt-queue/prompt-queue.class.js +15 -6
- package/dist/components/conversation/prompt-queue/prompt-queue.styles.js +1 -1
- package/dist/components/conversation/realtime-session/realtime-session.class.d.ts +3 -1
- package/dist/components/conversation/realtime-session/realtime-session.class.js +2 -1
- package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
- package/dist/components/conversation/streaming-text/markdown-detection.d.ts +2 -0
- package/dist/components/conversation/streaming-text/markdown-detection.js +4 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +6 -2
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +3 -3
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +34 -4
- package/dist/components/conversation/thread-list/thread-list.class.js +22 -15
- package/dist/components/conversation/thread-list/thread-list.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.styles.js +1 -1
- package/dist/components/conversation/transcript-feed/transcript-feed.class.d.ts +6 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +3 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.styles.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +3 -2
- package/dist/components/conversation/voice-picker/voice-picker.class.js +3 -2
- package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
- package/dist/components/data/calendar/calendar.class.d.ts +5 -2
- package/dist/components/data/calendar/calendar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +2 -2
- package/dist/components/data/data-grid/data-grid.class.d.ts +22 -8
- package/dist/components/data/data-grid/data-grid.class.js +20 -19
- package/dist/components/data/data-grid/data-grid.styles.js +1 -1
- package/dist/components/data/document-library/document-library.class.d.ts +31 -4
- package/dist/components/data/document-library/document-library.class.js +25 -12
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.d.ts +30 -6
- package/dist/components/data/file-tree/file-tree.class.js +4 -3
- package/dist/components/data/file-tree/file-tree.d.ts +1 -0
- package/dist/components/data/file-tree/file-tree.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +31 -6
- package/dist/components/data/flow-canvas/flow-canvas.class.js +40 -19
- package/dist/components/data/flow-canvas/flow-canvas.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-model.js +1 -1
- package/dist/components/data/flow-canvas/flow-source.js +1 -0
- package/dist/components/data/flow-canvas/flow-types.d.ts +4 -2
- package/dist/components/data/flow-canvas/flow-viewport-index.js +1 -0
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +9 -3
- package/dist/components/data/flow-minimap/flow-minimap.class.js +11 -2
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
- package/dist/components/data/funnel/funnel.class.d.ts +7 -3
- package/dist/components/data/funnel/funnel.class.js +2 -2
- package/dist/components/data/heatmap/calendar-grid.d.ts +1 -1
- package/dist/components/data/heatmap/calendar-grid.js +1 -1
- package/dist/components/data/heatmap/heatmap-grid-navigation.js +1 -1
- package/dist/components/data/heatmap/heatmap-limits.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap-matrix-source-controller.js +1 -0
- package/dist/components/data/heatmap/heatmap-matrix-source.d.ts +5 -0
- package/dist/components/data/heatmap/heatmap-matrix-source.js +1 -0
- package/dist/components/data/heatmap/heatmap-scale.d.ts +0 -16
- package/dist/components/data/heatmap/heatmap-scale.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +40 -11
- package/dist/components/data/heatmap/heatmap.class.js +26 -6
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/sequence-strip/sequence-strip-item.d.ts +17 -0
- package/dist/components/data/sequence-strip/sequence-strip-source-controller.js +1 -0
- package/dist/components/data/sequence-strip/sequence-strip-source.d.ts +5 -0
- package/dist/components/data/sequence-strip/sequence-strip-source.js +1 -0
- package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +24 -19
- package/dist/components/data/sequence-strip/sequence-strip.class.js +23 -4
- package/dist/components/data/sequence-strip/sequence-strip.styles.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.d.ts +17 -4
- package/dist/components/data/sparkline/sparkline.class.js +3 -3
- package/dist/components/data/sparkline/sparkline.styles.js +1 -1
- package/dist/components/data/table/table.class.d.ts +14 -10
- package/dist/components/data/table/table.class.js +17 -16
- package/dist/components/data/timeline/timeline.class.d.ts +5 -2
- package/dist/components/data/timeline/timeline.class.js +1 -1
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree-owner-controller.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +28 -6
- package/dist/components/data/tree/tree.class.js +3 -3
- package/dist/components/data/tree/tree.d.ts +1 -0
- package/dist/components/data/tree/tree.js +1 -1
- package/dist/components/data/word-cloud/word-cloud.class.d.ts +17 -7
- package/dist/components/data/word-cloud/word-cloud.class.js +6 -4
- package/dist/components/data/word-cloud/word-cloud.styles.js +1 -1
- package/dist/components/forms/catalog-picker-base.d.ts +1 -1
- package/dist/components/forms/catalog-picker-base.js +6 -6
- package/dist/components/forms/catalog-picker-base.styles.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -3
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/combobox/option.class.d.ts +4 -2
- package/dist/components/forms/combobox/option.class.js +2 -2
- package/dist/components/forms/country-picker/country-picker.class.d.ts +3 -1
- package/dist/components/forms/country-picker/country-picker.class.js +1 -1
- package/dist/components/forms/currency-picker/currency-picker.class.d.ts +2 -0
- package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
- package/dist/components/forms/currency-picker/currency-presentation.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +6 -2
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +3 -2
- package/dist/components/forms/emoji-picker/emoji-picker.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +8 -2
- package/dist/components/forms/locale-picker/locale-picker.class.js +5 -4
- package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +11 -3
- package/dist/components/forms/select/select.class.js +4 -4
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +2 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +6 -1
- package/dist/components/forms/token-input/token-input.class.js +15 -13
- package/dist/components/forms/unit-picker/unit-picker.class.d.ts +2 -0
- package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.class.d.ts +5 -2
- package/dist/components/layout/command-palette/command-palette.class.js +2 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/menu/menu-item.class.d.ts +2 -2
- package/dist/components/layout/menu/menu-item.class.js +2 -2
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.d.ts +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-item.class.d.ts +2 -2
- package/dist/components/layout/reorder-list/reorder-item.class.js +2 -2
- package/dist/components/layout/reorder-list/reorder-list.class.d.ts +1 -1
- package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +13 -9
- package/dist/components/layout/virtual-list/virtual-list.class.js +21 -17
- package/dist/components/media/av-player/av-cue-index.js +1 -0
- package/dist/components/media/av-player/av-cue-source.d.ts +13 -0
- package/dist/components/media/av-player/av-cue-source.js +1 -0
- package/dist/components/media/av-player/av-metadata.d.ts +2 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/av-player/av-player-cue-source-controller.js +1 -0
- package/dist/components/media/av-player/av-player.class.d.ts +34 -12
- package/dist/components/media/av-player/av-player.class.js +15 -10
- package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/lightbox/lightbox-source.js +1 -0
- package/dist/components/media/lightbox/lightbox-types.d.ts +15 -0
- package/dist/components/media/lightbox/lightbox.class.d.ts +22 -21
- package/dist/components/media/lightbox/lightbox.class.js +6 -4
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map-geojson-diff.d.ts +6 -6
- package/dist/components/media/map/map-geojson-diff.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +5 -1
- package/dist/components/media/map/map.class.d.ts +24 -6
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.d.ts +2 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.d.ts +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +30 -8
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +22 -8
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph-source-composition.js +1 -0
- package/dist/components/retrieval/graph/graph-source-controller.js +1 -0
- package/dist/components/retrieval/graph/graph-spatial-controller.js +2 -2
- package/dist/components/retrieval/graph/graph-spatial-model.js +1 -0
- package/dist/components/retrieval/graph/graph-spatial.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +31 -6
- package/dist/components/retrieval/graph/graph.class.js +26 -5
- package/dist/components/retrieval/graph/graph.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +33 -4
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +27 -17
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.d.ts +27 -4
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +29 -14
- package/dist/components/retrieval/knowledge-base/knowledge-base.styles.js +1 -1
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.d.ts +17 -3
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +15 -10
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.styles.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +24 -5
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +17 -10
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.d.ts +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map-model.js +1 -0
- package/dist/components/retrieval/mind-map/mind-map.class.d.ts +27 -4
- package/dist/components/retrieval/mind-map/mind-map.class.js +11 -7
- package/dist/components/retrieval/mind-map/mind-map.d.ts +1 -0
- package/dist/components/retrieval/mind-map/mind-map.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +24 -2
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +17 -3
- package/dist/components/retrieval/neighbor-list/neighbor-list.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.styles.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +8 -4
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +11 -7
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.styles.js +1 -1
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.d.ts +12 -6
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +30 -17
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.styles.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results-model.js +1 -0
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +46 -5
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +31 -9
- package/dist/components/retrieval/retrieval-results/retrieval-results.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.styles.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.d.ts +16 -8
- package/dist/components/utility/diff-view/diff-view.class.js +3 -2
- package/dist/components/utility/diff-view/diff-view.styles.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +31 -3
- package/dist/components/utility/json-viewer/json-viewer.class.js +13 -4
- package/dist/components/utility/json-viewer/json-viewer.d.ts +1 -0
- package/dist/components/utility/json-viewer/json-viewer.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +6 -4
- package/dist/components/utility/mention-popover/mention-popover.class.js +6 -5
- package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +34 -7
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +9 -7
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +28 -4
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +12 -11
- package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +3 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.js +17 -16
- package/dist/components/viewers/geojson-view/geojson-viewer.d.ts +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +31 -5
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +11 -8
- package/dist/components/viewers/table-viewer-shared.js +19 -3
- package/dist/components/viewers/viewer-search-limits.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.d.ts +35 -3
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +20 -5
- package/dist/components/viewers/xml-viewer/xml-viewer.d.ts +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
- package/dist/countries.js +1 -1
- package/dist/data-sources.d.ts +34 -0
- package/dist/data-sources.js +1 -0
- package/dist/events.d.ts +51 -7
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessibility-visibility.d.ts +4 -2
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/aria-controls.js +1 -1
- package/dist/internal/catalog-picker.d.ts +1 -7
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/default-strings/agent-tools.generated.js +1 -1
- package/dist/internal/default-strings/charts.generated.js +1 -1
- package/dist/internal/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/forms.generated.js +1 -1
- package/dist/internal/default-strings/layout.generated.js +1 -1
- package/dist/internal/default-strings/media.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/default-strings/shared.generated.js +1 -1
- package/dist/internal/default-strings/utility.generated.js +1 -1
- package/dist/internal/delimited-data.js +1 -1
- package/dist/internal/fixed-containing-block.js +1 -1
- package/dist/internal/flow-scene-envelope.js +1 -0
- package/dist/internal/graph-scene-controller.js +1 -0
- package/dist/internal/hierarchy-source-controller.js +1 -0
- package/dist/internal/hierarchy-source-view.js +29 -0
- package/dist/internal/hierarchy-source-view.styles.js +1 -0
- package/dist/internal/inherited-attribute-hub.d.ts +6 -0
- package/dist/internal/inherited-attribute-hub.js +1 -1
- package/dist/internal/intl-cache.js +1 -1
- package/dist/internal/keyed-index.js +1 -0
- package/dist/internal/locale-loaders.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/lyra-element.d.ts +2 -2
- package/dist/internal/lyra-element.js +3 -2
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/option-selection.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/resource-loader.d.ts +2 -0
- package/dist/internal/resource-loader.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/search-haystack.js +1 -0
- package/dist/internal/selection-catalog.d.ts +5 -0
- package/dist/internal/selection-catalog.js +1 -1
- package/dist/internal/shiki-language-sources.js +1 -0
- package/dist/internal/source-page-controller.js +1 -0
- package/dist/internal/source-page-scope.js +1 -0
- package/dist/internal/source-request-controller.js +1 -0
- package/dist/internal/source-window-controller.js +1 -0
- package/dist/internal/spatial-source-controller.js +1 -0
- package/dist/internal/text-quote.d.ts +2 -6
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/theme-watcher.js +1 -1
- package/dist/internal/virtual-list-composition.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/testing/interaction-drivers.js +1 -1
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/units.js +1 -1
- package/dist/utilities/data-preparation.d.ts +56 -0
- package/dist/utilities/data-preparation.js +1 -0
- package/dist/utilities/data-spatial.d.ts +26 -0
- package/dist/utilities/data-spatial.js +1 -0
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/llms/components/lr-activity-feed.md +7 -2
- package/llms/components/lr-agent-trace.md +49 -9
- package/llms/components/lr-agent-workspace.md +15 -8
- package/llms/components/lr-av-player.md +180 -10
- package/llms/components/lr-bar-chart.md +1 -1
- package/llms/components/lr-box-plot.md +8 -0
- package/llms/components/lr-bubble-chart.md +1 -1
- package/llms/components/lr-calendar.md +26 -3
- package/llms/components/lr-chart.md +310 -23
- package/llms/components/lr-chat-viewport.md +6 -0
- package/llms/components/lr-code-block-core.md +12 -7
- package/llms/components/lr-code-block.md +23 -9
- package/llms/components/lr-combobox.md +27 -15
- package/llms/components/lr-command-palette.md +16 -3
- package/llms/components/lr-country-picker.md +23 -6
- package/llms/components/lr-csv-viewer.md +95 -12
- package/llms/components/lr-currency-picker.md +23 -3
- package/llms/components/lr-data-grid.md +24 -6
- package/llms/components/lr-dataset-viewer.md +92 -11
- package/llms/components/lr-dialog.md +1 -1
- package/llms/components/lr-diff-view.md +19 -6
- package/llms/components/lr-document-library.md +60 -5
- package/llms/components/lr-doughnut-chart.md +1 -1
- package/llms/components/lr-embedding-explorer.md +89 -9
- package/llms/components/lr-emoji-picker.md +7 -2
- package/llms/components/lr-eval-dataset.md +56 -7
- package/llms/components/lr-eval-result.md +89 -4
- package/llms/components/lr-export-button.md +1 -1
- package/llms/components/lr-file-tree.md +60 -6
- package/llms/components/lr-flag.md +5 -2
- package/llms/components/lr-flow-canvas.md +152 -14
- package/llms/components/lr-flow-minimap.md +32 -4
- package/llms/components/lr-funnel.md +14 -0
- package/llms/components/lr-geojson-viewer.md +27 -10
- package/llms/components/lr-graph.md +43 -7
- package/llms/components/lr-heatmap.md +161 -5
- package/llms/components/lr-histogram.md +55 -9
- package/llms/components/lr-ingestion-queue.md +54 -3
- package/llms/components/lr-json-viewer.md +87 -7
- package/llms/components/lr-knowledge-base-admin.md +60 -4
- package/llms/components/lr-knowledge-base.md +121 -9
- package/llms/components/lr-knowledge-graph-explorer.md +106 -11
- package/llms/components/lr-lightbox.md +42 -6
- package/llms/components/lr-line-chart.md +28 -5
- package/llms/components/lr-lite-chart.md +96 -31
- package/llms/components/lr-locale-picker.md +6 -4
- package/llms/components/lr-map.md +67 -8
- package/llms/components/lr-markdown-core.md +10 -5
- package/llms/components/lr-markdown.md +23 -6
- package/llms/components/lr-mention-popover.md +11 -6
- package/llms/components/lr-mind-map.md +91 -10
- package/llms/components/lr-model-select.md +8 -4
- package/llms/components/lr-model-settings-panel.md +10 -2
- package/llms/components/lr-navigation-menu.md +1 -1
- package/llms/components/lr-neighbor-list.md +69 -2
- package/llms/components/lr-pie-chart.md +1 -1
- package/llms/components/lr-polar-area-chart.md +1 -1
- package/llms/components/lr-prompt-input.md +9 -2
- package/llms/components/lr-prompt-queue.md +11 -3
- package/llms/components/lr-radar-chart.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +9 -2
- package/llms/components/lr-realtime-session.md +6 -2
- package/llms/components/lr-reorder-list.md +4 -0
- package/llms/components/lr-retrieval-compare.md +9 -4
- package/llms/components/lr-retrieval-results.md +104 -6
- package/llms/components/lr-scatter-chart.md +1 -1
- package/llms/components/lr-select.md +20 -10
- package/llms/components/lr-sequence-strip.md +92 -2
- package/llms/components/lr-span-waterfall.md +78 -8
- package/llms/components/lr-sparkline.md +42 -11
- package/llms/components/lr-spreadsheet-viewer.md +109 -14
- package/llms/components/lr-streaming-text-core.md +4 -2
- package/llms/components/lr-streaming-text.md +5 -1
- package/llms/components/lr-table.md +96 -115
- package/llms/components/lr-task-list.md +93 -9
- package/llms/components/lr-terminal.md +9 -0
- package/llms/components/lr-test-results.md +77 -3
- package/llms/components/lr-thread-list.md +86 -1
- package/llms/components/lr-time-zone-picker.md +8 -3
- package/llms/components/lr-timeline.md +5 -0
- package/llms/components/lr-token-input.md +7 -2
- package/llms/components/lr-tool-timeline.md +13 -4
- package/llms/components/lr-trace-tree.md +96 -10
- package/llms/components/lr-transcript-feed.md +9 -2
- package/llms/components/lr-tree.md +87 -15
- package/llms/components/lr-unit-picker.md +8 -3
- package/llms/components/lr-video-playlist.md +2 -0
- package/llms/components/lr-virtual-list.md +17 -8
- package/llms/components/lr-voice-picker.md +8 -3
- package/llms/components/lr-word-cloud.md +128 -12
- package/llms/components/lr-xml-viewer.md +106 -9
- package/llms/index.md +1 -1
- package/llms/peers.md +3 -3
- package/llms/shared/events-and-types.md +725 -264
- package/llms/shared/forms-and-accessibility.md +3 -17
- package/llms/shared/imports-and-registration.md +4 -18
- package/llms/shared/localization-and-rtl.md +12 -7
- package/llms/shared/styles-and-tokens.md +27 -36
- package/llms/shared/testing-and-utilities.md +9 -5
- package/llms/shared.md +788 -355
- package/llms.txt +1 -2
- package/locales.json +264 -139
- package/package.json +19 -10
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +6 -8
- package/skills/lyra-ui/SKILL.md +20 -51
- package/skills/lyra-ui/commands/review.md +16 -33
- package/skills/lyra-ui/commands/update.md +6 -5
- package/skills/lyra-ui/online-api.md +15 -0
- 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&¤t.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&¤t.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.
|
|
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&¤t.add(callback),node=node.nodeType===11&&"host"in node?node.host:node.parentNode}if(!selection?.getComposedRanges&¤t.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&¤t.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
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup){activePlacementByPopup.get(popup)?.();const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
1
|
+
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup,strategy){activePlacementByPopup.get(popup)?.(),popup.style.position=strategy??"fixed";const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{asciiWhitespaceTokens,isSingleAsciiWhitespaceToken}from"./ascii-whitespace.js";import{sharedRealmRegistry}from"./a11y.js";import{registerDescriptionBaselineUpdater,resolveIdReferencesIn}from"./aria-reflection.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"./aria-reflection.js";const DESCRIPTION_RELATIONSHIP={attribute:"aria-describedby",property:"ariaDescribedByElements"},LABEL_RELATIONSHIP={attribute:"aria-labelledby",property:"ariaLabelledByElements"},CONTROLS_RELATIONSHIP={attribute:"aria-controls",property:"ariaControlsElements"},DESCRIPTION_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-description-ownership.v1"),LABEL_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-label-ownership.v1"),CONTROLS_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-controls-relationship-ownership.v1"),fallbackDescriptionOwnership=new WeakMap,fallbackLabelOwnership=new WeakMap,fallbackControlsOwnership=new WeakMap,descriptionOwnership=sharedRealmRegistry(DESCRIPTION_OWNERSHIP,()=>new WeakMap,fallbackDescriptionOwnership),labelOwnership=sharedRealmRegistry(LABEL_OWNERSHIP,()=>new WeakMap,fallbackLabelOwnership),controlsOwnership=sharedRealmRegistry(CONTROLS_OWNERSHIP,()=>new WeakMap,fallbackControlsOwnership);function relationshipDefinition(relationship){return relationship==="aria-describedby"?DESCRIPTION_RELATIONSHIP:LABEL_RELATIONSHIP}function relationshipOwnership(relationship){return relationship==="aria-describedby"?descriptionOwnership:relationship==="aria-labelledby"?labelOwnership:controlsOwnership}function reflectedRelationshipElements(target,definition){if(!(definition.property in target))return null;try{const reflected=Reflect.get(target,definition.property);return reflected===null?null:[...reflected]}catch{return null}}function relationshipSnapshot(target,definition){return{elements:reflectedRelationshipElements(target,definition),had:target.hasAttribute(definition.attribute),value:target.getAttribute(definition.attribute)}}function setLastApplied(state,definition){state.lastApplied=relationshipSnapshot(state.target,definition),state.lastAppliedDocument=state.target.ownerDocument,state.lastAppliedEndpointRoots=new Map(projectedRelationshipElements(state).map(element=>[element,element.getRootNode()])),state.lastAppliedResolvability=new Map(projectedRelationshipElements(state).map(element=>[element,isIdResolvableFromTarget(state.target,element)])),state.lastAppliedRoot=state.target.getRootNode(),state.lastAppliedUnresolvedBaselineIds=state.baseline.kind==="attribute"?[...asciiWhitespaceTokens(state.baseline.value)].filter(id=>!isIdResolvableIdFromTarget(state.target,id)):[]}function sameElements(first,second){return first===null||second===null?first===second:first.length===second.length&&first.every((element,index)=>element===second[index])}function sameRelationshipSnapshot(first,second){return first.had===second.had&&first.value===second.value&&sameElements(first.elements,second.elements)}function baselineFromSnapshot(snapshot){return snapshot.value===""&&snapshot.elements!==null?{elements:snapshot.elements,kind:"elements"}:{had:snapshot.had,kind:"attribute",value:snapshot.value}}function baselineElements(state){if(state.baseline.kind==="elements")return[...state.baseline.elements];try{return resolveIdReferencesIn(state.target.getRootNode(),state.baseline.value)}catch{return[]}}function relationshipElements(state,position){const elements=[],seen=new Set;for(const record of state.leases.values())if(record.position===position)for(const element of record.elements)seen.has(element)||(seen.add(element),elements.push(element));return elements}function projectedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...relationshipElements(state,"before"),...baselineElements(state),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function managedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...baselineElements(state),...relationshipElements(state,"before"),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function isIdResolvableFromTarget(target,element){if(!isSingleAsciiWhitespaceToken(element.id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(element.id)===element}catch{return!1}}function isIdResolvableIdFromTarget(target,id){if(!isSingleAsciiWhitespaceToken(id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(id)!==null}catch{return!1}}function setReflectedRelationshipElements(state,definition,elements){try{return state.writing+=1,Reflect.set(state.target,definition.property,elements===null?null:[...elements])}catch{return!1}finally{state.writing-=1}}function serializedRelationshipIds(state){const ids=[],seen=new Set,add=id=>{!id||seen.has(id)||(seen.add(id),ids.push(id))};for(const element of relationshipElements(state,"before"))isIdResolvableFromTarget(state.target,element)&&add(element.id);if(state.baseline.kind==="attribute")for(const id of asciiWhitespaceTokens(state.baseline.value))add(id);else for(const element of state.baseline.elements)isIdResolvableFromTarget(state.target,element)&&add(element.id);for(const element of relationshipElements(state,"after"))isIdResolvableFromTarget(state.target,element)&&add(element.id);return ids}function applyLatestRelationshipOwnership(state,definition,ownership){ownership.get(state.target)===state&&applyRelationshipOwnership(state,definition)}function applyRelationshipOwnership(state,definition){const before=relationshipElements(state,"before"),after=relationshipElements(state,"after");if(before.length===0&&after.length===0){restoreRelationshipBaseline(state,definition);return}const elements=projectedRelationshipElements(state),canReflect=definition.property in state.target,needsElementReferences=state.baseline.kind==="elements"||[...before,...after].some(element=>!isIdResolvableFromTarget(state.target,element));if(canReflect&&needsElementReferences&&setReflectedRelationshipElements(state,definition,elements)){setLastApplied(state,definition);return}canReflect&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);const ids=serializedRelationshipIds(state);try{state.writing+=1,ids.length>0?state.target.setAttribute(definition.attribute,ids.join(" ")):state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function restoreRelationshipBaseline(state,definition){if(state.baseline.kind==="elements"&&definition.property in state.target&&setReflectedRelationshipElements(state,definition,state.baseline.elements)){setLastApplied(state,definition);return}definition.property in state.target&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);try{state.writing+=1,state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,state.baseline.value??""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function adoptExternalRelationshipBaseline(state,definition,force=!1){if(state.writing>0)return!1;const current=relationshipSnapshot(state.target,definition);if(!force&&sameRelationshipSnapshot(current,state.lastApplied))return!1;if(!force&¤t.had===state.lastApplied.had&¤t.value===state.lastApplied.value)try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id)))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(wasResolvable&&!isIdResolvableFromTarget(state.target,element))return!1}catch{return!1}return state.baseline=baselineFromSnapshot(current),!0}function sameElementLists(first,second){return first.length===second.length&&first.every((element,index)=>element===second[index])}function clearRelationshipObserver(state,observer=state.observer){state.observer===observer&&(state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[]);try{observer?.disconnect()}catch{}}function processRelationshipRecords(state,definition,ownership,records){if(ownership.get(state.target)!==state||records.length===0)return;const targetChanged=records.some(record=>record.target===state.target&&record.type==="attributes"&&record.attributeName===definition.attribute);targetChanged&&adoptExternalRelationshipBaseline(state,definition,!0),(state.leases.size>0||targetChanged)&&(applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0))}function drainRelationshipObserver(state,definition,ownership){const observer=state.observer;if(!observer)return;let records;try{records=observer.takeRecords()}catch{clearRelationshipObserver(state,observer);return}processRelationshipRecords(state,definition,ownership,records)}function observeRelationshipOwnership(state,definition,ownership,force=!1){if(ownership.get(state.target)!==state||state.leases.size===0)return;let ownerDocument,root;try{ownerDocument=state.target.ownerDocument,root=state.target.getRootNode()}catch{return}const elements=managedRelationshipElements(state);if(!force&&state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&sameElementLists(state.observerElements,elements))return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[];try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(records=>{state.observer!==observer||state.observerGeneration!==generation||ownership.get(state.target)!==state||processRelationshipRecords(state,definition,ownership,records)})}catch{return}if(ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerElements=elements;try{observer.observe(state.target,{attributes:!0,attributeFilter:[definition.attribute]});for(const element of elements)element!==state.target&&observer.observe(element,{attributes:!0,attributeFilter:["id"]})}catch{clearRelationshipObserver(state,observer)}}function isRelationshipCurrent(state,definition){try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||!sameRelationshipSnapshot(relationshipSnapshot(state.target,definition),state.lastApplied))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(isIdResolvableFromTarget(state.target,element)!==wasResolvable)return!1;return!state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id))}catch{return!1}}function acquireFixedRelationship(target,elements,definition,position){const ownership=relationshipOwnership(definition.attribute);let state=ownership.get(target);if(state)drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition);else{const initial=relationshipSnapshot(target,definition);state={baseline:baselineFromSnapshot(initial),lastApplied:initial,lastAppliedDocument:target.ownerDocument,lastAppliedEndpointRoots:new Map,lastAppliedResolvability:new Map,lastAppliedRoot:target.getRootNode(),lastAppliedUnresolvedBaselineIds:[],leases:new Map,observerElements:[],observerGeneration:0,target,writing:0},ownership.set(target,state)}const token=Symbol(`aria-${definition.attribute}-owner`),record={elements:[...elements],position};state.leases.set(token,record),applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0);let active=!0;return{target,update(nextElements){if(!active||ownership.get(target)!==state)return;if(drainRelationshipObserver(state,definition,ownership),!adoptExternalRelationshipBaseline(state,definition)&&sameElementLists(record.elements,nextElements)&&isRelationshipCurrent(state,definition)){observeRelationshipOwnership(state,definition,ownership);return}record.elements=[...nextElements],applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0)},release(){active&&(active=!1,ownership.get(target)===state&&(drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition),state.leases.delete(token),applyLatestRelationshipOwnership(state,definition,ownership),state.leases.size===0?(clearRelationshipObserver(state),ownership.delete(target)):observeRelationshipOwnership(state,definition,ownership,!0)))}}}function updateExternalDescriptionBaseline(target,update){const state=descriptionOwnership.get(target);if(!state){update();return}drainRelationshipObserver(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),update(),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),applyLatestRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),observeRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership,!0)}registerDescriptionBaselineUpdater(updateExternalDescriptionBaseline);function acquireAriaDescription(target,descriptions){return acquireFixedRelationship(target,descriptions,DESCRIPTION_RELATIONSHIP,"after")}function acquireAriaControls(target,controls){return acquireFixedRelationship(target,controls,CONTROLS_RELATIONSHIP,"after")}function clearResolvedRelationshipObserver(state){const observer=state.observer;state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{observer?.disconnect()}catch{}}function resolvedRelationshipElements(state){try{return resolveIdReferencesIn(state.host.getRootNode(),state.host.getAttribute(state.relationship))}catch{return[]}}function refreshResolvedRelationship(state){!state.active||!state.target||!state.fixed||state.fixed.update(resolvedRelationshipElements(state))}function observeResolvedRelationship(state){if(!state.active)return;let ownerDocument,root;try{ownerDocument=state.host.ownerDocument,root=state.host.getRootNode()}catch{return}const watchesRoot=root!==state.host&&!asciiWhitespaceTokens(state.host.getAttribute(state.relationship)).next().done;if(state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&state.observerWatchesRoot===watchesRoot)return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||!state.active||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))})}catch{return}if(!state.active||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerWatchesRoot=watchesRoot;try{observer.observe(state.host,{attributes:!0,attributeFilter:[state.relationship]}),watchesRoot&&(state.stopRootObservation=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))}}))}catch{clearResolvedRelationshipObserver(state)}}function acquireResolvedAriaRelationship(host,initialTarget,relationship){const state={active:!0,host,observerGeneration:0,observerWatchesRoot:!1,relationship,target:null},definition=relationshipDefinition(relationship),update=nextTarget=>{if(state.active){if(state.target!==nextTarget){const previousFixed=state.fixed;state.fixed=void 0,state.target=nextTarget,previousFixed?.release(),nextTarget&&(state.fixed=acquireFixedRelationship(nextTarget,resolvedRelationshipElements(state),definition,"before"))}else refreshResolvedRelationship(state);observeResolvedRelationship(state)}},lease={host,relationship,get target(){return state.target},update,release(){if(!state.active)return;state.active=!1,clearResolvedRelationshipObserver(state);const fixed=state.fixed;state.fixed=void 0,state.target=null,fixed?.release()}};return update(initialTarget),lease}class HostDescriptionController{constructor(host,target,requiredDescriptions=()=>[]){this.host=host,this.target=target,this.requiredDescriptions=requiredDescriptions,host.addController(this)}hostConnected(){this.refresh()}hostUpdated(){this.refresh()}adopted(){this.release(),this.refresh()}hostDisconnected(){this.release()}refresh(){if(!this.host.isConnected)return;const target=this.target();if(this.external?this.external.update(target):this.external=acquireResolvedAriaRelationship(this.host,target,"aria-describedby"),!target){this.required?.release(),this.required=void 0;return}const descriptions=this.requiredDescriptions();if(!descriptions.length){this.required?.release(),this.required=void 0;return}this.required?.target!==target?(this.required?.release(),this.required=acquireAriaDescription(target,descriptions)):this.required.update(descriptions)}release(){this.required?.release(),this.required=void 0,this.external?.release(),this.external=void 0}}export{HostDescriptionController,acquireAriaControls,acquireAriaDescription,acquireResolvedAriaRelationship,syncAriaControlsElements,syncAriaDescribedByElements};
|
|
1
|
+
import{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{asciiWhitespaceTokens,isSingleAsciiWhitespaceToken}from"./ascii-whitespace.js";import{sharedRealmRegistry}from"./a11y.js";import{registerDescriptionBaselineUpdater,resolveIdReferencesIn}from"./aria-reflection.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"./aria-reflection.js";const DESCRIPTION_RELATIONSHIP={attribute:"aria-describedby",property:"ariaDescribedByElements"},LABEL_RELATIONSHIP={attribute:"aria-labelledby",property:"ariaLabelledByElements"},CONTROLS_RELATIONSHIP={attribute:"aria-controls",property:"ariaControlsElements"},DESCRIPTION_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-description-ownership.v1"),LABEL_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-label-ownership.v1"),CONTROLS_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-controls-relationship-ownership.v1"),fallbackDescriptionOwnership=new WeakMap,fallbackLabelOwnership=new WeakMap,fallbackControlsOwnership=new WeakMap,descriptionOwnership=sharedRealmRegistry(DESCRIPTION_OWNERSHIP,()=>new WeakMap,fallbackDescriptionOwnership),labelOwnership=sharedRealmRegistry(LABEL_OWNERSHIP,()=>new WeakMap,fallbackLabelOwnership),controlsOwnership=sharedRealmRegistry(CONTROLS_OWNERSHIP,()=>new WeakMap,fallbackControlsOwnership);function relationshipDefinition(relationship){return relationship==="aria-describedby"?DESCRIPTION_RELATIONSHIP:LABEL_RELATIONSHIP}function relationshipOwnership(relationship){return relationship==="aria-describedby"?descriptionOwnership:relationship==="aria-labelledby"?labelOwnership:controlsOwnership}function reflectedRelationshipElements(target,definition){if(!(definition.property in target))return null;try{const reflected=Reflect.get(target,definition.property);return reflected===null?null:[...reflected]}catch{return null}}function relationshipSnapshot(target,definition){return{elements:reflectedRelationshipElements(target,definition),had:target.hasAttribute(definition.attribute),value:target.getAttribute(definition.attribute)}}function setLastApplied(state,definition){state.lastApplied=relationshipSnapshot(state.target,definition),state.lastAppliedDocument=state.target.ownerDocument,state.lastAppliedEndpointRoots=new Map(projectedRelationshipElements(state).map(element=>[element,element.getRootNode()])),state.lastAppliedResolvability=new Map(projectedRelationshipElements(state).map(element=>[element,isIdResolvableFromTarget(state.target,element)])),state.lastAppliedRoot=state.target.getRootNode(),state.lastAppliedUnresolvedBaselineIds=state.baseline.kind==="attribute"?[...asciiWhitespaceTokens(state.baseline.value)].filter(id=>!isIdResolvableIdFromTarget(state.target,id)):[]}function sameElements(first,second){return first===null||second===null?first===second:first.length===second.length&&first.every((element,index)=>element===second[index])}function sameRelationshipSnapshot(first,second){return first.had===second.had&&first.value===second.value&&sameElements(first.elements,second.elements)}function baselineFromSnapshot(snapshot){return snapshot.value===""&&snapshot.elements!==null?{elements:snapshot.elements,kind:"elements"}:{had:snapshot.had,kind:"attribute",value:snapshot.value}}function baselineElements(state){if(state.baseline.kind==="elements")return[...state.baseline.elements];try{return resolveIdReferencesIn(state.target.getRootNode(),state.baseline.value)}catch{return[]}}function relationshipElements(state,position){const elements=[],seen=new Set;for(const record of state.leases.values())if(record.position===position)for(const element of record.elements)seen.has(element)||(seen.add(element),elements.push(element));return elements}function projectedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...relationshipElements(state,"before"),...baselineElements(state),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function managedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...baselineElements(state),...relationshipElements(state,"before"),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function isIdResolvableFromTarget(target,element){if(!isSingleAsciiWhitespaceToken(element.id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(element.id)===element}catch{return!1}}function isIdResolvableIdFromTarget(target,id){if(!isSingleAsciiWhitespaceToken(id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(id)!==null}catch{return!1}}function setReflectedRelationshipElements(state,definition,elements){try{return state.writing+=1,Reflect.set(state.target,definition.property,elements===null?null:[...elements])}catch{return!1}finally{state.writing-=1}}function serializedRelationshipIds(state){const ids=[],seen=new Set,add=id=>{!id||seen.has(id)||(seen.add(id),ids.push(id))};for(const element of relationshipElements(state,"before"))isIdResolvableFromTarget(state.target,element)&&add(element.id);if(state.baseline.kind==="attribute")for(const id of asciiWhitespaceTokens(state.baseline.value))add(id);else for(const element of state.baseline.elements)isIdResolvableFromTarget(state.target,element)&&add(element.id);for(const element of relationshipElements(state,"after"))isIdResolvableFromTarget(state.target,element)&&add(element.id);return ids}function applyLatestRelationshipOwnership(state,definition,ownership){ownership.get(state.target)===state&&applyRelationshipOwnership(state,definition)}function applyRelationshipOwnership(state,definition){const before=relationshipElements(state,"before"),after=relationshipElements(state,"after");if(before.length===0&&after.length===0){restoreRelationshipBaseline(state,definition);return}const elements=projectedRelationshipElements(state),canReflect=definition.property in state.target,needsElementReferences=state.baseline.kind==="elements"||[...before,...after].some(element=>!isIdResolvableFromTarget(state.target,element));if(canReflect&&needsElementReferences&&setReflectedRelationshipElements(state,definition,elements)){setLastApplied(state,definition);return}canReflect&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);const ids=serializedRelationshipIds(state);try{state.writing+=1,ids.length>0?state.target.setAttribute(definition.attribute,ids.join(" ")):state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function restoreRelationshipBaseline(state,definition){if(state.baseline.kind==="elements"&&definition.property in state.target&&setReflectedRelationshipElements(state,definition,state.baseline.elements)){setLastApplied(state,definition);return}definition.property in state.target&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);try{state.writing+=1,state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,state.baseline.value??""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function adoptExternalRelationshipBaseline(state,definition,force=!1){if(state.writing>0)return!1;const current=relationshipSnapshot(state.target,definition);if(!force&&sameRelationshipSnapshot(current,state.lastApplied))return!1;if(!force&¤t.had===state.lastApplied.had&¤t.value===state.lastApplied.value)try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id)))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(wasResolvable&&!isIdResolvableFromTarget(state.target,element))return!1}catch{return!1}return state.baseline=baselineFromSnapshot(current),!0}function sameElementLists(first,second){return first.length===second.length&&first.every((element,index)=>element===second[index])}function clearRelationshipObserver(state,observer=state.observer){state.observer===observer&&(state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[]);try{observer?.disconnect()}catch{}}function processRelationshipRecords(state,definition,ownership,records){if(ownership.get(state.target)!==state||records.length===0)return;const targetChanged=records.some(record=>record.target===state.target&&record.type==="attributes"&&record.attributeName===definition.attribute);targetChanged&&adoptExternalRelationshipBaseline(state,definition,!0),(state.leases.size>0||targetChanged)&&(applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0))}function drainRelationshipObserver(state,definition,ownership){const observer=state.observer;if(!observer)return;let records;try{records=observer.takeRecords()}catch{clearRelationshipObserver(state,observer);return}processRelationshipRecords(state,definition,ownership,records)}function observeRelationshipOwnership(state,definition,ownership,force=!1){if(ownership.get(state.target)!==state||state.leases.size===0)return;let ownerDocument,root;try{ownerDocument=state.target.ownerDocument,root=state.target.getRootNode()}catch{return}const elements=managedRelationshipElements(state);if(!force&&state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&sameElementLists(state.observerElements,elements))return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[];try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(records=>{state.observer!==observer||state.observerGeneration!==generation||ownership.get(state.target)!==state||processRelationshipRecords(state,definition,ownership,records)})}catch{return}if(ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerElements=elements;try{observer.observe(state.target,{attributes:!0,attributeFilter:[definition.attribute]});for(const element of elements)element!==state.target&&observer.observe(element,{attributes:!0,attributeFilter:["id"]})}catch{clearRelationshipObserver(state,observer)}}function isRelationshipCurrent(state,definition){try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||!sameRelationshipSnapshot(relationshipSnapshot(state.target,definition),state.lastApplied))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(isIdResolvableFromTarget(state.target,element)!==wasResolvable)return!1;return!state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id))}catch{return!1}}function acquireFixedRelationship(target,elements,definition,position){const ownership=relationshipOwnership(definition.attribute);let state=ownership.get(target);if(state)drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition);else{const initial=relationshipSnapshot(target,definition);state={baseline:baselineFromSnapshot(initial),lastApplied:initial,lastAppliedDocument:target.ownerDocument,lastAppliedEndpointRoots:new Map,lastAppliedResolvability:new Map,lastAppliedRoot:target.getRootNode(),lastAppliedUnresolvedBaselineIds:[],leases:new Map,observerElements:[],observerGeneration:0,target,writing:0},ownership.set(target,state)}const token=Symbol(`aria-${definition.attribute}-owner`),record={elements:[...elements],position};state.leases.set(token,record),applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0);let active=!0;return{target,update(nextElements){if(!active||ownership.get(target)!==state)return;if(drainRelationshipObserver(state,definition,ownership),!adoptExternalRelationshipBaseline(state,definition)&&sameElementLists(record.elements,nextElements)&&isRelationshipCurrent(state,definition)){observeRelationshipOwnership(state,definition,ownership);return}record.elements=[...nextElements],applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0)},release(){active&&(active=!1,ownership.get(target)===state&&(drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition),state.leases.delete(token),applyLatestRelationshipOwnership(state,definition,ownership),state.leases.size===0?(clearRelationshipObserver(state),ownership.delete(target)):observeRelationshipOwnership(state,definition,ownership,!0)))}}}function updateExternalDescriptionBaseline(target,update){const state=descriptionOwnership.get(target);if(!state){update();return}drainRelationshipObserver(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),update(),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),applyLatestRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),observeRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership,!0)}registerDescriptionBaselineUpdater(updateExternalDescriptionBaseline);function acquireAriaDescription(target,descriptions){return acquireFixedRelationship(target,descriptions,DESCRIPTION_RELATIONSHIP,"after")}function acquireAriaControls(target,controls){return acquireFixedRelationship(target,controls,CONTROLS_RELATIONSHIP,"after")}function clearResolvedRelationshipObserver(state){const observer=state.observer;state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{observer?.disconnect()}catch{}}function resolvedRelationshipElements(state){try{return resolveIdReferencesIn(state.host.getRootNode(),state.host.getAttribute(state.relationship))}catch{return[]}}function refreshResolvedRelationship(state){!state.active||!state.target||!state.fixed||state.fixed.update(resolvedRelationshipElements(state))}function observeResolvedRelationship(state){if(!state.active)return;let ownerDocument,root;try{ownerDocument=state.host.ownerDocument,root=state.host.getRootNode()}catch{return}const watchesRoot=root!==state.host&&!asciiWhitespaceTokens(state.host.getAttribute(state.relationship)).next().done;if(state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&state.observerWatchesRoot===watchesRoot)return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||!state.active||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))})}catch{return}if(!state.active||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerWatchesRoot=watchesRoot;try{observer.observe(state.host,{attributes:!0,attributeFilter:[state.relationship]}),watchesRoot&&(state.stopRootObservation=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))}}))}catch{clearResolvedRelationshipObserver(state)}}function acquireResolvedAriaRelationship(host,initialTarget,relationship){const state={active:!0,host,observerGeneration:0,observerWatchesRoot:!1,relationship,target:null},definition=relationshipDefinition(relationship),update=nextTarget=>{if(state.active){if(state.target!==nextTarget){const previousFixed=state.fixed;state.fixed=void 0,state.target=nextTarget,previousFixed?.release(),nextTarget&&(state.fixed=acquireFixedRelationship(nextTarget,resolvedRelationshipElements(state),definition,"before"))}else refreshResolvedRelationship(state);observeResolvedRelationship(state)}},lease={host,relationship,get target(){return state.target},update,release(){if(!state.active)return;state.active=!1,clearResolvedRelationshipObserver(state);const fixed=state.fixed;state.fixed=void 0,state.target=null,fixed?.release()}};return update(initialTarget),lease}class HostDescriptionController{constructor(host,target,requiredDescriptions=()=>[]){this.host=host,this.target=target,this.requiredDescriptions=requiredDescriptions,host.addController(this)}hostConnected(){this.refresh()}hostUpdated(){this.refresh()}adopted(){this.release(),this.refresh()}hostDisconnected(){this.release()}refresh(){if(!this.host.isConnected)return;const lit=this.host;if(typeof lit.createRenderRoot=="function"&&lit.renderRoot===void 0)return;const target=this.target();if(this.external?this.external.update(target):this.external=acquireResolvedAriaRelationship(this.host,target,"aria-describedby"),!target){this.required?.release(),this.required=void 0;return}const descriptions=this.requiredDescriptions();if(!descriptions.length){this.required?.release(),this.required=void 0;return}this.required?.target!==target?(this.required?.release(),this.required=acquireAriaDescription(target,descriptions)):this.required.update(descriptions)}release(){this.required?.release(),this.required=void 0,this.external?.release(),this.external=void 0}}export{HostDescriptionController,acquireAriaControls,acquireAriaDescription,acquireResolvedAriaRelationship,syncAriaControlsElements,syncAriaDescribedByElements};
|
|
@@ -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};
|