@aceshooting/lyra-ui 29.2.1 → 30.0.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 +126 -95
- package/README.md +8 -7
- package/dist/ai/snapshot.js +1 -1
- package/dist/all.d.ts +1 -1
- package/dist/all.js +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/cli/component-inventory.mjs +1 -1
- package/dist/cli/lyra-rename-ledger.mjs +1 -1
- package/dist/cli/migrate-wa.mjs +7 -3
- package/dist/cli/migration-analysis.mjs +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/cli/migration-contract.mjs +1 -1
- package/dist/cli/migration-immutable-collections.mjs +6 -0
- package/dist/cli/migration-renames.mjs +1 -1
- package/dist/cli/migration-transforms.mjs +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.d.ts +1 -2
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-run/agent-run.class.d.ts +3 -4
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +2 -2
- package/dist/components/agent-tools/background-runs/background-runs.class.d.ts +1 -2
- package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
- package/dist/components/agent-tools/change-review/change-review.class.d.ts +1 -2
- package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -2
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.d.ts +7 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
- package/dist/components/agent-tools/prompt-studio/prompt-studio.class.d.ts +2 -2
- package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +3 -3
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.d.ts +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +1 -2
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.d.ts +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +3 -4
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -5
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +3 -3
- package/dist/components/agent-tools/trace-tree/trace-tree.class.d.ts +1 -0
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart-3d/chart-3d-data.d.ts +50 -0
- package/dist/components/charts/chart-3d/chart-3d-data.js +1 -0
- package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -0
- package/dist/components/charts/chart-3d/chart-3d.class.d.ts +96 -0
- package/dist/components/charts/chart-3d/chart-3d.class.js +47 -0
- package/dist/components/charts/chart-3d/chart-3d.d.ts +1 -0
- package/dist/components/charts/chart-3d/chart-3d.js +1 -0
- package/dist/components/charts/chart-3d/chart-3d.styles.js +1 -0
- package/dist/components/charts/index.d.ts +1 -1
- package/dist/components/charts/index.js +1 -1
- package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +3 -3
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +4 -5
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/shiki-oniguruma.d.ts +3 -0
- package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -0
- package/dist/components/conversation/code-block/shiki-types.d.ts +3 -5
- package/dist/components/conversation/code-block/shiki-types.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-progressive.js +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -4
- package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +1 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +2 -2
- package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
- package/dist/components/conversation/widget-renderer/registry.js +1 -1
- package/dist/components/conversation/widget-renderer/resolve.js +1 -1
- package/dist/components/data/calendar/calendar.class.d.ts +3 -1
- package/dist/components/data/data-grid/data-grid.class.js +2 -2
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- package/dist/components/data/flow-canvas/flow-source.js +1 -1
- package/dist/components/data/flow-node/flow-node.class.d.ts +2 -3
- package/dist/components/data/flow-node/flow-node.class.js +2 -4
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.d.ts +0 -1
- package/dist/components/data/sparkline/sparkline.class.js +1 -1
- package/dist/components/data/table/table.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/date-picker/calendar-core.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/signature-pad/signature-pad.class.d.ts +4 -3
- package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
- package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +3 -2
- package/dist/components/forms/swatch-picker/swatch-picker.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.d.ts +0 -2
- package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +3 -3
- package/dist/components/layout/command-palette/command-palette.class.d.ts +1 -1
- package/dist/components/layout/details/accordion-item.class.d.ts +1 -2
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +4 -11
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar-item.class.d.ts +1 -1
- package/dist/components/layout/menubar/menubar.class.d.ts +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.d.ts +2 -6
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +3 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +5 -14
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/lr-chart-3d.js +1 -0
- package/dist/components/lr-model-viewer.js +1 -0
- package/dist/components/media/av-player/av-metadata.d.ts +1 -13
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/av-player/av-player.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +10 -13
- package/dist/components/media/file-input/file-input.class.js +3 -3
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +5 -0
- package/dist/components/media/image-viewer/image-viewer-panorama.js +8 -0
- package/dist/components/media/image-viewer/image-viewer-panorama.styles.js +1 -0
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +29 -5
- package/dist/components/media/image-viewer/image-viewer.class.js +8 -5
- package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -0
- package/dist/components/media/map/map-anchor-options.d.ts +14 -0
- package/dist/components/media/map/map-anchor-options.js +1 -0
- package/dist/components/media/map/map-camera.d.ts +34 -0
- package/dist/components/media/map/map-camera.js +1 -0
- package/dist/components/media/map/map-construction-scheduler.d.ts +13 -0
- package/dist/components/media/map/map-construction-scheduler.js +1 -0
- package/dist/components/media/map/map-control-options.d.ts +39 -0
- package/dist/components/media/map/map-control-options.js +1 -0
- package/dist/components/media/map/map-controls-lifecycle.js +1 -0
- package/dist/components/media/map/map-cursor.js +1 -0
- package/dist/components/media/map/map-data-layer-model.d.ts +40 -0
- package/dist/components/media/map/map-data-layer-model.js +1 -0
- package/dist/components/media/map/map-drawing-controller.js +1 -0
- package/dist/components/media/map/map-drawing-gesture.js +1 -0
- package/dist/components/media/map/map-drawing-pan.js +1 -0
- package/dist/components/media/map/map-drawing-pointer.js +1 -0
- package/dist/components/media/map/map-drawing.d.ts +29 -0
- package/dist/components/media/map/map-drawing.js +1 -0
- package/dist/components/media/map/map-empty-style.d.ts +8 -0
- package/dist/components/media/map/map-empty-style.js +1 -0
- package/dist/components/media/map/map-engine-events.js +1 -0
- package/dist/components/media/map/map-export-attribution.js +1 -0
- package/dist/components/media/map/map-external-source-effects.js +1 -0
- package/dist/components/media/map/map-feature-loader-core.js +1 -0
- package/dist/components/media/map/map-feature-loader.js +1 -0
- package/dist/components/media/map/map-feature-state-router.d.ts +16 -0
- package/dist/components/media/map/map-feature-state-router.js +1 -0
- package/dist/components/media/map/map-feature-state-routes.js +1 -0
- package/dist/components/media/map/map-feature-state.d.ts +16 -0
- package/dist/components/media/map/map-feature-state.js +1 -0
- package/dist/components/media/map/map-hash-option.js +1 -0
- package/dist/components/media/map/map-hash-owner.js +1 -0
- package/dist/components/media/map/map-hash.js +1 -0
- package/dist/components/media/map/map-hit-test.d.ts +17 -0
- package/dist/components/media/map/map-hit-test.js +1 -0
- package/dist/components/media/map/map-image-admission.d.ts +7 -0
- package/dist/components/media/map/map-image-admission.js +1 -0
- package/dist/components/media/map/map-image-export-controller.js +1 -0
- package/dist/components/media/map/map-image-export-error.d.ts +3 -0
- package/dist/components/media/map/map-image-export-error.js +1 -0
- package/dist/components/media/map/map-image-export.d.ts +15 -0
- package/dist/components/media/map/map-image-export.js +5 -0
- package/dist/components/media/map/map-image-limits.d.ts +4 -0
- package/dist/components/media/map/map-image-limits.js +1 -0
- package/dist/components/media/map/map-image-metadata.js +3 -0
- package/dist/components/media/map/map-image-provider.d.ts +33 -0
- package/dist/components/media/map/map-image-provider.js +1 -0
- package/dist/components/media/map/map-images.d.ts +9 -0
- package/dist/components/media/map/map-images.js +1 -0
- package/dist/components/media/map/map-interaction-options.d.ts +26 -0
- package/dist/components/media/map/map-interaction-options.js +1 -0
- package/dist/components/media/map/map-layer-order.js +1 -0
- package/dist/components/media/map/map-loader.d.ts +35 -5
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map-local-image-url.js +1 -0
- package/dist/components/media/map/map-local-image.js +1 -0
- package/dist/components/media/map/map-overlay-admission.d.ts +13 -0
- package/dist/components/media/map/map-overlay-admission.js +1 -0
- package/dist/components/media/map/map-owned-feature-input.js +1 -0
- package/dist/components/media/map/map-owned-features.js +1 -0
- package/dist/components/media/map/map-owned-resources.js +1 -0
- package/dist/components/media/map/map-paint-batch.js +1 -0
- package/dist/components/media/map/map-readers.js +1 -0
- package/dist/components/media/map/map-readiness.js +1 -0
- package/dist/components/media/map/map-resource-feature-loaders.js +1 -0
- package/dist/components/media/map/map-source-updates.js +1 -0
- package/dist/components/media/map/map-style-input.js +1 -0
- package/dist/components/media/map/map-style-lifecycle.js +1 -0
- package/dist/components/media/map/map-style-override-admission.d.ts +10 -0
- package/dist/components/media/map/map-style-override-admission.js +1 -0
- package/dist/components/media/map/map-style-overrides.js +1 -0
- package/dist/components/media/map/map-style-value.d.ts +3 -0
- package/dist/components/media/map/map-style-value.js +1 -0
- package/dist/components/media/map/map-vector-style.d.ts +10 -0
- package/dist/components/media/map/map-vector-style.js +1 -0
- package/dist/components/media/map/map.class.d.ts +558 -51
- package/dist/components/media/map/map.class.js +58 -11
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/qr-code/qr-code.class.d.ts +1 -3
- package/dist/components/media/qr-code/qr-code.class.js +1 -1
- package/dist/components/media/qr-code/qr-code.styles.js +1 -1
- package/dist/components/media/video/video.class.d.ts +25 -4
- package/dist/components/media/video/video.class.js +11 -3
- package/dist/components/media/video/video.styles.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.d.ts +0 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip-group.class.d.ts +1 -1
- package/dist/components/overlays/chip/chip-group.class.js +1 -1
- package/dist/components/overlays/dialog/confirm.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +1 -1
- package/dist/components/overlays/overlay/popover.class.js +2 -1
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +4 -7
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.d.ts +2 -2
- package/dist/components/retrieval/community-card/community-card.class.d.ts +1 -4
- package/dist/components/retrieval/community-card/community-card.class.js +1 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-data.d.ts +12 -0
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-data.js +1 -0
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -0
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +26 -7
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +35 -4
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.d.ts +3 -9
- package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -0
- package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -0
- package/dist/components/retrieval/graph/graph-engine-columns.js +1 -0
- package/dist/components/retrieval/graph/graph-model.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +13 -8
- package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -0
- package/dist/components/retrieval/graph/graph.class.d.ts +18 -5
- package/dist/components/retrieval/graph/graph.class.js +4 -4
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +6 -3
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +3 -3
- package/dist/components/retrieval/memory-panel/memory-panel.class.d.ts +3 -10
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/node-palette/node-palette.class.d.ts +1 -1
- package/dist/components/retrieval/path-strip/path-strip.class.d.ts +1 -4
- package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.d.ts +2 -8
- package/dist/components/retrieval/rag-answer/rag-answer.class.d.ts +2 -2
- package/dist/components/retrieval/rag-answer/rag-answer.class.js +2 -3
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +1 -11
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +8 -12
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +5 -6
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.d.ts +4 -7
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +2 -3
- package/dist/components/retrieval/source-card/source-card.class.d.ts +6 -9
- package/dist/components/retrieval/source-card/source-card.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -4
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon.class.d.ts +0 -5
- package/dist/components/utility/icon/icon.class.js +2 -2
- package/dist/components/utility/icon/icon.styles.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.d.ts +0 -3
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +3 -2
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer-kinds.d.ts +1 -1
- package/dist/components/viewers/document-viewer/document-viewer-kinds.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
- package/dist/components/viewers/document-viewer/registry.d.ts +1 -69
- package/dist/components/viewers/document-viewer/registry.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/index.d.ts +1 -1
- package/dist/components/viewers/index.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-document.js +1 -0
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -0
- package/dist/components/viewers/model-viewer/model-viewer-register.d.ts +1 -0
- package/dist/components/viewers/model-viewer/model-viewer-register.js +1 -0
- package/dist/components/viewers/model-viewer/model-viewer-source.d.ts +1 -0
- package/dist/components/viewers/model-viewer/model-viewer-source.js +1 -0
- package/dist/components/viewers/model-viewer/model-viewer.class.d.ts +61 -0
- package/dist/components/viewers/model-viewer/model-viewer.class.js +9 -0
- package/dist/components/viewers/model-viewer/model-viewer.d.ts +1 -0
- package/dist/components/viewers/model-viewer/model-viewer.js +1 -0
- package/dist/components/viewers/model-viewer/model-viewer.styles.js +1 -0
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- package/dist/components/viewers/page-rail/page-rail.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +3 -3
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +137 -92
- package/dist/framework-types.d.ts +2 -2
- package/dist/hydration.d.ts +1 -1
- package/dist/internal/ansi.d.ts +3 -1
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/av-metadata.d.ts +13 -0
- package/dist/internal/av-metadata.js +1 -0
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/component-loaders.generated.js +1 -1
- package/dist/internal/data-descriptors.d.ts +30 -0
- 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/media.generated.js +1 -1
- package/dist/internal/default-strings/shared.generated.js +1 -1
- package/dist/internal/default-strings/viewers.generated.js +1 -1
- package/dist/internal/document-renderer-registry.d.ts +75 -0
- package/dist/internal/document-renderer-registry.js +1 -0
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d-loader.d.ts +47 -0
- package/dist/internal/engine-3d-loader.js +1 -0
- package/dist/internal/engine-3d.d.ts +57 -0
- package/dist/internal/engine-3d.js +1 -0
- package/dist/internal/hierarchy-source-controller.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +2 -2
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/model-viewer-contract.d.ts +5 -0
- package/dist/internal/model-viewer-contract.js +1 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/rendered-state.js +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/typed-columns.d.ts +39 -0
- package/dist/internal/typed-columns.js +1 -0
- package/dist/localization.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -1
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +4 -4
- package/dist/ssr.js +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.d.ts +2 -2
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/theme/theme-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-accordion-item.md +2 -2
- package/llms/components/lr-agent-eval-dashboard.md +3 -3
- package/llms/components/lr-agent-run.md +3 -3
- package/llms/components/lr-agent-trace.md +1 -1
- package/llms/components/lr-agent-workspace.md +1 -1
- package/llms/components/lr-app-rail-item.md +1 -1
- package/llms/components/lr-app-rail.md +5 -6
- package/llms/components/lr-background-runs.md +4 -4
- package/llms/components/lr-calendar.md +1 -1
- package/llms/components/lr-change-review.md +5 -5
- package/llms/components/lr-chart-3d.md +164 -0
- package/llms/components/lr-chunk-inspector.md +4 -5
- package/llms/components/lr-citation-badge.md +1 -1
- package/llms/components/lr-code-block-core.md +2 -4
- package/llms/components/lr-command-palette.md +3 -3
- package/llms/components/lr-community-card.md +2 -2
- package/llms/components/lr-date-picker.md +1 -1
- package/llms/components/lr-details.md +2 -2
- package/llms/components/lr-diff-view.md +2 -2
- package/llms/components/lr-dock-panel.md +5 -10
- package/llms/components/lr-document-viewer.md +21 -14
- package/llms/components/lr-embedding-explorer.md +24 -4
- package/llms/components/lr-entity-dossier.md +3 -4
- package/llms/components/lr-eval-dataset.md +3 -3
- package/llms/components/lr-eval-run.md +7 -1
- package/llms/components/lr-file-input.md +10 -11
- package/llms/components/lr-flow-node.md +2 -3
- package/llms/components/lr-geojson-viewer.md +1 -1
- package/llms/components/lr-graph.md +21 -2
- package/llms/components/lr-grounding-summary.md +1 -1
- package/llms/components/lr-icon.md +1 -3
- package/llms/components/lr-image-viewer.md +29 -2
- package/llms/components/lr-ingestion-queue.md +1 -1
- package/llms/components/lr-knowledge-base-admin.md +2 -2
- package/llms/components/lr-knowledge-graph-explorer.md +7 -1
- package/llms/components/lr-known-date.md +3 -10
- package/llms/components/lr-lite-chart.md +1 -1
- package/llms/components/lr-map.md +861 -49
- package/llms/components/lr-markdown-core.md +1 -2
- package/llms/components/lr-memory-panel.md +4 -8
- package/llms/components/lr-model-viewer.md +170 -0
- package/llms/components/lr-navigation-menu.md +3 -4
- package/llms/components/lr-node-palette.md +1 -1
- package/llms/components/lr-path-strip.md +2 -3
- package/llms/components/lr-provenance-panel.md +3 -5
- package/llms/components/lr-qr-code.md +3 -4
- package/llms/components/lr-rag-answer.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +2 -5
- package/llms/components/lr-retrieval-results.md +6 -7
- package/llms/components/lr-retrieval-trace.md +3 -4
- package/llms/components/lr-signature-pad.md +4 -3
- package/llms/components/lr-source-card.md +1 -1
- package/llms/components/lr-source-list.md +5 -5
- package/llms/components/lr-source-picker.md +2 -3
- package/llms/components/lr-span-waterfall.md +4 -3
- package/llms/components/lr-sparkline.md +3 -3
- package/llms/components/lr-subagent-panel.md +3 -3
- package/llms/components/lr-tool-call-chip.md +6 -6
- package/llms/components/lr-tool-timeline.md +1 -1
- package/llms/components/lr-video-playlist.md +3 -3
- package/llms/components/lr-video.md +29 -2
- package/llms/components/lr-virtual-list.md +3 -2
- package/llms/components/lr-widget.md +6 -13
- package/llms/index.md +98 -95
- package/llms/migration.md +27 -38
- package/llms/peers.md +7 -6
- package/llms/shared/ai-and-peers.md +1 -1
- package/llms/shared/events-and-types.md +8 -0
- package/llms/shared/imports-and-registration.md +2 -2
- package/llms/shared/v29-to-v30-migration.md +256 -0
- package/llms/shared.md +11 -3
- package/llms.txt +4 -4
- package/locales.json +1 -2328
- package/package.json +42 -14
- package/registrations.json +1 -1
- package/skills/lyra-ui/SKILL.md +4 -3
- /package/dist/{components/viewers/document-viewer → internal}/deferred-teardown.js +0 -0
- /package/dist/{components/viewers/document-viewer/registry-ownership.js → internal/document-renderer-registry-ownership.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
const MAX_DROPPED_FOLDER_ENTRIES=1e4;function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class DropSessionController{constructor(host,callbacks){this.host=host,this.callbacks=callbacks,this.counter=0,this.token=0,this.sessionState="default",this.onDragEnter=e=>{if(e.preventDefault(),this.callbacks.isDisabled())return;this.counter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.sessionState=items.length?this.callbacks.previewRejects(items)?"reject":"accept":"default",this.callbacks.onStateChange()},this.onDragOver=e=>{e.preventDefault()},this.onDragLeave=e=>{this.callbacks.isDisabled()||(e.preventDefault(),this.counter=Math.max(0,this.counter-1),this.counter===0&&(this.sessionState="default",this.callbacks.onStateChange()))},host.addController(this)}get state(){return this.sessionState}get dragging(){return this.sessionState!=="default"}hostDisconnected(){this.reset()}reset(){this.token++,this.counter=0,this.sessionState="default",this.callbacks.onStateChange()}beginDrop(e){if(e.preventDefault(),this.callbacks.isDisabled())return;this.reset();const token=this.token,files=readFileList(e.dataTransfer?.files),folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,10001);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}const overLimit=(items?.length??0)>1e4;return{token,files,folders,overLimit}}isCurrent(token){return token===this.token&&this.host.isConnected&&!this.callbacks.isDisabled()}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readFolders(folders,token){const isCurrent=()=>this.isCurrent(token),files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=1e4?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}}function readFileList(list){const files=[];if(!list)return files;for(let index=0;index<list.length;index++){const file=list[index];isFileValue(file)&&files.push(file)}return files}export{DropSessionController,isFileValue,readFileList};
|
|
1
|
+
const MAX_DROPPED_FOLDER_ENTRIES=1e4;function isFileValue(value){if(value===null||typeof value!="object")return!1;try{if(typeof File!="function")return!1;const nameGetter=Object.getOwnPropertyDescriptor(File.prototype,"name")?.get;if(!nameGetter)return!1;nameGetter.call(value);const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class DropSessionController{constructor(host,callbacks){this.host=host,this.callbacks=callbacks,this.counter=0,this.token=0,this.sessionState="default",this.onDragEnter=e=>{if(e.preventDefault(),this.callbacks.isDisabled())return;this.counter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.sessionState=items.length?this.callbacks.previewRejects(items)?"reject":"accept":"default",this.callbacks.onStateChange()},this.onDragOver=e=>{e.preventDefault()},this.onDragLeave=e=>{this.callbacks.isDisabled()||(e.preventDefault(),this.counter=Math.max(0,this.counter-1),this.counter===0&&(this.sessionState="default",this.callbacks.onStateChange()))},host.addController(this)}get state(){return this.sessionState}get dragging(){return this.sessionState!=="default"}hostDisconnected(){this.reset()}reset(){this.token++,this.counter=0,this.sessionState="default",this.callbacks.onStateChange()}beginDrop(e){if(e.preventDefault(),this.callbacks.isDisabled())return;this.reset();const token=this.token,files=readFileList(e.dataTransfer?.files),folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,10001);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}const overLimit=(items?.length??0)>1e4;return{token,files,folders,overLimit}}isCurrent(token){return token===this.token&&this.host.isConnected&&!this.callbacks.isDisabled()}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readFolders(folders,token){const isCurrent=()=>this.isCurrent(token),files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=1e4?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}}function readFileList(list){const files=[];if(!list)return files;for(let index=0;index<list.length;index++){const file=list[index];isFileValue(file)&&files.push(file)}return files}export{DropSessionController,isFileValue,readFileList};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import{type OptionalPeerLoader}from'./optional-peer-capabilities.js';
|
|
2
|
+
/**
|
|
3
|
+
* The WebGL engines a component can load from the optional `@aceshooting/lyra-3d` companion, one
|
|
4
|
+
* package entry point each.
|
|
5
|
+
*/
|
|
6
|
+
export type Engine3dEntryPoint='graph'|'points'|'panorama'|'model';
|
|
7
|
+
/** The engine contract version this library speaks. */
|
|
8
|
+
export declare const ENGINE_3D_CONTRACT=1;
|
|
9
|
+
/** Keyboard modifiers and click count the engine reports with an activation. */
|
|
10
|
+
export interface Engine3dPickModifiers{readonly shift:boolean;readonly ctrl:boolean;readonly double:boolean;}
|
|
11
|
+
/**
|
|
12
|
+
* Callbacks a component hands to its engine. Owned structurally here so the optional companion's
|
|
13
|
+
* declarations never enter this library's public type graph.
|
|
14
|
+
*/
|
|
15
|
+
export interface Engine3dHost{hover(item:number|null):void;pick(item:number|null,modifiers:Engine3dPickModifiers):void;camera(camera:unknown):void;progress?(loaded:number,total:number):void;lost(reason:'context-lost'|'error',detail?:string):void;rendering?(info:{readonly software:boolean;}):void;restored?():void;}
|
|
16
|
+
/** The engine surface a component calls; data, camera and style stay opaque to the loader. */
|
|
17
|
+
export interface Engine3dInstance{readonly contract:typeof ENGINE_3D_CONTRACT;mount(container:HTMLElement,host:Engine3dHost):Promise<void>;setData(data:unknown,revision:number):void;setStyle(style:unknown):void;setState?(state:{readonly selected:ReadonlySet<number>;readonly dimmed:ReadonlySet<number>;readonly hover:number;readonly focus:number;}):void;setCamera(camera:unknown):void;fit?(padding?:number):unknown;focus?(item:number,zoom?:number):unknown;pick?(x:number,y:number):number|null;project?(item:number):{readonly x:number;readonly y:number;}|null;positionOf?(item:number):{readonly x:number;readonly y:number;readonly z:number;}|null;resize(width:number,height:number):void;dispose():void;}
|
|
18
|
+
/** What every engine entry point exports. */
|
|
19
|
+
export interface Engine3dModule{createEngine():unknown;}
|
|
20
|
+
/** Whether a loaded entry point exposes a callable `createEngine`. */
|
|
21
|
+
export declare function isEngine3dModule(candidate:unknown):candidate is Engine3dModule;
|
|
22
|
+
/**
|
|
23
|
+
* The first contract violation of a created engine, or `undefined` when it speaks this library's
|
|
24
|
+
* contract version and every required method (and every present optional one) is callable.
|
|
25
|
+
*/
|
|
26
|
+
export declare function engine3dContractViolation(candidate:unknown):string|undefined;export interface Engine3dLoaderOptions{readonly entry:Engine3dEntryPoint;
|
|
27
|
+
/** The requesting element's tag name, from `tag()`, for the development diagnostic. */
|
|
28
|
+
readonly tag:string;
|
|
29
|
+
/**
|
|
30
|
+
* Imports the entry point. Each component writes its own literal
|
|
31
|
+
* `() => import('@aceshooting/lyra-3d/<entry>')` so bundlers split it into a lazy chunk and an
|
|
32
|
+
* application that never opts in never downloads it.
|
|
33
|
+
*/
|
|
34
|
+
readonly load:()=>Promise<unknown>;}export interface Engine3dLoader extends OptionalPeerLoader<Engine3dModule>{readonly entry:Engine3dEntryPoint;
|
|
35
|
+
/**
|
|
36
|
+
* Loads the entry point (sharing one in-flight or successful load, retrying after a failure)
|
|
37
|
+
* and creates a validated engine. Resolves `null` when the companion is missing, the entry
|
|
38
|
+
* point lacks `createEngine`, creation throws, or the engine speaks another contract version.
|
|
39
|
+
*/
|
|
40
|
+
create():Promise<Engine3dInstance|null>;}
|
|
41
|
+
/**
|
|
42
|
+
* The shared loader for one `@aceshooting/lyra-3d` entry point. A failed import or an unusable
|
|
43
|
+
* module is never cached, so installing the companion or a transient network failure clears on the
|
|
44
|
+
* next attempt. Development builds warn once per entry point and failure kind; importer errors are
|
|
45
|
+
* never included because they can carry local paths.
|
|
46
|
+
*/
|
|
47
|
+
export declare function createEngine3dLoader(options:Engine3dLoaderOptions):Engine3dLoader;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{devWarnOnce}from"./dev-warning.js";import{createOptionalPeerLoader}from"./optional-peer-capabilities.js";const ENGINE_3D_CONTRACT=1,REQUIRED_METHODS=["mount","setData","setStyle","setCamera","resize","dispose"],OPTIONAL_METHODS=["setState","fit","focus","pick","project","positionOf"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isEngine3dModule(candidate){return isObjectLike(candidate)&&typeof candidate.createEngine=="function"}function engine3dContractViolation(candidate){if(!isObjectLike(candidate))return"engine object";if(candidate.contract!==ENGINE_3D_CONTRACT)return"contract";for(const method of REQUIRED_METHODS)if(typeof candidate[method]!="function")return method;for(const method of OPTIONAL_METHODS)if(candidate[method]!==void 0&&typeof candidate[method]!="function")return method}function createEngine3dLoader(options){const specifier=`@aceshooting/lyra-3d/${options.entry}`,peer=createOptionalPeerLoader({load:options.load,isCapability:isEngine3dModule,warningKey:`lyra-3d-${options.entry}-unavailable`,warning:`<${options.tag}> could not load its optional \`${specifier}\` engine — install it with \`pnpm add @aceshooting/lyra-3d\`.`}),incompatible=()=>devWarnOnce(`lyra-3d-${options.entry}-incompatible`,`<${options.tag}> cannot use the installed \`${specifier}\` engine: it does not implement engine contract ${ENGINE_3D_CONTRACT}. Install a matching @aceshooting/lyra-3d version.`);let generation=0;const clear=()=>{generation+=1,peer.clear()};return{...peer,clear,override(importer){generation+=1,peer.override(importer)},entry:options.entry,async create(){const owner=generation,module=await peer.get();if(!module)return null;try{const engine=module.createEngine();if(engine3dContractViolation(engine)===void 0)return engine}catch{}return owner===generation&&clear(),incompatible(),null}}}export{ENGINE_3D_CONTRACT,createEngine3dLoader,engine3dContractViolation,isEngine3dModule};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type{LyraMessage}from'./localization-types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Which renderer an element prefers for its 3D view. `'webgl'` is a preference, not a requirement:
|
|
4
|
+
* when the companion engine is missing, WebGL2 is unavailable, or the context is lost or fails, the
|
|
5
|
+
* element falls back to its built-in renderer and then to its list or text alternative.
|
|
6
|
+
*/
|
|
7
|
+
export type Engine3dPreference='builtin'|'webgl';
|
|
8
|
+
/**
|
|
9
|
+
* Normalizes the `engine` attribute and direct property writes alike: anything other than
|
|
10
|
+
* `'webgl'` resolves to `'builtin'`, so a typo never opts an application into a download.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ENGINE_3D_PREFERENCE:import("./converters.js").LiteralSetConverter<Engine3dPreference>;
|
|
13
|
+
/** What currently renders: the WebGL engine, the element's built-in renderer, or its list or text alternative. */
|
|
14
|
+
export type Engine3dRenderer='webgl'|'builtin'|'list';
|
|
15
|
+
/** Why an element moved down its fallback chain. */
|
|
16
|
+
export type Engine3dFallbackReason='unavailable'|'unsupported'|'context-lost'|'error';
|
|
17
|
+
/** Detail of the `lr-engine-fallback` event an element emits on every step down its chain. */
|
|
18
|
+
export interface Engine3dFallbackDetail{readonly from:Engine3dRenderer;readonly to:Engine3dRenderer;readonly reason:Engine3dFallbackReason;}export type Engine3dMessageKey='engine3dLoading'|'engine3dUnavailable'|'engine3dUnsupported'|'engine3dContextLost'|'engine3dError'|'engine3dSoftwareRendering'|'engine3dShowingBuiltin'|'engine3dShowingList';
|
|
19
|
+
/** English defaults an element merges into its own `defaultStrings` when it adopts the `engine` property. */
|
|
20
|
+
export declare const ENGINE_3D_DEFAULT_STRINGS:Readonly<Record<Engine3dMessageKey,LyraMessage>>;
|
|
21
|
+
/** Why an element fell back, as a message key; plain literal tables keep `localize()` keys checkable. */
|
|
22
|
+
export declare const ENGINE_3D_REASON_MESSAGE:{readonly unavailable:'engine3dUnavailable';readonly unsupported:'engine3dUnsupported';readonly'context-lost':'engine3dContextLost';readonly error:'engine3dError';};
|
|
23
|
+
/** What a fallback shows now, as a message key. A fallback never lands on the WebGL renderer. */
|
|
24
|
+
export declare const ENGINE_3D_SHOWING_MESSAGE:{readonly webgl:'engine3dShowingList';readonly builtin:'engine3dShowingBuiltin';readonly list:'engine3dShowingList';};
|
|
25
|
+
/**
|
|
26
|
+
* The two message keys of a fallback notice: why the element fell back, then what it shows now.
|
|
27
|
+
* They are separate sentences, each translated whole and rendered in its own node.
|
|
28
|
+
*/
|
|
29
|
+
export declare function engine3dFallbackNotice(detail:Engine3dFallbackDetail):{readonly reason:Engine3dMessageKey;readonly showing:Engine3dMessageKey;};
|
|
30
|
+
/**
|
|
31
|
+
* Maps an engine `mount()` rejection to a fallback reason. The companion rejects with
|
|
32
|
+
* `code: 'webgl-unavailable'` when the browser has no WebGL2; anything else is an engine error.
|
|
33
|
+
*/
|
|
34
|
+
export declare function engine3dFailureReason(error:unknown):Engine3dFallbackReason;
|
|
35
|
+
/**
|
|
36
|
+
* Whether this browser can create a WebGL2 context at all, checked before downloading an engine.
|
|
37
|
+
* The probe context is released at once so it does not count against the page's context budget.
|
|
38
|
+
*/
|
|
39
|
+
export declare function webgl2Available(createCanvas?:()=>HTMLCanvasElement):boolean;
|
|
40
|
+
/**
|
|
41
|
+
* The renderer state machine behind an element's `engine` property, kept free of rendering so the
|
|
42
|
+
* same rules apply to every component: the preference switches live, a failure moves one step down
|
|
43
|
+
* the chain (`webgl` -> `builtin` when the element has one -> `list`), and a restored context or a
|
|
44
|
+
* fresh preference write returns to WebGL.
|
|
45
|
+
*/
|
|
46
|
+
export declare class Engine3dSelection{private readonly hasBuiltin;private currentPreference;private currentRenderer;
|
|
47
|
+
/** `hasBuiltin`: whether the element has its own renderer between WebGL and the list. */
|
|
48
|
+
constructor(hasBuiltin:boolean);get preference():Engine3dPreference;get renderer():Engine3dRenderer;
|
|
49
|
+
/** Applies a normalized preference; returns whether the renderer to show changed. */
|
|
50
|
+
prefer(value:unknown):boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Moves one step down the chain after `reason` stopped the current renderer. Returns the event
|
|
53
|
+
* detail to emit, or `null` when the list or text alternative is already showing.
|
|
54
|
+
*/
|
|
55
|
+
fail(reason:Engine3dFallbackReason):Engine3dFallbackDetail|null;
|
|
56
|
+
/** Returns to WebGL after a restored context when WebGL is still preferred; reports a change. */
|
|
57
|
+
restore():boolean;}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{literalSetConverter}from"./converters.js";import{LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dError,LYRA_DEFAULT_engine3dLoading,LYRA_DEFAULT_engine3dShowingBuiltin,LYRA_DEFAULT_engine3dShowingList,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported}from"./default-strings/shared.generated.js";const ENGINE_3D_PREFERENCE=literalSetConverter(["builtin","webgl"],"builtin"),ENGINE_3D_DEFAULT_STRINGS=Object.freeze({engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList}),ENGINE_3D_REASON_MESSAGE={unavailable:"engine3dUnavailable",unsupported:"engine3dUnsupported","context-lost":"engine3dContextLost",error:"engine3dError"},ENGINE_3D_SHOWING_MESSAGE={webgl:"engine3dShowingList",builtin:"engine3dShowingBuiltin",list:"engine3dShowingList"};function engine3dFallbackNotice(detail){return{reason:ENGINE_3D_REASON_MESSAGE[detail.reason],showing:ENGINE_3D_SHOWING_MESSAGE[detail.to]}}function engine3dFailureReason(error){return typeof error=="object"&&error!==null&&error.code==="webgl-unavailable"?"unsupported":"error"}function webgl2Available(createCanvas=()=>document.createElement("canvas")){try{const context=createCanvas().getContext("webgl2");return context?.getExtension("WEBGL_lose_context")?.loseContext(),context!==null}catch{return!1}}class Engine3dSelection{constructor(hasBuiltin){this.hasBuiltin=hasBuiltin,this.currentPreference="builtin",this.currentRenderer=hasBuiltin?"builtin":"list"}get preference(){return this.currentPreference}get renderer(){return this.currentRenderer}prefer(value){const preference=ENGINE_3D_PREFERENCE.normalize(value),previous=this.currentRenderer;return this.currentPreference=preference,this.currentRenderer=preference==="webgl"?"webgl":this.hasBuiltin?"builtin":"list",previous!==this.currentRenderer}fail(reason){const from=this.currentRenderer,to=from==="webgl"?this.hasBuiltin?"builtin":"list":from==="builtin"?"list":null;return to===null?null:(this.currentRenderer=to,Object.freeze({from,to,reason}))}restore(){return this.currentPreference!=="webgl"||this.currentRenderer==="webgl"?!1:(this.currentRenderer="webgl",!0)}}export{ENGINE_3D_DEFAULT_STRINGS,ENGINE_3D_PREFERENCE,ENGINE_3D_REASON_MESSAGE,ENGINE_3D_SHOWING_MESSAGE,Engine3dSelection,engine3dFailureReason,engine3dFallbackNotice,webgl2Available};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SourceRequestController,sourceCount,sourceRevision}from"./source-request-controller.js";import{SourceWindowController}from"./source-window-controller.js";import{yieldViewerTask}from"./resource-loader.js";import{deepActiveElementIn}from"./active-element.js";function hierarchyField(value,key){if(value===null||typeof value!="object")throw new TypeError("Invalid hierarchy record");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Invalid hierarchy field");return descriptor?.value}function hierarchyKey(value){if(typeof value!="string"||value.length>65536||value.trim().length===0)throw new TypeError("Invalid hierarchy key");return value}function hierarchyText(value,fallback=""){if(typeof value=="string"&&value.length>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return typeof value=="string"?value:fallback}const EMPTY_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),UNAVAILABLE=Symbol("unavailable");function snapshotQuery(value){const search=hierarchyField(value,"search"),hidden=hierarchyField(value,"hiddenKinds");if(typeof search!="string"||search.length>4096||!Array.isArray(hidden))throw new TypeError("Invalid hierarchy query");const length=sourceCount(hierarchyField(hidden,"length"));if(length>64)throw new RangeError("Hierarchy query exceeds its budget");const kinds=new Set;for(let index=0;index<length;index++){const kind=hierarchyField(hidden,String(index));if(typeof kind!="string"||kind.length===0||kind.length>64)throw new TypeError("Invalid hierarchy kind");kinds.add(kind)}return Object.freeze({search,hiddenKinds:Object.freeze([...kinds].sort())})}function sameQuery(left,right){return left.search===right.search&&left.hiddenKinds.length===right.hiddenKinds.length&&left.hiddenKinds.every((kind,index)=>kind===right.hiddenKinds[index])}function snapshotSearch(value){const raw=hierarchyField(value,"hits");if(!Array.isArray(raw))throw new TypeError("Invalid hierarchy search result");const length=sourceCount(hierarchyField(raw,"length"));if(length>1e4)throw new RangeError("Hierarchy search exceeds its hit budget");const totalValue=hierarchyField(value,"total"),total=totalValue===null?null:sourceCount(totalValue),exhaustive=hierarchyField(value,"exhaustive");if(typeof exhaustive!="boolean"||total!==null&&(total<length||exhaustive&&total!==length))throw new TypeError("Inconsistent hierarchy search result");const seen=new Set,hits=[];let units=0;for(let index=0;index<length;index++){const key=hierarchyKey(hierarchyField(hierarchyField(raw,String(index)),"key"));if(units+=key.length,units>2e6||seen.has(key))throw new RangeError("Hierarchy search key budget exceeded");seen.add(key),hits.push(Object.freeze({key}))}return Object.freeze({hits:Object.freeze(hits),total,exhaustive})}async function boundedCopy(value,maxBytes,owner,current){if(typeof value!="string"||value.length>maxBytes)throw new RangeError("Invalid hierarchy copy result");let bytes=0,nextYield=65536;for(let index=0;index<value.length;index++){const code=value.charCodeAt(index);if(code<128?bytes++:code<2048?bytes+=2:code>=55296&&code<=56319&&index+1<value.length&&value.charCodeAt(index+1)>=56320&&value.charCodeAt(index+1)<=57343?(bytes+=4,index++):bytes+=3,bytes>maxBytes)throw new RangeError("Hierarchy copy exceeds its byte budget");if(index>=nextYield){if(await yieldViewerTask(owner.defaultView,current),!current())throw new Error("Hierarchy copy changed");nextYield=index+65536}}if(!current())throw new Error("Hierarchy copy changed");return value}class HierarchySourceController{get epoch(){return this.requests.epoch}constructor(host,options){if(this.host=host,this.options=options,this.locale="",this.query=EMPTY_QUERY,this.searchLane={scheduled:!1},this.copyLane={scheduled:!1},this.transaction=0,this.dirty=!0,this.completion=Promise.resolve(!1),this.pumpScheduled=!1,this.loading=!1,this.error=!1,this.mountedCheckScheduled=!1,this.mountedActive=!1,this.firstMountedIndex=0,this.rowError=!1,this.rowsObserved=!1,this.activeIndex=0,options.payload){const{maxUnits,maxRowUnits,unitsOf}=options.payload;if(!Number.isSafeInteger(maxUnits)||!Number.isSafeInteger(maxRowUnits)||maxRowUnits<1||maxUnits<=maxRowUnits+65536||typeof unitsOf!="function")throw new RangeError("Invalid hierarchy payload bounds");this.payload=Object.freeze({maxUnits,maxRowUnits,unitsOf})}this.requests=new SourceRequestController(host,{channels:["project","navigate","search","copy"],onReset:()=>this.reset()}),this.window=new SourceWindowController(host,{pageSize:100,maxRows:400,maxPages:4,maxConcurrent:2,...this.payload?{maxWeight:this.payload.maxUnits-this.payload.maxRowUnits-65536,weightOf:row=>this.rowUnits(row)}:{},keyOf:row=>row.key,normalize:value=>this.normalize(value),onChange:()=>this.changed()}),this.adapter=this.makeAdapter(),host.addController(this)}rowUnits(row){if(!this.payload)return 0;const valueUnits=this.payload.unitsOf(row.value);if(!Number.isSafeInteger(valueUnits)||valueUnits<0)throw new RangeError("Invalid hierarchy row weight");const units=valueUnits+row.key.length+(row.parentKey?.length??0);if(!Number.isSafeInteger(units)||units>this.payload.maxRowUnits)throw new RangeError("Hierarchy row payload exceeded");return units}requestRange(start,endExclusive){this.window.requestRange(start,endExclusive)}normalize(value){const field=key2=>hierarchyField(value,key2),key=hierarchyKey(field("key")),parent=field("parentKey"),parentKey=parent===null?null:hierarchyKey(parent),level=sourceCount(field("level")),position=sourceCount(field("position")),setSize=sourceCount(field("setSize")),childCount=sourceCount(field("childCount")),expanded=field("expanded"),selected=field("selected"),disabled=field("disabled"),selectionState=field("selectionState");if(level<1||position<1||position>setSize||typeof expanded!="boolean"||typeof selected!="boolean"||disabled!==void 0&&typeof disabled!="boolean"||selectionState!==void 0&&(typeof selectionState!="string"||!["none","partial","all"].includes(selectionState)))throw new TypeError("Invalid hierarchy metadata");return Object.freeze({key,value:this.options.normalize(field("value"),key,childCount),parentKey,level,position,setSize,childCount,expanded,selected,...disabled===void 0?{}:{disabled},...selectionState===void 0?{}:{selectionState}})}makeAdapter(){return{count:this.projection?.rows.count??0,itemAt:index=>({state:"loading",index}),keyAt:index=>this.focused?.index===index?this.focused.row.key:this.window.source.keyAt(index),indexOfKey:key=>key===this.focused?.row.key?this.focused.index:this.window.source.indexOfKey(key)}}slot(index){this.scheduleMountedCheck();const slot=this.focused?.index===index?{state:"ready",index,value:this.focused.row}:this.window.source.itemAt(index);if(slot.state==="ready"&&this.activeKey===void 0&&index<32&&!slot.value.disabled){this.activeIndex=index,this.activeKey=slot.value.key;const projection=this.projection;queueMicrotask(()=>{this.projection===projection&&this.host.isConnected&&this.changed()})}return slot}scheduleMountedCheck(){this.mountedCheckScheduled||(this.mountedCheckScheduled=!0,queueMicrotask(()=>{if(this.mountedCheckScheduled=!1,!this.host.isConnected||!this.list)return;let active=!1,error=!1,settled=!1;const rows=this.list.projectedRows;for(const element of rows){const row=element.querySelector("[data-source-key]");row&&(settled=!0,row.dataset.sourceKey===this.activeKey&&row.getAttribute("aria-disabled")!=="true"&&(active=!0)),element.querySelector('[part~="source-error"]')&&(error=!0,settled=!0)}const first=Number(rows[0]?.dataset.rowIndex??0),observed=this.rowsObserved||settled;active===this.mountedActive&&first===this.firstMountedIndex&&error===this.rowError&&observed===this.rowsObserved||(this.mountedActive=active,this.firstMountedIndex=first,this.rowError=error,this.rowsObserved=observed,this.changed())}))}update(source,locale,force=!1,query=EMPTY_QUERY){const transaction=++this.transaction;this.boundInput=source;let revision,acceptedQuery;try{if(acceptedQuery=snapshotQuery(query),transaction!==this.transaction)return;if(source!==void 0){if(source===null||typeof source!="object"&&typeof source!="function"||typeof source.project!="function")throw new TypeError("Invalid hierarchy source");revision=sourceRevision(source.revision)}}catch{if(transaction!==this.transaction||(this.source=void 0,this.revision=void 0,this.locale=locale,this.requests.setSource(void 0,void 0),transaction!==this.transaction))return;this.reset(),this.error=source!==void 0,this.dirty=!1,this.changed();return}if(transaction!==this.transaction||!force&&!this.dirty&&source===this.source&&revision===this.revision&&locale===this.locale&&sameQuery(acceptedQuery,this.query))return;this.query=acceptedQuery,this.source=source,this.revision=revision,this.locale=locale,this.dirty=!1;const replaced=this.requests.setSource(source,revision);transaction===this.transaction&&(replaced||this.requests.refresh(),transaction===this.transaction&&(source&&this.host.isConnected&&this.project({type:"reset"}),this.changed()))}refresh(){this.update(this.boundInput,this.locale,!0,this.query)}reset(){this.clearCapability(this.searchLane),this.clearCapability(this.copyLane);const active=deepActiveElementIn(this.host.ownerDocument);!this.source||!this.host.isConnected?this.recovery=void 0:active&&this.host.shadowRoot?.contains(active)&&this.activeKey?this.recovery={key:this.activeKey,origin:active}:active&&active!==this.host.ownerDocument.body&&(this.recovery=void 0),this.current?.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.projection=void 0,this.focused=void 0,this.activeKey=void 0,this.activeIndex=0,this.loading=!1,this.error=!1,this.mountedActive=!1,this.firstMountedIndex=0,this.rowError=!1,this.rowsObserved=!1,this.window?.bind(void 0),this.adapter=this.makeAdapter()}changed(){this.options.onChange(),this.list?.requestUpdate("renderItem")}async project(action,user=!1,row){if(!this.source||!this.host.isConnected||user&&(this.loading||this.error))return!1;if("key"in action)try{hierarchyKey(action.key)}catch{return!1}const source=this.source,lease=this.requests.begin("project",this.locale);if(!lease?.isCurrent()||source!==this.source||(this.requests.invalidate("navigate"),!lease.isCurrent()))return!1;this.current?.settle(!1),this.queued?.settle(!1);let settle;const done=new Promise(resolve=>{settle=resolve}),job={source,lease,action,query:this.query,state:this.projection?.state??null,user,row,settle};return lease.context.signal.addEventListener("abort",()=>{job.state=null,job.row=void 0,settle(!1)},{once:!0}),this.completion=done,this.current=job,this.queued=job,this.loading=!0,this.error=!1,this.changed(),this.schedulePump(),done}schedulePump(){this.pumpScheduled||(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){if(this.running)return;const job=this.queued;if(!job)return;this.queued=void 0;const current=()=>this.current===job&&job.lease.isCurrent()&&this.source===job.source;if(!current()){job.settle(!1);return}this.running=job;const recovery=this.recovery,focusedKey=this.focused?.row.key??recovery?.key,origin=recovery?.origin??deepActiveElementIn(this.host.ownerDocument);Promise.resolve().then(()=>{if(!current())return;const state=job.state;job.state=null;const project=job.source.project;if(current())return project.call(job.source,{...job.lease.context,query:job.query,state,action:job.action})}).then(async result=>{if(!current())return;if(!result)throw new TypeError("Invalid hierarchy projection");const state=result.state;if(typeof state!="string"||state.length===0||state.length>65536)throw new TypeError("Invalid hierarchy state");const total=sourceCount(result.total),view=result.rows,count=sourceCount(view?.count),focusIndex=result.focusIndex,indexed=typeof view.itemAt=="function";if(count>total||typeof view.indexOfKey!="function"||(indexed?typeof view.keyAt!="function":typeof view.read!="function"))throw new TypeError("Invalid hierarchy view");if(focusIndex!==void 0&&sourceCount(focusIndex)>=count)throw new RangeError("Invalid hierarchy focus");if(current()&&(this.window.bind({owner:job.source,revision:job.lease.context.revision,epoch:this.requests.epoch,locale:job.lease.context.locale,view}),!!current()&&(this.projection=Object.freeze({state,total,rows:view,...focusIndex===void 0?{}:{focusIndex}}),this.focused=void 0,this.recovery=void 0,this.activeIndex=Math.min(this.activeIndex,Math.max(0,count-1)),this.activeKey=void 0,this.adapter=this.makeAdapter(),this.loading=!1,this.error=!1,this.changed(),!!current()&&(job.user&&this.options.accepted(job.action,job.row,state,current),job.row=void 0,!!current()))))if(job.action.type==="reveal")job.settle(focusIndex!==void 0&&await this.navigate(focusIndex,0,origin));else if(focusedKey&&origin&&(recovery||this.host.shadowRoot?.contains(origin))){const index=await this.window.resolveKey(focusedKey);if(!current())return;await this.navigate(index??focusIndex??this.activeIndex,0,origin),current()&&job.settle(!0)}else job.settle(!0)}).catch(()=>{current()&&(this.loading=!1,this.error=!0,this.changed(),job.settle(!1))}).finally(()=>{job.state=null,job.row=void 0,this.running===job&&(this.running=void 0),this.schedulePump()})}clearCapability(lane){lane.current?.settle({status:"stale"}),lane.queued?.settle({status:"stale"}),lane.current=void 0,lane.queued=void 0}scheduleCapability(lane){lane.scheduled||(lane.scheduled=!0,queueMicrotask(()=>{if(lane.scheduled=!1,lane.running||!lane.queued)return;const job=lane.queued;if(lane.queued=void 0,lane.current!==job||!job.lease.isCurrent()){job.settle({status:"stale"});return}lane.running=job,job.run().finally(()=>{lane.running===job&&(lane.running=void 0),this.scheduleCapability(lane)})}))}capability(channel,lane,invoke,validate){const source=this.source;if(!source)return Promise.resolve({status:"unavailable"});if(!this.host.isConnected)return Promise.resolve({status:"stale"});const lease=this.requests.begin(channel,this.locale);if(!lease?.isCurrent()||source!==this.source)return Promise.resolve({status:"stale"});this.clearCapability(lane);let settle;const done=new Promise(resolve=>{settle=resolve}),current=()=>lane.current===job&&source===this.source&&lease.isCurrent(),job={lease,settle,run:async()=>{try{if(!current()){settle({status:"stale"});return}const raw=await invoke(source,lease);if(!current()){settle({status:"stale"});return}if(raw===UNAVAILABLE){settle({status:"unavailable"});return}const value=await validate(raw,current);settle(current()?{status:"ready",value,isCurrent:current}:{status:"stale"})}catch{settle({status:current()?"error":"stale"})}}};return lane.current=job,lane.queued=job,lease.context.signal.addEventListener("abort",()=>settle({status:"stale"}),{once:!0}),this.scheduleCapability(lane),done}cancelSearch(){const transaction=++this.transaction;if(this.clearCapability(this.searchLane),this.requests.invalidate("search"),transaction===this.transaction&&(this.clearCapability(this.copyLane),this.requests.invalidate("copy"),transaction===this.transaction&&(this.requests.invalidate("navigate"),transaction===this.transaction&&this.current?.action.type==="reveal"))){if(this.current.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.requests.invalidate("project"),transaction!==this.transaction)return;this.loading=!1,this.changed()}}search(){const transaction=this.transaction+1;if(this.cancelSearch(),transaction!==this.transaction)return Promise.resolve({status:"stale"});const query=this.query.search;return this.capability("search",this.searchLane,(source,lease)=>{const search=source.search;return!lease.isCurrent()||source!==this.source?UNAVAILABLE:typeof search=="function"?search.call(source,{...lease.context,query,limit:1e4}):UNAVAILABLE},snapshotSearch)}copy(key,scope,maxBytes){const transaction=++this.transaction;if(this.clearCapability(this.copyLane),this.requests.invalidate("copy"),transaction!==this.transaction)return Promise.resolve({status:"stale"});try{if(!["node","subtree","document"].includes(scope)||scope==="document"!=(key===null)||!Number.isSafeInteger(maxBytes)||maxBytes<1)throw new TypeError("Invalid hierarchy copy request");key!==null&&hierarchyKey(key)}catch{return Promise.resolve({status:"error"})}const owner=this.host.ownerDocument;return this.capability("copy",this.copyLane,(source,lease)=>{const copy=source.copy;return!lease.isCurrent()||source!==this.source?UNAVAILABLE:typeof copy=="function"?copy.call(source,{...lease.context,key,scope,maxBytes}):UNAVAILABLE},(value,current)=>boundedCopy(value,maxBytes,owner,current))}whenReady(){return this.completion}cancelPending(){if(!this.projection)return;const transaction=++this.transaction;this.current?.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.requests.invalidate("project"),transaction===this.transaction&&(this.requests.invalidate("navigate"),transaction===this.transaction&&(this.loading=!1,this.changed()))}reveal(key){try{hierarchyKey(key)}catch{return Promise.resolve(!1)}return this.project({type:"reveal",key})}retry(){this.project({type:"reset"})}focusRow(index,row){if(!row.disabled){if(this.payload){const projection=this.projection,transaction=this.transaction;try{this.rowUnits(row)}catch{return}if(projection!==this.projection||transaction!==this.transaction||!this.host.isConnected)return}this.activeIndex=index,this.activeKey=row.key,this.focused={index,row},this.changed()}}focusUnchanged(origin){const active=deepActiveElementIn(this.host.ownerDocument);return active===origin||active===this.host.ownerDocument.body||active===this.host||active===null}async navigate(index,step=0,origin=deepActiveElementIn(this.host.ownerDocument)){const projection=this.projection,lease=this.requests.begin("navigate",this.locale);if(!projection||!lease)return!1;const current=()=>lease.isCurrent()&&this.projection===projection;for(let attempts=0;attempts<32&&index>=0&&index<projection.rows.count;attempts++,index+=step){if(await this.host.updateComplete,!current()||!this.focusUnchanged(origin)||!this.list||(this.list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.nextFrame(lease)||!current())||!await this.window.ensure(index)||!current())return!1;const slot=this.window.source.itemAt(index);if(!current()||slot.state!=="ready")return!1;if(slot.value.disabled){if(!step)return!1;continue}if(this.activeIndex=index,this.activeKey=slot.value.key,this.changed(),await this.host.updateComplete,!current()||!this.list||(await this.list.updateComplete,!current()||!this.focusUnchanged(origin)))return!1;const row=this.list.projectedRows.find(element=>Number(element.dataset.rowIndex)===index)?.querySelector("[data-source-key]");return!row||(row.focus({preventScroll:!0}),!current())?!1:(this.focusRow(index,slot.value),!0)}return!1}nextFrame(lease){const view=this.host.ownerDocument.defaultView;return!view||!lease.isCurrent()?Promise.resolve(!1):new Promise(resolve=>{const signal=lease.context.signal,cancel=()=>{view.cancelAnimationFrame(frame),resolve(!1)},frame=view.requestAnimationFrame(()=>{signal.removeEventListener("abort",cancel),resolve(lease.isCurrent())});signal.addEventListener("abort",cancel,{once:!0}),lease.isCurrent()||cancel()})}keydown(event,row,index,rtl,select){if(event.altKey||event.ctrlKey||event.metaKey||this.loading||this.error)return;let target,step=0;if(event.key==="Home")target=0,step=1;else if(event.key==="End")target=(this.projection?.rows.count??0)-1,step=-1;else if(event.key==="ArrowDown")target=index+1,step=1;else if(event.key==="ArrowUp")target=index-1,step=-1;else if(row&&(event.key==="Enter"||event.key===" ")){event.preventDefault(),select(row);return}else if(row&&event.key===(rtl?"ArrowLeft":"ArrowRight")){event.preventDefault(),row.childCount&&!row.expanded?this.project({type:"toggle",key:row.key,expanded:!0},!0,row):row.childCount&&row.expanded&&this.navigate(index+1,1);return}else if(row&&event.key===(rtl?"ArrowRight":"ArrowLeft")){event.preventDefault(),row.childCount&&row.expanded?this.project({type:"toggle",key:row.key,expanded:!1},!0,row):row.parentKey&&this.reveal(row.parentKey);return}target!==void 0&&(event.preventDefault(),this.navigate(target,step))}adopted(){this.dirty=!0,this.requests.adopted(),this.window.adopted(),this.changed()}hostConnected(){this.dirty=!0,this.changed()}hostDisconnected(){this.dirty=!0,this.current?.settle(!1),this.queued?.settle(!1),this.list=void 0}}export{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText};
|
|
1
|
+
import{SourceRequestController,sourceCount,sourceRevision}from"./source-request-controller.js";import{SourceWindowController}from"./source-window-controller.js";import{yieldViewerTask}from"./resource-loader.js";import{deepActiveElementIn}from"./active-element.js";function hierarchyField(value,key){if(value===null||typeof value!="object")throw new TypeError("Invalid hierarchy record");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Invalid hierarchy field");return descriptor?.value}function hierarchyKey(value){if(typeof value!="string"||value.length>65536||value.trim().length===0)throw new TypeError("Invalid hierarchy key");return value}function hierarchyText(value,fallback=""){if(typeof value=="string"&&value.length>65536)throw new RangeError("Hierarchy display value exceeds its row budget");return typeof value=="string"?value:fallback}const EMPTY_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),UNAVAILABLE=Symbol("unavailable");function snapshotQuery(value){const search=hierarchyField(value,"search"),hidden=hierarchyField(value,"hiddenKinds");if(typeof search!="string"||search.length>4096||!Array.isArray(hidden))throw new TypeError("Invalid hierarchy query");const length=sourceCount(hierarchyField(hidden,"length"));if(length>64)throw new RangeError("Hierarchy query exceeds its budget");const kinds=new Set;for(let index=0;index<length;index++){const kind=hierarchyField(hidden,String(index));if(typeof kind!="string"||kind.length===0||kind.length>64)throw new TypeError("Invalid hierarchy kind");kinds.add(kind)}return Object.freeze({search,hiddenKinds:Object.freeze([...kinds].sort())})}function sameQuery(left,right){return left.search===right.search&&left.hiddenKinds.length===right.hiddenKinds.length&&left.hiddenKinds.every((kind,index)=>kind===right.hiddenKinds[index])}function snapshotSearch(value){const raw=hierarchyField(value,"hits");if(!Array.isArray(raw))throw new TypeError("Invalid hierarchy search result");const length=sourceCount(hierarchyField(raw,"length"));if(length>1e4)throw new RangeError("Hierarchy search exceeds its hit budget");const totalValue=hierarchyField(value,"total"),total=totalValue===null?null:sourceCount(totalValue),exhaustive=hierarchyField(value,"exhaustive");if(typeof exhaustive!="boolean"||total!==null&&(total<length||exhaustive&&total!==length))throw new TypeError("Inconsistent hierarchy search result");const seen=new Set,hits=[];let units=0;for(let index=0;index<length;index++){const key=hierarchyKey(hierarchyField(hierarchyField(raw,String(index)),"key"));if(units+=key.length,units>2e6||seen.has(key))throw new RangeError("Hierarchy search key budget exceeded");seen.add(key),hits.push(Object.freeze({key}))}return Object.freeze({hits:Object.freeze(hits),total,exhaustive})}async function boundedCopy(value,maxBytes,owner,current){if(typeof value!="string"||value.length>maxBytes)throw new RangeError("Invalid hierarchy copy result");let bytes=0,nextYield=65536;for(let index=0;index<value.length;index++){const code=value.charCodeAt(index);if(code<128?bytes++:code<2048?bytes+=2:code>=55296&&code<=56319&&index+1<value.length&&value.charCodeAt(index+1)>=56320&&value.charCodeAt(index+1)<=57343?(bytes+=4,index++):bytes+=3,bytes>maxBytes)throw new RangeError("Hierarchy copy exceeds its byte budget");if(index>=nextYield){if(await yieldViewerTask(owner.defaultView,current),!current())throw new Error("Hierarchy copy changed");nextYield=index+65536}}if(!current())throw new Error("Hierarchy copy changed");return value}class HierarchySourceController{get epoch(){return this.requests.epoch}constructor(host,options){if(this.host=host,this.options=options,this.locale="",this.query=EMPTY_QUERY,this.searchLane={scheduled:!1},this.copyLane={scheduled:!1},this.transaction=0,this.dirty=!0,this.completion=Promise.resolve(!1),this.pumpScheduled=!1,this.loading=!1,this.error=!1,this.mountedCheckScheduled=!1,this.mountedActive=!1,this.firstMountedIndex=0,this.rowError=!1,this.rowsObserved=!1,this.activeIndex=0,options.payload){const{maxUnits,maxRowUnits,unitsOf}=options.payload;if(!Number.isSafeInteger(maxUnits)||!Number.isSafeInteger(maxRowUnits)||maxRowUnits<1||maxUnits<=maxRowUnits+65536||typeof unitsOf!="function")throw new RangeError("Invalid hierarchy payload bounds");this.payload=Object.freeze({maxUnits,maxRowUnits,unitsOf})}this.requests=new SourceRequestController(host,{channels:["project","navigate","search","copy"],onReset:()=>this.reset()}),this.window=new SourceWindowController(host,{pageSize:100,maxRows:400,maxPages:4,maxConcurrent:2,...this.payload?{maxWeight:this.payload.maxUnits-this.payload.maxRowUnits-65536,weightOf:row=>this.rowUnits(row)}:{},keyOf:row=>row.key,normalize:value=>this.normalize(value),onChange:()=>this.changed()}),this.adapter=this.makeAdapter(),host.addController(this)}rowUnits(row){if(!this.payload)return 0;const valueUnits=this.payload.unitsOf(row.value);if(!Number.isSafeInteger(valueUnits)||valueUnits<0)throw new RangeError("Invalid hierarchy row weight");const units=valueUnits+row.key.length+(row.parentKey?.length??0);if(!Number.isSafeInteger(units)||units>this.payload.maxRowUnits)throw new RangeError("Hierarchy row payload exceeded");return units}requestRange(start,endExclusive){this.window.requestRange(start,endExclusive)}normalize(value){const field=key2=>hierarchyField(value,key2),key=hierarchyKey(field("key")),parent=field("parentKey"),parentKey=parent===null?null:hierarchyKey(parent);if(parentKey===key)throw new TypeError("Hierarchy row cannot be its own parent");const level=sourceCount(field("level")),position=sourceCount(field("position")),setSize=sourceCount(field("setSize")),childCount=sourceCount(field("childCount")),expanded=field("expanded"),selected=field("selected"),disabled=field("disabled"),selectionState=field("selectionState");if(level<1||position<1||position>setSize||typeof expanded!="boolean"||typeof selected!="boolean"||disabled!==void 0&&typeof disabled!="boolean"||selectionState!==void 0&&(typeof selectionState!="string"||!["none","partial","all"].includes(selectionState)))throw new TypeError("Invalid hierarchy metadata");return Object.freeze({key,value:this.options.normalize(field("value"),key,childCount),parentKey,level,position,setSize,childCount,expanded,selected,...disabled===void 0?{}:{disabled},...selectionState===void 0?{}:{selectionState}})}makeAdapter(){return{count:this.projection?.rows.count??0,itemAt:index=>({state:"loading",index}),keyAt:index=>this.focused?.index===index?this.focused.row.key:this.window.source.keyAt(index),indexOfKey:key=>key===this.focused?.row.key?this.focused.index:this.window.source.indexOfKey(key)}}slot(index){this.scheduleMountedCheck();const slot=this.focused?.index===index?{state:"ready",index,value:this.focused.row}:this.window.source.itemAt(index);if(slot.state==="ready"&&this.activeKey===void 0&&index<32&&!slot.value.disabled){this.activeIndex=index,this.activeKey=slot.value.key;const projection=this.projection;queueMicrotask(()=>{this.projection===projection&&this.host.isConnected&&this.changed()})}return slot}scheduleMountedCheck(){this.mountedCheckScheduled||(this.mountedCheckScheduled=!0,queueMicrotask(()=>{if(this.mountedCheckScheduled=!1,!this.host.isConnected||!this.list)return;let active=!1,error=!1,settled=!1;const rows=this.list.projectedRows;for(const element of rows){const row=element.querySelector("[data-source-key]");row&&(settled=!0,row.dataset.sourceKey===this.activeKey&&row.getAttribute("aria-disabled")!=="true"&&(active=!0)),element.querySelector('[part~="source-error"]')&&(error=!0,settled=!0)}const first=Number(rows[0]?.dataset.rowIndex??0),observed=this.rowsObserved||settled;active===this.mountedActive&&first===this.firstMountedIndex&&error===this.rowError&&observed===this.rowsObserved||(this.mountedActive=active,this.firstMountedIndex=first,this.rowError=error,this.rowsObserved=observed,this.changed())}))}update(source,locale,force=!1,query=EMPTY_QUERY){const transaction=++this.transaction;this.boundInput=source;let revision,acceptedQuery;try{if(acceptedQuery=snapshotQuery(query),transaction!==this.transaction)return;if(source!==void 0){if(source===null||typeof source!="object"&&typeof source!="function"||typeof source.project!="function")throw new TypeError("Invalid hierarchy source");revision=sourceRevision(source.revision)}}catch{if(transaction!==this.transaction||(this.source=void 0,this.revision=void 0,this.locale=locale,this.requests.setSource(void 0,void 0),transaction!==this.transaction))return;this.reset(),this.error=source!==void 0,this.dirty=!1,this.changed();return}if(transaction!==this.transaction||!force&&!this.dirty&&source===this.source&&revision===this.revision&&locale===this.locale&&sameQuery(acceptedQuery,this.query))return;this.query=acceptedQuery,this.source=source,this.revision=revision,this.locale=locale,this.dirty=!1;const replaced=this.requests.setSource(source,revision);transaction===this.transaction&&(replaced||this.requests.refresh(),transaction===this.transaction&&(source&&this.host.isConnected&&this.project({type:"reset"}),this.changed()))}refresh(){this.update(this.boundInput,this.locale,!0,this.query)}reset(){this.clearCapability(this.searchLane),this.clearCapability(this.copyLane);const active=deepActiveElementIn(this.host.ownerDocument);!this.source||!this.host.isConnected?this.recovery=void 0:active&&this.host.shadowRoot?.contains(active)&&this.activeKey?this.recovery={key:this.activeKey,origin:active}:active&&active!==this.host.ownerDocument.body&&(this.recovery=void 0),this.current?.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.projection=void 0,this.focused=void 0,this.activeKey=void 0,this.activeIndex=0,this.loading=!1,this.error=!1,this.mountedActive=!1,this.firstMountedIndex=0,this.rowError=!1,this.rowsObserved=!1,this.window?.bind(void 0),this.adapter=this.makeAdapter()}changed(){this.options.onChange(),this.list?.requestUpdate("renderItem")}async project(action,user=!1,row){if(!this.source||!this.host.isConnected||user&&(this.loading||this.error))return!1;if("key"in action)try{hierarchyKey(action.key)}catch{return!1}const source=this.source,lease=this.requests.begin("project",this.locale);if(!lease?.isCurrent()||source!==this.source||(this.requests.invalidate("navigate"),!lease.isCurrent()))return!1;this.current?.settle(!1),this.queued?.settle(!1);let settle;const done=new Promise(resolve=>{settle=resolve}),job={source,lease,action,query:this.query,state:this.projection?.state??null,user,row,settle};return lease.context.signal.addEventListener("abort",()=>{job.state=null,job.row=void 0,settle(!1)},{once:!0}),this.completion=done,this.current=job,this.queued=job,this.loading=!0,this.error=!1,this.changed(),this.schedulePump(),done}schedulePump(){this.pumpScheduled||(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){if(this.running)return;const job=this.queued;if(!job)return;this.queued=void 0;const current=()=>this.current===job&&job.lease.isCurrent()&&this.source===job.source;if(!current()){job.settle(!1);return}this.running=job;const recovery=this.recovery,focusedKey=this.focused?.row.key??recovery?.key,origin=recovery?.origin??deepActiveElementIn(this.host.ownerDocument);Promise.resolve().then(()=>{if(!current())return;const state=job.state;job.state=null;const project=job.source.project;if(current())return project.call(job.source,{...job.lease.context,query:job.query,state,action:job.action})}).then(async result=>{if(!current())return;if(!result)throw new TypeError("Invalid hierarchy projection");const state=result.state;if(typeof state!="string"||state.length===0||state.length>65536)throw new TypeError("Invalid hierarchy state");const total=sourceCount(result.total),view=result.rows,count=sourceCount(view?.count),focusIndex=result.focusIndex,indexed=typeof view.itemAt=="function";if(count>total||typeof view.indexOfKey!="function"||(indexed?typeof view.keyAt!="function":typeof view.read!="function"))throw new TypeError("Invalid hierarchy view");if(focusIndex!==void 0&&sourceCount(focusIndex)>=count)throw new RangeError("Invalid hierarchy focus");if(current()&&(this.window.bind({owner:job.source,revision:job.lease.context.revision,epoch:this.requests.epoch,locale:job.lease.context.locale,view}),!!current()&&(this.projection=Object.freeze({state,total,rows:view,...focusIndex===void 0?{}:{focusIndex}}),this.focused=void 0,this.recovery=void 0,this.activeIndex=Math.min(this.activeIndex,Math.max(0,count-1)),this.activeKey=void 0,this.adapter=this.makeAdapter(),this.loading=!1,this.error=!1,this.changed(),!!current()&&(job.user&&this.options.accepted(job.action,job.row,state,current),job.row=void 0,!!current()))))if(job.action.type==="reveal")job.settle(focusIndex!==void 0&&await this.navigate(focusIndex,0,origin));else if(focusedKey&&origin&&(recovery||this.host.shadowRoot?.contains(origin))){const index=await this.window.resolveKey(focusedKey);if(!current())return;await this.navigate(index??focusIndex??this.activeIndex,0,origin),current()&&job.settle(!0)}else job.settle(!0)}).catch(()=>{current()&&(this.loading=!1,this.error=!0,this.changed(),job.settle(!1))}).finally(()=>{job.state=null,job.row=void 0,this.running===job&&(this.running=void 0),this.schedulePump()})}clearCapability(lane){lane.current?.settle({status:"stale"}),lane.queued?.settle({status:"stale"}),lane.current=void 0,lane.queued=void 0}scheduleCapability(lane){lane.scheduled||(lane.scheduled=!0,queueMicrotask(()=>{if(lane.scheduled=!1,lane.running||!lane.queued)return;const job=lane.queued;if(lane.queued=void 0,lane.current!==job||!job.lease.isCurrent()){job.settle({status:"stale"});return}lane.running=job,job.run().finally(()=>{lane.running===job&&(lane.running=void 0),this.scheduleCapability(lane)})}))}capability(channel,lane,invoke,validate){const source=this.source;if(!source)return Promise.resolve({status:"unavailable"});if(!this.host.isConnected)return Promise.resolve({status:"stale"});const lease=this.requests.begin(channel,this.locale);if(!lease?.isCurrent()||source!==this.source)return Promise.resolve({status:"stale"});this.clearCapability(lane);let settle;const done=new Promise(resolve=>{settle=resolve}),current=()=>lane.current===job&&source===this.source&&lease.isCurrent(),job={lease,settle,run:async()=>{try{if(!current()){settle({status:"stale"});return}const raw=await invoke(source,lease);if(!current()){settle({status:"stale"});return}if(raw===UNAVAILABLE){settle({status:"unavailable"});return}const value=await validate(raw,current);settle(current()?{status:"ready",value,isCurrent:current}:{status:"stale"})}catch{settle({status:current()?"error":"stale"})}}};return lane.current=job,lane.queued=job,lease.context.signal.addEventListener("abort",()=>settle({status:"stale"}),{once:!0}),this.scheduleCapability(lane),done}cancelSearch(){const transaction=++this.transaction;if(this.clearCapability(this.searchLane),this.requests.invalidate("search"),transaction===this.transaction&&(this.clearCapability(this.copyLane),this.requests.invalidate("copy"),transaction===this.transaction&&(this.requests.invalidate("navigate"),transaction===this.transaction&&this.current?.action.type==="reveal"))){if(this.current.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.requests.invalidate("project"),transaction!==this.transaction)return;this.loading=!1,this.changed()}}search(){const transaction=this.transaction+1;if(this.cancelSearch(),transaction!==this.transaction)return Promise.resolve({status:"stale"});const query=this.query.search;return this.capability("search",this.searchLane,(source,lease)=>{const search=source.search;return!lease.isCurrent()||source!==this.source?UNAVAILABLE:typeof search=="function"?search.call(source,{...lease.context,query,limit:1e4}):UNAVAILABLE},snapshotSearch)}copy(key,scope,maxBytes){const transaction=++this.transaction;if(this.clearCapability(this.copyLane),this.requests.invalidate("copy"),transaction!==this.transaction)return Promise.resolve({status:"stale"});try{if(!["node","subtree","document"].includes(scope)||scope==="document"!=(key===null)||!Number.isSafeInteger(maxBytes)||maxBytes<1)throw new TypeError("Invalid hierarchy copy request");key!==null&&hierarchyKey(key)}catch{return Promise.resolve({status:"error"})}const owner=this.host.ownerDocument;return this.capability("copy",this.copyLane,(source,lease)=>{const copy=source.copy;return!lease.isCurrent()||source!==this.source?UNAVAILABLE:typeof copy=="function"?copy.call(source,{...lease.context,key,scope,maxBytes}):UNAVAILABLE},(value,current)=>boundedCopy(value,maxBytes,owner,current))}whenReady(){return this.completion}cancelPending(){if(!this.projection)return;const transaction=++this.transaction;this.current?.settle(!1),this.queued?.settle(!1),this.current=void 0,this.queued=void 0,this.requests.invalidate("project"),transaction===this.transaction&&(this.requests.invalidate("navigate"),transaction===this.transaction&&(this.loading=!1,this.changed()))}reveal(key){try{hierarchyKey(key)}catch{return Promise.resolve(!1)}return this.project({type:"reveal",key})}retry(){this.project({type:"reset"})}focusRow(index,row){if(!row.disabled){if(this.payload){const projection=this.projection,transaction=this.transaction;try{this.rowUnits(row)}catch{return}if(projection!==this.projection||transaction!==this.transaction||!this.host.isConnected)return}this.activeIndex=index,this.activeKey=row.key,this.focused={index,row},this.changed()}}focusUnchanged(origin){const active=deepActiveElementIn(this.host.ownerDocument);return active===origin||active===this.host.ownerDocument.body||active===this.host||active===null}async navigate(index,step=0,origin=deepActiveElementIn(this.host.ownerDocument)){const projection=this.projection,lease=this.requests.begin("navigate",this.locale);if(!projection||!lease)return!1;const current=()=>lease.isCurrent()&&this.projection===projection;for(let attempts=0;attempts<32&&index>=0&&index<projection.rows.count;attempts++,index+=step){if(await this.host.updateComplete,!current()||!this.focusUnchanged(origin)||!this.list||(this.list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.nextFrame(lease)||!current())||!await this.window.ensure(index)||!current())return!1;const slot=this.window.source.itemAt(index);if(!current()||slot.state!=="ready")return!1;if(slot.value.disabled){if(!step)return!1;continue}if(this.activeIndex=index,this.activeKey=slot.value.key,this.changed(),await this.host.updateComplete,!current()||!this.list||(await this.list.updateComplete,!current()||!this.focusUnchanged(origin)))return!1;const row=this.list.projectedRows.find(element=>Number(element.dataset.rowIndex)===index)?.querySelector("[data-source-key]");return!row||(row.focus({preventScroll:!0}),!current())?!1:(this.focusRow(index,slot.value),!0)}return!1}nextFrame(lease){const view=this.host.ownerDocument.defaultView;return!view||!lease.isCurrent()?Promise.resolve(!1):new Promise(resolve=>{const signal=lease.context.signal,cancel=()=>{view.cancelAnimationFrame(frame),resolve(!1)},frame=view.requestAnimationFrame(()=>{signal.removeEventListener("abort",cancel),resolve(lease.isCurrent())});signal.addEventListener("abort",cancel,{once:!0}),lease.isCurrent()||cancel()})}keydown(event,row,index,rtl,select){if(event.altKey||event.ctrlKey||event.metaKey||this.loading||this.error)return;let target,step=0;if(event.key==="Home")target=0,step=1;else if(event.key==="End")target=(this.projection?.rows.count??0)-1,step=-1;else if(event.key==="ArrowDown")target=index+1,step=1;else if(event.key==="ArrowUp")target=index-1,step=-1;else if(row&&(event.key==="Enter"||event.key===" ")){event.preventDefault(),select(row);return}else if(row&&event.key===(rtl?"ArrowLeft":"ArrowRight")){event.preventDefault(),row.childCount&&!row.expanded?this.project({type:"toggle",key:row.key,expanded:!0},!0,row):row.childCount&&row.expanded&&this.navigate(index+1,1);return}else if(row&&event.key===(rtl?"ArrowRight":"ArrowLeft")){event.preventDefault(),row.childCount&&row.expanded?this.project({type:"toggle",key:row.key,expanded:!1},!0,row):row.parentKey&&this.reveal(row.parentKey);return}target!==void 0&&(event.preventDefault(),this.navigate(target,step))}adopted(){this.dirty=!0,this.requests.adopted(),this.window.adopted(),this.changed()}hostConnected(){this.dirty=!0,this.changed()}hostDisconnected(){this.dirty=!0,this.current?.settle(!1),this.queued?.settle(!1),this.list=void 0}}export{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{canonicalizeLocaleTag}from"./locale-tag.js";import{warnLocaleFallback}from"./dev-warning.js";import{domParentElement,flattenedParentElement,ownerView}from"./composed-tree.js";import{getPluralRules}from"./intl-cache.js";import{isPlainRecord}from"./object-guards.js";const MAX_LOCALE_CANDIDATES=64,MAX_LOCALE_PARENT_DEPTH=32,MAX_LOCALE_SUBTAGS=32,MAX_LOCALE_TAG_LENGTH=255,MAX_LOCALE_CACHE_ENTRIES=128,MAX_CACHEABLE_LOCALE_LENGTH=512,LEGACY_LOCALE_PATTERN=/^[a-z0-9]{1,32}(?:-[a-z0-9]{1,32})*$/,locales=new Map,localePublicTags=new Map,localeMeta=new Map,localeParents=new Map,wellFormedLocales=new Set,exactOnlyLocales=new Set,localeCatalogRevisions=new Map,listeners=new Set,hostLocaleListeners=new Set,hostLocaleFinalizer=new FinalizationRegistry(subscription=>{hostLocaleListeners.delete(subscription)}),ownerDocumentsWithBrowsingContext=new WeakSet,registryListeners=new Set;let activeLocale="",catalogRevision=0;const localeIdentityCache=new Map,EMPTY_LOCALE_IDENTITY=Object.freeze({publicTag:"",lookupKey:"",wellFormed:!1,candidateBounded:!0,storable:!1}),localeCandidateCache=new Map,ENGLISH_ONLY_CANDIDATES=Object.freeze(["en"]);function cacheBounded(cache,key,value){cache.size>=MAX_LOCALE_CACHE_ENTRIES&&cache.clear(),cache.set(key,value)}function subtagCountWithinBounds(tag){if(tag.length>MAX_LOCALE_TAG_LENGTH)return!1;let count=tag?1:0;for(let index=0;index<tag.length;index+=1)if(tag.charCodeAt(index)===45&&++count>MAX_LOCALE_SUBTAGS)return!1;return!0}function localeIdentity(locale){const known=typeof locale=="string"&&locale.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeIdentityCache.get(locale):void 0;if(known)return known;const normalized=typeof locale=="string"?locale.trim().replace(/_/g,"-"):"";if(!normalized)return EMPTY_LOCALE_IDENTITY;const cached=normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeIdentityCache.get(normalized):void 0;if(cached)return rememberLocaleSpelling(locale,normalized,cached),cached;let publicTag=normalized.toLowerCase(),wellFormed=!1;try{const canonical=canonicalizeLocaleTag(normalized);canonical&&(publicTag=canonical,wellFormed=!0)}catch{}const lookupKey=publicTag.toLowerCase(),candidateBounded=subtagCountWithinBounds(lookupKey),identity={publicTag,lookupKey,wellFormed,candidateBounded,storable:wellFormed||candidateBounded&&LEGACY_LOCALE_PATTERN.test(lookupKey)};return normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeIdentityCache,normalized,identity),rememberLocaleSpelling(locale,normalized,identity),identity}function rememberLocaleSpelling(locale,normalized,identity){locale!==normalized&&locale.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeIdentityCache,locale,identity)}function storedLocaleIdentity(locale,required){if(typeof locale!="string")throw new TypeError("A locale must be a string.");const identity=localeIdentity(locale);if(!identity.publicTag){if(!required)return identity;throw new TypeError("A locale is required.")}if(!identity.storable)throw new TypeError("The locale must be BCP-47 or a bounded alphanumeric custom tag.");return identity}function canonicalizeLyraLocale(locale){const identity=localeIdentity(locale);return identity.storable?identity.publicTag:"en"}const likelySubtagsCache=new Map;function likelySubtags(key){let likely=likelySubtagsCache.get(key);if(!likely){try{const{script="",region=""}=new Intl.Locale(key).maximize();likely=[script==="Zzzz"?"":script.toLowerCase(),region.toLowerCase()]}catch{return["",""]}key.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(likelySubtagsCache,key,likely)}return likely}function regionalFallbacks(requestedKey,limit,wellFormed){if(limit<=0||!wellFormed)return[];const separator=requestedKey.indexOf("-"),language=separator===-1?requestedKey:requestedKey.slice(0,separator);if(!language)return[];const requestedSubtags=new Set(requestedKey.split("-")),siblings=[...locales.keys()].filter(key=>wellFormedLocales.has(key)&&!exactOnlyLocales.has(key)&&(key===language||key.startsWith(`${language}-`))&&!isPrefixOf(key,requestedKey));if(siblings.length<2)return siblings;const[script,region]=likelySubtags(requestedKey),rank=key=>{const[keyScript,keyRegion]=likelySubtags(key);return(script&&keyScript===script?1e4:0)+(region&&keyRegion===region?1e3:0)+key.split("-").filter(subtag=>requestedSubtags.has(subtag)).length};return siblings.map(key=>[rank(key),key]).sort(([a,x],[b,y])=>b-a||(x<y?-1:x>y?1:0)).slice(0,limit).map(([,key])=>key)}function isPrefixOf(key,requestedKey){return key===requestedKey||requestedKey.startsWith(`${key}-`)}function localeCandidates(locale){const identity=localeIdentity(locale),normalized=identity.lookupKey;if(!normalized)return ENGLISH_ONLY_CANDIDATES;const cached=normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeCandidateCache.get(normalized):void 0;if(cached)return cached;const candidates=[];if((identity.wellFormed||identity.candidateBounded)&&candidates.push(normalized),identity.candidateBounded){for(let index=normalized.length-1;index>=0;index-=1)normalized.charCodeAt(index)===45&&index>0&&candidates.push(normalized.slice(0,index));const regionalBudget=Math.max(0,MAX_LOCALE_CANDIDATES-candidates.length-1);candidates.push(...regionalFallbacks(normalized,regionalBudget,identity.wellFormed))}else if(identity.wellFormed){const separator=normalized.indexOf("-");separator>0&&candidates.push(normalized.slice(0,separator))}const expanded=[],seen=new Set;for(const candidate of candidates){let current=candidate;for(;current&&!seen.has(current)&&expanded.length<MAX_LOCALE_CANDIDATES-1;)seen.add(current),expanded.push(current),current=localeParents.get(current)}seen.has("en")||expanded.push("en");const frozen=Object.freeze(expanded);return normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeCandidateCache,normalized,frozen),frozen}function lyraLocaleCatalogVersion(locale){return localeCandidates(locale).map(candidate=>localeCatalogRevisions.get(candidate)??0).join(",")}function getRegisteredLyraLocales(){const keys=new Set(["en",...localePublicTags.values()]);return Object.freeze([...keys].sort())}const NO_REGISTERED_LOCALE_KEYS=Object.freeze([]);function getRegisteredLyraLocaleKeys(locale){const identity=localeIdentity(locale);if(!identity.lookupKey)return NO_REGISTERED_LOCALE_KEYS;const catalog=locales.get(identity.lookupKey);return catalog?Object.freeze(Object.keys(catalog)):NO_REGISTERED_LOCALE_KEYS}function subscribeLyraLocaleRegistry(listener){return registryListeners.add(listener),()=>registryListeners.delete(listener)}const MAX_CATALOG_MESSAGES=4096,MAX_CATALOG_PROPERTY_READS=MAX_CATALOG_MESSAGES*2,MAX_MESSAGE_KEY_LENGTH=256,PLURAL_CATEGORIES=new Set(["zero","one","two","few","many","other"]),trustedMessageRecords=new WeakSet;function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return!descriptor||!("value"in descriptor)?{found:!1}:{found:!0,value:descriptor.value}}catch{return{found:!1}}}function snapshotPluralMessage(value){if(!isPlainRecord(value))return;const snapshot=Object.create(null);let count=0;try{for(const key in value){if(++count>PLURAL_CATEGORIES.size||!PLURAL_CATEGORIES.has(key)||!Object.prototype.hasOwnProperty.call(value,key))return;const entry=ownDataValue(value,key);if(!entry.found||typeof entry.value!="string")return;snapshot[key]=entry.value}}catch{return}if(typeof snapshot.other!="string")return;const frozen=Object.freeze(snapshot);return trustedMessageRecords.add(frozen),frozen}function snapshotMessage(value){return typeof value=="string"?value:snapshotPluralMessage(value)}function snapshotCatalog(strings){const snapshot=Object.create(null);if(!isPlainRecord(strings)){const frozen2=Object.freeze(snapshot);return trustedMessageRecords.add(frozen2),frozen2}let keys;try{keys=Reflect.ownKeys(strings).slice(0,MAX_CATALOG_PROPERTY_READS)}catch{const frozen2=Object.freeze(snapshot);return trustedMessageRecords.add(frozen2),frozen2}let count=0;for(const key of keys){if(count>=MAX_CATALOG_MESSAGES)break;if(typeof key!="string"||!key||key.length>MAX_MESSAGE_KEY_LENGTH)continue;let descriptor;try{descriptor=Reflect.getOwnPropertyDescriptor(strings,key)}catch{continue}if(!descriptor?.enumerable||!("value"in descriptor))continue;count+=1;const message=snapshotMessage(descriptor.value);message!==void 0&&(snapshot[key]=message)}const frozen=Object.freeze(snapshot);return trustedMessageRecords.add(frozen),frozen}function mergeCatalogs(current,incoming){const merged=Object.assign(Object.create(null),current??{},incoming);return Object.freeze(merged),trustedMessageRecords.add(merged),merged}function snapshotLocaleMeta(meta){if(meta===void 0)return;if(!isPlainRecord(meta))return Object.freeze({});const snapshot={},dir=ownDataValue(meta,"dir");dir.found&&(dir.value==="ltr"||dir.value==="rtl")&&(snapshot.dir=dir.value);const name=ownDataValue(meta,"name");return name.found&&typeof name.value=="string"&&(snapshot.name=name.value),Object.freeze(snapshot)}function snapshotLyraLocaleStrings(strings){return snapshotCatalog(strings)}let emptyLocaleStrings;function emptyLyraLocaleStrings(){return emptyLocaleStrings??=snapshotLyraLocaleStrings({})}const trustedDefaultCatalogs=new WeakMap;function trustedLyraDefaultStrings(defaults){const known=trustedDefaultCatalogs.get(defaults);if(known)return known;let trusted=defaults;if(isPlainRecord(defaults)&&!trustedMessageRecords.has(defaults))try{Reflect.ownKeys(defaults).length<=MAX_CATALOG_MESSAGES&&(trusted=snapshotCatalog(defaults))}catch{}return trustedDefaultCatalogs.set(defaults,trusted),trusted}function safeMessageAt(source,key){if(!isPlainRecord(source))return;if(trustedMessageRecords.has(source))return source[key];const entry=ownDataValue(source,key);return entry.found?snapshotMessage(entry.value):void 0}function deliverLocaleListeners(groups,operation){const errors=[];for(const group of groups)for(const listener of group)try{listener()}catch(error){errors.push(error)}if(errors.length>0)throw new AggregateError(errors,`${operation} committed, but ${errors.length} locale subscriber${errors.length===1?"":"s"} failed.`)}function localeUsesCatalog(locale,lookupKey){return localeCandidates(locale).includes(lookupKey)}function recordLyraOwnerDocumentConnection(host){ownerView(host)&&ownerDocumentsWithBrowsingContext.add(host.ownerDocument)}function forgetHostLocaleSubscription(subscription){hostLocaleListeners.delete(subscription),hostLocaleFinalizer.unregister(subscription)}function liveHostLocaleSubscriptions(){const live=[];for(const subscription of[...hostLocaleListeners]){const host=subscription.host.deref();if(!host||!host.isConnected||ownerDocumentsWithBrowsingContext.has(host.ownerDocument)&&ownerView(host)===null){forgetHostLocaleSubscription(subscription);continue}live.push({host})}return live}function registerLocale(locale,strings,meta,exactOnly,parentKey){const identity=storedLocaleIdentity(locale,!0),key=identity.lookupKey,incomingStrings=snapshotCatalog(strings),incomingMeta=snapshotLocaleMeta(meta);parentKey!==void 0&&validateLocaleParent(key,parentKey);const isNewLocale=!locales.has(key),candidateTopologyChanged=isNewLocale||parentKey!==void 0&&localeParents.get(key)!==parentKey||exactOnly&&!exactOnlyLocales.has(key)||identity.wellFormed&&!wellFormedLocales.has(key),previouslyAffectedActive=candidateTopologyChanged&&activeLocale!==""&&localeUsesCatalog(activeLocale,key),previouslyAffectedHosts=new Set(candidateTopologyChanged?liveHostLocaleSubscriptions().filter(({host})=>localeUsesCatalog(inheritedLocale(host),key)).map(({host})=>host):[]);exactOnly&&exactOnlyLocales.add(key),parentKey!==void 0&&localeParents.set(key,parentKey),identity.wellFormed&&wellFormedLocales.add(key),locales.set(key,mergeCatalogs(locales.get(key),incomingStrings)),localePublicTags.set(key,identity.publicTag),incomingMeta&&localeMeta.set(key,Object.freeze({...localeMeta.get(key)??{},...incomingMeta})),localeCatalogRevisions.set(key,++catalogRevision),candidateTopologyChanged&&(pluralLocaleCache.clear(),localeCandidateCache.clear());const activeSnapshot=previouslyAffectedActive||activeLocale&&localeUsesCatalog(activeLocale,key)?[...listeners]:[],hostSnapshot=liveHostLocaleSubscriptions().filter(({host})=>previouslyAffectedHosts.has(host)||localeUsesCatalog(inheritedLocale(host),key)).map(({host})=>()=>host.requestUpdate()),registrySnapshot=isNewLocale?[...registryListeners]:[];deliverLocaleListeners([activeSnapshot,hostSnapshot,registrySnapshot],`registerLyraLocale(${JSON.stringify(identity.publicTag)})`)}function registerLyraLocale(locale,strings,meta){registerLocale(locale,strings,meta,!1)}function validateLocaleParent(childKey,parentKey){for(const origin of new Set([childKey,...localeParents.keys()])){const visited=new Set;let current=origin,depth=0;for(;current;){if(visited.has(current))throw new TypeError("Locale parent relationships must not contain cycles.");if(visited.add(current),current=current===childKey?parentKey:localeParents.get(current),current&&++depth>MAX_LOCALE_PARENT_DEPTH)throw new TypeError("Locale parent chains must not exceed 32 edges.")}}}function registerLyraLocaleDelta(locale,parent,strings,meta){const parentKey=storedLocaleIdentity(parent,!0).lookupKey;registerLocale(locale,strings,meta,!0,parentKey)}function registerLyraExactLocale(locale,strings,meta){registerLocale(locale,strings,meta,!0)}function getLyraLocaleDirection(locale){const identity=localeIdentity(locale);if(!identity.publicTag)return"ltr";for(const candidate of localeCandidates(identity.publicTag)){const declared=localeMeta.get(candidate)?.dir;if(declared)return declared}try{const resolved=new Intl.Locale(identity.publicTag);return(resolved.textInfo?.direction??resolved.getTextInfo?.().direction)==="rtl"?"rtl":"ltr"}catch{return"ltr"}}function setLyraLocale(locale){const next=storedLocaleIdentity(locale,!1).publicTag;if(activeLocale===next)return;const hostSnapshot=liveHostLocaleSubscriptions(),previousHostLocales=hostSnapshot.map(({host})=>inheritedLocale(host));activeLocale=next;const affectedHostListeners=hostSnapshot.filter(({host},index)=>inheritedLocale(host)!==previousHostLocales[index]).map(({host})=>()=>host.requestUpdate());deliverLocaleListeners([[...listeners],affectedHostListeners],`setLyraLocale(${JSON.stringify(next)})`)}function getLyraLocale(){return activeLocale}function resolveActiveOrExplicitLocale(locale){const trimmed=locale?.trim();return trimmed&&trimmed.toLowerCase()!=="auto"?locale:activeLocale||void 0}function subscribeLyraLocale(listener){return listeners.add(listener),()=>listeners.delete(listener)}function subscribeLyraLocaleForHost(host){recordLyraOwnerDocumentConnection(host);const subscription={host:new WeakRef(host)};return hostLocaleListeners.add(subscription),hostLocaleFinalizer.register(host,subscription,subscription),()=>forgetHostLocaleSubscription(subscription)}function inheritedLocale(host,localeAttribute=host.getAttribute("locale")){const explicit=localeAttribute||host.getAttribute("lang");if(explicit)return canonicalizeLyraLocale(explicit);if(host.getAttribute("lang")==="")return activeLocale||"en";const documentElement=host.ownerDocument?.documentElement;let parent=domParentElement(host);for(;parent;){const isDocumentElement=parent===documentElement,locale=isDocumentElement?parent.getAttribute("locale"):parent.getAttribute("locale")||parent.getAttribute("lang");if(locale)return canonicalizeLyraLocale(locale);if(!isDocumentElement&&parent.getAttribute("lang")==="")return activeLocale||"en";parent=domParentElement(parent)}if(activeLocale)return activeLocale;const documentLocale=documentElement?.getAttribute("lang");return documentLocale?canonicalizeLyraLocale(documentLocale):"en"}const hostContextCaches=new WeakMap;function enableLyraLocaleCache(host){hostContextCaches.has(host)||hostContextCaches.set(host,{})}function invalidateLyraLocaleCache(host){const cache=hostContextCaches.get(host);cache&&(cache.attribute=void 0,cache.locale=void 0,cache.direction=void 0)}function resolveLyraLocale(host){return cachedLocale(host,host.getAttribute("locale")||"")}function cachedLocale(host,localeAttribute){const cache=hostContextCaches.get(host);if(!cache)return inheritedLocale(host,localeAttribute);let locale=cache.locale;return(locale===void 0||cache.attribute!==localeAttribute)&&(locale=inheritedLocale(host,localeAttribute),cache.attribute=localeAttribute,cache.locale=locale),locale}function resolveLyraLocaleWithHostOverride(host,localeOverride){return localeOverride?canonicalizeLyraLocale(localeOverride):cachedLocale(host,localeOverride)}function inheritedDirection(host){const explicit=host.getAttribute("dir")?.toLowerCase();if(explicit==="rtl"||explicit==="ltr")return explicit;const view=ownerView(host);if(view)try{const getComputedStyle=view.getComputedStyle;if(typeof getComputedStyle=="function"){const computed=getComputedStyle.call(view,host).direction;if(computed==="rtl"||computed==="ltr")return computed}}catch{}let parent=flattenedParentElement(host);for(;parent;){const inherited=parent.getAttribute("dir")?.toLowerCase();if(inherited==="rtl"||inherited==="ltr")return inherited;parent=flattenedParentElement(parent)}return"ltr"}function resolveLyraDirection(host){const cache=hostContextCaches.get(host);if(!cache)return inheritedDirection(host);let direction=cache.direction;return direction===void 0&&(direction=inheritedDirection(host),cache.direction=direction),direction}function peekLyraLocale(host){return hostContextCaches.get(host)?.locale}function peekLyraDirection(host){return hostContextCaches.get(host)?.direction}const PLURAL_CATEGORY_FALLBACKS={zero:["zero","other"],one:["one","other"],two:["two","few","many","other"],few:["few","many","other"],many:["many","few","other"],other:["other"]};function pluralSelector(values){let raw;try{raw=values.pluralCount??values.count}catch{return}return typeof raw=="number"&&Number.isFinite(raw)?raw:void 0}const pluralLocaleCache=new Map,MAX_PLURAL_LOCALE_ENTRIES=64;function pluralLocale(locale){const cached=pluralLocaleCache.get(locale);if(cached!==void 0)return cached;const resolved=localeCandidates(locale)[0];return pluralLocaleCache.size>=MAX_PLURAL_LOCALE_ENTRIES&&pluralLocaleCache.clear(),pluralLocaleCache.set(locale,resolved),resolved}function selectPluralMessage(message,locale,count){if(count===void 0)return message.other;const tag=pluralLocale(locale),category=getPluralRules(tag).select(count);for(const candidate of PLURAL_CATEGORY_FALLBACKS[category]??PLURAL_CATEGORY_FALLBACKS.other){const text=message[candidate];if(text!==void 0)return text}return message.other}function resolveLyraString(host,key,overrides,fallback,values,defaults){return resolveLyraStringWithLocale(()=>resolveLyraLocale(host),key,overrides,fallback,values,defaults)}function resolveLyraStringWithLocale(resolveLocale,key,overrides,fallback,values,defaults){let message=safeMessageAt(overrides,key);message===void 0&&typeof fallback=="string"&&(message=fallback);let locale;if(message===void 0){locale=resolveLocale();for(const candidate of localeCandidates(locale)){const registered=safeMessageAt(locales.get(candidate),key);if(registered!==void 0){message=registered;break}}message===void 0&&warnLocaleFallback(locale,key)}message??=safeMessageAt(defaults,key)??key;let text;return typeof message!="string"?(locale??=resolveLocale(),text=selectPluralMessage(message,locale,values?pluralSelector(values):void 0)):text=message,values?text.replace(/\{(\w+)\}/g,(match,name)=>{try{const value=values[name];return typeof value=="string"||typeof value=="number"?String(value):match}catch{return match}}):text}function resolveLocalizedParts(template,interpolate){const privateUse=new Set;for(let index=0;index<template.length;index+=1){const code=template.charCodeAt(index);code>=57344&&code<=63743&&privateUse.add(code)}let marker="";for(let code=57344;code<=63743;code+=1)if(!privateUse.has(code)){marker=String.fromCharCode(code);break}if(!marker){const counts=new Uint32Array(65536);for(let index=0;index<template.length;index+=1){const code=template.charCodeAt(index);counts[code]=(counts[code]??0)+1}let leastCode=0,leastCount=Number.POSITIVE_INFINITY;for(let code=0;code<counts.length;code+=1){const count=counts[code]??0;if(count===0){marker=String.fromCharCode(code);break}count<leastCount&&(leastCode=code,leastCount=count)}if(!marker){const followers=new Uint8Array(65536);for(let index=0;index+1<template.length;index+=1)template.charCodeAt(index)===leastCode&&(followers[template.charCodeAt(index+1)]=1);let follower=0;for(;follower<followers.length&&followers[follower]!==0;)follower+=1;marker=String.fromCharCode(leastCode,follower<followers.length?follower:leastCode)}}return interpolate(marker).split(marker)}export{canonicalizeLyraLocale,emptyLyraLocaleStrings,enableLyraLocaleCache,getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocaleKeys,getRegisteredLyraLocales,invalidateLyraLocaleCache,lyraLocaleCatalogVersion,peekLyraDirection,peekLyraLocale,recordLyraOwnerDocumentConnection,registerLyraExactLocale,registerLyraLocale,registerLyraLocaleDelta,resolveActiveOrExplicitLocale,resolveLocalizedParts,resolveLyraDirection,resolveLyraLocale,resolveLyraLocaleWithHostOverride,resolveLyraString,resolveLyraStringWithLocale,setLyraLocale,snapshotLyraLocaleStrings,subscribeLyraLocale,subscribeLyraLocaleForHost,subscribeLyraLocaleRegistry,trustedLyraDefaultStrings};
|
|
1
|
+
import{canonicalizeLocaleTag}from"./locale-tag.js";import{warnLocaleFallback}from"./dev-warning.js";import{domParentElement,flattenedParentElement,ownerView}from"./composed-tree.js";import{getPluralRules}from"./intl-cache.js";import{isPlainRecord}from"./object-guards.js";const MAX_LOCALE_CANDIDATES=64,MAX_LOCALE_PARENT_DEPTH=32,MAX_LOCALE_SUBTAGS=32,MAX_LOCALE_TAG_LENGTH=255,MAX_LOCALE_CACHE_ENTRIES=128,MAX_CACHEABLE_LOCALE_LENGTH=512,LEGACY_LOCALE_PATTERN=/^[a-z0-9]{1,32}(?:-[a-z0-9]{1,32})*$/,locales=new Map,localePublicTags=new Map,localeMeta=new Map,localeParents=new Map,wellFormedLocales=new Set,exactOnlyLocales=new Set,localeCatalogRevisions=new Map,listeners=new Set,hostLocaleListeners=new Set,hostLocaleFinalizer=new FinalizationRegistry(subscription=>{hostLocaleListeners.delete(subscription)}),ownerDocumentsWithBrowsingContext=new WeakSet,registryListeners=new Set;let activeLocale="",catalogRevision=0;const localeIdentityCache=new Map,EMPTY_LOCALE_IDENTITY=Object.freeze({publicTag:"",lookupKey:"",wellFormed:!1,candidateBounded:!0,storable:!1}),localeCandidateCache=new Map,ENGLISH_ONLY_CANDIDATES=Object.freeze(["en"]);function cacheBounded(cache,key,value){cache.size>=MAX_LOCALE_CACHE_ENTRIES&&cache.clear(),cache.set(key,value)}function subtagCountWithinBounds(tag){if(tag.length>MAX_LOCALE_TAG_LENGTH)return!1;let count=tag?1:0;for(let index=0;index<tag.length;index+=1)if(tag.charCodeAt(index)===45&&++count>MAX_LOCALE_SUBTAGS)return!1;return!0}function localeIdentity(locale){const known=typeof locale=="string"&&locale.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeIdentityCache.get(locale):void 0;if(known)return known;const normalized=typeof locale=="string"?locale.trim().replace(/_/g,"-"):"";if(!normalized)return EMPTY_LOCALE_IDENTITY;const cached=normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeIdentityCache.get(normalized):void 0;if(cached)return rememberLocaleSpelling(locale,normalized,cached),cached;let publicTag=normalized.toLowerCase(),wellFormed=!1;try{const canonical=canonicalizeLocaleTag(normalized);canonical&&(publicTag=canonical,wellFormed=!0)}catch{}const lookupKey=publicTag.toLowerCase(),candidateBounded=subtagCountWithinBounds(lookupKey),identity={publicTag,lookupKey,wellFormed,candidateBounded,storable:wellFormed||candidateBounded&&LEGACY_LOCALE_PATTERN.test(lookupKey)};return normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeIdentityCache,normalized,identity),rememberLocaleSpelling(locale,normalized,identity),identity}function rememberLocaleSpelling(locale,normalized,identity){locale!==normalized&&locale.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeIdentityCache,locale,identity)}function storedLocaleIdentity(locale,required){if(typeof locale!="string")throw new TypeError("A locale must be a string.");const identity=localeIdentity(locale);if(!identity.publicTag){if(!required)return identity;throw new TypeError("A locale is required.")}if(!identity.storable)throw new TypeError("The locale must be BCP-47 or a bounded alphanumeric custom tag.");return identity}function canonicalizeLyraLocale(locale){const identity=localeIdentity(locale);return identity.storable?identity.publicTag:"en"}const likelySubtagsCache=new Map;function likelySubtags(key){let likely=likelySubtagsCache.get(key);if(!likely){try{const{script="",region=""}=new Intl.Locale(key).maximize();likely=[script==="Zzzz"?"":script.toLowerCase(),region.toLowerCase()]}catch{return["",""]}key.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(likelySubtagsCache,key,likely)}return likely}function regionalFallbacks(requestedKey,limit,wellFormed){if(limit<=0||!wellFormed)return[];const separator=requestedKey.indexOf("-"),language=separator===-1?requestedKey:requestedKey.slice(0,separator);if(!language)return[];const requestedSubtags=new Set(requestedKey.split("-")),siblings=[...locales.keys()].filter(key=>wellFormedLocales.has(key)&&!exactOnlyLocales.has(key)&&(key===language||key.startsWith(`${language}-`))&&!isPrefixOf(key,requestedKey));if(siblings.length<2)return siblings;const[script,region]=likelySubtags(requestedKey),rank=key=>{const[keyScript,keyRegion]=likelySubtags(key);return(script&&keyScript===script?1e4:0)+(region&&keyRegion===region?1e3:0)+key.split("-").filter(subtag=>requestedSubtags.has(subtag)).length};return siblings.map(key=>[rank(key),key]).sort(([a,x],[b,y])=>b-a||(x<y?-1:x>y?1:0)).slice(0,limit).map(([,key])=>key)}function isPrefixOf(key,requestedKey){return key===requestedKey||requestedKey.startsWith(`${key}-`)}function localeCandidates(locale){const identity=localeIdentity(locale),normalized=identity.lookupKey;if(!normalized)return ENGLISH_ONLY_CANDIDATES;const cached=normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH?localeCandidateCache.get(normalized):void 0;if(cached)return cached;const candidates=[];if((identity.wellFormed||identity.candidateBounded)&&candidates.push(normalized),identity.candidateBounded){for(let index=normalized.length-1;index>=0;index-=1)normalized.charCodeAt(index)===45&&index>0&&candidates.push(normalized.slice(0,index));const regionalBudget=Math.max(0,MAX_LOCALE_CANDIDATES-candidates.length-1);candidates.push(...regionalFallbacks(normalized,regionalBudget,identity.wellFormed))}else if(identity.wellFormed){const separator=normalized.indexOf("-");separator>0&&candidates.push(normalized.slice(0,separator))}const expanded=[],seen=new Set;for(const candidate of candidates){let current=candidate;for(;current&&!seen.has(current)&&expanded.length<MAX_LOCALE_CANDIDATES-1;)seen.add(current),expanded.push(current),current=localeParents.get(current)}seen.has("en")||expanded.push("en");const frozen=Object.freeze(expanded);return normalized.length<=MAX_CACHEABLE_LOCALE_LENGTH&&cacheBounded(localeCandidateCache,normalized,frozen),frozen}function lyraLocaleCatalogVersion(locale){return localeCandidates(locale).map(candidate=>localeCatalogRevisions.get(candidate)??0).join(",")}function getRegisteredLyraLocales(){const keys=new Set(["en",...localePublicTags.values()]);return Object.freeze([...keys].sort())}const NO_REGISTERED_LOCALE_KEYS=Object.freeze([]);function getRegisteredLyraLocaleKeys(locale){const identity=localeIdentity(locale);if(!identity.lookupKey)return NO_REGISTERED_LOCALE_KEYS;const catalog=locales.get(identity.lookupKey);return catalog?Object.freeze(Object.keys(catalog)):NO_REGISTERED_LOCALE_KEYS}function subscribeLyraLocaleRegistry(listener){return registryListeners.add(listener),()=>registryListeners.delete(listener)}const MAX_CATALOG_MESSAGES=4096,MAX_CATALOG_PROPERTY_READS=MAX_CATALOG_MESSAGES*2,MAX_MESSAGE_KEY_LENGTH=256,PLURAL_CATEGORIES=new Set(["zero","one","two","few","many","other"]),trustedMessageRecords=new WeakSet;function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function snapshotPluralMessage(value){if(!isPlainRecord(value))return;const snapshot=Object.create(null);let count=0;try{for(const key in value){if(++count>PLURAL_CATEGORIES.size||!PLURAL_CATEGORIES.has(key)||!Object.prototype.hasOwnProperty.call(value,key))return;const entry=ownDataValue(value,key);if(typeof entry!="string")return;snapshot[key]=entry}}catch{return}if(typeof snapshot.other!="string")return;const frozen=Object.freeze(snapshot);return trustedMessageRecords.add(frozen),frozen}function snapshotMessage(value){return typeof value=="string"?value:snapshotPluralMessage(value)}function snapshotCatalog(strings){const snapshot=Object.create(null);if(!isPlainRecord(strings)){const frozen2=Object.freeze(snapshot);return trustedMessageRecords.add(frozen2),frozen2}let keys;try{keys=Reflect.ownKeys(strings).slice(0,MAX_CATALOG_PROPERTY_READS)}catch{const frozen2=Object.freeze(snapshot);return trustedMessageRecords.add(frozen2),frozen2}let count=0;for(const key of keys){if(count>=MAX_CATALOG_MESSAGES)break;if(typeof key!="string"||!key||key.length>MAX_MESSAGE_KEY_LENGTH)continue;let descriptor;try{descriptor=Reflect.getOwnPropertyDescriptor(strings,key)}catch{continue}if(!descriptor?.enumerable||!("value"in descriptor))continue;count+=1;const message=snapshotMessage(descriptor.value);message!==void 0&&(snapshot[key]=message)}const frozen=Object.freeze(snapshot);return trustedMessageRecords.add(frozen),frozen}function mergeCatalogs(current,incoming){const merged=Object.assign(Object.create(null),current??{},incoming);return Object.freeze(merged),trustedMessageRecords.add(merged),merged}function snapshotLocaleMeta(meta){if(meta===void 0)return;if(!isPlainRecord(meta))return Object.freeze({});const snapshot={},dir=ownDataValue(meta,"dir");(dir==="ltr"||dir==="rtl")&&(snapshot.dir=dir);const name=ownDataValue(meta,"name");return typeof name=="string"&&(snapshot.name=name),Object.freeze(snapshot)}function snapshotLyraLocaleStrings(strings){return snapshotCatalog(strings)}let emptyLocaleStrings;function emptyLyraLocaleStrings(){return emptyLocaleStrings??=snapshotLyraLocaleStrings({})}const trustedDefaultCatalogs=new WeakMap;function trustedLyraDefaultStrings(defaults){const known=trustedDefaultCatalogs.get(defaults);if(known)return known;let trusted=defaults;if(isPlainRecord(defaults)&&!trustedMessageRecords.has(defaults))try{Reflect.ownKeys(defaults).length<=MAX_CATALOG_MESSAGES&&(trusted=snapshotCatalog(defaults))}catch{}return trustedDefaultCatalogs.set(defaults,trusted),trusted}function safeMessageAt(source,key){if(isPlainRecord(source))return trustedMessageRecords.has(source)?source[key]:snapshotMessage(ownDataValue(source,key))}function deliverLocaleListeners(groups,operation){const errors=[];for(const group of groups)for(const listener of group)try{listener()}catch(error){errors.push(error)}if(errors.length>0)throw new AggregateError(errors,`${operation} committed, but ${errors.length} locale subscriber${errors.length===1?"":"s"} failed.`)}function localeUsesCatalog(locale,lookupKey){return localeCandidates(locale).includes(lookupKey)}function recordLyraOwnerDocumentConnection(host){ownerView(host)&&ownerDocumentsWithBrowsingContext.add(host.ownerDocument)}function forgetHostLocaleSubscription(subscription){hostLocaleListeners.delete(subscription),hostLocaleFinalizer.unregister(subscription)}function liveHostLocaleSubscriptions(){const live=[];for(const subscription of[...hostLocaleListeners]){const host=subscription.deref();if(!host||!host.isConnected||ownerDocumentsWithBrowsingContext.has(host.ownerDocument)&&ownerView(host)===null){forgetHostLocaleSubscription(subscription);continue}live.push(host)}return live}function registerLocale(locale,strings,meta,exactOnly,parentKey){const identity=storedLocaleIdentity(locale,!0),key=identity.lookupKey,incomingStrings=snapshotCatalog(strings),incomingMeta=snapshotLocaleMeta(meta);parentKey!==void 0&&validateLocaleParent(key,parentKey);const isNewLocale=!locales.has(key),candidateTopologyChanged=isNewLocale||parentKey!==void 0&&localeParents.get(key)!==parentKey||exactOnly&&!exactOnlyLocales.has(key)||identity.wellFormed&&!wellFormedLocales.has(key),previouslyAffectedActive=candidateTopologyChanged&&activeLocale!==""&&localeUsesCatalog(activeLocale,key),previouslyAffectedHosts=new Set(candidateTopologyChanged?liveHostLocaleSubscriptions().filter(host=>localeUsesCatalog(inheritedLocale(host),key)):[]);exactOnly&&exactOnlyLocales.add(key),parentKey!==void 0&&localeParents.set(key,parentKey),identity.wellFormed&&wellFormedLocales.add(key),locales.set(key,mergeCatalogs(locales.get(key),incomingStrings)),localePublicTags.set(key,identity.publicTag),incomingMeta&&localeMeta.set(key,Object.freeze({...localeMeta.get(key)??{},...incomingMeta})),localeCatalogRevisions.set(key,++catalogRevision),candidateTopologyChanged&&(pluralLocaleCache.clear(),localeCandidateCache.clear());const activeSnapshot=previouslyAffectedActive||activeLocale&&localeUsesCatalog(activeLocale,key)?[...listeners]:[],hostSnapshot=liveHostLocaleSubscriptions().filter(host=>previouslyAffectedHosts.has(host)||localeUsesCatalog(inheritedLocale(host),key)).map(host=>()=>host.requestUpdate()),registrySnapshot=isNewLocale?[...registryListeners]:[];deliverLocaleListeners([activeSnapshot,hostSnapshot,registrySnapshot],`registerLyraLocale(${JSON.stringify(identity.publicTag)})`)}function registerLyraLocale(locale,strings,meta){registerLocale(locale,strings,meta,!1)}function validateLocaleParent(childKey,parentKey){for(const origin of new Set([childKey,...localeParents.keys()])){const visited=new Set;let current=origin,depth=0;for(;current;){if(visited.has(current))throw new TypeError("Locale parent relationships must not contain cycles.");if(visited.add(current),current=current===childKey?parentKey:localeParents.get(current),current&&++depth>MAX_LOCALE_PARENT_DEPTH)throw new TypeError("Locale parent chains must not exceed 32 edges.")}}}function registerLyraLocaleDelta(locale,parent,strings,meta){const parentKey=storedLocaleIdentity(parent,!0).lookupKey;registerLocale(locale,strings,meta,!0,parentKey)}function registerLyraExactLocale(locale,strings,meta){registerLocale(locale,strings,meta,!0)}function getLyraLocaleDirection(locale){const identity=localeIdentity(locale);if(!identity.publicTag)return"ltr";for(const candidate of localeCandidates(identity.publicTag)){const declared=localeMeta.get(candidate)?.dir;if(declared)return declared}try{const resolved=new Intl.Locale(identity.publicTag);return(resolved.textInfo?.direction??resolved.getTextInfo?.().direction)==="rtl"?"rtl":"ltr"}catch{return"ltr"}}function setLyraLocale(locale){const next=storedLocaleIdentity(locale,!1).publicTag;if(activeLocale===next)return;const hostSnapshot=liveHostLocaleSubscriptions(),previousHostLocales=hostSnapshot.map(host=>inheritedLocale(host));activeLocale=next;const affectedHostListeners=hostSnapshot.filter((host,index)=>inheritedLocale(host)!==previousHostLocales[index]).map(host=>()=>host.requestUpdate());deliverLocaleListeners([[...listeners],affectedHostListeners],`setLyraLocale(${JSON.stringify(next)})`)}function getLyraLocale(){return activeLocale}function resolveActiveOrExplicitLocale(locale){const trimmed=locale?.trim();return trimmed&&trimmed.toLowerCase()!=="auto"?locale:activeLocale||void 0}function subscribeLyraLocale(listener){return listeners.add(listener),()=>listeners.delete(listener)}function subscribeLyraLocaleForHost(host){recordLyraOwnerDocumentConnection(host);const subscription=new WeakRef(host);return hostLocaleListeners.add(subscription),hostLocaleFinalizer.register(host,subscription,subscription),()=>forgetHostLocaleSubscription(subscription)}function inheritedLocale(host,localeAttribute=host.getAttribute("locale")){const explicit=localeAttribute||host.getAttribute("lang");if(explicit)return canonicalizeLyraLocale(explicit);if(host.getAttribute("lang")==="")return activeLocale||"en";const documentElement=host.ownerDocument?.documentElement;let parent=domParentElement(host);for(;parent;){const isDocumentElement=parent===documentElement,locale=isDocumentElement?parent.getAttribute("locale"):parent.getAttribute("locale")||parent.getAttribute("lang");if(locale)return canonicalizeLyraLocale(locale);if(!isDocumentElement&&parent.getAttribute("lang")==="")return activeLocale||"en";parent=domParentElement(parent)}if(activeLocale)return activeLocale;const documentLocale=documentElement?.getAttribute("lang");return documentLocale?canonicalizeLyraLocale(documentLocale):"en"}const hostContextCaches=new WeakMap;function enableLyraLocaleCache(host){hostContextCaches.has(host)||hostContextCaches.set(host,{})}function invalidateLyraLocaleCache(host){const cache=hostContextCaches.get(host);cache&&(cache.attribute=void 0,cache.locale=void 0,cache.direction=void 0)}function resolveLyraLocale(host){return cachedLocale(host,host.getAttribute("locale")||"")}function cachedLocale(host,localeAttribute){const cache=hostContextCaches.get(host);if(!cache)return inheritedLocale(host,localeAttribute);let locale=cache.locale;return(locale===void 0||cache.attribute!==localeAttribute)&&(locale=inheritedLocale(host,localeAttribute),cache.attribute=localeAttribute,cache.locale=locale),locale}function resolveLyraLocaleWithHostOverride(host,localeOverride){return localeOverride?canonicalizeLyraLocale(localeOverride):cachedLocale(host,localeOverride)}function inheritedDirection(host){const explicit=host.getAttribute("dir")?.toLowerCase();if(explicit==="rtl"||explicit==="ltr")return explicit;const view=ownerView(host);if(view)try{const getComputedStyle=view.getComputedStyle;if(typeof getComputedStyle=="function"){const computed=getComputedStyle.call(view,host).direction;if(computed==="rtl"||computed==="ltr")return computed}}catch{}let parent=flattenedParentElement(host);for(;parent;){const inherited=parent.getAttribute("dir")?.toLowerCase();if(inherited==="rtl"||inherited==="ltr")return inherited;parent=flattenedParentElement(parent)}return"ltr"}function resolveLyraDirection(host){const cache=hostContextCaches.get(host);if(!cache)return inheritedDirection(host);let direction=cache.direction;return direction===void 0&&(direction=inheritedDirection(host),cache.direction=direction),direction}function peekLyraLocale(host){return hostContextCaches.get(host)?.locale}function peekLyraDirection(host){return hostContextCaches.get(host)?.direction}const PLURAL_CATEGORY_FALLBACKS={zero:["zero","other"],one:["one","other"],two:["two","few","many","other"],few:["few","many","other"],many:["many","few","other"],other:["other"]};function pluralSelector(values){let raw;try{raw=values.pluralCount??values.count}catch{return}return typeof raw=="number"&&Number.isFinite(raw)?raw:void 0}const pluralLocaleCache=new Map,MAX_PLURAL_LOCALE_ENTRIES=64;function pluralLocale(locale){const cached=pluralLocaleCache.get(locale);if(cached!==void 0)return cached;const resolved=localeCandidates(locale)[0];return pluralLocaleCache.size>=MAX_PLURAL_LOCALE_ENTRIES&&pluralLocaleCache.clear(),pluralLocaleCache.set(locale,resolved),resolved}function selectPluralMessage(message,locale,count){if(count===void 0)return message.other;const tag=pluralLocale(locale),category=getPluralRules(tag).select(count);for(const candidate of PLURAL_CATEGORY_FALLBACKS[category]??PLURAL_CATEGORY_FALLBACKS.other){const text=message[candidate];if(text!==void 0)return text}return message.other}function resolveLyraString(host,key,overrides,fallback,values,defaults){return resolveLyraStringWithLocale(()=>resolveLyraLocale(host),key,overrides,fallback,values,defaults)}function resolveLyraStringWithLocale(resolveLocale,key,overrides,fallback,values,defaults){let message=safeMessageAt(overrides,key);message===void 0&&typeof fallback=="string"&&(message=fallback);let locale;if(message===void 0){locale=resolveLocale();for(const candidate of localeCandidates(locale)){const registered=safeMessageAt(locales.get(candidate),key);if(registered!==void 0){message=registered;break}}message===void 0&&warnLocaleFallback(locale,key)}message??=safeMessageAt(defaults,key)??key;let text;return typeof message!="string"?(locale??=resolveLocale(),text=selectPluralMessage(message,locale,values?pluralSelector(values):void 0)):text=message,values?text.replace(/\{(\w+)\}/g,(match,name)=>{try{const value=values[name];return typeof value=="string"||typeof value=="number"?String(value):match}catch{return match}}):text}function resolveLocalizedParts(template,interpolate){const privateUse=new Set;for(let index=0;index<template.length;index+=1){const code=template.charCodeAt(index);code>=57344&&code<=63743&&privateUse.add(code)}let marker="";for(let code=57344;code<=63743;code+=1)if(!privateUse.has(code)){marker=String.fromCharCode(code);break}if(!marker){const counts=new Uint32Array(65536);for(let index=0;index<template.length;index+=1){const code=template.charCodeAt(index);counts[code]=(counts[code]??0)+1}let leastCode=0,leastCount=Number.POSITIVE_INFINITY;for(let code=0;code<counts.length;code+=1){const count=counts[code]??0;if(count===0){marker=String.fromCharCode(code);break}count<leastCount&&(leastCode=code,leastCount=count)}if(!marker){const followers=new Uint8Array(65536);for(let index=0;index+1<template.length;index+=1)template.charCodeAt(index)===leastCode&&(followers[template.charCodeAt(index+1)]=1);let follower=0;for(;follower<followers.length&&followers[follower]!==0;)follower+=1;marker=String.fromCharCode(leastCode,follower<followers.length?follower:leastCode)}}return interpolate(marker).split(marker)}export{canonicalizeLyraLocale,emptyLyraLocaleStrings,enableLyraLocaleCache,getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocaleKeys,getRegisteredLyraLocales,invalidateLyraLocaleCache,lyraLocaleCatalogVersion,peekLyraDirection,peekLyraLocale,recordLyraOwnerDocumentConnection,registerLyraExactLocale,registerLyraLocale,registerLyraLocaleDelta,resolveActiveOrExplicitLocale,resolveLocalizedParts,resolveLyraDirection,resolveLyraLocale,resolveLyraLocaleWithHostOverride,resolveLyraString,resolveLyraStringWithLocale,setLyraLocale,snapshotLyraLocaleStrings,subscribeLyraLocale,subscribeLyraLocaleForHost,subscribeLyraLocaleRegistry,trustedLyraDefaultStrings};
|