@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,12 +1,15 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SpatialSourceController,spatialContains}from"../../../internal/spatial-source-controller.js";import{snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{isPlainDataRecord,readOwnDataValue}from"../../../internal/data-descriptors.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{extent,finiteRange,finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{styles}from"./embedding-explorer.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_embeddingExplorerEmpty,LYRA_DEFAULT_embeddingExplorerLabel,LYRA_DEFAULT_embeddingExplorerPoint,LYRA_DEFAULT_embeddingExplorerPointLimit,LYRA_DEFAULT_embeddingExplorerSpatialBin,LYRA_DEFAULT_embeddingExplorerSpatialBounds,LYRA_DEFAULT_embeddingExplorerSpatialError,LYRA_DEFAULT_embeddingExplorerSpatialLoading,LYRA_DEFAULT_embeddingExplorerSpatialSummary}from"../../../internal/default-strings/retrieval.generated.js";const WIDTH=640,HEIGHT=360,PAD=24,MAX_RENDERED_POINTS=1e3,PALETTE=["var(--lr-color-chart-1)","var(--lr-color-chart-2)","var(--lr-color-chart-3)","var(--lr-color-chart-4)","var(--lr-color-chart-5)","var(--lr-color-chart-6)","var(--lr-color-chart-7)","var(--lr-color-chart-8)"];function decimatePoints(items,max){if(items.length<=max||max<=0)return[...items];if(max===1)return[items[0]];const step=(items.length-1)/(max-1),result=[],seen=new Set;for(let i=0;i<max;i++){const index=Math.min(items.length-1,Math.round(i*step));seen.has(index)||(seen.add(index),result.push(items[index]))}return result}function validPointId(point){if(!isPlainDataRecord(point))return;const id=readOwnDataValue(point,"id");return typeof id=="string"&&id.trim()&&Number.isFinite(readOwnDataValue(point,"x"))&&Number.isFinite(readOwnDataValue(point,"y"))?id:void 0}class LyraEmbeddingExplorer extends LyraElement{constructor(){super(...arguments),this.spatial=new SpatialSourceController(this,()=>this.spatialChanged(),()=>this.effectiveLocale),this.spatialWaiters=new Set,this.revealToken={},this._source=null,this.viewport=null,this._points=Object.freeze([]),this.pointsSource=this._points,this.sampledFrom=0,this.pointGeneration=0,this.resumePointScan=!1,this.validPoints=[],this.renderedPoints=[],this.sampledPoints=[],this.sampledPointSet=new Set,this.pointPositions=new Map,this.bounds={minX:0,maxX:0,minY:0,maxY:0},this.clusters=[],this.maxRenderedPoints=1e3,this.selectedPointId="",this.height="360px",this.label=null,this.accessibleLabel=null,this.activeIndex=0,this.refocusAfterUpdate=!1}static{this.defaultStrings={...super.defaultStrings,embeddingExplorerEmpty:LYRA_DEFAULT_embeddingExplorerEmpty,embeddingExplorerLabel:LYRA_DEFAULT_embeddingExplorerLabel,embeddingExplorerPoint:LYRA_DEFAULT_embeddingExplorerPoint,embeddingExplorerPointLimit:LYRA_DEFAULT_embeddingExplorerPointLimit,embeddingExplorerSpatialBin:LYRA_DEFAULT_embeddingExplorerSpatialBin,embeddingExplorerSpatialBounds:LYRA_DEFAULT_embeddingExplorerSpatialBounds,embeddingExplorerSpatialError:LYRA_DEFAULT_embeddingExplorerSpatialError,embeddingExplorerSpatialLoading:LYRA_DEFAULT_embeddingExplorerSpatialLoading,embeddingExplorerSpatialSummary:LYRA_DEFAULT_embeddingExplorerSpatialSummary}}static{this.styles=[LyraElement.styles,specialistTokens,styles]}get source(){return this._source}set source(value){const old=this._source;this._source=value,this.requestUpdate("source",old)}spatialChanged(){if(super.requestUpdate("spatial"),!this.spatial?.loading||this.spatial.error){for(const resolve of this.spatialWaiters??[])resolve();this.spatialWaiters?.clear()}}invalidateReveal(){const token=this.revealToken={};for(const resolve of this.spatialWaiters??[])resolve();return this.spatialWaiters?.clear(),token}async revealSourcePoint(id){const token=this.invalidateReveal(),epoch=this.spatial.authority.epoch,current=()=>this.revealToken===token&&this.isConnected&&this.source!==null&&this.spatial.authority.epoch===epoch;if(!current()||this.spatial.error)return!1;const point=await this.spatial.reveal(id);if(!point||!current())return!1;const viewport=this.spatial.panTo(point);if(viewport===void 0||(viewport!==this.viewport&&(this.viewport=viewport),await this.updateComplete,!current())||(this.spatial.loading&&await new Promise(resolve=>this.spatialWaiters.add(resolve)),!current()||this.spatial.error)||(await this.updateComplete,!current()))return!1;const index=this.renderedPoints.findIndex(item=>item.id===id);return index<0||(this.activeIndex=index,await this.updateComplete,!current())?!1:(this.renderRoot.querySelector(`[data-index="${index}"]`)?.focus(),shadowFocusTarget(this)?.getAttribute("data-id")===id)}get points(){return this._points}set points(value){Object.is(value,this.pointsSource)||Object.is(value,this._points)||(this.pointsSource=value,this.source===null&&this.refreshPoints())}cancelPointScan(){this.pointGeneration++,clearTimeout(this.pointScan?.timer),this.pointScan=void 0}publishPoints(snapshot,sourceLength){const previous=this._points;this.sampledFrom=sourceLength,this._points=snapshot,this.requestUpdate("points",previous)}refreshPoints(){this.cancelPointScan(),this.resumePointScan=!1;const generation=this.pointGeneration,value=this.pointsSource,view=this.ownerDocument?.defaultView;let truncation;const snapshot=snapshotPublicCollection(value,view,{onTruncate:report=>truncation=report});if(generation!==this.pointGeneration)return;if(!truncation||!Array.isArray(value)){this.publishPoints(snapshot,0);return}const candidates=new Set,count=truncation.retained;for(let index=0;index<count;index++){const position=count>1?Math.round(index*(truncation.source-1)/(count-1)):0,id=validPointId(readOwnDataValue(value,String(position)));id!==void 0&&candidates.add(id)}generation===this.pointGeneration&&(this.pointScan={source:value,length:truncation.source,candidates,winners:new Map,cursor:0},this.queuePointScan(),this.requestUpdate("pointScan"))}queuePointScan(){const scan=this.pointScan;!scan||scan.timer!==void 0||!this.isConnected||(scan.timer=setTimeout(()=>{if(scan.timer=void 0,!this.isConnected||this.pointScan!==scan)return;const end=Math.min(scan.length,scan.cursor+1e4);for(;scan.cursor<end&&scan.winners.size<scan.candidates.size;scan.cursor++){const point=readOwnDataValue(scan.source,String(scan.cursor)),id=validPointId(point);id!==void 0&&scan.candidates.has(id)&&!scan.winners.has(id)&&scan.winners.set(id,point)}if(scan.cursor<scan.length&&scan.winners.size<scan.candidates.size)this.queuePointScan();else{const snapshot=snapshotPublicCollection([...scan.winners.values()],this.ownerDocument?.defaultView);if(this.pointScan!==scan||!this.isConnected)return;this.pointScan=void 0,this.publishPoints(snapshot,scan.length)}},0))}requestUpdate(name,oldValue,options){this.spatial&&(name==="source"||name===void 0)?(this.invalidateReveal(),this.cancelPointScan(),this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId),this.source===null&&this.pointsSource!==void 0&&this.refreshPoints()):this.source&&this.spatial?((name==="viewport"||name==="maxRenderedPoints")&&this.spatial.configure(this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4))),name==="selectedPointId"&&this.spatial.setSelected(this.selectedPointId)):name===void 0&&this.pointsSource!==void 0&&this.refreshPoints(),super.requestUpdate(name,oldValue,options)}connectedCallback(){super.connectedCallback(),this.source?this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId):this.resumePointScan?this.refreshPoints():this.queuePointScan()}disconnectedCallback(){this.invalidateReveal(),this.spatial.reset(),this.spatialChanged(),this.resumePointScan=this.pointScan!==void 0,this.cancelPointScan(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.spatial.authority.adopted(),this.source&&this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId)}willUpdate(changed){if(super.willUpdate(changed),this.source){this.renderedPoints=[...this.spatial.points()].filter(point=>!this.spatial.view||spatialContains(this.spatial.view,point)),this.activeIndex=Math.max(0,Math.min(this.activeIndex,this.renderedPoints.length+(this.spatial.result?.bins.length??0)-1));return}const previousRenderedPoints=this.renderedPoints;if(changed.has("points")&&(this.validPoints=firstByRetrievalIdentity(Array.isArray(this.points)?this.points:[],point=>Number.isFinite(point.x)&&Number.isFinite(point.y)?point.id:void 0),this.pointPositions=new Map(this.validPoints.map((point,index)=>[point.id,{point,index}])),this.bounds=extent(this.validPoints,point=>point.x,point=>point.y)??{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0},this.clusters=[...new Set(this.validPoints.map(point=>String(point.cluster??"").trim()))].sort()),(changed.has("points")||changed.has("maxRenderedPoints"))&&(this.sampledPoints=decimatePoints(this.validPoints,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4))),this.sampledPointSet=new Set(this.sampledPoints)),changed.has("points")||changed.has("selectedPointId")||changed.has("maxRenderedPoints")){const selected=this.pointPositions.get(this.selectedPointId);if(this.renderedPoints=this.sampledPoints,selected&&!this.sampledPointSet.has(selected.point)){const following=this.sampledPoints.findIndex(point=>this.pointPositions.get(point.id).index>selected.index),index=following<0?this.sampledPoints.length:following;this.renderedPoints=[...this.sampledPoints.slice(0,index),selected.point,...this.sampledPoints.slice(index)]}}if(!changed.has("points")&&!changed.has("maxRenderedPoints")&&previousRenderedPoints===this.renderedPoints)return;const active=shadowFocusTarget(this)??null,focusedId=active?.getAttribute("data-id"),points=this.renderedPoints,matchingIndex=focusedId?points.findIndex(point=>point.id===focusedId):-1;this.activeIndex=matchingIndex>=0?matchingIndex:Math.min(this.activeIndex,Math.max(0,points.length-1)),this.refocusAfterUpdate=active?.getAttribute("part")==="point"}updated(changed){super.updated(changed),changed.has("height")&&this.applyHeight(),this.refocusAfterUpdate&&(this.refocusAfterUpdate=!1,this.renderRoot.querySelector(`[data-index="${this.activeIndex}"]`)?.focus())}applyHeight(){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--lr-embedding-explorer-height",height):this.style.removeProperty("--lr-embedding-explorer-height")}position(point,bounds){const{minX,maxX,minY,maxY}=bounds;if(this.source){const ratio=(value,min,max)=>min===max?.5:Number.isFinite(max-min)?(value-min)/(max-min):(value/2-min/2)/(max/2-min/2);return{x:PAD+ratio(point.x,minX,maxX)*(WIDTH-PAD*2),y:HEIGHT-PAD-ratio(point.y,minY,maxY)*(HEIGHT-PAD*2)}}const x=PAD+finiteRange((point.x-minX)/(maxX-minX||1),.5,0,1)*(WIDTH-PAD*2),y=HEIGHT-PAD-finiteRange((point.y-minY)/(maxY-minY||1),.5,0,1)*(HEIGHT-PAD*2);return{x,y}}announceLabel(point,index){return this.localize("embeddingExplorerPoint",void 0,{label:point.label||point.id,index:getNumberFormat(this.effectiveLocale).format(index+1)})}select(point){this.source&&(this.spatial.loading||this.spatial.error)||this.emit("lr-point-select",{point})}activatePoint(point,index){this.activeIndex=index,this.select(point)}onPointKeyDown(event,point,index,current=()=>!0){const total=this.renderedPoints.length+(this.source?this.spatial.result?.bins.length??0:0);if(event.key==="Enter"||event.key===" "){event.preventDefault(),event.repeat||this.select(point);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=index;if(event.key===forward||event.key==="ArrowDown")next=Math.min(total-1,index+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,index-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=total-1;else return;event.preventDefault(),this.activeIndex=next,this.updateComplete.then(()=>{current()&&this.renderRoot.querySelector(`[data-index="${next}"]`)?.focus()})}spatialActionGuard(member){const source=this.source,model=this.spatial,binding=model.binding,result=model.result,owner=this.ownerDocument,epoch=model.authority.epoch;return event=>{const control=event?.currentTarget;return source!==null&&this.source===source&&this.isConnected&&this.ownerDocument===owner&&model.binding===binding&&model.result===result&&model.authority.epoch===epoch&&!model.loading&&!model.error&&member()&&(!event||!!control?.isConnected&&control.ownerDocument===owner&&control.getRootNode()===this.renderRoot)}}renderPoint(point,index,bounds,clusterIndices){const current=this.source?this.spatialActionGuard(()=>this.spatial.result?.points.includes(point)===!0||this.spatial.selected===point||this.spatial.revealed===point):()=>!0,{x,y}=this.position(point,bounds),label=this.announceLabel(point,this.source?point.sourceIndex:index),cluster=String(point.cluster??"").trim(),selected=point.id===this.selectedPointId;return svg`<g
|
|
1
|
+
import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{ENGINE_3D_PREFERENCE,ENGINE_3D_REASON_MESSAGE,ENGINE_3D_SHOWING_MESSAGE}from"../../../internal/engine-3d.js";import{LARGE_DATA_PAGE_SIZE,largeDataPage,validatePointColumns,typedColumnIssueMessage}from"../../../internal/typed-columns.js";import{EmbeddingRows}from"./embedding-explorer-data.js";import{EmbeddingEngineController}from"./embedding-explorer-engine.js";import{SpatialSourceController,spatialContains}from"../../../internal/spatial-source-controller.js";import{snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{isPlainDataRecord,readOwnDataValue}from"../../../internal/data-descriptors.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{extent,finiteRange,finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{styles}from"./embedding-explorer.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_embeddingExplorerEmpty,LYRA_DEFAULT_embeddingExplorerLabel,LYRA_DEFAULT_embeddingExplorerPoint,LYRA_DEFAULT_embeddingExplorerPointLimit,LYRA_DEFAULT_embeddingExplorerSpatialBin,LYRA_DEFAULT_embeddingExplorerSpatialBounds,LYRA_DEFAULT_embeddingExplorerSpatialError,LYRA_DEFAULT_embeddingExplorerSpatialLoading,LYRA_DEFAULT_embeddingExplorerSpatialSummary}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dError,LYRA_DEFAULT_engine3dLoading,LYRA_DEFAULT_engine3dShowingBuiltin,LYRA_DEFAULT_engine3dShowingList,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_largeDataInvalid,LYRA_DEFAULT_largeDataLimit,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationApplied,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_previous}from"../../../internal/default-strings/shared.generated.js";const WIDTH=640,HEIGHT=360,PAD=24,MAX_RENDERED_POINTS=1e3,PALETTE=["var(--lr-color-chart-1)","var(--lr-color-chart-2)","var(--lr-color-chart-3)","var(--lr-color-chart-4)","var(--lr-color-chart-5)","var(--lr-color-chart-6)","var(--lr-color-chart-7)","var(--lr-color-chart-8)"];function decimatePoints(items,max){if(items.length<=max||max<=0)return[...items];if(max===1)return[items[0]];const step=(items.length-1)/(max-1),result=[],seen=new Set;for(let i=0;i<max;i++){const index=Math.min(items.length-1,Math.round(i*step));seen.has(index)||(seen.add(index),result.push(items[index]))}return result}function validPointId(point){if(!isPlainDataRecord(point))return;const id=readOwnDataValue(point,"id");return typeof id=="string"&&id.trim()&&Number.isFinite(readOwnDataValue(point,"x"))&&Number.isFinite(readOwnDataValue(point,"y"))&&(readOwnDataValue(point,"z")===void 0||Number.isFinite(readOwnDataValue(point,"z")))?id:void 0}class LyraEmbeddingExplorer extends LyraElement{constructor(){super(...arguments),this.announcements=new AnnouncementSinkController(this),this.updatingRenderer=!1,this.renderer=new EmbeddingEngineController(this,()=>{const update=()=>super.requestUpdate("engineState",void 0,{hasChanged:()=>!0});this.updatingRenderer?this.scheduleAfterUpdate(update,"engine-state"):update()},detail=>{this.announcements.announceAssertive(this.localize(ENGINE_3D_REASON_MESSAGE[detail.reason])),this.announcements.announcePolite(this.localize(ENGINE_3D_SHOWING_MESSAGE[detail.to])),this.emit("lr-engine-fallback",detail)},index=>{const point=this.rows?.point(index);point&&(this.activeIndex=index,this.select(point,index))}),this._engine="builtin",this._pointColumns=null,this.columnRows=null,this.columnIssue=null,this.ordinaryRows=null,this.spatial=new SpatialSourceController(this,()=>this.spatialChanged(),()=>this.effectiveLocale),this.spatialWaiters=new Set,this.revealToken={},this._source=null,this.viewport=null,this._points=Object.freeze([]),this.pointsSource=this._points,this.sampledFrom=0,this.pointGeneration=0,this.resumePointScan=!1,this.validPoints=[],this.renderedPoints=[],this.sampledPoints=[],this.sampledPointSet=new Set,this.pointPositions=new Map,this.bounds={minX:0,maxX:0,minY:0,maxY:0},this.clusters=[],this.maxRenderedPoints=1e3,this.selectedPointId="",this.height="360px",this.label=null,this.accessibleLabel=null,this.activeIndex=0,this.refocusAfterUpdate=!1,this.hasCompletedUpdate=!1}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,embeddingExplorerEmpty:LYRA_DEFAULT_embeddingExplorerEmpty,embeddingExplorerLabel:LYRA_DEFAULT_embeddingExplorerLabel,embeddingExplorerPoint:LYRA_DEFAULT_embeddingExplorerPoint,embeddingExplorerPointLimit:LYRA_DEFAULT_embeddingExplorerPointLimit,embeddingExplorerSpatialBin:LYRA_DEFAULT_embeddingExplorerSpatialBin,embeddingExplorerSpatialBounds:LYRA_DEFAULT_embeddingExplorerSpatialBounds,embeddingExplorerSpatialError:LYRA_DEFAULT_embeddingExplorerSpatialError,embeddingExplorerSpatialLoading:LYRA_DEFAULT_embeddingExplorerSpatialLoading,embeddingExplorerSpatialSummary:LYRA_DEFAULT_embeddingExplorerSpatialSummary,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,largeDataInvalid:LYRA_DEFAULT_largeDataInvalid,largeDataLimit:LYRA_DEFAULT_largeDataLimit,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationApplied:LYRA_DEFAULT_paginationApplied,paginationLabel:LYRA_DEFAULT_paginationLabel,previous:LYRA_DEFAULT_previous}}static{this.styles=[LyraElement.styles,specialistTokens,styles]}get engine(){return this._engine}set engine(value){const old=this._engine,normalized=ENGINE_3D_PREFERENCE.normalize(value);normalized!==old&&(this._engine=normalized,this.renderer?.invalidate(),this.requestUpdate("engine",old))}get pointColumns(){return this._pointColumns}set pointColumns(value){const old=this._pointColumns;if(old!==value){if(this._pointColumns=value,this.columnRows=null,this.columnIssue=null,value!=null){const admitted=validatePointColumns(value);if(admitted.ok){const blank=admitted.columns.ids.findIndex(id=>!id.trim());blank>=0?this.columnIssue={code:"invalid-id",column:"ids",index:blank}:this.columnRows=new EmbeddingRows(admitted.columns)}else this.columnIssue=admitted.issue}this.source||this.renderer?.invalidate(),this.source||(this.activeIndex=0),this.cancelPointScan(),value==null&&!this.source&&this.refreshPoints(),this.requestUpdate("pointColumns",old)}}get rows(){return this.pointColumns!=null?this.columnRows:this.ordinaryRows}get enhanced(){return!this.source&&(this.pointColumns!=null||this.engine==="webgl")}get source(){return this._source}set source(value){const old=this._source;value===null&&old===null||(this._source=value,value!==old&&this.renderer?.invalidate(),this.requestUpdate("source",old))}spatialChanged(){if(super.requestUpdate("spatial",void 0,{hasChanged:()=>!0}),!this.spatial?.loading||this.spatial.error){for(const resolve of this.spatialWaiters??[])resolve();this.spatialWaiters?.clear()}}invalidateReveal(){const token=this.revealToken={};for(const resolve of this.spatialWaiters??[])resolve();return this.spatialWaiters?.clear(),token}async revealSourcePoint(id){const token=this.invalidateReveal(),epoch=this.spatial.authority.epoch,current=()=>this.revealToken===token&&this.isConnected&&this.source!==null&&this.spatial.authority.epoch===epoch;if(!current()||this.spatial.error)return!1;const point=await this.spatial.reveal(id);if(!point||!current())return!1;const viewport=this.spatial.panTo(point);if(viewport===void 0||(viewport!==this.viewport&&(this.viewport=viewport),await this.updateComplete,!current())||(this.spatial.loading&&await new Promise(resolve=>this.spatialWaiters.add(resolve)),!current()||this.spatial.error)||(await this.updateComplete,!current()))return!1;const index=this.renderedPoints.findIndex(item=>item.id===id);return index<0||(this.activeIndex=index,await this.updateComplete,!current())?!1:(this.renderRoot.querySelector(`[data-index="${index}"]`)?.focus(),shadowFocusTarget(this)?.getAttribute("data-id")===id)}get points(){return this._points}set points(value){Object.is(value,this.pointsSource)||Object.is(value,this._points)||(this.pointsSource=value,this.source===null&&this.pointColumns==null&&this.refreshPoints())}cancelPointScan(){this.pointGeneration++,clearTimeout(this.pointScan?.timer),this.pointScan=void 0}publishPoints(snapshot,sourceLength){this.renderer?.invalidate();const previous=this._points;this.sampledFrom=sourceLength,this._points=snapshot,this.requestUpdate("points",previous)}refreshPoints(){this.cancelPointScan(),this.resumePointScan=!1;const generation=this.pointGeneration,value=this.pointsSource,view=this.ownerDocument?.defaultView;let truncation;const snapshot=snapshotPublicCollection(value,view,{onTruncate:report=>truncation=report});if(generation!==this.pointGeneration)return;if(!truncation||!Array.isArray(value)){this.publishPoints(snapshot,0);return}const candidates=new Set,count=truncation.retained;for(let index=0;index<count;index++){const position=count>1?Math.round(index*(truncation.source-1)/(count-1)):0,id=validPointId(readOwnDataValue(value,String(position)));id!==void 0&&candidates.add(id)}generation===this.pointGeneration&&(this.pointScan={source:value,length:truncation.source,candidates,winners:new Map,cursor:0},this.queuePointScan(),this.requestUpdate("pointScan"))}queuePointScan(){const scan=this.pointScan;!scan||scan.timer!==void 0||!this.isConnected||(scan.timer=setTimeout(()=>{if(scan.timer=void 0,!this.isConnected||this.pointScan!==scan)return;const end=Math.min(scan.length,scan.cursor+1e4);for(;scan.cursor<end&&scan.winners.size<scan.candidates.size;scan.cursor++){const point=readOwnDataValue(scan.source,String(scan.cursor)),id=validPointId(point);id!==void 0&&scan.candidates.has(id)&&!scan.winners.has(id)&&scan.winners.set(id,point)}if(scan.cursor<scan.length&&scan.winners.size<scan.candidates.size)this.queuePointScan();else{const snapshot=snapshotPublicCollection([...scan.winners.values()],this.ownerDocument?.defaultView);if(this.pointScan!==scan||!this.isConnected)return;this.pointScan=void 0,this.publishPoints(snapshot,scan.length)}},0))}requestUpdate(name,oldValue,options){this.spatial&&(name==="source"||name===void 0)?(this.invalidateReveal(),this.cancelPointScan(),this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId),this.source===null&&this.pointColumns==null&&this.pointsSource!==void 0&&this.refreshPoints()):this.source&&this.spatial?((name==="viewport"||name==="maxRenderedPoints")&&this.spatial.configure(this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4))),name==="selectedPointId"&&this.spatial.setSelected(this.selectedPointId)):name===void 0&&this.pointColumns==null&&this.pointsSource!==void 0&&this.refreshPoints(),super.requestUpdate(name,oldValue,options)}connectedCallback(){super.connectedCallback(),super.requestUpdate("engineReconnect",void 0,{hasChanged:()=>!0}),this.source?this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId):this.resumePointScan?this.refreshPoints():this.queuePointScan()}disconnectedCallback(){this.renderer.disconnect(),this.invalidateReveal(),this.spatial.reset(),this.spatialChanged(),this.resumePointScan=this.pointScan!==void 0,this.cancelPointScan(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.renderer.disconnect(),this.announcements.adopted(),super.requestUpdate("engineAdopted",void 0,{hasChanged:()=>!0}),this.spatial.authority.adopted(),this.source&&this.spatial.bind(this.source,this.viewport,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4)),this.selectedPointId)}willUpdate(changed){if(super.willUpdate(changed),this.source){this.renderedPoints=[...this.spatial.points()].filter(point=>!this.spatial.view||spatialContains(this.spatial.view,point)),this.activeIndex=Math.max(0,Math.min(this.activeIndex,this.renderedPoints.length+(this.spatial.result?.bins.length??0)-1));return}const previousRenderedPoints=this.renderedPoints;if(changed.has("points")&&(this.validPoints=firstByRetrievalIdentity(Array.isArray(this.points)?this.points:[],point=>Number.isFinite(point.x)&&Number.isFinite(point.y)&&(point.z===void 0||Number.isFinite(point.z))?point.id:void 0),this.ordinaryRows=new EmbeddingRows(null,this.validPoints),this.pointPositions=new Map(this.validPoints.map((point,index)=>[point.id,{point,index}])),this.bounds=extent(this.validPoints,point=>point.x,point=>point.y)??{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0},this.clusters=[...new Set(this.validPoints.map(point=>String(point.cluster??"").trim()))].sort()),this.enhanced){const rows=this.rows;if(changed.has("pointColumns")||changed.has("points")||changed.has("engine")||changed.has("engineState")){const active2=shadowFocusTarget(this),id=active2?.getAttribute("data-id"),index=id?rows?.indices.get(id):void 0;index!==void 0&&(this.activeIndex=index),this.refocusAfterUpdate=active2?.getAttribute("part")==="point"||active2?.getAttribute("part")==="row"}this.activeIndex=Math.min(Math.max(0,this.activeIndex),Math.max(0,(rows?.count??0)-1));const page=largeDataPage(rows?.count??0,Math.floor(this.activeIndex/LARGE_DATA_PAGE_SIZE));this.renderedPoints=rows?Array.from({length:page.end-page.start},(_,offset)=>rows.point(page.start+offset)):[];return}if((changed.has("points")||changed.has("maxRenderedPoints")||changed.has("engine")||changed.has("pointColumns")||changed.has("source"))&&(this.sampledPoints=decimatePoints(this.validPoints,Math.max(1,finiteCount(this.maxRenderedPoints,MAX_RENDERED_POINTS,1e4))),this.sampledPointSet=new Set(this.sampledPoints)),changed.has("points")||changed.has("selectedPointId")||changed.has("maxRenderedPoints")||changed.has("engine")||changed.has("pointColumns")||changed.has("source")){const selected=this.pointPositions.get(this.selectedPointId);if(this.renderedPoints=this.sampledPoints,selected&&!this.sampledPointSet.has(selected.point)){const following=this.sampledPoints.findIndex(point=>this.pointPositions.get(point.id).index>selected.index),index=following<0?this.sampledPoints.length:following;this.renderedPoints=[...this.sampledPoints.slice(0,index),selected.point,...this.sampledPoints.slice(index)]}}if(!changed.has("points")&&!changed.has("maxRenderedPoints")&&previousRenderedPoints===this.renderedPoints)return;const active=shadowFocusTarget(this)??null,focusedId=active?.getAttribute("data-id"),points=this.renderedPoints,matchingIndex=focusedId?points.findIndex(point=>point.id===focusedId):-1;this.activeIndex=matchingIndex>=0?matchingIndex:Math.min(this.activeIndex,Math.max(0,points.length-1)),this.refocusAfterUpdate=active?.getAttribute("part")==="point"}updated(changed){super.updated(changed),changed.has("height")&&this.applyHeight(),this.updatingRenderer=!0;try{this.renderer.update(this.engine,this.source?null:this.rows,this.source!==null,this.renderRoot.querySelector('[part="engine"]'),this.rows?.indices.get(this.selectedPointId)??-1,this.activeIndex)}finally{this.updatingRenderer=!1}this.hasCompletedUpdate&&changed.has("pointColumns")&&this.columnIssue&&!this.source&&this.announcements.announceAssertive(this.columnError()),this.hasCompletedUpdate=!0,this.refocusAfterUpdate&&(this.refocusAfterUpdate=!1,this.renderRoot.querySelector(`[data-index="${this.activeIndex}"]`)?.focus())}applyHeight(){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--lr-embedding-explorer-height",height):this.style.removeProperty("--lr-embedding-explorer-height")}position(point,bounds){const{minX,maxX,minY,maxY}=bounds;if(this.source||this.enhanced){const ratio=(value,min,max)=>min===max?.5:Number.isFinite(max-min)?(value-min)/(max-min):(value/2-min/2)/(max/2-min/2);return{x:PAD+ratio(point.x,minX,maxX)*(WIDTH-PAD*2),y:HEIGHT-PAD-ratio(point.y,minY,maxY)*(HEIGHT-PAD*2)}}const x=PAD+finiteRange((point.x-minX)/(maxX-minX||1),.5,0,1)*(WIDTH-PAD*2),y=HEIGHT-PAD-finiteRange((point.y-minY)/(maxY-minY||1),.5,0,1)*(HEIGHT-PAD*2);return{x,y}}announceLabel(point,index,label=point.label||point.id){return this.localize("embeddingExplorerPoint",void 0,{label,index:getNumberFormat(this.effectiveLocale).format(index+1)})}select(point,index){if(this.source&&(this.spatial.loading||this.spatial.error))return;const row=this.source?point.sourceIndex:this.rows?.indices.get(point.id)??index??-1;this.emit("lr-point-select",{point,id:point.id,index:row})}activatePoint(point,index){this.activeIndex=index,this.select(point,index)}onPointKeyDown(event,point,index,current=()=>!0){const points=this.renderedPoints,total=this.enhanced?this.rows?.count??0:points.length+(this.source?this.spatial.result?.bins.length??0:0);if(event.key==="Enter"||event.key===" "){event.preventDefault(),event.repeat||this.select(point);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=index;if(event.key===forward||event.key==="ArrowDown")next=Math.min(total-1,index+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,index-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=total-1;else return;event.preventDefault(),this.activeIndex=next,this.updateComplete.then(()=>{current()&&this.renderRoot.querySelector(`[data-index="${next}"]`)?.focus()})}spatialActionGuard(member){const source=this.source,model=this.spatial,binding=model.binding,result=model.result,owner=this.ownerDocument,epoch=model.authority.epoch;return event=>{const control=event?.currentTarget;return source!==null&&this.source===source&&this.isConnected&&this.ownerDocument===owner&&model.binding===binding&&model.result===result&&model.authority.epoch===epoch&&!model.loading&&!model.error&&member()&&(!event||!!control?.isConnected&&control.ownerDocument===owner&&control.getRootNode()===this.renderRoot)}}renderPoint(point,index,bounds,clusterIndices){const rows=this.rows,enhanced=this.enhanced,current=this.source?this.spatialActionGuard(()=>this.spatial.result?.points.includes(point)===!0||this.spatial.selected===point||this.spatial.revealed===point):()=>!enhanced||this.isConnected&&!this.source&&rows===this.rows,{x,y}=this.position(point,bounds),label=this.announceLabel(point,this.source?point.sourceIndex:index),cluster=String(point.cluster??"").trim(),selected=point.id===this.selectedPointId;return svg`<g
|
|
2
2
|
part="point"
|
|
3
3
|
data-index=${index}
|
|
4
|
+
data-row=${index}
|
|
4
5
|
data-id=${point.id}
|
|
5
6
|
data-selected=${selected?"true":"false"}
|
|
6
7
|
transform="translate(${x} ${y})"
|
|
7
8
|
tabindex=${index===this.activeIndex?"0":"-1"}
|
|
8
9
|
role="option"
|
|
9
10
|
aria-selected=${selected?"true":"false"}
|
|
11
|
+
aria-posinset=${enhanced?index+1:nothing}
|
|
12
|
+
aria-setsize=${enhanced?rows?.count:nothing}
|
|
10
13
|
aria-label=${label}
|
|
11
14
|
aria-description=${cluster||nothing}
|
|
12
15
|
@click=${event=>{current(event)&&this.activatePoint(point,index)}}
|
|
@@ -23,9 +26,10 @@ import{__decorate}from"tslib";import{SpatialSourceController,spatialContains}fro
|
|
|
23
26
|
focusable="false"
|
|
24
27
|
vector-effect="non-scaling-stroke"
|
|
25
28
|
></line>
|
|
26
|
-
<circle class="point-marker" r="6" fill=${PALETTE[(clusterIndices.get(cluster)??0)%PALETTE.length]}></circle>
|
|
29
|
+
<circle class="point-marker" r="6" fill=${PALETTE[(!this.source&&this.pointColumns!=null?rows?.category(index)??0:clusterIndices.get(cluster)??0)%PALETTE.length]}></circle>
|
|
27
30
|
${nativeSvgTitle(label)}
|
|
28
31
|
</g>`}activateBin(bin){const binding=this.spatial.binding;!binding||this.spatial.loading||this.spatial.error||this.emit("lr-spatial-bin-select",Object.freeze({revision:binding.revision,bounds:bin.bounds,count:bin.count}))}renderSpatial(){const model=this.spatial,binding=model.binding,view=model.view,label=this.hasAttribute("aria-label")?this.getAttribute("aria-label"):this.label??this.accessibleLabel??this.localize("embeddingExplorerLabel"),number=getNumberFormat(this.effectiveLocale),formatBounds=bounds=>bounds?this.localize("embeddingExplorerSpatialBounds",void 0,{minX:number.format(bounds.minX),maxX:number.format(bounds.maxX),minY:number.format(bounds.minY),maxY:number.format(bounds.maxY)}):this.localize("embeddingExplorerEmpty"),summary=this.localize("embeddingExplorerSpatialSummary",void 0,{total:number.format(binding?.count??0),matched:number.format(model.result?.matchedCount??0),global:formatBounds(binding?.bounds),viewport:formatBounds(view)}),points=this.renderedPoints,bins=model.result?.bins??[];return html`<div part="base" role="region" aria-label=${label} aria-busy=${model.loading?"true":"false"}>
|
|
32
|
+
${this.engineNotice()}
|
|
29
33
|
${model.error?html`<p part="error">${this.localize("embeddingExplorerSpatialError")}</p>`:nothing}
|
|
30
34
|
${view&&model.result&&!model.error?html`<svg part="plot" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="listbox" aria-label=${label} aria-description=${summary} aria-disabled=${model.loading?"true":"false"}>
|
|
31
35
|
${bins.map((bin,offset)=>{const a=this.position({id:"",x:bin.bounds.minX,y:bin.bounds.maxY},view),b=this.position({id:"",x:bin.bounds.maxX,y:bin.bounds.minY},view),index=points.length+offset,current=this.spatialActionGuard(()=>this.spatial.result?.bins.includes(bin)===!0),name=this.localize("embeddingExplorerSpatialBin",void 0,{count:number.format(bin.count),bounds:formatBounds(bin.bounds)});return svg`<g part="bin" role="option" aria-selected="false" aria-label=${name} tabindex=${index===this.activeIndex?"0":"-1"} data-index=${index}
|
|
@@ -39,7 +43,34 @@ import{__decorate}from"tslib";import{SpatialSourceController,spatialContains}fro
|
|
|
39
43
|
</svg>`:nothing}
|
|
40
44
|
${model.loading?html`<p part="limit">${this.localize("embeddingExplorerSpatialLoading")}</p>`:html`<p part="limit">${summary}</p>`}
|
|
41
45
|
${!model.loading&&!model.error&&binding?.count===0?html`<p part="empty">${this.localize("embeddingExplorerEmpty")}</p>`:nothing}
|
|
42
|
-
</div>`}
|
|
46
|
+
</div>`}columnError(){if(!this.columnIssue)return"";const message=typedColumnIssueMessage(this.columnIssue,"pointColumns",value=>getNumberFormat(this.effectiveLocale).format(value));return this.localize(message.key==="largeDataLimit"?"largeDataLimit":"largeDataInvalid",void 0,message.values)}engineNotice(){const notice=this.renderer.notice;return notice?html`<div part="engine-notice"><p>${this.localize(ENGINE_3D_REASON_MESSAGE[notice.reason])}</p><p>${this.localize(ENGINE_3D_SHOWING_MESSAGE[notice.to])}</p></div>`:this.renderer.loading?html`<p part="engine-notice">${this.localize("engine3dLoading")}</p>`:this.renderer.software?html`<p part="engine-notice">${this.localize("engine3dSoftwareRendering")}</p>`:nothing}movePage(delta){const page=largeDataPage(this.rows?.count??0,Math.floor(this.activeIndex/LARGE_DATA_PAGE_SIZE)+delta);this.activeIndex=page.start}renderEnhanced(){const rows=this.rows,label=this.hasAttribute("aria-label")?this.getAttribute("aria-label"):this.label??this.accessibleLabel??this.localize("embeddingExplorerLabel"),page=largeDataPage(rows?.count??0,Math.floor(this.activeIndex/LARGE_DATA_PAGE_SIZE)),number=getNumberFormat(this.effectiveLocale),clusterIndices=new Map(rows?.clusters.map((cluster,index)=>[cluster,index])??[]),textOnly=this.renderer.ready||this.renderer.selection.renderer==="list",current=()=>this.isConnected&&!this.source&&rows===this.rows;return html`<div part="base" role="region" aria-label=${label} aria-busy=${this.renderer.loading?"true":"false"}>
|
|
47
|
+
${this.engineNotice()}
|
|
48
|
+
${this.columnIssue?html`<p part="error">${this.columnError()}</p>`:nothing}
|
|
49
|
+
${!this.columnIssue&&!rows?.count?html`<p part="empty">${this.localize("embeddingExplorerEmpty")}</p>`:nothing}
|
|
50
|
+
${rows?.count?html`
|
|
51
|
+
<div class="engine-viewport">
|
|
52
|
+
${this.engine==="webgl"?html`<div part="engine" aria-hidden="true" ?hidden=${this.renderer.notice!==null}></div>`:nothing}
|
|
53
|
+
${textOnly?nothing:html`<svg part="plot" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="listbox" aria-label=${label}>
|
|
54
|
+
${this.renderedPoints.map((point,offset)=>this.renderPoint(point,page.start+offset,rows.bounds,clusterIndices))}
|
|
55
|
+
</svg>`}
|
|
56
|
+
</div>
|
|
57
|
+
${textOnly?html`<div part="rows" role="listbox" aria-label=${label}>
|
|
58
|
+
${this.renderedPoints.map((point,offset)=>{const index=page.start+offset,coordinates=(point.z===void 0?[point.x,point.y]:[point.x,point.y,point.z]).map(value=>number.format(value)).join(", "),visibleLabel=[point.label||point.id,coordinates,point.cluster??""].join(" ").trim();return html`<div part="row" role="option" data-index=${index} data-row=${index} data-id=${point.id}
|
|
59
|
+
tabindex=${index===this.activeIndex?"0":"-1"} aria-selected=${point.id===this.selectedPointId?"true":"false"}
|
|
60
|
+
aria-posinset=${index+1} aria-setsize=${rows.count}
|
|
61
|
+
aria-label=${this.announceLabel(point,index,visibleLabel)} aria-description=${String(point.cluster??"").trim()||nothing}
|
|
62
|
+
@focus=${()=>{current()&&(this.activeIndex=index)}}
|
|
63
|
+
@click=${()=>{current()&&this.activatePoint(point,index)}}
|
|
64
|
+
@keydown=${event=>{current()&&this.onPointKeyDown(event,point,index,current)}}
|
|
65
|
+
><span>${point.label||point.id}</span> <span>${coordinates}</span> <span>${point.cluster??""}</span></div>`})}
|
|
66
|
+
</div>`:nothing}
|
|
67
|
+
${textOnly?nothing:html`<div part="legend" role="list">${[...new Map(this.renderedPoints.map((point,offset)=>[String(point.cluster??""),page.start+offset])).entries()].filter(([cluster])=>cluster.trim()).map(([cluster,index])=>html`<span part="legend-item" role="listitem"><svg part="legend-swatch" viewBox="0 0 12 12" aria-hidden="true" focusable="false"><circle cx="6" cy="6" r="5" fill=${PALETTE[rows.category(index)%PALETTE.length]}></circle></svg><span part="legend-label">${cluster}</span></span>`)}</div>`}
|
|
68
|
+
<div part="pagination" role="group" aria-label=${this.localize("paginationLabel")}>
|
|
69
|
+
<button part="page-button" type="button" ?disabled=${page.page===0} @click=${()=>{current()&&this.movePage(-1)}}>${this.localize("previous")}</button>
|
|
70
|
+
<span>${this.localize("paginationApplied",void 0,{page:number.format(page.page+1),totalPages:number.format(page.pageCount)})}</span>
|
|
71
|
+
<button part="page-button" type="button" ?disabled=${page.page+1===page.pageCount} @click=${()=>{current()&&this.movePage(1)}}>${this.localize("next")}</button>
|
|
72
|
+
</div>`:nothing}
|
|
73
|
+
</div>`}render(){if(this.source)return this.renderSpatial();if(this.enhanced)return this.renderEnhanced();const points=this.validPoints,label=this.hasAttribute("aria-label")?this.getAttribute("aria-label"):this.label??this.accessibleLabel??this.localize("embeddingExplorerLabel");if(points.length===0)return html`<div part="base" role="region" aria-label=${label} aria-busy=${this.pointScan?"true":"false"}>
|
|
43
74
|
${this.pointScan?nothing:html`<p part="empty">${this.localize("embeddingExplorerEmpty")}</p>`}
|
|
44
75
|
</div>`;const renderedPoints=this.renderedPoints,bounds=this.bounds,clusters=this.clusters,clusterIndices=new Map(clusters.map((cluster,index)=>[cluster,index])),visibleClusters=clusters.filter(cluster=>cluster.trim()!==""),numberFormat=getNumberFormat(this.effectiveLocale);return html`<div part="base" aria-busy=${this.pointScan?"true":"false"}>
|
|
45
76
|
<svg
|
|
@@ -73,4 +104,4 @@ import{__decorate}from"tslib";import{SpatialSourceController,spatialContains}fro
|
|
|
73
104
|
<span part="legend-label">${cluster}</span>
|
|
74
105
|
</span>`)}
|
|
75
106
|
</div>`:nothing}
|
|
76
|
-
</div>`}}__decorate([property({attribute:!1,noAccessor:!0})],LyraEmbeddingExplorer.prototype,"source",null),__decorate([property({attribute:!1})],LyraEmbeddingExplorer.prototype,"viewport",void 0),__decorate([property({attribute:!1})],LyraEmbeddingExplorer.prototype,"points",null),__decorate([property({type:Number,attribute:"max-rendered-points"})],LyraEmbeddingExplorer.prototype,"maxRenderedPoints",void 0),__decorate([property({attribute:"selected-point-id"})],LyraEmbeddingExplorer.prototype,"selectedPointId",void 0),__decorate([property()],LyraEmbeddingExplorer.prototype,"height",void 0),__decorate([property()],LyraEmbeddingExplorer.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraEmbeddingExplorer.prototype,"accessibleLabel",void 0),__decorate([state()],LyraEmbeddingExplorer.prototype,"activeIndex",void 0);export{LyraEmbeddingExplorer};
|
|
107
|
+
</div>`}}__decorate([property({converter:ENGINE_3D_PREFERENCE,noAccessor:!0})],LyraEmbeddingExplorer.prototype,"engine",null),__decorate([property({attribute:!1,noAccessor:!0})],LyraEmbeddingExplorer.prototype,"pointColumns",null),__decorate([property({attribute:!1,noAccessor:!0})],LyraEmbeddingExplorer.prototype,"source",null),__decorate([property({attribute:!1})],LyraEmbeddingExplorer.prototype,"viewport",void 0),__decorate([property({attribute:!1})],LyraEmbeddingExplorer.prototype,"points",null),__decorate([property({type:Number,attribute:"max-rendered-points"})],LyraEmbeddingExplorer.prototype,"maxRenderedPoints",void 0),__decorate([property({attribute:"selected-point-id"})],LyraEmbeddingExplorer.prototype,"selectedPointId",void 0),__decorate([property()],LyraEmbeddingExplorer.prototype,"height",void 0),__decorate([property()],LyraEmbeddingExplorer.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraEmbeddingExplorer.prototype,"accessibleLabel",void 0),__decorate([state()],LyraEmbeddingExplorer.prototype,"activeIndex",void 0);export{LyraEmbeddingExplorer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";const styles=css` :host { display: block; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); } [part='plot'] { display: block; inline-size: 100%; block-size: var(--lr-embedding-explorer-height, auto); overflow: visible; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-xs); background: var(--lr-color-surface); } [part='point'] { cursor: pointer; outline: none; transition: stroke var(--lr-transition-fast), stroke-width var(--lr-transition-fast); } .point-hit { fill: none; stroke: transparent; stroke-width: var(--lr-size-24px); stroke-linecap: round; vector-effect: non-scaling-stroke; pointer-events: stroke; } [part='point']:hover, [part='point']:focus-visible { outline: none; } [part='point']:hover .point-marker, [part='point']:focus-visible .point-marker { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-medium); } [part='point']:active .point-marker { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-thick); } [part='point'][data-selected='true'] .point-marker { stroke: var(--lr-embedding-explorer-selected-stroke, var(--lr-color-brand)); stroke-width: var(--lr-border-width-medium); } [part='point'][data-selected='true']:hover .point-marker, [part='point'][data-selected='true']:focus-visible .point-marker { stroke-width: var(--lr-border-width-thick); } [part='point'][data-selected='true']:active .point-marker { stroke-width: calc(var(--lr-border-width-thick) + var(--lr-border-width-thin)); } [part='bin'] { cursor: pointer; outline: none; min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); } .bin-region { fill: var(--lr-color-brand); } .bin-hit { stroke: transparent; stroke-width: var(--lr-icon-button-size); pointer-events: stroke; } .bin-axis { stroke: var(--lr-color-brand); stroke-width: var(--lr-border-width-medium); } [part='bin']:hover .bin-axis, [part='bin']:focus-visible .bin-axis { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-thick); } [part='bin']:hover .bin-region, [part='bin']:focus-visible .bin-region { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-medium); } [part='bin']:active .bin-region { stroke-width: var(--lr-border-width-thick); } [part='error'] { color: var(--lr-color-danger); } [part='legend'] { display: flex; flex-wrap: wrap; min-inline-size: 0; max-inline-size: 100%; gap: var(--lr-space-s); align-items: center; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); } [part='legend-item'] { display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; gap: var(--lr-space-2xs); } [part='legend-swatch'] { inline-size: var(--lr-size-0-75rem); block-size: var(--lr-size-0-75rem); border-radius: var(--lr-radius-xs); flex: none; } [part='legend-label'] { min-inline-size: 0; overflow-wrap: anywhere; } [part='empty'] { margin: 0; color: var(--lr-color-text-quiet); } @container ${compactContainerQuery} { [part='plot'] { min-block-size: var(--lr-size-12rem); } } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";const styles=css` :host { display: block; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); } [part='plot'] { display: block; inline-size: 100%; block-size: var(--lr-embedding-explorer-height, auto); overflow: visible; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-xs); background: var(--lr-color-surface); } [part='point'] { cursor: pointer; outline: none; transition: stroke var(--lr-transition-fast), stroke-width var(--lr-transition-fast); } .point-hit { fill: none; stroke: transparent; stroke-width: var(--lr-size-24px); stroke-linecap: round; vector-effect: non-scaling-stroke; pointer-events: stroke; } [part='point']:hover, [part='point']:focus-visible { outline: none; } [part='point']:hover .point-marker, [part='point']:focus-visible .point-marker { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-medium); } [part='point']:active .point-marker { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-thick); } [part='point'][data-selected='true'] .point-marker { stroke: var(--lr-embedding-explorer-selected-stroke, var(--lr-color-brand)); stroke-width: var(--lr-border-width-medium); } [part='point'][data-selected='true']:hover .point-marker, [part='point'][data-selected='true']:focus-visible .point-marker { stroke-width: var(--lr-border-width-thick); } [part='point'][data-selected='true']:active .point-marker { stroke-width: calc(var(--lr-border-width-thick) + var(--lr-border-width-thin)); } [part='bin'] { cursor: pointer; outline: none; min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); } .bin-region { fill: var(--lr-color-brand); } .bin-hit { stroke: transparent; stroke-width: var(--lr-icon-button-size); pointer-events: stroke; } .bin-axis { stroke: var(--lr-color-brand); stroke-width: var(--lr-border-width-medium); } [part='bin']:hover .bin-axis, [part='bin']:focus-visible .bin-axis { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-thick); } [part='bin']:hover .bin-region, [part='bin']:focus-visible .bin-region { stroke: var(--lr-color-text); stroke-width: var(--lr-border-width-medium); } [part='bin']:active .bin-region { stroke-width: var(--lr-border-width-thick); } [part='error'] { color: var(--lr-color-danger); } .engine-viewport { display: grid; min-inline-size: 0; } .engine-viewport > * { grid-area: 1 / 1; } [part='engine'] { inline-size: 100%; block-size: var(--lr-embedding-explorer-height, var(--lr-size-20rem)); min-block-size: var(--lr-size-12rem); overflow: hidden; border-radius: var(--lr-radius-xs); } [part='engine'][hidden] { display: none; } [part='engine'] canvas { display: block; inline-size: 100%; block-size: 100%; } [part='engine-notice'] { color: var(--lr-color-text-quiet); overflow-wrap: anywhere; } [part='engine-notice'] p { margin: 0; } [part='rows'] { display: flex; flex-direction: column; min-inline-size: 0; } [part='row'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); align-items: center; min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs); overflow-wrap: anywhere; cursor: pointer; color: var(--lr-color-text); background: var(--lr-color-surface); } [part='row']:where([aria-selected='true']) { font-weight: var(--lr-font-weight-bold); } [part='row']:hover { text-decoration: underline; } [part='row']:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part='row']:active { outline: var(--lr-border-width-medium) solid var(--lr-color-brand); } [part='pagination'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-s); } [part='page-button'] { transition: var(--lr-transition-interactive); min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); color: var(--lr-color-text); background: var(--lr-color-surface); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-xs); font: inherit; cursor: pointer; } [part='page-button']:hover { text-decoration: underline; } [part='page-button']:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part='page-button']:active { border-color: var(--lr-color-brand); } [part='page-button']:disabled { cursor: default; opacity: var(--lr-opacity-disabled); } [part='legend'] { display: flex; flex-wrap: wrap; min-inline-size: 0; max-inline-size: 100%; gap: var(--lr-space-s); align-items: center; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); } [part='legend-item'] { display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; gap: var(--lr-space-2xs); } [part='legend-swatch'] { inline-size: var(--lr-size-0-75rem); block-size: var(--lr-size-0-75rem); border-radius: var(--lr-radius-xs); flex: none; } [part='legend-label'] { min-inline-size: 0; overflow-wrap: anywhere; } [part='empty'] { margin: 0; color: var(--lr-color-text-quiet); } @container ${compactContainerQuery} { [part='plot'] { min-block-size: var(--lr-size-12rem); } } `;export{styles};
|
|
@@ -12,18 +12,16 @@ export interface LyraEntityDossierConfidence{readonly label:string;readonly valu
|
|
|
12
12
|
/** Exact value shown as a hover/focus tooltip on the headline value -- see `lr-stat.exactValue`. */
|
|
13
13
|
readonly exactValue?:string;readonly caption?:string;
|
|
14
14
|
/** Breakdown rows (e.g. per-signal sub-scores) -- see `lr-stat.rows`. */
|
|
15
|
-
readonly rows?:readonly StatRow[];}export interface LyraEntityDossierEventMap extends Omit<LyraNeighborListEventMap,'lr-entity-select'>,Omit<LyraChunkInspectorEventMap,'lr-toggle'>,Omit<LyraProvenancePanelEventMap,'lr-entity-
|
|
15
|
+
readonly rows?:readonly StatRow[];}export interface LyraEntityDossierEventMap extends Omit<LyraNeighborListEventMap,'lr-entity-select'>,Omit<LyraChunkInspectorEventMap,'lr-toggle'>,Omit<LyraProvenancePanelEventMap,'lr-entity-select'>,Omit<LyraTabGroupEventMap,'lr-tab-show'>{
|
|
16
16
|
/** Canonical "user picked this entity" gesture from any composed child; a path strip adds `occurrenceIndex`. */
|
|
17
|
-
'lr-entity-select':CustomEvent<{entityId:string;occurrenceIndex?:number;}>;
|
|
18
|
-
/** @deprecated Use `lr-entity-select`. */
|
|
19
|
-
'lr-entity-activate':CustomEvent<{entityId:string;occurrenceIndex?:number;}>;'lr-tab-show':CustomEvent<{tabId:LyraEntityDossierTab;}>;}
|
|
17
|
+
'lr-entity-select':CustomEvent<{entityId:string;occurrenceIndex?:number;}>;'lr-tab-show':CustomEvent<{tabId:LyraEntityDossierTab;}>;}
|
|
20
18
|
/**
|
|
21
19
|
* `<lr-entity-dossier>` — a full entity detail surface: a persistent header (`lr-entity-card` plus
|
|
22
20
|
* an optional confidence `lr-stat`) above a `lr-tab-group` strip for Relationships (`lr-neighbor-list`),
|
|
23
21
|
* Supporting chunks (`lr-chunk-inspector`), and Provenance (`lr-provenance-panel`). Pure layout —
|
|
24
22
|
* it never fetches, ranks, or mutates graph/document state, and never re-renders what any of those
|
|
25
23
|
* five composed components already render themselves; every one of their own events (`
|
|
26
|
-
* lr-entity-select`, `lr-
|
|
24
|
+
* lr-entity-select`, `lr-node-expand`, `lr-chunk-open`,
|
|
27
25
|
* `lr-toggle`, `lr-tab-show`, plus the provenance panel's own conduit set — `lr-entity-open`, `lr-drill`,
|
|
28
26
|
* `lr-relation-activate`) bubbles through unmodified (`composed: true` crosses this component's own
|
|
29
27
|
* shadow boundary with no re-dispatch needed), except direct chunk-inspector `lr-toggle` events,
|
|
@@ -53,14 +51,10 @@ readonly rows?:readonly StatRow[];}export interface LyraEntityDossierEventMap ex
|
|
|
53
51
|
* @customElement lr-entity-dossier
|
|
54
52
|
* @event lr-entity-select - Surfaced unchanged from the embedded entity card, neighbor list, or
|
|
55
53
|
* the provenance panel's community card or path strip. `detail: { entityId, occurrenceIndex? }`.
|
|
56
|
-
* @event lr-entity-activate - Deprecated alias of `lr-entity-select` from the provenance panel's
|
|
57
|
-
* community card or path strip, dispatched right after it.
|
|
58
54
|
* @event lr-node-expand - Surfaced unchanged from the embedded neighbor list.
|
|
59
55
|
* `detail: { nodeId }`.
|
|
60
56
|
* @event lr-chunk-open - Surfaced unchanged from the embedded chunk inspector.
|
|
61
57
|
* `detail: { chunkId, sourceId, anchor? }`.
|
|
62
|
-
* @event lr-chunk-toggle - Surfaced unchanged from the embedded chunk inspector.
|
|
63
|
-
* `detail: { chunkId, expanded }`.
|
|
64
58
|
* @event lr-toggle - A section or chunk disclosure changed. Direct supporting-chunk toggles
|
|
65
59
|
* gain `section: 'chunks'`; provenance-panel toggles pass through unchanged.
|
|
66
60
|
* `detail: { section, expanded, itemId? }`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{finiteRange}from"../../../internal/numbers.js";import{graphLinkIdentity}from"./graph-model.js";import{SpatialHitIndex,SpatialProjectionWorkspace,projectSpatialScene}from"./graph-spatial.js";const EMPTY_DASH={values:[],key:""},DANGLING_DASH={values:[4,4],key:"4,4"},selectionSets=new WeakMap;function selectedIds(ids){if(!Object.isFrozen(ids))return new Set(ids);let result=selectionSets.get(ids);return result||(result=new Set(ids),selectionSets.set(ids,result)),result}class GraphBuiltin3dEngine{constructor(canvas,context){this.projectionWorkspace=new SpatialProjectionWorkspace,this.projectedById=new Map,this.edgeDashes=new WeakMap,this.textWidths=new Map,this.measuredFont="",this.canvas=canvas,this.context=context}invalidate(){this.scene=void 0,this.hitIndex=void 0}dispose(){this.canvas&&(this.canvas=void 0,this.context=void 0,this.world=void 0,this.edges=void 0,this.camera=void 0,this.scene=void 0,this.hitIndex=void 0,this.sceneViewport=void 0,this.sceneVisibleEdges=void 0,this.projectedById.clear(),this.textWidths.clear(),this.measuredFont="",this.edgeDashes=new WeakMap,this.projectionWorkspace=new SpatialProjectionWorkspace)}projectedScene(frame){const{viewport,paint}=frame,previousEdges=this.sceneVisibleEdges;return(this.world!==frame.world||this.edges!==frame.edges||this.camera!==frame.camera||this.sceneViewport?.width!==viewport.width||this.sceneViewport.height!==viewport.height||!previousEdges||previousEdges!==paint.visibleEdges&&(previousEdges.size!==paint.visibleEdges.size||[...paint.visibleEdges].some(id=>!previousEdges.has(id))))&&(this.scene=void 0),this.scene||(this.scene=projectSpatialScene(frame.world,frame.edges.filter(edge=>paint.visibleEdges.has(graphLinkIdentity(edge))),frame.camera,viewport,this.projectionWorkspace),this.hitIndex=new SpatialHitIndex(this.scene),this.projectedById=new Map(this.scene.nodes.map(node=>[node.node.id,node])),this.sceneViewport={...viewport},this.world=frame.world,this.edges=frame.edges,this.camera=frame.camera),this.sceneVisibleEdges=paint.visibleEdges,this.scene}textWidth(ctx,text){this.measuredFont!==ctx.font&&(this.measuredFont=ctx.font,this.textWidths.clear());let width=this.textWidths.get(text);return width===void 0&&(width=ctx.measureText(text).width,this.textWidths.size>=1e4&&this.textWidths.delete(this.textWidths.keys().next().value),this.textWidths.set(text,width)),width}draw(frame){const canvas=this.canvas,ctx=this.context;if(!canvas||!ctx)return;const size=frame.viewport,dpr=finiteRange(canvas.ownerDocument.defaultView?.devicePixelRatio??1,1,1,4),scale=Math.min(dpr,8192/Math.max(size.width,size.height)),width=Math.max(1,Math.round(size.width*scale)),height=Math.max(1,Math.round(size.height*scale));(canvas.width!==width||canvas.height!==height)&&(canvas.width=width,canvas.height=height),ctx.setTransform(scale,0,0,scale,0,0),ctx.clearRect(0,0,size.width,size.height);const paint=frame.paint;ctx.save(),ctx.font=`${paint.fontSize}px ${paint.font}`,ctx.textBaseline="middle";const selectedNodes=selectedIds(frame.selectedNodeIds),selectedEdges=selectedIds(frame.selectedEdgeIds),dimmedNodes=selectedIds(frame.dimmedNodeIds),dimmedEdges=selectedIds(frame.dimmedEdgeIds),zoom=frame.fittedDistance/frame.camera.distance,scene=this.projectedScene(frame),outside=(left,top,right,bottom)=>right<0||bottom<0||left>size.width||top>size.height,nodeLabels=frame.nodeLabels!=="none"&&(frame.nodeLabels==="always"||zoom>=.5);let strokeStyle;const flushStroke=()=>{strokeStyle!==void 0&&(ctx.stroke(),strokeStyle=void 0)};for(const primitive of scene.primitives)if(primitive.kind==="node"){const entry=primitive.value,id=entry.node.id,radius=entry.screenRadius*Math.SQRT2+Math.max(6,paint.fontSize),labelWidth=nodeLabels?this.textWidth(ctx,entry.node.label??id):0;if(outside(entry.x-radius,entry.y-radius,entry.x+radius+labelWidth,entry.y+radius))continue;flushStroke(),ctx.setLineDash([]),ctx.textAlign="left",ctx.globalAlpha=dimmedNodes.has(id)?paint.dimmedOpacity:1,this.drawNode(ctx,entry,paint.nodes.get(id)??paint.text),(selectedNodes.has(id)||frame.focusNodeId===id||frame.hover?.kind==="node"&&frame.hover.id===id)&&(ctx.strokeStyle=paint.selected,ctx.lineWidth=2,ctx.beginPath(),ctx.arc(entry.x,entry.y,entry.screenRadius+4,0,Math.PI*2),ctx.stroke()),nodeLabels&&(ctx.fillStyle=paint.text,ctx.fillText(entry.node.label??entry.node.id,entry.x+entry.screenRadius+4,entry.y)),entry.node.expandable&&(ctx.fillStyle=paint.text,ctx.fillText("+",entry.x+entry.screenRadius,entry.y-entry.screenRadius))}else{const entry=primitive.value,padding=Math.max(6,finiteRange(entry.edge.width??1.5,1.5,0,1e3)*3,this.projectedById.get(entry.edge.target)?.screenRadius??0),labelPoint=entry.labelPoint??entry.a,labelWidth=entry.middle&&frame.withEdgeLabels&&entry.edge.label?this.textWidth(ctx,entry.edge.label):0;if(outside(Math.min(entry.a.x,entry.b.x,labelWidth?labelPoint.x:entry.a.x)-padding,Math.min(entry.a.y,entry.b.y,labelWidth?labelPoint.y:entry.a.y)-padding-paint.fontSize,Math.max(entry.a.x,entry.b.x,labelWidth?labelPoint.x+labelWidth:entry.a.x)+padding,Math.max(entry.a.y,entry.b.y,labelWidth?labelPoint.y:entry.a.y)+padding))continue;const alpha=dimmedEdges.has(entry.id)?paint.dimmedOpacity:1,selected=selectedEdges.has(entry.id)||frame.hover?.kind==="link"&&frame.hover.id===entry.id,color=selected?paint.selected:paint.edges.get(entry.id)??paint.text,width2=finiteRange(entry.edge.width??1.5,1.5,0,1e3),labeled=entry.middle&&frame.withEdgeLabels&&entry.edge.label,dash=this.dashPattern(entry.edge,entry.dangling),opaque=alpha===1&&(/^rgb\([\d.,\s]+\)$/.test(color)||/^#[\da-f]{6}$/i.test(color));if(!entry.edge.directed&&!labeled&&width2>0&&opaque){const style=`${color}|${width2+(selected?2:0)}|${alpha}|${dash.key}|${entry.offset}`;strokeStyle!==style&&(flushStroke(),ctx.beginPath(),strokeStyle=style,ctx.strokeStyle=color,ctx.lineWidth=width2+(selected?2:0),ctx.globalAlpha=alpha,ctx.setLineDash(dash.values),ctx.lineDashOffset=-entry.offset),ctx.moveTo(entry.a.x,entry.a.y),ctx.lineTo(entry.b.x,entry.b.y);continue}flushStroke(),ctx.globalAlpha=alpha,this.drawSegment(ctx,entry,selected?paint.selected:paint.edges.get(entry.id)??paint.text,selected,this.projectedById.get(entry.edge.target)?.screenRadius??0),entry.middle&&frame.withEdgeLabels&&zoom>=finiteRange(frame.edgeLabelMinZoom,.6,.001,1e3)&&entry.edge.label&&(ctx.fillStyle=paint.text,ctx.fillText(entry.edge.label,labelPoint.x,labelPoint.y-paint.fontSize))}flushStroke(),ctx.restore()}drawNode(ctx,node,fill){ctx.fillStyle=fill,ctx.beginPath();const r=node.screenRadius;if(node.shape==="circle")ctx.arc(node.x,node.y,r,0,Math.PI*2);else if(node.shape==="square"){const half=r*Math.sqrt(Math.PI)/2;ctx.rect(node.x-half,node.y-half,2*half,2*half)}else{const half=r*Math.sqrt(Math.PI/2);ctx.moveTo(node.x,node.y-half),ctx.lineTo(node.x+half,node.y),ctx.lineTo(node.x,node.y+half),ctx.lineTo(node.x-half,node.y),ctx.closePath()}ctx.fill()}dashPattern(edge,dangling){if(dangling)return DANGLING_DASH;const cached=this.edgeDashes.get(edge);if(cached)return cached;const dash=edge.dash,result=Array.isArray(dash)&&dash.length>0&&dash.length<=32&&dash.every(value=>Number.isFinite(value)&&value>=0)?{values:[...dash],key:dash.join(",")}:EMPTY_DASH;return Object.isFrozen(edge)&&this.edgeDashes.set(edge,result),result}drawSegment(ctx,segment,color,selected,targetRadius){const{a,b,edge}=segment;if(ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=finiteRange(edge.width??1.5,1.5,0,1e3)+(selected?2:0),ctx.setLineDash(this.dashPattern(edge,segment.dangling).values),ctx.lineDashOffset=-segment.offset,ctx.beginPath(),ctx.moveTo(a.x,a.y),ctx.lineTo(b.x,b.y),ctx.stroke(),segment.last&&edge.directed){const angle=Math.atan2(b.y-a.y,b.x-a.x),inset=targetRadius,x=b.x-Math.cos(angle)*inset,y=b.y-Math.sin(angle)*inset,size=Math.max(6,ctx.lineWidth*3);ctx.beginPath(),ctx.moveTo(x,y),ctx.lineTo(x-Math.cos(angle-.45)*size,y-Math.sin(angle-.45)*size),ctx.lineTo(x-Math.cos(angle+.45)*size,y-Math.sin(angle+.45)*size),ctx.closePath(),ctx.fill()}}hit(clientX,clientY,frame){const bounds=this.canvas?.getBoundingClientRect();if(bounds)return this.projectedScene(frame),this.hitIndex?.hit(clientX-bounds.left,clientY-bounds.top)}}export{GraphBuiltin3dEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{tag}from"../../../internal/prefix.js";const loader=createEngine3dLoader({entry:"graph",tag:tag("graph"),load:()=>import("@aceshooting/lyra-3d/graph")});class GraphEngineAdapter{constructor(services={}){this.services=services,this.generation=0,this.disposed=new WeakSet}release(engine){this.disposed.has(engine)||(this.disposed.add(engine),engine.dispose())}close(){this.generation++;const previous=this.engine;this.engine=void 0,previous&&this.release(previous)}async open(request){this.close();const generation=this.generation;if(request.preference!=="webgl"||!request.eligible||!request.visible)return null;const available=(this.services.available??webgl2Available)();if(generation!==this.generation)return null;if(!available)return request.failure("unsupported"),null;let engine;try{engine=await(this.services.create??(()=>loader.create()))()}catch{return generation===this.generation&&request.failure("unavailable"),null}if(generation!==this.generation)return engine&&this.release(engine),null;if(!engine)return request.failure("unavailable"),null;let appearance=!1;try{appearance=typeof engine.setAppearance=="function"}catch{}if(generation!==this.generation)return this.release(engine),null;if(!appearance)return this.release(engine),request.failure("unavailable"),null;this.engine=engine;const current=()=>generation===this.generation&&this.engine===engine;let callbackThrew=!1,callbackError;const invoke=action=>{if(current())try{action()}catch(error){throw callbackThrew=!0,callbackError=error,error}},host={hover:item=>{invoke(()=>request.host.hover(item))},pick:(item,modifiers)=>{invoke(()=>request.host.pick(item,modifiers))},camera:camera=>{invoke(()=>request.host.camera(camera))},lost:(reason,detail)=>{invoke(()=>request.host.lost(reason,detail))},restored:()=>{invoke(()=>request.host.restored?.())},rendering:info=>{invoke(()=>request.host.rendering?.(info))},progress:(loaded,total)=>{invoke(()=>request.host.progress?.(loaded,total))}};try{await engine.mount(request.container,host)}catch(error){const active=current();if(active&&(this.engine=void 0,this.generation++),this.release(engine),callbackThrew&&Object.is(error,callbackError))throw error;return active&&request.failure(engine3dFailureReason(error)),null}return current()?engine:(this.release(engine),null)}}export{GraphEngineAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{largeDataPage,validateGraphColumns}from"../../../internal/typed-columns.js";function admitGraphEngineColumns(input){const result=validateGraphColumns(input);if(!result.ok)return result;const columns=result.columns,count=result.count;for(const axis of["x","y","z"]){const values=columns[axis];if(values){for(let index=0;index<count;index++)if(Math.abs(values[index])>1e7)return{ok:!1,issue:{code:"out-of-range",column:axis,index}}}}if(columns.size){for(let index=0;index<count;index++)if(columns.size[index]>2e7)return{ok:!1,issue:{code:"out-of-range",column:"size",index}}}let labelLength=0;for(const label of columns.labels??[])if(labelLength+=label.length,labelLength>4*1024*1024)return{ok:!1,issue:{code:"too-many",column:"labels",limit:4*1024*1024}};const positions=columns.x||columns.y||columns.z?new Float32Array(count*3):void 0;if(positions)for(let row=0;row<count;row++)positions[row*3]=columns.x?.[row]??0,positions[row*3+1]=columns.y?.[row]??0,positions[row*3+2]=columns.z?.[row]??0;const indices=new Map;for(let row=0;row<count;row++)indices.set(columns.ids[row],row);const item=index=>{if(!Number.isInteger(index)||index<0||index>=count+columns.source.length)return;if(index<count)return{kind:"node",row:index,id:columns.ids[index],label:columns.labels?.[index]??columns.ids[index]};const row=index-count;return{kind:"edge",row,source:columns.ids[columns.source[row]],target:columns.ids[columns.target[row]]}};return{ok:!0,value:{columns,data:{nodeCount:count,positions,source:columns.source,target:columns.target,sizes:columns.size,categories:columns.category,labels:columns.labels},row:id=>indices.get(id),item,page(requested){const page=largeDataPage(count+columns.source.length,requested),rows=[];for(let index=page.start;index<page.end;index++)rows.push(item(index));return{page:page.page,pageCount:page.pageCount,rows}}}}}function graphEngineColumnScene(admitted,hiddenTypes){const columns=admitted.columns,count=admitted.data.nodeCount,hidden=new Set(hiddenTypes),remap=new Int32Array(count).fill(-1);let nodes=0;for(let row=0;row<count;row++){const name=columns.category===void 0?void 0:columns.categories?.[columns.category[row]];(name===void 0||!hidden.has(name))&&(remap[row]=nodes++)}const nodeRows=new Uint32Array(nodes);for(let row=0;row<count;row++)remap[row]>=0&&(nodeRows[remap[row]]=row);let edges=0;for(let row=0;row<columns.source.length;row++)remap[columns.source[row]]>=0&&remap[columns.target[row]]>=0&&edges++;const edgeRows=new Uint32Array(edges),source=new Uint32Array(edges),target=new Uint32Array(edges),edgeCategories=columns.edgeCategory===void 0?void 0:new Uint16Array(edges);let next=0;for(let row=0;row<columns.source.length;row++){const a=remap[columns.source[row]],b=remap[columns.target[row]];a<0||b<0||(edgeRows[next]=row,source[next]=a,target[next]=b,edgeCategories&&(edgeCategories[next]=columns.edgeCategory[row]),next++)}const originalPositions=admitted.data.positions,positions=originalPositions===void 0?void 0:new Float32Array(nodes*3),sizes=columns.size===void 0?void 0:new Float32Array(nodes),categories=columns.category===void 0?void 0:new Uint16Array(nodes),labels=columns.labels===void 0?void 0:new Array(nodes);for(let row=0;row<nodes;row++){const original=nodeRows[row];positions&&(positions[row*3]=originalPositions[original*3],positions[row*3+1]=originalPositions[original*3+1],positions[row*3+2]=originalPositions[original*3+2]),sizes&&(sizes[row]=columns.size[original]),categories&&(categories[row]=columns.category[original]),labels&&(labels[row]=columns.labels[original])}const itemCount=nodes+edges,item=index=>{if(!Number.isInteger(index)||index<0||index>=itemCount)return;if(index<nodes){const row2=nodeRows[index];return{kind:"node",row:row2,id:columns.ids[row2],label:columns.labels?.[row2]??columns.ids[row2]}}const row=edgeRows[index-nodes];return{kind:"edge",row,source:columns.ids[columns.source[row]],target:columns.ids[columns.target[row]]}};return{data:{nodeCount:nodes,positions,source,target,sizes,categories,labels,edgeCategories,spatialAppearance:{sizeUnits:"world",nodeShapes:new Uint8Array(nodes)}},nodeRows,edgeRows,categoryNames:columns.categories,itemCount,nodeIndex(id){const original=admitted.row(id);if(original===void 0)return;const row=remap[original];return row<0?void 0:row},item,page(requested){const page=largeDataPage(itemCount,requested),rows=[];for(let index=page.start;index<page.end;index++)rows.push(item(index));return{page:page.page,pageCount:page.pageCount,rows}}}}export{admitGraphEngineColumns,graphEngineColumnScene};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{canonicalIdentityList,firstByRetrievalIdentity,isNonBlankIdentity}from"../retrieval-identity.js";const GRAPH_LENGTH_WITH_UNIT=new RegExp(`^${CSS_NUMBER_SOURCE}(?:px|rem|em|vw|vh)$`,"i"),graphLengthConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return GRAPH_LENGTH_WITH_UNIT.test(trimmed)?trimmed:Number(value)}},graphLinkIdentityOverrides=new WeakMap;function
|
|
1
|
+
import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{canonicalIdentityList,firstByRetrievalIdentity,isNonBlankIdentity}from"../retrieval-identity.js";const GRAPH_LENGTH_WITH_UNIT=new RegExp(`^${CSS_NUMBER_SOURCE}(?:px|rem|em|vw|vh)$`,"i"),graphLengthConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return GRAPH_LENGTH_WITH_UNIT.test(trimmed)?trimmed:Number(value)}},graphLinkIdentityOverrides=new WeakMap,anonymousEndpointKeys=new WeakMap;let anonymousEndpointCount=0;function linkEndpointIdentity(endpoint){if(typeof endpoint!="object"||endpoint===null)return String(endpoint);const id=endpoint.id;if(id!=null)return String(id);let key=anonymousEndpointKeys.get(endpoint);return key===void 0&&(key=`anonymous-endpoint:${++anonymousEndpointCount}`,anonymousEndpointKeys.set(endpoint,key)),key}function graphLinkIdentity(link){return graphLinkIdentityOverrides.get(link)??link.id??`${linkEndpointIdentity(link.source)}->${linkEndpointIdentity(link.target)}`}function copyGraphLinkIdentity(source,target){const identity=graphLinkIdentityOverrides.get(source);return identity!==void 0&&graphLinkIdentityOverrides.set(target,identity),target}function normalizeLinks(values){const valid=(Array.isArray(values)?values:[]).filter(value=>value===null||typeof value!="object"?!1:isNonBlankIdentity(value.source)&&isNonBlankIdentity(value.target)&&(value.id===void 0||isNonBlankIdentity(value.id))),explicitIds=new Set(valid.flatMap(value=>value.id===void 0?[]:[value.id])),implicitIdentities=new Map,seen=new Set,retained=[];for(const value of valid){const baseIdentity=value.id??`${value.source}->${value.target}`;let identity=baseIdentity;if(value.id===void 0&&explicitIds.has(baseIdentity)){identity=implicitIdentities.get(baseIdentity)??`implicit:${baseIdentity}`;let suffix=2;for(;explicitIds.has(identity);)identity=`implicit:${baseIdentity}#${suffix++}`;implicitIdentities.set(baseIdentity,identity)}if(!seen.has(identity))if(seen.add(identity),identity===baseIdentity)retained.push(value);else{const copy={...value};graphLinkIdentityOverrides.set(copy,identity),retained.push(copy)}}return Object.freeze(retained)}function normalizeCommunities(values){return Object.freeze(firstByRetrievalIdentity(values,community=>community?.id).map(community=>Object.freeze({...community,memberIds:canonicalIdentityList(community.memberIds??[])})))}function normalizeGraphModel(nodes,links,nodeTypes,communities){return Object.freeze({nodes:Object.freeze(firstByRetrievalIdentity(nodes,node=>node?.id)),links:normalizeLinks(links),nodeTypes:Object.freeze(firstByRetrievalIdentity(nodeTypes,type=>type?.id)),communities:normalizeCommunities(communities)})}export{copyGraphLinkIdentity,graphLengthConverter,graphLinkIdentity,normalizeGraphModel};
|
|
@@ -1,30 +1,35 @@
|
|
|
1
|
-
import{html,nothing}from"lit";import{finiteRange}from"../../../internal/numbers.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{graphLinkIdentity}from"./graph-model.js";import{SpatialHitIndex,SpatialProjectionWorkspace,fittedGraphCamera,normalizeGraphCamera,panGraphCamera,projectSpatialPoint,projectSpatialScene,spatialNodePosition}from"./graph-spatial.js";const EMPTY_DASH={values:[],key:""},DANGLING_DASH={values:[4,4],key:"4,4"},selectionSets=new WeakMap;function selectedIds(ids){if(!Object.isFrozen(ids))return new Set(ids);let result=selectionSets.get(ids);return result||(result=new Set(ids),selectionSets.set(ids,result)),result}const PAGE_SIZE=200,ORBIT_STEP=Math.PI/18;class GraphSpatialController{constructor(host,options){this.host=host,this.options=options,this.world=[],this.edges=[],this.items=[],this.communityCounts=new Map,this.worldById=new Map,this.nodeIndexById=new Map,this.currentCamera=normalizeGraphCamera(void 0,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.fittedDistance=500,this.cameraInitialized=!1,this.pendingInitialFit=!1,this.projectedById=new Map,this.hoverGeneration=0,this.projectionWorkspace=new SpatialProjectionWorkspace,this.edgeDashes=new WeakMap,this.textWidths=new Map,this.measuredFont="",this.visible=!0,this.notifyCamera=!1,this.contextFailed=!1,this.page=0,this.focusAfterViewChange=!1,this.instructionsId=nextId("graph-spatial-instructions"),this.pointerDown=event=>{if(!(event.button!==0||this.gesture)){this.cancelHover(),this.canvas?.focus(),this.gesture={id:event.pointerId,startX:event.clientX,startY:event.clientY,x:event.clientX,y:event.clientY,moved:!1,pan:event.shiftKey};try{this.canvas?.setPointerCapture(event.pointerId)}catch{}this.setHover(void 0)}},this.pointerMove=event=>{const gesture=this.gesture;if(!gesture){this.queueHover(event.clientX,event.clientY);return}if(gesture.id!==event.pointerId)return;gesture.moved||=Math.hypot(event.clientX-gesture.startX,event.clientY-gesture.startY)>5;const dx=event.clientX-gesture.x,dy=event.clientY-gesture.y;gesture.x=event.clientX,gesture.y=event.clientY,gesture.moved&&(gesture.pan?this.changeCamera(panGraphCamera(this.currentCamera,dx,dy,this.viewport())):this.orbit(dx*.008,-dy*.008))},this.pointerUp=event=>{const gesture=this.gesture;if(!(!gesture||gesture.id!==event.pointerId)&&(this.cancelGesture(),!gesture.moved&&Math.hypot(event.clientX-gesture.startX,event.clientY-gesture.startY)<=5)){const hit=this.hit(event.clientX,event.clientY);hit&&this.options.activate(hit,event)}},this.pointerCancel=event=>{this.cancelHover(),event.pointerId===this.gesture?.id&&this.cancelGesture()},this.wheel=event=>{this.host.shadowRoot?.activeElement!==this.canvas&&!this.gesture||(event.preventDefault(),this.zoom(Math.exp(-finiteRange(event.deltaY,0,-300,300)*.002)))},this.keyDown=event=>{const direction=this.options.direction()==="rtl"?-1:1,dx=event.key==="ArrowRight"?direction:event.key==="ArrowLeft"?-direction:0,dy=event.key==="ArrowDown"?1:event.key==="ArrowUp"?-1:0;dx||dy?(event.preventDefault(),event.shiftKey?this.changeCamera(panGraphCamera(this.currentCamera,dx*24,dy*24,this.viewport())):this.orbit(dx*ORBIT_STEP,-dy*ORBIT_STEP)):event.key==="+"||event.key==="="||event.key==="-"?(event.preventDefault(),this.zoom(event.key==="-"?1/1.2:1.2)):event.key==="Home"?(event.preventDefault(),this.fit()):event.key==="Escape"&&this.options.clearSelection()}}prepare(){const model=this.options.model();if(this.source!==model||this.hiddenTypes!==this.host.hiddenTypes){this.source=model,this.hiddenTypes=this.host.hiddenTypes;const hidden=new Set(this.host.hiddenTypes),allIds=new Set(model.nodes.map(node=>node.id));this.world=model.nodes.filter(node=>node.type==null||!hidden.has(node.type)).map(node=>({node,position:spatialNodePosition(node),radius:finiteRange(node.radius??15,15,6,24),shape:this.options.nodeShape(node)})),this.worldById=new Map(this.world.map(node=>[node.node.id,node])),this.nodeIndexById=new Map(this.world.map((node,index)=>[node.node.id,index])),this.edges=model.links.filter(edge=>this.worldById.has(edge.source)&&(this.worldById.has(edge.target)||!allIds.has(edge.target)));const communityMembers=new Map;for(const{node}of this.world){if(!node.communityId)continue;let members=communityMembers.get(node.communityId);members||communityMembers.set(node.communityId,members=new Set),members.add(node.id)}this.communityCounts=new Map;const communities=model.communities.filter(community=>{const members=communityMembers.get(community.id)??new Set;for(const id of community.memberIds)this.worldById.has(id)&&members.add(id);return this.communityCounts.set(community.id,members.size),members.size>0});this.items=[...this.world.map(({node})=>({kind:"node",node})),...this.edges.map(edge=>({kind:"link",edge})),...communities.map(community=>({kind:"community",community}))];const focused=this.host.shadowRoot?.activeElement;if(focused?.getAttribute("part")==="spatial-list-item"){const id=focused.getAttribute("data-node-id");id&&!this.worldById.has(id)&&(this.focusAfterViewChange=!0)}this.page=Math.min(this.page,Math.max(0,Math.ceil(this.items.length/PAGE_SIZE)-1)),this.scene=void 0,this.setHover(void 0),!this.cameraInitialized&&this.world.length&&(this.currentCamera=fittedGraphCamera(this.world,this.viewport()),this.fittedDistance=this.currentCamera.distance,this.cameraInitialized=!0,this.pendingInitialFit=!0)}this.authoredCamera!==this.host.camera&&(this.authoredCamera=this.host.camera,this.pendingInitialFit=!1,this.currentCamera=this.authoredCamera?normalizeGraphCamera(this.authoredCamera,this.currentCamera):fittedGraphCamera(this.world,this.viewport()),this.scene=void 0)}update(repaint=!0){if(!this.host.isConnected||this.host.view==="2d"){this.disconnect();return}repaint&&(this.paint=void 0);const next=this.host.renderRoot.querySelector('[part="spatial-canvas"]')??void 0;if(this.canvas!==next){this.cancelGesture(),this.resize?.disconnect(),this.intersection?.disconnect(),this.canvas=next,this.scene=void 0,this.fitInitialCanvas();try{this.context=next?.getContext("2d")??void 0}catch{this.context=void 0}next&&!this.context&&!this.contextFailed&&(this.contextFailed=!0,this.options.afterUpdate(()=>{!this.contextFailed||this.host.view!=="3d"||(this.options.unavailable(),this.options.repaint())},"graph-spatial-context"));const view=this.host.ownerDocument.defaultView;if(next&&view){const Resize=view.ResizeObserver;Resize&&(this.resize=new Resize(()=>{this.fitInitialCanvas(),this.scene=void 0,this.schedule()}),this.resize.observe(next));const Intersection=view.IntersectionObserver;Intersection&&(this.intersection=new Intersection(entries=>{this.visible=entries[0]?.isIntersecting??!0,this.visible&&this.schedule()}),this.intersection.observe(next))}}this.schedule(),this.focusAfterViewChange&&(this.focusAfterViewChange=!1,(this.host.renderRoot.querySelector('[part="spatial-list-item"]')??this.host.renderRoot.querySelector('[part="spatial-canvas"]')??this.host.renderRoot.querySelector('[data-spatial-action="3d"]'))?.focus())}disconnect(){this.cancelHover(),this.hitIndex=void 0,this.cancelGesture(),this.frame!==void 0&&this.frameWindow?.cancelAnimationFrame(this.frame),this.frame=void 0,this.frameWindow=void 0,this.notifyCamera=!1,this.lastKeyActivation=void 0,this.resize?.disconnect(),this.resize=void 0,this.intersection?.disconnect(),this.intersection=void 0,this.canvas=void 0,this.context=void 0,this.scene=void 0,this.hover=void 0,this.visible=!0,this.contextFailed=!1}invalidate(){this.paint=void 0,this.scene=void 0,this.schedule()}fitInitialCanvas(){!this.pendingInitialFit||!this.canvas?.clientWidth||!this.canvas.clientHeight||(this.pendingInitialFit=!1,this.currentCamera=fittedGraphCamera(this.world,this.viewport()),this.fittedDistance=this.currentCamera.distance,this.scene=void 0)}viewport(){return{width:Math.max(1,this.canvas?.clientWidth||this.options.viewport().width),height:Math.max(1,this.canvas?.clientHeight||this.options.viewport().height)}}position(id){return this.prepare(),this.worldById.get(id)?.position}screenPosition(id){if(this.host.view!=="3d"||!this.canvas)return;const node=this.worldById.get(id),point=node&&projectSpatialPoint(node.position,this.currentCamera,this.viewport());if(!point)return;const bounds=this.canvas.getBoundingClientRect(),hostBounds=this.host.getBoundingClientRect();return{x:bounds.left-hostBounds.left+point.x,y:bounds.top-hostBounds.top+point.y}}fit(padding){if(this.prepare(),!this.world.length)return;const camera=fittedGraphCamera(this.world,this.viewport(),padding);this.fittedDistance=camera.distance,this.changeCamera(camera)}focusNode(id,zoom){this.prepare();const node=this.worldById.get(id);return node?((this.host.view==="list"||this.contextFailed)&&(this.page=Math.floor((this.nodeIndexById.get(id)??0)/PAGE_SIZE),this.options.repaint()),this.changeCamera({...this.currentCamera,target:node.position,distance:zoom===void 0?this.currentCamera.distance:this.fittedDistance/this.safeZoom(zoom)}),!0):!1}safeZoom(value){const min=finiteRange(this.host.minZoom,.1,.001,1e3),max=finiteRange(this.host.maxZoom,8,.001,1e3);return finiteRange(value,1,Math.min(min,max),Math.max(min,max))}zoom(factor){const zoom=this.safeZoom(this.fittedDistance/this.currentCamera.distance*factor);this.changeCamera({...this.currentCamera,distance:this.fittedDistance/zoom})}orbit(yaw,pitch){this.changeCamera({...this.currentCamera,yaw:this.currentCamera.yaw+yaw,pitch:this.currentCamera.pitch+pitch})}changeCamera(camera){this.pendingInitialFit=!1,this.currentCamera=normalizeGraphCamera(camera,this.currentCamera),this.scene=void 0,this.notifyCamera=!0,this.schedule()}schedule(){if(!this.host.isConnected||this.host.view==="2d"||this.frame!==void 0||!this.visible&&!this.notifyCamera)return;const view=this.host.ownerDocument.defaultView;view&&(this.frameWindow=view,this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.frameWindow=void 0,!(!this.host.isConnected||this.host.view==="2d")&&(this.visible&&this.draw(),this.notifyCamera&&(this.notifyCamera=!1,this.options.cameraChanged(normalizeGraphCamera(this.currentCamera,this.currentCamera))))}))}projectedScene(viewport=this.viewport()){const paint=this.paint??=this.options.paint(this.world,this.edges),previousEdges=this.sceneVisibleEdges;return(this.sceneViewport?.width!==viewport.width||this.sceneViewport.height!==viewport.height||!previousEdges||previousEdges!==paint.visibleEdges&&(previousEdges.size!==paint.visibleEdges.size||[...paint.visibleEdges].some(id=>!previousEdges.has(id))))&&(this.scene=void 0),this.scene||(this.scene=projectSpatialScene(this.world,this.edges.filter(edge=>paint.visibleEdges.has(graphLinkIdentity(edge))),this.currentCamera,viewport,this.projectionWorkspace),this.hitIndex=new SpatialHitIndex(this.scene),this.projectedById=new Map(this.scene.nodes.map(node=>[node.node.id,node])),this.sceneViewport=viewport),this.sceneVisibleEdges=paint.visibleEdges,this.scene}textWidth(ctx,text){this.measuredFont!==ctx.font&&(this.measuredFont=ctx.font,this.textWidths.clear());let width=this.textWidths.get(text);return width===void 0&&(width=ctx.measureText(text).width,this.textWidths.size>=1e4&&this.textWidths.delete(this.textWidths.keys().next().value),this.textWidths.set(text,width)),width}draw(){const canvas=this.canvas,ctx=this.context;if(!canvas||!ctx||this.host.view!=="3d")return;const size=this.viewport(),dpr=finiteRange(this.host.ownerDocument.defaultView?.devicePixelRatio??1,1,1,4),scale=Math.min(dpr,8192/Math.max(size.width,size.height)),width=Math.max(1,Math.round(size.width*scale)),height=Math.max(1,Math.round(size.height*scale));(canvas.width!==width||canvas.height!==height)&&(canvas.width=width,canvas.height=height),ctx.setTransform(scale,0,0,scale,0,0),ctx.clearRect(0,0,size.width,size.height);const paint=this.paint??=this.options.paint(this.world,this.edges);ctx.save(),ctx.font=`${paint.fontSize}px ${paint.font}`,ctx.textBaseline="middle";const selectedNodes=selectedIds(this.host.selectedNodeIds),selectedEdges=selectedIds(this.host.selectedEdgeIds),dimmedNodes=selectedIds(this.host.dimmedNodeIds),dimmedEdges=selectedIds(this.host.dimmedEdgeIds),zoom=this.fittedDistance/this.currentCamera.distance,scene=this.projectedScene(size),outside=(left,top,right,bottom)=>right<0||bottom<0||left>size.width||top>size.height,nodeLabels=this.host.nodeLabels!=="none"&&(this.host.nodeLabels==="always"||zoom>=.5);let strokeStyle;const flushStroke=()=>{strokeStyle!==void 0&&(ctx.stroke(),strokeStyle=void 0)};for(const primitive of scene.primitives)if(primitive.kind==="node"){const entry=primitive.value,id=entry.node.id,radius=entry.screenRadius*Math.SQRT2+Math.max(6,paint.fontSize),labelWidth=nodeLabels?this.textWidth(ctx,entry.node.label??id):0;if(outside(entry.x-radius,entry.y-radius,entry.x+radius+labelWidth,entry.y+radius))continue;flushStroke(),ctx.setLineDash([]),ctx.textAlign="left",ctx.globalAlpha=dimmedNodes.has(id)?paint.dimmedOpacity:1,this.drawNode(ctx,entry,paint.nodes.get(id)??paint.text),(selectedNodes.has(id)||this.host.focusNodeId===id||this.hover?.kind==="node"&&this.hover.id===id)&&(ctx.strokeStyle=paint.selected,ctx.lineWidth=2,ctx.beginPath(),ctx.arc(entry.x,entry.y,entry.screenRadius+4,0,Math.PI*2),ctx.stroke()),nodeLabels&&(ctx.fillStyle=paint.text,ctx.fillText(entry.node.label??entry.node.id,entry.x+entry.screenRadius+4,entry.y)),entry.node.expandable&&(ctx.fillStyle=paint.text,ctx.fillText("+",entry.x+entry.screenRadius,entry.y-entry.screenRadius))}else{const entry=primitive.value,padding=Math.max(6,finiteRange(entry.edge.width??1.5,1.5,0,1e3)*3,this.projectedById.get(entry.edge.target)?.screenRadius??0),labelPoint=entry.labelPoint??entry.a,labelWidth=entry.middle&&this.host.withEdgeLabels&&entry.edge.label?this.textWidth(ctx,entry.edge.label):0;if(outside(Math.min(entry.a.x,entry.b.x,labelWidth?labelPoint.x:entry.a.x)-padding,Math.min(entry.a.y,entry.b.y,labelWidth?labelPoint.y:entry.a.y)-padding-paint.fontSize,Math.max(entry.a.x,entry.b.x,labelWidth?labelPoint.x+labelWidth:entry.a.x)+padding,Math.max(entry.a.y,entry.b.y,labelWidth?labelPoint.y:entry.a.y)+padding))continue;const alpha=dimmedEdges.has(entry.id)?paint.dimmedOpacity:1,selected=selectedEdges.has(entry.id)||this.hover?.kind==="link"&&this.hover.id===entry.id,color=selected?paint.selected:paint.edges.get(entry.id)??paint.text,width2=finiteRange(entry.edge.width??1.5,1.5,0,1e3),labeled=entry.middle&&this.host.withEdgeLabels&&entry.edge.label,dash=this.dashPattern(entry.edge,entry.dangling),opaque=alpha===1&&(/^rgb\([\d.,\s]+\)$/.test(color)||/^#[\da-f]{6}$/i.test(color));if(!entry.edge.directed&&!labeled&&width2>0&&opaque){const style=`${color}|${width2+(selected?2:0)}|${alpha}|${dash.key}|${entry.offset}`;strokeStyle!==style&&(flushStroke(),ctx.beginPath(),strokeStyle=style,ctx.strokeStyle=color,ctx.lineWidth=width2+(selected?2:0),ctx.globalAlpha=alpha,ctx.setLineDash(dash.values),ctx.lineDashOffset=-entry.offset),ctx.moveTo(entry.a.x,entry.a.y),ctx.lineTo(entry.b.x,entry.b.y);continue}flushStroke(),ctx.globalAlpha=alpha,this.drawSegment(ctx,entry,selected?paint.selected:paint.edges.get(entry.id)??paint.text,selected,this.projectedById.get(entry.edge.target)?.screenRadius??0),entry.middle&&this.host.withEdgeLabels&&zoom>=finiteRange(this.host.edgeLabelMinZoom,.6,.001,1e3)&&entry.edge.label&&(ctx.fillStyle=paint.text,ctx.fillText(entry.edge.label,labelPoint.x,labelPoint.y-paint.fontSize))}flushStroke(),ctx.restore()}drawNode(ctx,node,fill){ctx.fillStyle=fill,ctx.beginPath();const r=node.screenRadius;if(node.shape==="circle")ctx.arc(node.x,node.y,r,0,Math.PI*2);else if(node.shape==="square"){const half=r*Math.sqrt(Math.PI)/2;ctx.rect(node.x-half,node.y-half,2*half,2*half)}else{const half=r*Math.sqrt(Math.PI/2);ctx.moveTo(node.x,node.y-half),ctx.lineTo(node.x+half,node.y),ctx.lineTo(node.x,node.y+half),ctx.lineTo(node.x-half,node.y),ctx.closePath()}ctx.fill()}dashPattern(edge,dangling){if(dangling)return DANGLING_DASH;const cached=this.edgeDashes.get(edge);if(cached)return cached;const dash=edge.dash,result=Array.isArray(dash)&&dash.length>0&&dash.length<=32&&dash.every(value=>Number.isFinite(value)&&value>=0)?{values:[...dash],key:dash.join(",")}:EMPTY_DASH;return Object.isFrozen(edge)&&this.edgeDashes.set(edge,result),result}drawSegment(ctx,segment,color,selected,targetRadius){const{a,b,edge}=segment;if(ctx.strokeStyle=color,ctx.fillStyle=color,ctx.lineWidth=finiteRange(edge.width??1.5,1.5,0,1e3)+(selected?2:0),ctx.setLineDash(this.dashPattern(edge,segment.dangling).values),ctx.lineDashOffset=-segment.offset,ctx.beginPath(),ctx.moveTo(a.x,a.y),ctx.lineTo(b.x,b.y),ctx.stroke(),segment.last&&edge.directed){const angle=Math.atan2(b.y-a.y,b.x-a.x),inset=targetRadius,x=b.x-Math.cos(angle)*inset,y=b.y-Math.sin(angle)*inset,size=Math.max(6,ctx.lineWidth*3);ctx.beginPath(),ctx.moveTo(x,y),ctx.lineTo(x-Math.cos(angle-.45)*size,y-Math.sin(angle-.45)*size),ctx.lineTo(x-Math.cos(angle+.45)*size,y-Math.sin(angle+.45)*size),ctx.closePath(),ctx.fill()}}hit(clientX,clientY){const bounds=this.canvas?.getBoundingClientRect();if(bounds)return this.projectedScene(),this.hitIndex?.hit(clientX-bounds.left,clientY-bounds.top)}cancelHover(){this.hoverGeneration++,this.hoverFrame!==void 0&&this.hoverFrameWindow?.cancelAnimationFrame(this.hoverFrame),this.hoverFrame=void 0,this.hoverFrameWindow=void 0,this.pendingHover=void 0}queueHover(x,y){if(this.pendingHover={x,y},this.hoverFrame!==void 0)return;const view=this.host.ownerDocument.defaultView;if(!view)return;const generation=this.hoverGeneration;this.hoverFrameWindow=view,this.hoverFrame=view.requestAnimationFrame(()=>{if(generation!==this.hoverGeneration)return;this.hoverFrame=void 0,this.hoverFrameWindow=void 0;const point=this.pendingHover;this.pendingHover=void 0,point&&this.host.isConnected&&this.host.view==="3d"&&!this.gesture&&this.setHover(this.hit(point.x,point.y))})}setHover(next){if(this.hover?.kind===next?.kind&&this.hover?.id===next?.id)return;const previous=this.hover;this.hover=next,this.canvas&&(this.canvas.title=next?.kind==="node"?this.options.nodeTooltip(next.node):next?.kind==="link"?this.options.edgeTooltip(next.edge):""),this.options.hover(previous,next),this.schedule()}cancelGesture(){const gesture=this.gesture;this.gesture=void 0,gesture&&this.canvas?.hasPointerCapture(gesture.id)&&this.canvas.releasePointerCapture(gesture.id)}changeView(view){this.cancelGesture(),view==="3d"&&(this.contextFailed=!1),this.host.view=view,this.options.repaint(),this.focusAfterViewChange=!0,this.options.viewChanged()}changePage(delta){this.page=Math.max(0,Math.min(Math.ceil(this.items.length/PAGE_SIZE)-1,this.page+delta)),this.focusAfterViewChange=!0,this.options.repaint()}listKeyDown(item,event){if(item.kind!=="node"||event.key!=="Enter"&&event.key!==" "||event.repeat)return;const time=this.host.ownerDocument.defaultView?.performance.now()??0;this.lastKeyActivation?.id===item.node.id&&time-this.lastKeyActivation.time<=500?(this.lastKeyActivation=void 0,this.options.expand(item.node.id)):this.lastKeyActivation={id:item.node.id,time}}activateItem(item,event){item.kind==="node"?this.options.activate({kind:"node",id:item.node.id,node:item.node},event):item.kind==="link"?this.options.activate({kind:"link",id:graphLinkIdentity(item.edge),edge:item.edge},event):this.options.community(item.community)}render(limitNotices){this.prepare();const messages=this.options.messages(),list=this.host.view==="list"||this.contextFailed,pageItems=this.items.slice(this.page*PAGE_SIZE,(this.page+1)*PAGE_SIZE),number=getNumberFormat(this.options.locale()),selectedNodes=selectedIds(this.host.selectedNodeIds),selectedEdges=selectedIds(this.host.selectedEdgeIds),button=(action,label,callback)=>html`<button type="button" part="spatial-control" data-spatial-action=${action} @click=${callback}>${label}</button>`;return html`<div part="base" class="spatial-base">
|
|
1
|
+
import{composedParentElement,isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{Engine3dSelection,engine3dFallbackNotice}from"../../../internal/engine-3d.js";import{GraphEngineAdapter}from"./graph-engine-adapter.js";import{graphEngineColumnScene}from"./graph-engine-columns.js";import{graphWebglCamera,graphWebglData}from"./graph-webgl-engine.js";import{html,nothing}from"lit";import{finiteRange}from"../../../internal/numbers.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{graphLinkIdentity}from"./graph-model.js";import{fittedGraphCamera,normalizeGraphCamera,panGraphCamera,projectSpatialPoint,spatialNodePosition}from"./graph-spatial.js";import{GraphBuiltin3dEngine}from"./graph-builtin-3d-engine.js";const selectionSets=new WeakMap;function selectedIds(ids){if(!Object.isFrozen(ids))return new Set(ids);let result=selectionSets.get(ids);return result||(result=new Set(ids),selectionSets.set(ids,result)),result}const PAGE_SIZE=200,ORBIT_STEP=Math.PI/18;class GraphSpatialController{constructor(host,options){this.host=host,this.options=options,this.selection=new Engine3dSelection(!0),this.enginePending=!1,this.engineEpoch=0,this.engineRevision=0,this.engineStyleKey="",this.engineSizeKey="",this.edgeRows=new Map,this.pendingFallbacks=[],this.rgbaCache=new Map,this.world=[],this.edges=[],this.items=[],this.communityCounts=new Map,this.worldById=new Map,this.nodeIndexById=new Map,this.currentCamera=normalizeGraphCamera(void 0,{yaw:0,pitch:0,distance:500,target:{x:0,y:0,z:0}}),this.fittedDistance=500,this.cameraInitialized=!1,this.pendingInitialFit=!1,this.hoverGeneration=0,this.visible=!0,this.notifyCamera=!1,this.contextFailed=!1,this.page=0,this.focusAfterViewChange=!1,this.instructionsId=nextId("graph-spatial-instructions"),this.enginePointerDown={capture:!0,handleEvent:()=>{this.engineSurface?.focus()}},this.enginePointerMove={capture:!0,handleEvent:()=>{this.schedule()}},this.pointerDown=event=>{if(this.selection.renderer!=="webgl"&&!(event.button!==0||this.gesture)){this.cancelHover(),this.canvas?.focus(),this.gesture={id:event.pointerId,startX:event.clientX,startY:event.clientY,x:event.clientX,y:event.clientY,moved:!1,pan:event.shiftKey};try{this.canvas?.setPointerCapture(event.pointerId)}catch{}this.setHover(void 0)}},this.pointerMove=event=>{if(this.selection.renderer==="webgl"){this.schedule();return}const gesture=this.gesture;if(!gesture){this.queueHover(event.clientX,event.clientY);return}if(gesture.id!==event.pointerId)return;gesture.moved||=Math.hypot(event.clientX-gesture.startX,event.clientY-gesture.startY)>5;const dx=event.clientX-gesture.x,dy=event.clientY-gesture.y;gesture.x=event.clientX,gesture.y=event.clientY,gesture.moved&&(gesture.pan?this.changeCamera(this.panCamera(dx,dy)):this.orbit(dx*.008,-dy*.008))},this.pointerUp=event=>{const gesture=this.gesture;if(!(!gesture||gesture.id!==event.pointerId)&&(this.cancelGesture(),!gesture.moved&&Math.hypot(event.clientX-gesture.startX,event.clientY-gesture.startY)<=5)){const hit=this.hit(event.clientX,event.clientY);hit&&this.options.activate(hit,event)}},this.pointerCancel=event=>{this.cancelHover(),event.pointerId===this.gesture?.id&&this.cancelGesture()},this.wheel=event=>{if(this.selection.renderer==="webgl"){if(this.host.shadowRoot?.activeElement!==this.engineSurface)return;event.preventDefault(),this.zoom(Math.exp(-finiteRange(event.deltaY,0,-300,300)*.002));return}this.host.shadowRoot?.activeElement!==this.canvas&&!this.gesture||(event.preventDefault(),this.zoom(Math.exp(-finiteRange(event.deltaY,0,-300,300)*.002)))},this.keyDown=event=>{const direction=this.options.direction()==="rtl"?-1:1,dx=event.key==="ArrowRight"?direction:event.key==="ArrowLeft"?-direction:0,dy=event.key==="ArrowDown"?1:event.key==="ArrowUp"?-1:0;dx||dy?(event.preventDefault(),event.shiftKey?this.changeCamera(this.panCamera(dx*24,dy*24)):this.orbit(dx*ORBIT_STEP,-dy*ORBIT_STEP)):event.key==="+"||event.key==="="||event.key==="-"?(event.preventDefault(),this.zoom(event.key==="-"?1/1.2:1.2)):event.key==="Home"?(event.preventDefault(),this.fit()):event.key==="Escape"&&this.options.clearSelection()},this.adapter=new GraphEngineAdapter(options.engineServices)}get itemCount(){return this.columnScene?.itemCount??this.items.length}columnItem(index){const item=this.columnScene?.item(index);if(item)return item.kind==="node"?{kind:"node",node:{id:item.id,label:item.label,type:this.columns?.columns.category?this.columns.columns.categories?.[this.columns.columns.category[item.row]]:void 0}}:{kind:"link",edge:{id:`column-edge-${item.row}`,source:item.source,target:item.target}}}pageItems(){if(!this.columnScene)return this.items.slice(this.page*PAGE_SIZE,(this.page+1)*PAGE_SIZE);const result=[];for(let i=this.page*PAGE_SIZE;i<Math.min(this.itemCount,(this.page+1)*PAGE_SIZE);i++){const item=this.columnItem(i);item&&result.push(item)}return result}engineHit(index){if(this.engineDataKey!==(this.columnScene??this.world)||index===null||!Number.isInteger(index)||index<0)return;if(this.columnScene){const item=this.columnItem(index);return item?.kind==="node"?{kind:"node",id:item.node.id,node:item.node}:item?.kind==="link"?{kind:"link",id:graphLinkIdentity(item.edge),edge:item.edge}:void 0}const node=this.world[index]?.node;if(node)return{kind:"node",id:node.id,node};const edge=this.edges[index-this.world.length];return edge?{kind:"link",id:graphLinkIdentity(edge),edge}:void 0}snapshotEnginePositions(){if(!(!this.engine||this.columnScene||this.engineDataKey!==this.world)){for(let row=0;row<this.world.length;row++){const position=this.engine.positionOf?.(row);if(!position)continue;const entry={...this.world[row],position:Object.freeze({...position})};this.world[row]=entry,this.worldById.set(entry.node.id,entry)}this.builtin?.invalidate()}}retryEngine(){this.closeEngine(),this.selection.prefer(this.preference),this.fallback=void 0,this.contextFailed=!1,this.options.repaint()}closeEngine(){this.snapshotEnginePositions(),this.eligibility?.disconnect(),this.eligibility=void 0,this.engineEpoch++,this.enginePending=!1,this.engine=void 0,this.engineDataKey=this.enginePaintKey=void 0,this.engineStyleKey=this.engineSizeKey="",this.stateInputs=void 0,this.edgeRowsKey=void 0,this.adapter.close()}failEngine(reason){this.snapshotEnginePositions();const detail=this.selection.fail(reason);detail&&(this.fallback=detail,this.setHover(void 0),this.pendingFallbacks.push({detail,epoch:this.engineEpoch}),this.options.afterUpdate(()=>{const pending=this.pendingFallbacks;this.pendingFallbacks=[];for(const entry of pending)!this.host.isConnected||entry.epoch!==this.engineEpoch||this.options.engineFallback?.(entry.detail);this.host.isConnected&&this.options.repaint()},"graph-engine-fallback"))}ensureEngine(){const surface=this.engineSurface;if(!surface||this.engine||this.enginePending||!this.host.isConnected||this.host.view!=="3d"||this.selection.renderer!=="webgl")return;if(!this.visible||!isAccessibilityVisible(surface)){const view=this.host.ownerDocument.defaultView;if(!this.eligibility&&view?.MutationObserver){const epoch2=this.engineEpoch;this.eligibility=new view.MutationObserver(()=>{epoch2!==this.engineEpoch||this.engineSurface!==surface||!this.host.isConnected||(view.IntersectionObserver||(this.visible=surface.clientWidth>0&&surface.clientHeight>0),this.ensureEngine())});let ancestor=surface,depth=0;for(;ancestor&&depth++<=256;)this.eligibility.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","inert","hidden","style","class","open"]}),ancestor=composedParentElement(ancestor)}return}this.eligibility?.disconnect(),this.eligibility=void 0,this.enginePending=!0;const epoch=++this.engineEpoch;this.options.afterUpdate(()=>this.options.repaint(),"graph-engine-loading"),this.adapter.open({preference:this.preference,eligible:!this.options.sourceMode?.(),visible:this.visible,container:surface,host:{hover:item=>{this.selection.renderer==="webgl"&&this.setHover(this.engineHit(item))},pick:(item,modifiers)=>{if(this.selection.renderer!=="webgl")return;const hit=this.engineHit(item);if(!hit)return;if(modifiers.double&&hit.kind==="node"){this.options.expand(hit.id);return}const Mouse=this.host.ownerDocument.defaultView?.MouseEvent;Mouse&&this.options.activate(hit,new Mouse("click",{ctrlKey:modifiers.ctrl,shiftKey:modifiers.shift}))},camera:value=>{this.selection.renderer==="webgl"&&(this.currentCamera=graphWebglCamera(value,this.currentCamera),this.notifyCamera=!0,this.schedule())},lost:reason=>{this.selection.renderer==="webgl"&&(reason==="error"&&this.closeEngine(),this.failEngine(reason))},restored:()=>{this.selection.restore()&&(this.fallback=void 0,this.enginePaintKey=void 0,this.options.repaint(),this.schedule())}},failure:reason=>{epoch===this.engineEpoch&&this.failEngine(reason)}}).then(engine=>{epoch!==this.engineEpoch||!this.host.isConnected||this.engineSurface!==surface||(this.enginePending=!1,this.engine=engine??void 0,engine&&(surface.querySelector("canvas:not([data-graph-labels])")?.setAttribute("aria-hidden","true"),this.drawEngine(!0)),this.options.repaint())})}rgba(value){const previous=this.rgbaCache.get(value);if(previous)return previous;if(!this.rgbaContext){const canvas=this.host.ownerDocument.createElement("canvas");canvas.width=canvas.height=1,this.rgbaContext=canvas.getContext("2d",{willReadFrequently:!0})??void 0}const ctx=this.rgbaContext;if(!ctx)throw new Error("Color canvas unavailable");ctx.clearRect(0,0,1,1),ctx.fillStyle="#000000",ctx.fillStyle=value,ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=255]=ctx.getImageData(0,0,1,1).data,result=[r/255,g/255,b/255,a/255];return this.rgbaCache.set(value,result),result}engineState(){const nodes=this.columnScene?.data.nodeCount??this.world.length,nodeRow=id=>this.columnScene?this.columnScene.nodeIndex(id):this.nodeIndexById.get(id),key=this.columnScene??this.world;key!==this.edgeRowsKey&&(this.edgeRowsKey=key,this.edgeRows.clear(),this.columnScene?this.columnScene.edgeRows.forEach((original,row)=>this.edgeRows.set(`column-edge-${original}`,nodes+row)):this.edges.forEach((edge,row)=>this.edgeRows.set(graphLinkIdentity(edge),nodes+row)));const edges=this.edgeRows,map=(nodeIds,edgeIds)=>{const result=new Set;for(const id of nodeIds){const row=nodeRow(id);row!==void 0&&result.add(row)}for(const id of edgeIds){const row=edges.get(id);row!==void 0&&result.add(row)}return result};return{selected:map(this.host.selectedNodeIds,this.host.selectedEdgeIds),dimmed:map(this.host.dimmedNodeIds,this.host.dimmedEdgeIds),focus:this.host.focusNodeId?nodeRow(this.host.focusNodeId)??-1:-1,hover:this.hover?this.hover.kind==="node"?nodeRow(this.hover.id)??-1:edges.get(this.hover.id)??-1:-1}}columnData(paint){const scene=this.columnScene,data=scene.data,palette=this.options.categoryColors?.()??["#808080"],colors=new Float32Array(data.nodeCount*4),edges=new Float32Array(data.source.length*4);for(let row=0;row<data.nodeCount;row++)colors.set(this.rgba(palette[(data.categories?.[row]??0)%palette.length]),row*4);for(let row=0;row<data.source.length;row++)edges.set(this.rgba(palette[(data.edgeCategories?.[row]??0)%palette.length]),row*4);const labelLimit=Math.min(256,Math.floor(4*1024*1024/Math.max(1,data.nodeCount))),labels=data.labels??Array.from(scene.nodeRows,row=>this.columns.columns.ids[row].slice(0,labelLimit));return{...data,labels,nodeLabels:this.host.nodeLabels==="always"?"always":this.host.nodeLabels==="none"?"none":"zoom",withEdgeLabels:!1,spatialAppearance:{...data.spatialAppearance,nodeColors:colors,edgeColors:edges,dimmedOpacity:paint.dimmedOpacity}}}panCamera(dx,dy){if(this.preference!=="webgl")return panGraphCamera(this.currentCamera,dx,dy,this.viewport());const camera=this.currentCamera,units=2*camera.distance*Math.tan(Math.PI/8)/this.viewport().height,sy=Math.sin(camera.yaw),cy=Math.cos(camera.yaw),sp=Math.sin(camera.pitch),cp=Math.cos(camera.pitch);return graphWebglCamera({...camera,target:{x:camera.target.x-units*(cy*dx+sy*sp*dy),y:camera.target.y-units*cp*dy,z:camera.target.z-units*(-sy*dx+cy*sp*dy)}},camera)}drawEngine(initial=!1){const engine=this.engine;if(!engine||this.selection.renderer!=="webgl")return;const paint=this.paint??=this.options.paint(this.world,this.edges),size=this.viewport(),key=this.columnScene??this.world;try{if(key!==this.engineDataKey||paint!==this.enginePaintKey){const input=this.columnScene?this.columnData(paint):graphWebglData(this.world,this.edges,paint,color=>this.rgba(color));key!==this.engineDataKey?engine.setData(input,this.engineRevision++):engine.setAppearance({spatialAppearance:input.spatialAppearance,labels:"labels"in input?input.labels:void 0,nodeLabels:input.nodeLabels,withEdgeLabels:input.withEdgeLabels}),this.engineDataKey=key,this.enginePaintKey=paint}const view=this.host.ownerDocument.defaultView,reducedMotion=view?.matchMedia("(prefers-reduced-motion: reduce)").matches??!0,forcedColors=view?.matchMedia("(forced-colors: active)").matches??!1,styleKey=[paint.text,paint.selected,paint.font,paint.fontSize,view?.devicePixelRatio,reducedMotion,forcedColors].join("|");styleKey!==this.engineStyleKey&&(this.engineStyleKey=styleKey,engine.setStyle({background:"rgba(0,0,0,0)",foreground:paint.text,muted:paint.text,accent:paint.selected,focus:paint.selected,palette:[paint.text],fontFamily:paint.font,fontSize:paint.fontSize,devicePixelRatio:view?.devicePixelRatio??1,reducedMotion,forcedColors}));const stateInputs=[key,this.host.selectedNodeIds,this.host.selectedEdgeIds,this.host.dimmedNodeIds,this.host.dimmedEdgeIds,this.host.focusNodeId,this.hover?.kind,this.hover?.id];(!this.stateInputs||stateInputs.some((value,index)=>value!==this.stateInputs[index]))&&(this.stateInputs=stateInputs,engine.setState?.(this.engineState()));const sizeKey=`${size.width}|${size.height}`;sizeKey!==this.engineSizeKey&&(this.engineSizeKey=sizeKey,engine.resize(size.width,size.height)),initial&&!this.host.camera&&!this.cameraInitialized&&engine.fit&&(this.currentCamera=graphWebglCamera(engine.fit(),this.currentCamera),this.fittedDistance=this.currentCamera.distance,this.cameraInitialized=!0),initial&&engine.setCamera(this.currentCamera),this.drawEngineLabels(paint,size)}catch{this.closeEngine(),this.failEngine("error")}}drawEngineLabels(paint,size){const canvas=this.engineSurface?.querySelector("[data-graph-labels]"),ctx=canvas?.getContext("2d");if(!canvas||!ctx||!this.engine)return;if(this.columnScene){ctx.setTransform(1,0,0,1,0,0),ctx.clearRect(0,0,canvas.width,canvas.height);return}const ratio=Math.min(finiteRange(this.host.ownerDocument.defaultView?.devicePixelRatio??1,1,1,4),8192/Math.max(size.width,size.height));canvas.width=Math.max(1,Math.round(size.width*ratio)),canvas.height=Math.max(1,Math.round(size.height*ratio)),ctx.setTransform(ratio,0,0,ratio,0,0),ctx.font=`${paint.fontSize}px ${paint.font}`,ctx.fillStyle=paint.text,ctx.textBaseline="middle";const zoom=this.fittedDistance/this.currentCamera.distance;if(this.host.nodeLabels!=="none"&&(this.host.nodeLabels==="always"||zoom>=.5)){const count=this.world.length;for(let row=0;row<count;row++){const point=this.engine.project?.(row),position=this.engine.positionOf?.(row);if(!point||!position)continue;const label=this.world[row].node.label??this.world[row].node.id,id=this.world[row].node.id,projected=projectSpatialPoint(position,this.currentCamera,size),radius=this.world[row]?.radius??15;!projected||point.x<-512||point.x>size.width||point.y<0||point.y>size.height||(ctx.globalAlpha=selectedIds(this.host.dimmedNodeIds).has(id)?paint.dimmedOpacity:1,ctx.fillText(label,point.x+radius*projected.scale+4,point.y))}}if(!this.columnScene&&this.host.withEdgeLabels&&zoom>=finiteRange(this.host.edgeLabelMinZoom,.6,.001,1e3))for(const edge of this.edges){if(!edge.label||!paint.visibleEdges.has(graphLinkIdentity(edge)))continue;const a=this.position(edge.source),b=this.position(edge.target);if(!a)continue;const radius=this.worldById.get(edge.source)?.radius??15,anchor=edge.source===edge.target?{x:a.x,y:a.y-radius*3.2,z:a.z}:b?{x:(a.x+b.x)/2,y:(a.y+b.y)/2,z:(a.z+b.z)/2}:{x:a.x+14,y:a.y-14,z:a.z},point=projectSpatialPoint(anchor,this.currentCamera,size);point&&(ctx.globalAlpha=selectedIds(this.host.dimmedEdgeIds).has(graphLinkIdentity(edge))?paint.dimmedOpacity:1,ctx.fillText(edge.label,point.x,point.y-paint.fontSize))}ctx.globalAlpha=1}prepare(){const preference=this.options.sourceMode?.()?"builtin":this.host.engine??"builtin";this.preference!==preference&&(this.closeEngine(),this.preference=preference,this.selection.prefer(preference),this.fallback=void 0,this.contextFailed=!1);const columns=this.options.columns?.();if(columns){(this.columns!==columns||this.hiddenTypes!==this.host.hiddenTypes)&&(this.columns=columns,this.hiddenTypes=this.host.hiddenTypes,this.columnScene=graphEngineColumnScene(columns,this.hiddenTypes),this.world=[],this.edges=[],this.items=[],this.worldById.clear(),this.nodeIndexById.clear(),this.source=void 0,this.paint=void 0,this.engineDataKey=void 0,this.page=Math.min(this.page,Math.max(0,Math.ceil(this.itemCount/PAGE_SIZE)-1)),this.setHover(void 0)),this.selection.renderer==="builtin"&&this.host.view==="3d"&&this.failEngine("unsupported"),this.admitCamera();return}this.columns&&(this.columns=void 0,this.columnScene=void 0,this.source=void 0,this.engineDataKey=void 0);const model=this.options.model();if(this.source!==model||this.hiddenTypes!==this.host.hiddenTypes){this.source=model,this.hiddenTypes=this.host.hiddenTypes;const hidden=new Set(this.host.hiddenTypes),allIds=new Set(model.nodes.map(node=>node.id));this.world=model.nodes.filter(node=>node.type==null||!hidden.has(node.type)).map(node=>({node,position:spatialNodePosition(node),radius:finiteRange(node.radius??15,15,6,24),shape:this.options.nodeShape(node)})),this.worldById=new Map(this.world.map(node=>[node.node.id,node])),this.nodeIndexById=new Map(this.world.map((node,index)=>[node.node.id,index])),this.edges=model.links.filter(edge=>this.worldById.has(edge.source)&&(this.worldById.has(edge.target)||!allIds.has(edge.target)));const communityMembers=new Map;for(const{node}of this.world){if(!node.communityId)continue;let members=communityMembers.get(node.communityId);members||communityMembers.set(node.communityId,members=new Set),members.add(node.id)}this.communityCounts=new Map;const communities=model.communities.filter(community=>{const members=communityMembers.get(community.id)??new Set;for(const id of community.memberIds)this.worldById.has(id)&&members.add(id);return this.communityCounts.set(community.id,members.size),members.size>0});this.items=[...this.world.map(({node})=>({kind:"node",node})),...this.edges.map(edge=>({kind:"link",edge})),...communities.map(community=>({kind:"community",community}))];const focused=this.host.shadowRoot?.activeElement;if(focused?.getAttribute("part")==="spatial-list-item"){const id=focused.getAttribute("data-node-id");id&&!this.worldById.has(id)&&(this.focusAfterViewChange=!0)}this.page=Math.min(this.page,Math.max(0,Math.ceil(this.itemCount/PAGE_SIZE)-1)),this.builtin?.invalidate(),this.setHover(void 0),!this.cameraInitialized&&this.world.length&&(this.currentCamera=fittedGraphCamera(this.world,this.viewport()),this.fittedDistance=this.currentCamera.distance,this.cameraInitialized=!0,this.pendingInitialFit=!0)}this.admitCamera()}normalizeCamera(value){return this.preference==="webgl"?graphWebglCamera(value,this.currentCamera):normalizeGraphCamera(value,this.currentCamera)}admitCamera(){this.authoredCamera!==this.host.camera&&(this.authoredCamera=this.host.camera,this.pendingInitialFit=!1,this.currentCamera=this.authoredCamera?this.normalizeCamera(this.authoredCamera):this.engine?.fit?this.normalizeCamera(this.engine.fit()):fittedGraphCamera(this.world,this.viewport()),this.engine?.setCamera(this.currentCamera),this.builtin?.invalidate())}update(repaint=!0){if(!this.host.isConnected||this.host.view==="2d"){this.disconnect();return}repaint&&(this.paint=void 0,this.rgbaCache.clear());const next=this.host.renderRoot.querySelector('canvas[part="spatial-canvas"]')??void 0,engineSurface=this.host.renderRoot.querySelector("[data-webgl-host]")??void 0;if(this.engineSurface!==engineSurface&&(this.closeEngine(),this.engineSurface=engineSurface),this.canvas!==next){this.cancelGesture(),this.builtin?.dispose(),this.builtin=void 0,this.canvas=next,this.fitInitialCanvas();try{this.context=next?.getContext("2d")??void 0}catch{this.context=void 0}next&&this.context&&(this.builtin=new GraphBuiltin3dEngine(next,this.context)),next&&!this.context&&!this.contextFailed&&(this.contextFailed=!0,this.options.afterUpdate(()=>{!this.contextFailed||this.host.view!=="3d"||(this.failEngine("unsupported"),this.options.unavailable(),this.options.repaint())},"graph-spatial-context"))}const surface=this.selection.renderer==="webgl"?engineSurface:next;if(this.observedSurface!==surface){this.resize?.disconnect(),this.intersection?.disconnect(),this.observedSurface=surface,this.visible=this.selection.renderer!=="webgl";const view=this.host.ownerDocument.defaultView;if(surface&&view){const Resize=view.ResizeObserver;Resize&&(this.resize=new Resize(()=>{this.fitInitialCanvas(),this.builtin?.invalidate(),this.schedule()}),this.resize.observe(surface));const Intersection=view.IntersectionObserver;Intersection?(this.intersection=new Intersection(entries=>{this.visible=entries[0]?.isIntersecting??!1,this.visible&&(this.ensureEngine(),this.schedule())}),this.intersection.observe(surface)):this.visible=surface.clientWidth>0&&surface.clientHeight>0}}this.ensureEngine(),this.schedule(),this.focusAfterViewChange&&(this.focusAfterViewChange=!1,(this.host.renderRoot.querySelector('[part="spatial-list-item"]')??this.host.renderRoot.querySelector('[part="spatial-canvas"]')??this.host.renderRoot.querySelector('[data-spatial-action="3d"]'))?.focus())}disconnect(){this.closeEngine(),this.preference=void 0,this.fallback=void 0,this.engineSurface=void 0,this.observedSurface=void 0,this.cancelHover(),this.builtin?.dispose(),this.builtin=void 0,this.cancelGesture(),this.frame!==void 0&&this.frameWindow?.cancelAnimationFrame(this.frame),this.frame=void 0,this.frameWindow=void 0,this.notifyCamera=!1,this.lastKeyActivation=void 0,this.resize?.disconnect(),this.resize=void 0,this.intersection?.disconnect(),this.intersection=void 0,this.canvas=void 0,this.context=void 0,this.hover=void 0,this.visible=!0,this.contextFailed=!1}invalidate(){this.paint=void 0,this.builtin?.invalidate(),this.schedule()}fitInitialCanvas(){!this.pendingInitialFit||!this.canvas?.clientWidth||!this.canvas.clientHeight||(this.pendingInitialFit=!1,this.currentCamera=fittedGraphCamera(this.world,this.viewport()),this.fittedDistance=this.currentCamera.distance,this.builtin?.invalidate())}viewport(){const surface=this.selection.renderer==="webgl"?this.engineSurface:this.canvas;return{width:Math.max(1,surface?.clientWidth||this.options.viewport().width),height:Math.max(1,surface?.clientHeight||this.options.viewport().height)}}position(id){this.prepare();const row=this.columnScene?.nodeIndex(id)??this.nodeIndexById.get(id),point=row===void 0||this.engineDataKey!==(this.columnScene??this.world)||this.selection.renderer!=="webgl"?void 0:this.engine?.positionOf?.(row);if(point)return Object.freeze({...point});if(this.columnScene){const data=this.columnScene.data;return row===void 0?void 0:data.positions?Object.freeze({x:data.positions[row*3],y:data.positions[row*3+1],z:data.positions[row*3+2]}):spatialNodePosition({id})}return this.worldById.get(id)?.position}screenPosition(id){if(this.host.view!=="3d"||this.selection.renderer==="list")return;if(this.selection.renderer==="webgl"){if(this.engineDataKey!==(this.columnScene??this.world))return;const row=this.columnScene?.nodeIndex(id)??this.nodeIndexById.get(id),point2=row===void 0?null:this.engine?.project?.(row);if(!point2||!this.engineSurface)return;const bounds2=this.engineSurface.getBoundingClientRect(),host=this.host.getBoundingClientRect();return{x:bounds2.left-host.left+point2.x,y:bounds2.top-host.top+point2.y}}if(!this.canvas)return;const node=this.worldById.get(id),point=node&&projectSpatialPoint(node.position,this.currentCamera,this.viewport());if(!point)return;const bounds=this.canvas.getBoundingClientRect(),hostBounds=this.host.getBoundingClientRect();return{x:bounds.left-hostBounds.left+point.x,y:bounds.top-hostBounds.top+point.y}}fit(padding){if(this.prepare(),this.selection.renderer==="webgl"&&this.engine?.fit){const camera2=this.engine.fit(padding);this.currentCamera=this.normalizeCamera(camera2),this.fittedDistance=this.currentCamera.distance,this.changeCamera(this.currentCamera);return}if(!this.world.length)return;const camera=fittedGraphCamera(this.world,this.viewport(),padding);this.fittedDistance=camera.distance,this.changeCamera(camera)}focusNode(id,zoom){this.prepare();const position=this.position(id);return position?((this.host.view==="list"||this.contextFailed||this.selection.renderer==="list")&&(this.page=Math.floor((this.columnScene?.nodeIndex(id)??this.nodeIndexById.get(id)??0)/PAGE_SIZE),this.options.repaint()),this.changeCamera({...this.currentCamera,target:position,distance:zoom===void 0?this.currentCamera.distance:this.fittedDistance/this.safeZoom(zoom)}),!0):!1}safeZoom(value){const min=finiteRange(this.host.minZoom,.1,.001,1e3),max=finiteRange(this.host.maxZoom,8,.001,1e3);return finiteRange(value,1,Math.min(min,max),Math.max(min,max))}zoom(factor){const zoom=this.safeZoom(this.fittedDistance/this.currentCamera.distance*factor);this.changeCamera({...this.currentCamera,distance:this.fittedDistance/zoom})}orbit(yaw,pitch){this.changeCamera({...this.currentCamera,yaw:this.currentCamera.yaw+yaw,pitch:this.currentCamera.pitch+pitch})}changeCamera(camera){this.pendingInitialFit=!1,this.currentCamera=this.normalizeCamera(camera),this.engine?.setCamera(this.currentCamera),this.builtin?.invalidate(),this.notifyCamera=!0,this.schedule()}schedule(){if(!this.host.isConnected||this.host.view==="2d"||this.frame!==void 0||!this.visible&&!this.notifyCamera)return;const view=this.host.ownerDocument.defaultView;view&&(this.frameWindow=view,this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.frameWindow=void 0,!(!this.host.isConnected||this.host.view==="2d")&&(this.visible&&this.draw(),this.notifyCamera&&(this.notifyCamera=!1,this.options.cameraChanged(this.normalizeCamera(this.currentCamera))))}))}builtinFrame(){return{world:this.world,edges:this.edges,camera:this.currentCamera,viewport:this.viewport(),paint:this.paint??=this.options.paint(this.world,this.edges),fittedDistance:this.fittedDistance,selectedNodeIds:this.host.selectedNodeIds,selectedEdgeIds:this.host.selectedEdgeIds,dimmedNodeIds:this.host.dimmedNodeIds,dimmedEdgeIds:this.host.dimmedEdgeIds,focusNodeId:this.host.focusNodeId,hover:this.hover,nodeLabels:this.host.nodeLabels,withEdgeLabels:this.host.withEdgeLabels,edgeLabelMinZoom:this.host.edgeLabelMinZoom}}draw(){if(this.host.view==="3d"){if(this.selection.renderer==="webgl"){this.drawEngine();return}this.builtin?.draw(this.builtinFrame())}}hit(clientX,clientY){if(this.selection.renderer==="webgl"&&this.engineSurface){const bounds=this.engineSurface.getBoundingClientRect();return this.engineHit(this.engine?.pick?.(clientX-bounds.left,clientY-bounds.top)??null)}return this.builtin?.hit(clientX,clientY,this.builtinFrame())}cancelHover(){this.hoverGeneration++,this.hoverFrame!==void 0&&this.hoverFrameWindow?.cancelAnimationFrame(this.hoverFrame),this.hoverFrame=void 0,this.hoverFrameWindow=void 0,this.pendingHover=void 0}queueHover(x,y){if(this.pendingHover={x,y},this.hoverFrame!==void 0)return;const view=this.host.ownerDocument.defaultView;if(!view)return;const generation=this.hoverGeneration;this.hoverFrameWindow=view,this.hoverFrame=view.requestAnimationFrame(()=>{if(generation!==this.hoverGeneration)return;this.hoverFrame=void 0,this.hoverFrameWindow=void 0;const point=this.pendingHover;this.pendingHover=void 0,point&&this.host.isConnected&&this.host.view==="3d"&&!this.gesture&&this.setHover(this.hit(point.x,point.y))})}setHover(next){if(this.hover?.kind===next?.kind&&this.hover?.id===next?.id)return;const previous=this.hover;this.hover=next;const surface=this.selection.renderer==="webgl"?this.engineSurface:this.canvas;surface&&(surface.title=next?.kind==="node"?this.options.nodeTooltip(next.node):next?.kind==="link"?this.options.edgeTooltip(next.edge):""),this.options.hover(previous,next),this.schedule()}cancelGesture(){const gesture=this.gesture;this.gesture=void 0,gesture&&this.canvas?.hasPointerCapture(gesture.id)&&this.canvas.releasePointerCapture(gesture.id)}changeView(view){this.cancelGesture(),view==="3d"&&(this.contextFailed=!1,this.selection.prefer(this.preference),this.fallback=void 0),this.host.view=view,this.options.repaint(),this.focusAfterViewChange=!0,this.options.viewChanged()}changePage(delta){this.page=Math.max(0,Math.min(Math.ceil(this.itemCount/PAGE_SIZE)-1,this.page+delta)),this.focusAfterViewChange=!0,this.options.repaint()}listKeyDown(item,event){if(item.kind!=="node"||event.key!=="Enter"&&event.key!==" "||event.repeat)return;const time=this.host.ownerDocument.defaultView?.performance.now()??0;this.lastKeyActivation?.id===item.node.id&&time-this.lastKeyActivation.time<=500?(this.lastKeyActivation=void 0,this.options.expand(item.node.id)):this.lastKeyActivation={id:item.node.id,time}}activateItem(item,event){item.kind==="node"?this.options.activate({kind:"node",id:item.node.id,node:item.node},event):item.kind==="link"?this.options.activate({kind:"link",id:graphLinkIdentity(item.edge),edge:item.edge},event):this.options.community(item.community)}render(limitNotices){this.prepare();const messages=this.options.messages(),list=this.host.view==="list"||this.contextFailed||this.selection.renderer==="list",pageItems=this.pageItems(),number=getNumberFormat(this.options.locale()),selectedNodes=selectedIds(this.host.selectedNodeIds),selectedEdges=selectedIds(this.host.selectedEdgeIds),button=(action,label,callback)=>html`<button type="button" part="spatial-control" data-spatial-action=${action} @click=${callback}>${label}</button>`;return html`<div part="base" class="spatial-base">
|
|
2
2
|
<div part="spatial-toolbar" role="group" aria-label=${messages.controls}>
|
|
3
3
|
<button type="button" part="spatial-control" data-spatial-action="3d" aria-pressed=${String(!list)} @click=${()=>this.changeView("3d")}>${messages.view3d}</button>
|
|
4
4
|
<button type="button" part="spatial-control" data-spatial-action="list" aria-pressed=${String(list)} @click=${()=>this.changeView("list")}>${messages.viewList}</button>
|
|
5
5
|
${list?nothing:html`${button("fit",messages.fit,()=>this.fit())}${button("left",messages.left,()=>this.orbit(-ORBIT_STEP,0))}${button("right",messages.right,()=>this.orbit(ORBIT_STEP,0))}${button("up",messages.up,()=>this.orbit(0,ORBIT_STEP))}${button("down",messages.down,()=>this.orbit(0,-ORBIT_STEP))}${button("zoom-in",messages.zoomIn,()=>this.zoom(1.2))}${button("zoom-out",messages.zoomOut,()=>this.zoom(1/1.2))}`}
|
|
6
6
|
</div>
|
|
7
7
|
${this.contextFailed?html`<p part="error">${messages.unavailable}</p>`:nothing}
|
|
8
|
+
${this.fallback?html`<p part="engine-notice">${this.options.engineMessage?.(engine3dFallbackNotice(this.fallback).reason)} ${this.options.engineMessage?.(engine3dFallbackNotice(this.fallback).showing)}</p>`:nothing}
|
|
9
|
+
${this.enginePending?html`<p part="loading">${this.options.engineMessage?.("engine3dLoading")}</p>`:nothing}
|
|
10
|
+
${this.host.view==="3d"&&this.preference==="webgl"?html`<div data-webgl-host part="spatial-canvas" class="webgl-surface" ?hidden=${this.selection.renderer!=="webgl"} tabindex="0" role="img"
|
|
11
|
+
aria-label=${this.host.accessibleLabel??this.host.label??messages.view3d} aria-describedby=${this.instructionsId} @keydown=${this.keyDown} @wheel=${this.wheel} @pointermove=${this.enginePointerMove}
|
|
12
|
+
@pointerdown=${this.enginePointerDown}><canvas data-graph-labels aria-hidden="true"></canvas></div>`:nothing}
|
|
8
13
|
${list?html`<div part="spatial-list" tabindex="-1" @keydown=${event=>{event.key==="Escape"&&this.options.clearSelection()}}>
|
|
9
14
|
<ul aria-label=${messages.dataList}>
|
|
10
|
-
${pageItems.map((item,index)=>{const id=item.kind==="node"?item.node.id:item.kind==="link"?graphLinkIdentity(item.edge):item.community.id,selected=item.kind==="node"?selectedNodes.has(id):item.kind==="link"?selectedEdges.has(id):!1,text=item.kind==="node"?this.options.nodeText(item.node):item.kind==="link"?this.options.edgeText(item.edge):this.options.communityText({label:item.community.label??id,count:number.format(this.communityCounts.get(id)??0)});return html`<li aria-posinset=${this.page*PAGE_SIZE+index+1} aria-setsize=${this.
|
|
15
|
+
${pageItems.map((item,index)=>{const id=item.kind==="node"?item.node.id:item.kind==="link"?graphLinkIdentity(item.edge):item.community.id,selected=item.kind==="node"?selectedNodes.has(id):item.kind==="link"?selectedEdges.has(id):!1,text=item.kind==="node"?this.options.nodeText(item.node):item.kind==="link"?this.options.edgeText(item.edge):this.options.communityText({label:item.community.label??id,count:number.format(this.communityCounts.get(id)??0)});return html`<li aria-posinset=${this.page*PAGE_SIZE+index+1} aria-setsize=${this.itemCount}><button type="button" part="spatial-list-item" data-node-id=${item.kind==="node"?id:nothing}
|
|
11
16
|
aria-pressed=${item.kind!=="community"&&this.host.selectionMode!=="none"?String(selected):nothing}
|
|
12
17
|
aria-current=${item.kind!=="community"&&this.host.selectionMode==="none"&&selected?"true":nothing}
|
|
13
18
|
@keydown=${event=>this.listKeyDown(item,event)} @click=${event=>this.activateItem(item,event)} @dblclick=${()=>{item.kind==="node"&&this.options.expand(id)}}
|
|
14
19
|
>${text}</button></li>`})}
|
|
15
20
|
</ul>
|
|
16
|
-
${this.
|
|
17
|
-
<p part="spatial-page-count">${this.options.pageText({page:number.format(this.page+1),pages:number.format(Math.max(1,Math.ceil(this.
|
|
21
|
+
${this.itemCount?nothing:html`<p part="empty">${messages.noData}</p>`}
|
|
22
|
+
<p part="spatial-page-count">${this.options.pageText({page:number.format(this.page+1),pages:number.format(Math.max(1,Math.ceil(this.itemCount/PAGE_SIZE))),total:number.format(this.itemCount)})}</p>
|
|
18
23
|
<div part="spatial-pagination">
|
|
19
24
|
<button type="button" part="spatial-control" data-spatial-action="previous" ?disabled=${this.page===0} @click=${()=>this.changePage(-1)}>${messages.previous}</button>
|
|
20
|
-
<button type="button" part="spatial-control" data-spatial-action="next" ?disabled=${(this.page+1)*PAGE_SIZE>=this.
|
|
25
|
+
<button type="button" part="spatial-control" data-spatial-action="next" ?disabled=${(this.page+1)*PAGE_SIZE>=this.itemCount} @click=${()=>this.changePage(1)}>${messages.next}</button>
|
|
21
26
|
</div>
|
|
22
27
|
</div>`:html`<p part="spatial-instructions" id=${this.instructionsId}>${messages.instructions}</p>
|
|
23
|
-
|
|
28
|
+
${this.selection.renderer!=="webgl"?html`<canvas part="spatial-canvas" tabindex="0" role="img" aria-label=${this.host.accessibleLabel??this.host.label??messages.view3d}
|
|
24
29
|
aria-describedby=${this.instructionsId} @pointerdown=${this.pointerDown} @pointermove=${this.pointerMove} @pointerup=${this.pointerUp}
|
|
25
30
|
@pointercancel=${this.pointerCancel} @lostpointercapture=${this.pointerCancel} @pointerleave=${()=>{this.gesture||(this.cancelHover(),this.setHover(void 0))}}
|
|
26
31
|
@wheel=${this.wheel} @keydown=${this.keyDown} @dblclick=${event=>{const hit=this.hit(event.clientX,event.clientY);hit?.kind==="node"&&this.options.expand(hit.id)}}
|
|
27
|
-
></canvas
|
|
28
|
-
${this.world.length?nothing:html`<p part="empty">${messages.noData}</p>`}`}
|
|
32
|
+
></canvas>`:nothing}
|
|
33
|
+
${this.columnScene?.data.nodeCount??this.world.length?nothing:html`<p part="empty">${messages.noData}</p>`}`}
|
|
29
34
|
${limitNotices}
|
|
30
35
|
</div>`}}export{GraphSpatialController};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{finiteRange}from"../../../internal/numbers.js";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{graphLinkIdentity}from"./graph-model.js";const CAMERA_LIMIT=34028234663852886e22/8;function own(value,key){if(!value||typeof value!="object")return;const descriptor=getOwnDataDescriptor(value,key);return typeof descriptor=="object"?descriptor.value:void 0}function graphWebglCamera(value,fallback){const number=(input,otherwise,min,max)=>finiteRange(typeof input=="number"?input:NaN,otherwise,min,max),target=own(value,"target");return Object.freeze({yaw:number(own(value,"yaw"),fallback.yaw,-CAMERA_LIMIT,CAMERA_LIMIT)%(Math.PI*2),pitch:number(own(value,"pitch"),fallback.pitch,-Math.PI/2+.01,Math.PI/2-.01),distance:number(own(value,"distance"),fallback.distance,.01,CAMERA_LIMIT),target:Object.freeze({x:number(own(target,"x"),fallback.target.x,-1e7,1e7),y:number(own(target,"y"),fallback.target.y,-1e7,1e7),z:number(own(target,"z"),fallback.target.z,-1e7,1e7)})})}function graphWebglData(world,edges,paint,rgba){const count=world.length,positions=new Float32Array(count*3),sizes=new Float32Array(count),shapes=new Uint8Array(count),expandable=new Uint8Array(count),colors=new Float32Array(count*4),rows=new Map;world.forEach((entry,row)=>{rows.set(entry.node.id,row),positions.set([entry.position.x,entry.position.y,entry.position.z],row*3),sizes[row]=entry.radius*2,shapes[row]=entry.shape==="square"?1:entry.shape==="diamond"?2:0,expandable[row]=entry.node.expandable?1:0,colors.set(rgba(paint.nodes.get(entry.node.id)??paint.text),row*4)});const source=new Uint32Array(edges.length),target=new Uint32Array(edges.length),directed=new Uint8Array(edges.length),dangling=new Uint8Array(edges.length),edgeColors=new Float32Array(edges.length*4),widths=new Float32Array(edges.length),dashes=[];return edges.forEach((edge,row)=>{source[row]=rows.get(edge.source),target[row]=rows.get(edge.target)??source[row],dangling[row]=rows.has(edge.target)?0:1,directed[row]=edge.directed?1:0;const id=graphLinkIdentity(edge);widths[row]=paint.visibleEdges.has(id)?finiteRange(edge.width??1.5,1.5,0,1e3):0,edgeColors.set(rgba(paint.edges.get(id)??paint.text),row*4),dashes.push(Array.isArray(edge.dash)&&edge.dash.length<=32&&edge.dash.every(v=>Number.isFinite(v)&&v>=0&&v<=1e7)?[...edge.dash]:[])}),{nodeCount:count,positions,sizes,source,target,directed,nodeLabels:"none",withEdgeLabels:!1,spatialAppearance:{sizeUnits:"world",nodeShapes:shapes,expandable,nodeColors:colors,edgeColors,edgeWidths:widths,edgeDashes:dashes,dangling,dimmedOpacity:paint.dimmedOpacity}}}export{graphWebglCamera,graphWebglData};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type{LyraGraphSource}from'../../../data-sources.js';import'../../data/pagination/pagination.class.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraNodeTypeStyle}from'../../../internal/node-type-style.js';export type{LyraNodeTypeStyle}from'../../../internal/node-type-style.js';import{type LyraGraphCamera,type LyraGraphPosition,type LyraGraphView,type LyraGraphCommunity,type LyraGraphEdge,type LyraGraphNode}from'./graph-model.js';export type{LyraGraphCamera,LyraGraphPosition,LyraGraphView,LyraGraphCommunity,LyraGraphEdge,LyraGraphNode,}from'./graph-model.js';import'../../overlays/skeleton/skeleton.class.js';
|
|
1
|
+
import{type Engine3dPreference,type Engine3dFallbackDetail}from'../../../internal/engine-3d.js';import type{LyraGraphColumns}from'../../../internal/typed-columns.js';import type{LyraGraphSource}from'../../../data-sources.js';import'../../data/pagination/pagination.class.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraNodeTypeStyle}from'../../../internal/node-type-style.js';export type{LyraNodeTypeStyle}from'../../../internal/node-type-style.js';import{type LyraGraphCamera,type LyraGraphPosition,type LyraGraphView,type LyraGraphCommunity,type LyraGraphEdge,type LyraGraphNode}from'./graph-model.js';export type{LyraGraphCamera,LyraGraphPosition,LyraGraphView,LyraGraphCommunity,LyraGraphEdge,LyraGraphNode,}from'./graph-model.js';import'../../overlays/skeleton/skeleton.class.js';
|
|
2
2
|
/** Complete host-owned node/edge catalog with bounded graph scenes. Source edges require stable IDs. */
|
|
3
3
|
export type GraphSource=LyraGraphSource<LyraGraphNode,LyraGraphEdge&{readonly id:string;}>;export type LyraGraphLayout='force'|'layered';export type LyraGraphRenderer='svg'|'canvas';export type LyraGraphSelectionMode='none'|'single'|'multiple';export type LyraGraphPickKind='node'|'link';
|
|
4
4
|
/** See `nodeLabels`'s own doc for the per-renderer default when unset. */
|
|
5
5
|
export type LyraGraphNodeLabelsMode='always'|'zoom'|'none';
|
|
6
6
|
/** See `fitTo`'s own doc. `'none'` keeps the numeric `width`/`height` as the drawing space;
|
|
7
7
|
* `'container'` measures the host's own content box instead. */
|
|
8
|
-
export type LyraGraphFit='none'|'container';export type{LyraScoreThresholds}from'../../../internal/score-tiers.js';export interface LyraGraphEventMap{'lr-node-activate':CustomEvent<{nodeId:string;x:number;y:number;z?:number;}>;'lr-camera-change':CustomEvent<{camera:LyraGraphCamera;}>;'lr-view-change':CustomEvent<{view:LyraGraphView;}>;'lr-edge-activate':CustomEvent<{sourceNodeId:string;targetNodeId:string;edgeId?:string;}>;'lr-node-enter':CustomEvent<{nodeId:string;}>;'lr-node-leave':CustomEvent<{nodeId:string;}>;
|
|
8
|
+
export type LyraGraphFit='none'|'container';export type{LyraScoreThresholds}from'../../../internal/score-tiers.js';export interface LyraGraphEventMap{'lr-node-activate':CustomEvent<{nodeId:string;x:number;y:number;z?:number;}>;'lr-engine-fallback':CustomEvent<Engine3dFallbackDetail>;'lr-camera-change':CustomEvent<{camera:LyraGraphCamera;}>;'lr-view-change':CustomEvent<{view:LyraGraphView;}>;'lr-edge-activate':CustomEvent<{sourceNodeId:string;targetNodeId:string;edgeId?:string;}>;'lr-node-enter':CustomEvent<{nodeId:string;}>;'lr-node-leave':CustomEvent<{nodeId:string;}>;
|
|
9
9
|
/** An edge was hovered. */
|
|
10
10
|
'lr-edge-enter':CustomEvent<{sourceNodeId:string;targetNodeId:string;edgeId?:string;}>;
|
|
11
11
|
/** The hover from `lr-edge-enter` ended. */
|
|
@@ -85,6 +85,7 @@ export type LyraGraphFit='none'|'container';export type{LyraScoreThresholds}from
|
|
|
85
85
|
* @event lr-node-activate - Pointer or keyboard node activation with `{ nodeId, x, y }` detail;
|
|
86
86
|
* `x` and `y` are the node's current coordinates in the graph's local drawing space.
|
|
87
87
|
* Spatial/list activation returns world x/y and adds `z`; these are never screen pixels.
|
|
88
|
+
* @event lr-engine-fallback - Renderer fell back, with `{ from, to, reason }`.
|
|
88
89
|
* @event lr-camera-change - Spatial camera changed by a gesture, fit or focus, with `{ camera }`.
|
|
89
90
|
* Coalesced to one event per animation frame. Property assignments are silent.
|
|
90
91
|
* @event lr-view-change - User switched the spatial toolbar view, with `{ view }`.
|
|
@@ -213,13 +214,25 @@ nodeTypes:readonly LyraNodeTypeStyle[];
|
|
|
213
214
|
hiddenTypes:readonly string[];
|
|
214
215
|
/** Renders one translucent hull per entry, behind links/nodes. Membership is the union of
|
|
215
216
|
* `memberIds` and every node whose `communityId` matches this entry's `id`. */
|
|
216
|
-
communities:readonly LyraGraphCommunity[];private normalizedGraphModel?;private normalizedGraphSources?;private get graphModel();private
|
|
217
|
+
communities:readonly LyraGraphCommunity[];private normalizedGraphModel?;private normalizedGraphSources?;private get graphModel();private _engine;
|
|
218
|
+
/** Optional 3D renderer preference. The default never downloads the companion. Failures use
|
|
219
|
+
* the builtin spatial renderer, then the paginated list. Has no effect in the 2D view. */
|
|
220
|
+
get engine():Engine3dPreference;set engine(value:Engine3dPreference);private _graphColumns?;private engineColumns?;private engineColumnsInvalid;
|
|
221
|
+
/** Immutable typed columns for 3D/list views, up to 200,000 nodes and 1,000,000 links.
|
|
222
|
+
* Takes precedence over local nodes/edges; graphSource remains authoritative. Assign a new
|
|
223
|
+
* object after changes. The builtin fallback lists all rows in pages of 200 without truncation.
|
|
224
|
+
* Columns require view="3d" or view="list"; 2D reports invalid data instead of showing stale arrays.
|
|
225
|
+
* Coordinates are limited to ±10,000,000 graph units. Visual column labels are bounded by the
|
|
226
|
+
* companion; the paginated list retains full text. Column edge IDs are `column-edge-${row}`. */
|
|
227
|
+
get graphColumns():LyraGraphColumns|undefined;set graphColumns(value:LyraGraphColumns|undefined);private _view;
|
|
217
228
|
/** Default '2d' preserves existing SVG/canvas layouts. '3d' uses perspective and true x/y/z
|
|
218
229
|
* positions; 'list' provides visible paginated activation. The latter two need no optional peer. */
|
|
219
|
-
get view():LyraGraphView;set view(value:LyraGraphView);private _camera?;
|
|
230
|
+
get view():LyraGraphView;set view(value:LyraGraphView);private _camera?;private builtinCamera?;
|
|
220
231
|
/** Optional spatial camera input, defensively copied. Angles are radians; distance and target
|
|
221
232
|
* use graph units. Gestures update internal state and emit lr-camera-change, not this input.
|
|
222
|
-
* Omission fits the initial spatial scene. Invalid numeric fields use a safe default.
|
|
233
|
+
* Omission fits the initial spatial scene. Invalid numeric fields use a safe default.
|
|
234
|
+
* WebGL camera distance has an independent range up to Float32 maximum / 8; camera targets
|
|
235
|
+
* remain within ±10,000,000 graph units. The builtin renderer retains its existing limits. */
|
|
223
236
|
get camera():LyraGraphCamera|undefined;set camera(value:LyraGraphCamera|undefined);private _layout;
|
|
224
237
|
/** `'force'` (default) runs the existing d3-force simulation, untouched. `'layered'` computes a
|
|
225
238
|
* deterministic Sugiyama-lite layout (`src/internal/layered-layout.ts`, a shared,
|