@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,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,writeNormalizedOwnedCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourcePickerMatches,LYRA_DEFAULT_sourcePickerSelection}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.withoutSelectAll=!1,this.withoutSearch=!1,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerMatches:LYRA_DEFAULT_sourcePickerMatches,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-sources-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}isFiltering(){return!this.withoutSearch&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering){const locale=this.effectiveLocale,query=this.query.trim().toLocaleLowerCase(locale);for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(node.entry.label.toLocaleLowerCase(locale).includes(query)||node.children.some(child=>matches.has(child)))&&matches.add(node)}}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");writeNormalizedOwnedCollection(this,"selectedSourceIds",()=>{this.selectedSourceIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("withoutSearch"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(shadowFocusTarget(this)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||this.withoutSearch?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const locale=this.effectiveLocale,query=this.query.trim().toLocaleLowerCase(locale),count=this.visibleRows().filter(row=>row.entry.label.toLocaleLowerCase(locale).includes(query)).length,signature=`${query}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,this.announcementSink?.announce(count===0?this.localize("noMatches"):this.localize("sourcePickerMatches",void 0,{count:getNumberFormat(locale).format(count),pluralCount:count})))}reportSelection(selectedSourceIds){this.emit("lr-selection-change",{selectedSourceIds}),this.emit("lr-sources-change",{selectedSourceIds})}commitSelection(next){this.selectedSourceIds=next,this.reportSelection(next)}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}selectAllTargets(rows){return this.isFiltering()?rows.filter(row=>!row.hasChildren).map(row=>row.entry.id):this.allLeafIds()}toggleSelectAll(){const targets=this.selectAllTargets(this.visibleRows());if(!targets.length)return;const selected=new Set(this.normalizedSelectedSourceIds()),allSelected=targets.every(id=>selected.has(id));for(const id of targets)allSelected?selected.delete(id):selected.add(id);this.commitSelection([...selected])}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,writeNormalizedOwnedCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourcePickerMatches,LYRA_DEFAULT_sourcePickerSelection}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.withoutSelectAll=!1,this.withoutSearch=!1,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerMatches:LYRA_DEFAULT_sourcePickerMatches,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}isFiltering(){return!this.withoutSearch&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering){const locale=this.effectiveLocale,query=this.query.trim().toLocaleLowerCase(locale);for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(node.entry.label.toLocaleLowerCase(locale).includes(query)||node.children.some(child=>matches.has(child)))&&matches.add(node)}}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");writeNormalizedOwnedCollection(this,"selectedSourceIds",()=>{this.selectedSourceIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("withoutSearch"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(shadowFocusTarget(this)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||this.withoutSearch?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const locale=this.effectiveLocale,query=this.query.trim().toLocaleLowerCase(locale),count=this.visibleRows().filter(row=>row.entry.label.toLocaleLowerCase(locale).includes(query)).length,signature=`${query}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,this.announcementSink?.announce(count===0?this.localize("noMatches"):this.localize("sourcePickerMatches",void 0,{count:getNumberFormat(locale).format(count),pluralCount:count})))}reportSelection(selectedSourceIds){this.emit("lr-selection-change",{selectedSourceIds})}commitSelection(next){this.selectedSourceIds=next,this.reportSelection(next)}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}selectAllTargets(rows){return this.isFiltering()?rows.filter(row=>!row.hasChildren).map(row=>row.entry.id):this.allLeafIds()}toggleSelectAll(){const targets=this.selectAllTargets(this.visibleRows());if(!targets.length)return;const selected=new Set(this.normalizedSelectedSourceIds()),allSelected=targets.every(id=>selected.has(id));for(const id of targets)allSelected?selected.delete(id):selected.add(id);this.commitSelection([...selected])}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
|
|
2
2
|
<div
|
|
3
3
|
part="item"
|
|
4
4
|
role="treeitem"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++){if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({opIndex:index})}if(!budget.complete){matchCountExact=!1;break}}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
|
|
1
|
+
import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++)if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)&&matches.push({opIndex:index}),!budget.complete){matchCountExact=!1;break}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
|
|
2
2
|
`)}isCurrentCopy(generation,owner){return this.isConnected&&this.copyable&&!this.diffTooLarge&&generation===this.copyGeneration&&this.ownerDocument.defaultView===owner}showCopyStatus(status,generation){const owner=this.ownerDocument.defaultView;if(!owner||!this.isCurrentCopy(generation,owner))return;this.copyStatus=status,this.copyAnnouncementSink?.announce(status==="success"?this.localize("copied"):this.localize("copyFailed")),this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||!this.isCurrentCopy(generation,owner)||(this.copyTimer=void 0,this.copyStatus="rest")},COPY_CONFIRM_MS),this.copyTimer={owner,handle,generation}}async copy(){if(!this.copyable||this.diffTooLarge)return;const generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyStatus="rest";const text=this.unifiedText,owner=this.isConnected?this.ownerDocument.defaultView:null;if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.showCopyStatus("error",generation),this.emit("lr-error"),this.emit("lr-copy-error",outcome);return}this.showCopyStatus("success",generation),this.emit("lr-copy",outcome)}}lineRenderContext(){const{perOp,owners,order,total}=this.resolvedHighlightOps();return{perOp,owners,order,total,matchedOpIndexes:new Set(this.searchMatches.map(match=>match.opIndex)),activeMatchOpIndex:this.searchMatches[this.searchActiveIndex]?.opIndex??-1}}renderDiffLine(op,marker,content,context){const index=this.opIndexMap.get(op),isMatch=index!==void 0&&context.matchedOpIndexes.has(index),isActiveMatch=index!==void 0&&index===context.activeMatchOpIndex,highlight=context.perOp.get(op),owner=highlight&&context.owners.get(highlight)===op?highlight:void 0,ownerLabel=owner?this.highlightActionLabel(owner,context.order.get(owner)??0,context.total):"",text=html`${marker} ${content}`;return html`<div
|
|
3
3
|
part="line"
|
|
4
4
|
data-type=${op.type}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{finiteInteger,finiteRange}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";const NUMBER_TYPES=["currency","decimal","percent"],NUMBER_NOTATIONS=["standard","compact","scientific","engineering"],CURRENCY_DISPLAYS=["symbol","narrowSymbol","code","name"],DISPLAY_STYLES=["long","short","narrow"],BYTE_UNITS=["byte","kilobyte","megabyte","gigabyte","terabyte","petabyte"],BIT_UNITS=["bit","kilobit","megabit","gigabit","terabit","petabit"],DATE_STYLES=["full","long","medium","short"],DATE_TEXT_STYLES=["narrow","short","long"],DATE_NUMERIC_STYLES=["numeric","2-digit"],MONTH_STYLES=["numeric","2-digit","narrow","short","long"],TIME_ZONE_NAME_STYLES=["short","long"],HOUR_FORMATS=["auto","12","24"],NUMERIC_DATE_SOURCE=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,dateSourceConverter={fromAttribute(value){const source=value??"",normalized=source.trim();if(NUMERIC_DATE_SOURCE.test(normalized)){const epoch=Number(normalized);if(Number.isFinite(epoch))return epoch}return source}};function closedValue(value,values,fallback){return typeof value=="string"&&values.includes(value)?value:fallback}function optionalClosedValue(value,values){return typeof value=="string"&&values.includes(value)?value:void 0}function numberFormatOptions(input){const type=closedValue(input.type,NUMBER_TYPES,"decimal"),notation=closedValue(input.notation,NUMBER_NOTATIONS,"standard"),currencyDisplay=closedValue(input.currencyDisplay,CURRENCY_DISPLAYS,"symbol"),options={style:type,notation};return(input.withoutGrouping||input.noGrouping)&&(options.useGrouping=!1),type==="currency"&&(options.currency=
|
|
1
|
+
import{finiteInteger,finiteRange}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";const NUMBER_TYPES=["currency","decimal","percent"],NUMBER_NOTATIONS=["standard","compact","scientific","engineering"],CURRENCY_DISPLAYS=["symbol","narrowSymbol","code","name"],DISPLAY_STYLES=["long","short","narrow"],BYTE_UNITS=["byte","kilobyte","megabyte","gigabyte","terabyte","petabyte"],BIT_UNITS=["bit","kilobit","megabit","gigabit","terabit","petabit"],DATE_STYLES=["full","long","medium","short"],DATE_TEXT_STYLES=["narrow","short","long"],DATE_NUMERIC_STYLES=["numeric","2-digit"],MONTH_STYLES=["numeric","2-digit","narrow","short","long"],TIME_ZONE_NAME_STYLES=["short","long"],HOUR_FORMATS=["auto","12","24"],NUMERIC_DATE_SOURCE=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,dateSourceConverter={fromAttribute(value){const source=value??"",normalized=source.trim();if(NUMERIC_DATE_SOURCE.test(normalized)){const epoch=Number(normalized);if(Number.isFinite(epoch))return epoch}return source}};function closedValue(value,values,fallback){return typeof value=="string"&&values.includes(value)?value:fallback}function optionalClosedValue(value,values){return typeof value=="string"&&values.includes(value)?value:void 0}function numberFormatOptions(input){const type=closedValue(input.type,NUMBER_TYPES,"decimal"),notation=closedValue(input.notation,NUMBER_NOTATIONS,"standard"),currencyDisplay=closedValue(input.currencyDisplay,CURRENCY_DISPLAYS,"symbol"),options={style:type,notation};return(input.withoutGrouping||input.noGrouping)&&(options.useGrouping=!1),type==="currency"&&(options.currency=typeof input.currency=="string"&&input.currency.trim()||"USD",options.currencyDisplay=currencyDisplay),input.minimumIntegerDigits!==void 0&&(options.minimumIntegerDigits=input.minimumIntegerDigits),input.minimumFractionDigits!==void 0&&(options.minimumFractionDigits=input.minimumFractionDigits),input.maximumFractionDigits!==void 0&&(options.maximumFractionDigits=input.maximumFractionDigits),input.minimumSignificantDigits!==void 0&&(options.minimumSignificantDigits=input.minimumSignificantDigits),input.maximumSignificantDigits!==void 0&&(options.maximumSignificantDigits=input.maximumSignificantDigits),options}function dateTimeFormatOptions(input){const dateStyle=optionalClosedValue(input.dateStyle,DATE_STYLES),timeStyle=optionalClosedValue(input.timeStyle,DATE_STYLES),options=dateStyle||timeStyle?{dateStyle,timeStyle}:{weekday:optionalClosedValue(input.weekday,DATE_TEXT_STYLES),era:optionalClosedValue(input.era,DATE_TEXT_STYLES),year:optionalClosedValue(input.year,DATE_NUMERIC_STYLES),month:optionalClosedValue(input.month,MONTH_STYLES),day:optionalClosedValue(input.day,DATE_NUMERIC_STYLES),hour:optionalClosedValue(input.hour,DATE_NUMERIC_STYLES),minute:optionalClosedValue(input.minute,DATE_NUMERIC_STYLES),second:optionalClosedValue(input.second,DATE_NUMERIC_STYLES),timeZoneName:optionalClosedValue(input.timeZoneName,TIME_ZONE_NAME_STYLES)};typeof input.timeZone=="string"&&input.timeZone.trim()&&(options.timeZone=input.timeZone.trim());const hourFormat=closedValue(input.hourFormat,HOUR_FORMATS,"auto");return hourFormat!=="auto"&&(options.hour12=hourFormat==="12"),options}function byteFormat(value,unit,display,unitStep,decimals){const units=closedValue(unit,["byte","bit"],"byte")==="bit"?BIT_UNITS:BYTE_UNITS,safeStep=safeByteUnitStep(unitStep),index=byteUnitIndex(value,unitStep,units.length);return{amount:value/safeStep**index,options:{style:"unit",unit:units[index],unitDisplay:closedValue(display,DISPLAY_STYLES,"short"),maximumFractionDigits:finiteInteger(decimals,1,0,10)}}}const BYTE_SCALE_UNIT_COUNT=BYTE_UNITS.length;function safeByteUnitStep(unitStep){const step=finiteRange(unitStep,1e3,1);return step>1?step:1e3}function byteUnitIndex(value,unitStep,unitCount=BYTE_SCALE_UNIT_COUNT){const safeStep=safeByteUnitStep(unitStep);return value===0?0:Math.max(0,Math.min(unitCount-1,Math.floor(Math.log(Math.abs(value))/Math.log(safeStep))))}function relativeTimeFormatOptions(format,numeric){return{style:closedValue(format,DISPLAY_STYLES,"long"),numeric:closedValue(numeric,["always","auto"],"auto")}}function resolveDateSource(value){if(value==null)return new Date;if(typeof value=="string"||typeof value=="number"){const date=new Date(value);return Number.isNaN(date.getTime())?void 0:date}if(isDateObject(value))try{const epoch=Date.prototype.getTime.call(value);return Number.isFinite(epoch)?new Date(epoch):void 0}catch{return}}const RELATIVE_TIME_DIVISORS={year:31536e3,quarter:7884e3,month:2628e3,week:604800,day:86400,hour:3600,minute:60,second:1},RELATIVE_TIME_UNITS=Object.keys(RELATIVE_TIME_DIVISORS);function relativeTimeDivisor(unit){return RELATIVE_TIME_DIVISORS[unit]}function resolveRelativeTimeState(seconds,unit){const requestedUnit=unit==="auto"||RELATIVE_TIME_UNITS.includes(unit)?unit:"auto",selected=requestedUnit==="auto"?RELATIVE_TIME_UNITS.find(candidate=>Math.abs(seconds)>=relativeTimeDivisor(candidate))??"second":requestedUnit;return{seconds,requestedUnit,selected,value:Math.round(seconds/relativeTimeDivisor(selected))}}export{RELATIVE_TIME_UNITS,byteFormat,byteUnitIndex,dateSourceConverter,dateTimeFormatOptions,numberFormatOptions,relativeTimeDivisor,relativeTimeFormatOptions,resolveDateSource,resolveRelativeTimeState,safeByteUnitStep};
|
|
@@ -100,11 +100,6 @@ flip?:LyraIconFlip;
|
|
|
100
100
|
/** Layout canvas. Unset/`fixed` is 1.25em × 1em; `auto` follows intrinsic width at 1em high;
|
|
101
101
|
* `square` is 1.25em × 1.25em; `roomy` is 1.5em × 1.5em. */
|
|
102
102
|
canvas?:LyraIconCanvas;
|
|
103
|
-
/** Compatibility alias for `canvas="auto"`. Purely a CSS-level alias — it never reads or
|
|
104
|
-
* writes `canvas` — so an explicit `canvas` attribute/property always wins and this becomes a
|
|
105
|
-
* no-op while one is set.
|
|
106
|
-
* @deprecated Use `canvas="auto"` instead. */
|
|
107
|
-
autoWidth:boolean;
|
|
108
103
|
/** Swaps the primary and secondary opacity hooks used by duotone SVGs. */
|
|
109
104
|
swapOpacity:boolean;
|
|
110
105
|
/** Optional built-in motion treatment; all variants honor `prefers-reduced-motion`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&©.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
|
|
2
2
|
part="svg"
|
|
3
3
|
viewBox="0 0 24 24"
|
|
4
4
|
fill="none"
|
|
@@ -16,4 +16,4 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
|
|
|
16
16
|
aria-label=${label||nothing}
|
|
17
17
|
aria-hidden=${label?"false":"true"}
|
|
18
18
|
>${content}</span
|
|
19
|
-
>`}}__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"name",null),__decorate([property()],LyraIcon.prototype,"path",void 0),__decorate([property()],LyraIcon.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"library",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"family",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"variant",void 0),__decorate([property()],LyraIcon.prototype,"src",null),__decorate([property({type:Number,reflect:!0,useDefault:!0})],LyraIcon.prototype,"rotate",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"flip",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"canvas",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"
|
|
19
|
+
>`}}__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"name",null),__decorate([property()],LyraIcon.prototype,"path",void 0),__decorate([property()],LyraIcon.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"library",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"family",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraIcon.prototype,"variant",void 0),__decorate([property()],LyraIcon.prototype,"src",null),__decorate([property({type:Number,reflect:!0,useDefault:!0})],LyraIcon.prototype,"rotate",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"flip",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"canvas",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"swap-opacity"})],LyraIcon.prototype,"swapOpacity",void 0),__decorate([property({reflect:!0})],LyraIcon.prototype,"animation",void 0),__decorate([state()],LyraIcon.prototype,"fetchState",void 0),__decorate([query("svg")],LyraIcon.prototype,"svgEl",void 0),__decorate([query("slot")],LyraIcon.prototype,"customSlot",void 0);export{LyraIcon};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";const styles=css`:host{inline-size:var(--lr-icon-size,calc(var(--lr-size-1em) * 1.25));block-size:var(--lr-icon-size,var(--lr-size-1em));color:inherit;justify-content:center;align-items:center;display:inline-flex}svg{block-size:100%;inline-size:auto;max-inline-size:100%;display:block;overflow:visible}.semantic-owner{justify-content:center;align-items:center;block-size:100%;inline-size:100%;display:inline-flex}slot{display:none}:host(:where([canvas=auto]))
|
|
1
|
+
import{css}from"lit";const styles=css`:host{inline-size:var(--lr-icon-size,calc(var(--lr-size-1em) * 1.25));block-size:var(--lr-icon-size,var(--lr-size-1em));color:inherit;justify-content:center;align-items:center;display:inline-flex}svg{block-size:100%;inline-size:auto;max-inline-size:100%;display:block;overflow:visible}.semantic-owner{justify-content:center;align-items:center;block-size:100%;inline-size:100%;display:inline-flex}slot{display:none}:host(:where([canvas=auto])){inline-size:auto}:host(:where([canvas=square])){inline-size:var(--lr-icon-size,calc(var(--lr-size-1em) * 1.25));block-size:var(--lr-icon-size,calc(var(--lr-size-1em) * 1.25))}:host(:where([canvas=roomy])){inline-size:var(--lr-icon-size,var(--lr-size-1-5em));block-size:var(--lr-icon-size,var(--lr-size-1-5em))}:host(:where([rotate],[flip])){transform:rotate(var(--lr-icon-rotate,0deg)) scale(var(--lr-icon-flip-x,var(--_lr-icon-flip-x,1)), var(--lr-icon-flip-y,var(--_lr-icon-flip-y,1)))}:host(:where([flip=x],[flip=horizontal])){--_lr-icon-flip-x:-1}:host(:where([flip=y],[flip=vertical])){--_lr-icon-flip-y:-1}:host(:where([flip=both])){--_lr-icon-flip-x:-1;--_lr-icon-flip-y:-1}.fa-primary{fill:var(--primary-color,currentColor);opacity:var(--primary-opacity,1)}.fa-secondary{fill:var(--secondary-color,currentColor);opacity:var(--secondary-opacity,.4)}:host(:where([swap-opacity])) .fa-primary{opacity:var(--secondary-opacity,.4)}:host(:where([swap-opacity])) .fa-secondary{opacity:var(--primary-opacity,1)}:host(:where([animation])) svg{animation-delay:var(--animation-delay,0s);animation-direction:var(--animation-direction,normal);animation-duration:var(--_lr-motion-duration,var(--animation-duration,var(--lr-duration-icon)));animation-iteration-count:var(--animation-iteration-count,infinite);animation-timing-function:var(--animation-timing,var(--lr-easing-emphasized));transform-origin:50%}:host(:where([animation=beat])) svg{animation-name:var(--_lr-motion-animation,lr-icon-beat)}:host(:where([animation=fade])) svg{animation-name:var(--_lr-motion-animation,lr-icon-fade)}:host(:where([animation=beat-fade])) svg{animation-name:var(--_lr-motion-animation,lr-icon-beat-fade)}:host(:where([animation=bounce])) svg{animation-name:var(--_lr-motion-animation,lr-icon-bounce)}:host(:where([animation=flip])) svg{animation-name:var(--_lr-motion-animation,lr-icon-flip)}:host(:where([animation=flip-360])) svg{animation-name:var(--_lr-motion-animation,lr-icon-flip-360)}:host(:where([animation=shake])) svg{animation-name:var(--_lr-motion-animation,lr-icon-shake)}:host(:where([animation=spin])),:host(:where([animation=spin-reverse])),:host(:where([animation=spin-snap])),:host(:where([animation=spin-snap-4])),:host(:where([animation=spin-snap-8])){perspective:calc(var(--lr-size-1em) * 8)}:host(:where([animation=spin])) svg,:host(:where([animation=spin-reverse])) svg,:host(:where([animation=spin-snap])) svg,:host(:where([animation=spin-snap-4])) svg,:host(:where([animation=spin-snap-8])) svg{animation-name:var(--_lr-motion-animation,lr-icon-spin)}:host(:where([animation=spin-reverse])) svg{animation-direction:var(--animation-direction,reverse)}:host(:where([animation=spin-snap])) svg{animation-timing-function:var(--animation-timing,steps(6))}:host(:where([animation=spin-snap-4])) svg{animation-timing-function:var(--animation-timing,steps(4))}:host(:where([animation=spin-snap-8])) svg{animation-timing-function:var(--animation-timing,steps(8))}:host(:where([animation=spin-pulse])) svg{animation-name:var(--_lr-motion-animation,lr-icon-spin-pulse)}:host(:where([animation=buzz])) svg{animation-name:var(--_lr-motion-animation,lr-icon-buzz)}:host(:where([animation=wag])) svg{animation-name:var(--_lr-motion-animation,lr-icon-wag)}:host(:where([animation=float])) svg{animation-name:var(--_lr-motion-animation,lr-icon-float)}:host(:where([animation=swing])) svg{animation-name:var(--_lr-motion-animation,lr-icon-swing)}:host(:where([animation=jello])) svg{animation-name:var(--_lr-motion-animation,lr-icon-jello)}@keyframes lr-icon-beat{50%{transform:scale(var(--beat-scale,1.25))}}@keyframes lr-icon-fade{50%{opacity:var(--fade-opacity,.4)}}@keyframes lr-icon-beat-fade{50%{opacity:var(--beat-fade-opacity,.4);transform:scale(var(--beat-fade-scale,1.25))}}@keyframes lr-icon-bounce{0%,to{transform:translateY(var(--bounce-anticipation,0)) scale(var(--bounce-start-scale-x,1), var(--bounce-start-scale-y,1))}45%{transform:translateY(var(--bounce-height,calc(var(--lr-size-0-5em) * -1))) scale(var(--bounce-jump-scale-x,.95), var(--bounce-jump-scale-y,1.05))}70%{transform:translateY(var(--bounce-rebound,calc(var(--lr-size-1em) * -.1))) scale(var(--bounce-land-scale-x,1.08), var(--bounce-land-scale-y,.92))}}@keyframes lr-icon-flip{50%{transform:scale(var(--flip-anticipation-scale,.9)) rotate3d(var(--flip-x,0), var(--flip-y,1), var(--flip-z,0), calc(var(--flip-angle,180deg) + var(--flip-overshoot,0deg)))}}@keyframes lr-icon-flip-360{0%{transform:scale(var(--flip-anticipation-scale,.9))}to{transform:rotate3d(var(--flip-x,0), var(--flip-y,1), var(--flip-z,0), calc(var(--flip-angle,360deg) + var(--flip-overshoot,0deg)))}}@keyframes lr-icon-shake{20%,60%{transform:translateX(calc(var(--lr-size-1em) * -.12))}40%,80%{transform:translateX(calc(var(--lr-size-1em) * .12))}}@keyframes lr-icon-spin{to{transform:rotate(1turn)}}@keyframes lr-icon-spin-pulse{50%{opacity:var(--fade-opacity,.4);transform:rotate(.5turn) scale(var(--beat-scale,1.1))}to{transform:rotate(1turn)}}@keyframes lr-icon-buzz{25%{transform:translateX(calc(var(--buzz-distance,calc(var(--lr-size-1em) * .12)) * -1)) rotate(-4deg)}75%{transform:translateX(var(--buzz-distance,calc(var(--lr-size-1em) * .12))) rotate(4deg)}}@keyframes lr-icon-wag{25%{transform:rotate(calc(var(--wag-angle,12deg) * -1))}75%{transform:rotate(var(--wag-angle,12deg))}}@keyframes lr-icon-swing{20%{transform:rotate(var(--swing-angle,15deg))}40%{transform:rotate(calc(var(--swing-angle,15deg) * -.7))}60%{transform:rotate(calc(var(--swing-angle,15deg) * .45))}80%{transform:rotate(calc(var(--swing-angle,15deg) * -.2))}}@keyframes lr-icon-jello{30%{transform:scale(var(--jello-scale-x,1.18), var(--jello-scale-y,.82))}55%{transform:scale(calc(2 - var(--jello-scale-x,1.18)), calc(2 - var(--jello-scale-y,.82)))}75%{transform:scale(calc((var(--jello-scale-x,1.18) + 2) / 3), calc((var(--jello-scale-y,.82) + 2) / 3))}}@keyframes lr-icon-float{0%,to{transform:translateX(0) translateY(0) rotate(0deg) scale(var(--float-squash-x,1.04), var(--float-squash-y,.96))}50%{transform:translateX(var(--float-drift,0)) translateY(var(--float-height,calc(var(--lr-size-0-5em) * -1))) rotate(var(--float-tilt,4deg)) scale(var(--float-stretch-x,.96), var(--float-stretch-y,1.04))}}@media (prefers-reduced-motion:reduce){:host(:where([animation])) svg{animation:none!important}}`;export{styles};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}projected.length=retainedLength;try{return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}return projected.length=retainedLength,Object.freeze(projected)}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
2
2
|
@keydown=${event=>event.stopPropagation()}
|
|
3
3
|
@click=${event=>{event.stopPropagation();const button=event.currentTarget;button.isConnected&&button.getRootNode()===this.renderRoot&&!this.hierarchy.loading&&projection===this.hierarchy.projection&&source===this.treeSource&&epoch===this.hierarchy.epoch&&this.copySource(key,node?node.kind==="object"||node.kind==="array"||node.kind==="element"?"subtree":"node":"document")}}>${this.copyLabel(key??"toolbar",this.localize("copy"))}</button>`}renderSourceNode(node){const match=this.sourceHits?.isCurrent()&&this.sourceHitKeys.has(node.path),active=this.sourceHits?.value.hits[this.activeSearchIndex]?.key===node.path;return html`<span part="key" ?data-match=${match} ?data-active=${active}>${node.name}</span><span aria-hidden="true">:</span><span
|
|
4
4
|
part="value" data-type=${node.kind==="scalar"?"string":node.kind} ?data-match=${match} ?data-active=${active}>${node.value??node.kind}</span>${this.sourceCopyButton(node)}`}renderSource(){const partial=!this.sourceSearchExact&&!!this.query,count=this.sourceHitKeys.size;return html`<div class="source-shell" style=${styleMap({"--lr-json-viewer-max-height":sanitizeCssLength(this.maxHeight)??"var(--lr-size-20rem)"})}>
|
|
@@ -80,9 +80,6 @@ field:LyraKnownDateField;}export interface LyraKnownDateEventMap{'lr-invalid':Cu
|
|
|
80
80
|
* @csspart fieldset - The `<fieldset>` grouping the three fields.
|
|
81
81
|
* @csspart legend - The `<legend>` element.
|
|
82
82
|
* @csspart form-control-label - The visible label wrapper inside the legend.
|
|
83
|
-
* @csspart label - Deprecated in 8.0.0; compatibility alias for `form-control-label`. Web Awesome
|
|
84
|
-
* still publishes its own deprecated `label` part on `<wa-known-date>`, so this alias stays on
|
|
85
|
-
* the same node until upstream drops it.
|
|
86
83
|
* @csspart fields - The row wrapping the three field blocks.
|
|
87
84
|
* @csspart form-control-input - Alias on the fields row matching other form controls.
|
|
88
85
|
* @csspart field - Each field block (label + input), repeated three times; distinguished by
|
|
@@ -41,7 +41,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
41
41
|
/>
|
|
42
42
|
<fieldset part="fieldset" aria-label=${this.accessibleLabel??nothing}>
|
|
43
43
|
<legend part="legend" ?hidden=${!hasLabel}>
|
|
44
|
-
<span part="form-control-label
|
|
44
|
+
<span part="form-control-label">
|
|
45
45
|
<slot name="label"
|
|
46
46
|
>${this.label}</slot
|
|
47
47
|
>
|
|
@@ -170,11 +170,12 @@ export declare class LyraMentionPopover extends LyraElement<LyraMentionPopoverEv
|
|
|
170
170
|
* `<textarea>`/single-line text `<input>`, positioning is caret-precise
|
|
171
171
|
* (see the class doc); any other element anchors the whole popup under
|
|
172
172
|
* that element's own box, the same as `<lr-combobox>`'s trigger. */
|
|
173
|
-
anchor?:HTMLElement;private itemPositions;private _items;
|
|
173
|
+
anchor?:HTMLElement;private itemPositions;private _items;private itemsSource?;
|
|
174
174
|
/** The candidate set, pre-`query`-filtering. Admits the first 10,000 array positions and
|
|
175
175
|
* displays a localized limit notice when additional candidates are omitted. Assignment takes a shallow frozen snapshot;
|
|
176
176
|
* malformed rows without a string `label` remain in that snapshot but are omitted from every
|
|
177
|
-
* filtered/rendered projection.
|
|
177
|
+
* filtered/rendered projection. Assign a new array to update: mutating an array and assigning it
|
|
178
|
+
* again does not. */
|
|
178
179
|
get items():readonly Readonly<LyraMentionItem>[];set items(next:readonly LyraMentionItem[]);
|
|
179
180
|
/** The text typed since the trigger character (`@`/`/`/…) — drives the
|
|
180
181
|
* built-in internal filtering (see `filter` to override it). Removing the attribute
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"],caretMirrors=new WeakMap;function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length,before=el.value.slice(0,index),after=el.value.slice(index)||"";prefix.data!==before&&(prefix.data=before),suffix.data!==after&&(suffix.data=after),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),name===void 0&&(this.filteredMemo=void 0),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items;if(next===previous){this.requestUpdate();return}const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.visibleItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),shadowFocusTarget(this)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"],caretMirrors=new WeakMap;function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length,before=el.value.slice(0,index),after=el.value.slice(index)||"";prefix.textContent!==before&&(prefix.textContent=before),suffix.textContent!==after&&(suffix.textContent=after),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),name===void 0&&(this.filteredMemo=void 0),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items;if(next===this.itemsSource||next===previous)return;this.itemsSource=next;const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.visibleItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),shadowFocusTarget(this)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="option"
|
|
4
4
|
id=${id}
|