@aceshooting/lyra-ui 27.0.0 → 28.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 +55 -63
- package/README.md +7 -3
- package/dist/cli/css-declarations.mjs +1 -0
- package/dist/cli/lyra-rename-ledger.mjs +1 -1
- package/dist/cli/migrate-wa.mjs +9 -4
- package/dist/cli/migration-contract.json +1 -1
- package/dist/cli/migration-renames.mjs +2 -2
- package/dist/cli/migration-theme-scopes.mjs +3 -0
- package/dist/cli/theme-scope-vocabulary.generated.mjs +1 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-question/agent-question.class.js +1 -1
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -1
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +1 -1
- package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +1 -1
- package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +1 -1
- package/dist/components/agent-tools/connector-manager/connector-manager.class.js +1 -1
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
- package/dist/components/agent-tools/permission-grant/permission-grant.class.js +1 -1
- package/dist/components/agent-tools/permission-rules/permission-rules.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
- package/dist/components/agent-tools/result-card/result-field.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/stack-trace/stack-trace.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/terminal/terminal.class.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-result-view/tool-result-view.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/box-plot.class.js +1 -1
- package/dist/components/charts/chart/chart-token-cache.js +2 -2
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +3 -3
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -1
- package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
- package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/handoff-divider/handoff-divider.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.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 +1 -1
- package/dist/components/conversation/prompt-queue/prompt-queue.class.js +1 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/stream-status/stream-status.class.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +1 -1
- package/dist/components/data/condition-builder/condition-builder.class.js +1 -1
- package/dist/components/data/context-meter/context-meter.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +2 -2
- package/dist/components/data/data-grid/data-grid.class.js +3 -3
- package/dist/components/data/document-library/document-library.class.js +1 -1
- package/dist/components/data/env-list/env-list.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.d.ts +2 -2
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-controls/flow-controls.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/flow-node/flow-node.class.js +1 -1
- package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
- package/dist/components/data/funnel/funnel.class.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.d.ts +2 -0
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/pagination/pagination.styles.js +1 -1
- package/dist/components/data/sequence-strip/sequence-strip.class.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.js +1 -1
- package/dist/components/data/stat/stat.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +23 -2
- package/dist/components/data/table/table.class.js +5 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.js +1 -1
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.d.ts +8 -4
- package/dist/components/forms/color-picker/color-picker.class.js +2 -2
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/country-picker/country-picker.class.js +1 -1
- package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +7 -4
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -0
- package/dist/components/forms/icon-button/icon-button.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
- package/dist/components/forms/input/input-shared.js +1 -1
- package/dist/components/forms/input/input.class.js +1 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/number-input.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.js +1 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +4 -4
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +70 -7
- package/dist/components/layout/app-rail/app-rail.class.js +16 -4
- package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/breadcrumb/breadcrumb.class.js +1 -1
- package/dist/components/layout/card/card.class.js +1 -1
- package/dist/components/layout/carousel/carousel.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/details/details.class.js +1 -1
- 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/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +7 -4
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/av-player/av-player.class.js +1 -1
- package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
- package/dist/components/media/drop-zone/drop-zone.class.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +4 -2
- package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.class.js +1 -1
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/media/media-card/media-card.class.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/qr-code/qr-code.class.d.ts +2 -2
- package/dist/components/media/qr-code/qr-code.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video/video.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/zoomable-frame/zoomable-frame.class.js +1 -1
- package/dist/components/overlays/alert/alert.class.js +1 -1
- package/dist/components/overlays/badge/tag.class.js +1 -1
- package/dist/components/overlays/callout/callout.class.js +1 -1
- package/dist/components/overlays/chip/chip-group.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
- package/dist/components/overlays/dialog/confirm.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-bar.class.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/overlays/skeleton/skeleton.class.js +1 -1
- package/dist/components/overlays/spinner/spinner.class.js +1 -1
- package/dist/components/overlays/toast/toast-item.class.js +1 -1
- package/dist/components/overlays/toast/toast.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +1 -1
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/community-card/community-card.class.js +1 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +1 -1
- package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +1 -1
- package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/research-progress/research-progress.class.js +1 -1
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-card/source-card.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/utility/poll-status/poll-status.class.js +1 -1
- package/dist/components/utility/random-content/random-content.class.js +1 -1
- package/dist/components/utility/tour/tour.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/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +2 -2
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
- package/dist/components/viewers/highlight-layer/highlight-layer.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/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/page-rail/page-rail.class.d.ts +1 -1
- package/dist/components/viewers/page-rail/page-rail.class.js +3 -3
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
- package/dist/events.d.ts +6 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/default-strings/agent-tools.generated.js +1 -0
- package/dist/internal/default-strings/charts.generated.js +1 -0
- package/dist/internal/default-strings/conversation.generated.js +1 -0
- package/dist/internal/default-strings/data.generated.js +1 -0
- package/dist/internal/default-strings/forms.generated.js +1 -0
- package/dist/internal/default-strings/layout.generated.js +1 -0
- package/dist/internal/default-strings/media.generated.js +1 -0
- package/dist/internal/default-strings/overlays.generated.js +1 -0
- package/dist/internal/default-strings/retrieval.generated.js +1 -0
- package/dist/internal/default-strings/shared.generated.js +1 -0
- package/dist/internal/default-strings/utility.generated.js +1 -0
- package/dist/internal/default-strings/viewers.generated.js +5 -0
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.production.js +1 -1
- package/dist/internal/document-tokens.d.ts +11 -0
- package/dist/internal/document-tokens.generated.js +15 -0
- package/dist/internal/document-tokens.js +3 -0
- package/dist/internal/form-associated.d.ts +1 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/glass-surface.styles.js +1 -1
- package/dist/internal/host-tokens.styles.js +1 -0
- package/dist/internal/image-zoom.js +1 -0
- package/dist/internal/intl-cache.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/lyra-element.d.ts +4 -2
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/opaque-content-border.styles.js +1 -1
- package/dist/internal/open-overlay-raise.styles.js +1 -0
- package/dist/internal/optional-peer-failure.js +1 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/prefix.js +1 -1
- package/dist/internal/specialist-host-tokens.styles.js +1 -0
- package/dist/internal/specialist-tokens.generated.js +2 -0
- package/dist/internal/step-value.js +1 -1
- package/dist/internal/theme-observation.js +1 -1
- package/dist/internal/theme-scopes.d.ts +11 -0
- package/dist/internal/theme-scopes.js +1 -0
- package/dist/looks/shadcn.css +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/styles/design-tokens.css +1 -1
- package/dist/styles/tokens-root.css +1 -1
- package/dist/surfaces/glass.css +1 -1
- package/dist/testing/happy-dom-shims.d.ts +21 -2
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/interaction-drivers.d.ts +66 -7
- package/dist/testing/interaction-drivers.js +1 -1
- package/dist/testing/jsdom-shims.d.ts +70 -0
- package/dist/testing/jsdom-shims.js +1 -0
- package/dist/theme/look-inputs.d.ts +1 -1
- package/dist/theme/look-inputs.js +37 -41
- package/dist/theme/theme.d.ts +13 -0
- package/dist/theme/theme.js +1 -1
- package/dist/theme.css +1 -1
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/dist/utilities/scoped-registry.d.ts +3 -0
- package/dist/utilities/scoped-registry.js +1 -1
- package/dist/utilities/theme-scopes.d.ts +1 -0
- package/dist/utilities/theme-scopes.js +1 -0
- package/dist/utilities/tokens.d.ts +1 -0
- package/dist/utilities/tokens.js +1 -0
- package/llms/components/lr-app-rail.md +51 -4
- package/llms/components/lr-emoji-picker.md +13 -8
- package/llms/components/lr-icon-button.md +13 -1
- package/llms/components/lr-image-viewer.md +8 -0
- package/llms/components/lr-pagination.md +4 -2
- package/llms/components/lr-segmented.md +7 -3
- package/llms/components/lr-table.md +14 -12
- package/llms/components/lr-thread-list.md +4 -3
- package/llms/migration.md +9 -0
- package/llms/peers.md +1 -1
- package/llms/shared/events-and-types.md +41 -0
- package/llms/shared/frameworks-and-ssr.md +16 -0
- package/llms/shared/imports-and-registration.md +4 -3
- package/llms/shared/native-styles-and-utilities.md +38 -3
- package/llms/shared/styles-and-tokens.md +242 -102
- package/llms/shared/testing-and-utilities.md +90 -6
- package/llms/shared.md +431 -114
- package/llms/tokens.md +31 -49
- package/locales.json +138 -138
- package/package.json +14 -7
- package/registrations.json +1 -1
- package/dist/internal/default-strings.generated.js +0 -5
- package/dist/internal/specialist-tokens.styles.js +0 -1
- package/dist/internal/tokens/palette.styles.js +0 -1
- package/dist/internal/tokens.styles.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{tag}from"../../../internal/prefix.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{setMapCanvasReadyCallback}from"../../../internal/map-canvas-ready.js";import{loadMaplibre}from"../../media/map/map-loader.js";import{styles}from"./geojson-view.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_geojsonViewFeatureCount,LYRA_DEFAULT_geojsonViewInvalid,LYRA_DEFAULT_geojsonViewLabel,LYRA_DEFAULT_geojsonViewMissingMapLibrary,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";const GEOMETRY_TYPES=new Set(["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection"]),MAX_GEOJSON_POSITIONS=1e4,MAX_GEOJSON_NODES=5e4,MAX_GEOJSON_DEPTH=64,MAX_GEOJSON_TEXT_UNITS=2*1024*1024,MAX_GEOJSON_SERIALIZED_UNITS=4*1024*1024,GEOJSON_BASE_MAP_STYLE={version:8,sources:{},layers:[]};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function assertGeoJsonGraphWithinLimits(root){const tasks=[{value:root,depth:0}],seen=new WeakSet;let graphUnits=0,textUnits=0;const accountGraphUnit=()=>{if(graphUnits++,graphUnits+tasks.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.")},accountText=value=>{if(textUnits+=value.length,textUnits>MAX_GEOJSON_TEXT_UNITS)throw new LyraResourceLimitError("The GeoJSON contains too much text.")};for(;tasks.length>0;){const task=tasks.pop();if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");accountGraphUnit();const value=task.value;if(typeof value=="string"){accountText(value);continue}if(!(value===null||typeof value=="boolean")){if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("invalid JSON number");continue}if(typeof value!="object")throw new Error("invalid JSON value");if(seen.has(value))throw new Error("cyclic JSON graph");if(seen.add(value),Array.isArray(value)){if(graphUnits+tasks.length+value.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=value.length-1;index>=0;index--)tasks.push({value:value[index],depth:task.depth+1});continue}for(const key in value)Object.hasOwn(value,key)&&(accountGraphUnit(),accountText(key),tasks.push({value:value[key],depth:task.depth+1}))}}}function analyzeGeoJson(value){if(assertGeoJsonGraphWithinLimits(value),!isRecord(value))throw new Error("not a GeoJSON object");const root=value,tasks=[{kind:"geo",value,depth:0,mode:"any"}];let processedNodes=0,positionCount=0,bounds=null;const pushTask=task=>{if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(processedNodes+tasks.length>=MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");tasks.push(task)},pushArray=(items,kind,depth)=>{if(processedNodes+tasks.length+items.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=items.length-1;index>=0;index--)pushTask({kind,value:items[index],depth})},requireArray=(candidate,minimum=0)=>{if(!Array.isArray(candidate)||candidate.length<minimum)throw new Error("invalid GeoJSON coordinates");return candidate};for(;tasks.length>0;){const task=tasks.pop();if(processedNodes++,processedNodes>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(task.kind==="position"){const position=requireArray(task.value,2);if(!position.every(coordinate=>typeof coordinate=="number"&&Number.isFinite(coordinate)))throw new Error("invalid GeoJSON position");const[lng,lat]=position;if(lng<-180||lng>180||lat<-90||lat>90)throw new Error("invalid GeoJSON position");if(positionCount++,positionCount>MAX_GEOJSON_POSITIONS)throw new LyraResourceLimitError("The GeoJSON contains too many positions.");const shiftedLng=lng<0?lng+360:lng;bounds?(bounds.minLng=Math.min(bounds.minLng,lng),bounds.maxLng=Math.max(bounds.maxLng,lng),bounds.minShiftedLng=Math.min(bounds.minShiftedLng,shiftedLng),bounds.maxShiftedLng=Math.max(bounds.maxShiftedLng,shiftedLng),bounds.minLat=Math.min(bounds.minLat,lat),bounds.maxLat=Math.max(bounds.maxLat,lat)):bounds={minLng:lng,maxLng:lng,minShiftedLng:shiftedLng,maxShiftedLng:shiftedLng,minLat:lat,maxLat:lat};continue}if(task.kind==="positions"||task.kind==="line"||task.kind==="ring"){const minimum=task.kind==="ring"?4:task.kind==="line"?2:0,positions=requireArray(task.value,minimum);if(task.kind==="ring"){const first=positions[0],last=positions[positions.length-1];if(!Array.isArray(first)||!Array.isArray(last)||first.length!==last.length||first.some((item,index)=>item!==last[index]))throw new Error("GeoJSON polygon rings must be closed")}pushArray(positions,"position",task.depth+1);continue}if(task.kind==="polygon"||task.kind==="multi-line"){const parts=requireArray(task.value);pushArray(parts,task.kind==="polygon"?"ring":"line",task.depth+1);continue}if(task.kind==="multi-polygon"){pushArray(requireArray(task.value),"polygon",task.depth+1);continue}if(task.kind!=="geo")throw new Error("invalid GeoJSON coordinate structure");if(!isRecord(task.value)||typeof task.value.type!="string")throw new Error("invalid GeoJSON member");const member=task.value,type=member.type;if(task.mode==="feature"&&type!=="Feature")throw new Error("FeatureCollection contains a non-Feature");if(task.mode==="geometry"&&!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON geometry");if(type==="Feature"){if(task.mode==="geometry"||!Object.hasOwn(member,"geometry")||!Object.hasOwn(member,"properties"))throw new Error("invalid GeoJSON Feature");if(member.properties!==null&&!isRecord(member.properties))throw new Error("invalid GeoJSON Feature properties");member.geometry!==null&&pushTask({kind:"geo",value:member.geometry,depth:task.depth+1,mode:"geometry"});continue}if(type==="FeatureCollection"){if(task.mode!=="any"||!Array.isArray(member.features))throw new Error("invalid GeoJSON FeatureCollection");for(let index=member.features.length-1;index>=0;index--)pushTask({kind:"geo",value:member.features[index],depth:task.depth+1,mode:"feature"});continue}if(!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON type");if(type==="GeometryCollection"){if(!Array.isArray(member.geometries))throw new Error("invalid GeoJSON GeometryCollection");for(let index=member.geometries.length-1;index>=0;index--)pushTask({kind:"geo",value:member.geometries[index],depth:task.depth+1,mode:"geometry"});continue}if(!Object.hasOwn(member,"coordinates"))throw new Error("GeoJSON geometry has no coordinates");pushTask({kind:{Point:"position",LineString:"line",Polygon:"polygon",MultiPoint:"positions",MultiLineString:"multi-line",MultiPolygon:"multi-polygon"}[type],value:member.coordinates,depth:task.depth+1})}const count=root.type==="FeatureCollection"&&Array.isArray(root.features)?root.features.length:1,metadata=JSON.stringify(root,null,2);if(metadata.length>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.");return{value:root,metadata,featureCount:count,bounds}}const FIT_PADDING=24,MAX_FIT_ZOOM=18;function crossesAntimeridian(bounds){return bounds.maxShiftedLng-bounds.minShiftedLng<bounds.maxLng-bounds.minLng-1e-9}function fitBboxToView(bounds){const crosses=crossesAntimeridian(bounds);let centerLng=crosses?(bounds.minShiftedLng+bounds.maxShiftedLng)/2:(bounds.minLng+bounds.maxLng)/2;centerLng>180&&(centerLng-=360);const center=[centerLng,(bounds.minLat+bounds.maxLat)/2],lngSpan=Math.max(crosses?bounds.maxShiftedLng-bounds.minShiftedLng:bounds.maxLng-bounds.minLng,1e-4),latSpan=Math.max(bounds.maxLat-bounds.minLat,1e-4),span=Math.max(lngSpan,latSpan*2)*1.4,zoom=Math.max(0,Math.min(MAX_FIT_ZOOM,Math.floor(Math.log2(360/span))));return{center,zoom}}class LyraGeoJsonViewerBase extends LyraElement{}class LyraGeoJsonViewer extends TextViewerTarget(LyraGeoJsonViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.mapReady?this.mapCanvas:this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this.maxHeight="",this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.pendingFitBounds=null,this.generation=0,this.lastLoadSrc="",this.registeredMap=null,this.announcements=new ViewerAnnouncementController(this),this.forceMissingMaplibreForTesting=!1}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,geojsonViewFeatureCount:LYRA_DEFAULT_geojsonViewFeatureCount,geojsonViewInvalid:LYRA_DEFAULT_geojsonViewInvalid,geojsonViewLabel:LYRA_DEFAULT_geojsonViewLabel,geojsonViewMissingMapLibrary:LYRA_DEFAULT_geojsonViewMissingMapLibrary,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}textContentRoot(){return this.renderRoot.querySelector('[part="base"]')}stopChildEvent(event){event.stopPropagation()}onMapCanvasReady(map,canvas){if(!this.isConnected||map!==this.registeredMap||this.shadowRoot?.querySelector(tag("map"))!==map||this.loadState.kind!=="loaded"||!this.loadState.peerAvailable||this.src!==this.lastLoadSrc)return;this.mapReady=!0,this.mapCanvas=canvas;const base=this.shadowRoot?.querySelector('[part="base"]');base?.removeAttribute("role"),base?.removeAttribute("aria-label"),this.hostDescription.refresh()}syncMapCanvasReadyCallback(){const next=this.shadowRoot?.querySelector(tag("map"));next!==this.registeredMap&&(this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=next,next&&setMapCanvasReadyCallback(next,canvas=>this.onMapCanvasReady(next,canvas)))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=null,this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}updated(changed){if(super.updated(changed),this.loadState.kind==="loaded"){const peerAvailable=this.loadState.peerAvailable;this.announcements.transition("load",peerAvailable?"loaded":"error",peerAvailable?this.featureCountStatus(this.loadState.featureCount):this.localize("geojsonViewMissingMapLibrary"),peerAvailable?"polite":"assertive")}else this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument"));this.syncMapCanvasReadyCallback(),this.fitLoadedData(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}fitLoadedData(){const bounds=this.pendingFitBounds,map=this.registeredMap;if(!bounds||!map||this.loadState.kind!=="loaded")return;this.pendingFitBounds=null;const crosses=crossesAntimeridian(bounds),west=crosses?bounds.minShiftedLng:bounds.minLng,east=crosses?bounds.maxShiftedLng:bounds.maxLng,fit=()=>{map.fitBounds([[west,bounds.minLat],[east,bounds.maxLat]],{padding:FIT_PADDING,maxZoom:MAX_FIT_ZOOM,animate:!1})};typeof map.fitBounds=="function"?fit():customElements.whenDefined(map.localName).then(fit)}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,this.mapReady=!1,this.mapCanvas=null,!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const parsed=JSON.parse(text),analysis=analyzeGeoJson(parsed),{center,zoom}=analysis.bounds?fitBboxToView(analysis.bounds):{center:[0,0],zoom:1};this.pendingFitBounds=analysis.bounds??null;const maplibre=this.forceMissingMaplibreForTesting?null:await loadMaplibre();if(!this.isConnected||generation!==this.generation)return;this.loadState={kind:"loaded",value:analysis.value,metadata:analysis.metadata,featureCount:analysis.featureCount,center,zoom,peerAvailable:maplibre!==null},maplibre||this.emit("lr-render-error",{error:new LyraUserFacingError(this.localize("geojsonViewMissingMapLibrary"))})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"geojsonViewInvalid")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.loadState={kind:"error",message},this.emit("lr-render-error",{error})}get effectiveLabel(){return hostAriaLabel(this)??(this.name?.trim()?this.name:this.localize("geojsonViewLabel"))}featureCountStatus(featureCount){return this.localize("geojsonViewFeatureCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(featureCount),pluralCount:featureCount})}renderBody(){switch(this.loadState.kind){case"loaded":{const{value,metadata,featureCount,center,zoom,peerAvailable}=this.loadState,statusText=this.featureCountStatus(featureCount);return peerAvailable?html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{tag}from"../../../internal/prefix.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{setMapCanvasReadyCallback}from"../../../internal/map-canvas-ready.js";import{loadMaplibre}from"../../media/map/map-loader.js";import{styles}from"./geojson-view.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_geojsonViewFeatureCount,LYRA_DEFAULT_geojsonViewInvalid,LYRA_DEFAULT_geojsonViewLabel,LYRA_DEFAULT_geojsonViewMissingMapLibrary,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const GEOMETRY_TYPES=new Set(["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection"]),MAX_GEOJSON_POSITIONS=1e4,MAX_GEOJSON_NODES=5e4,MAX_GEOJSON_DEPTH=64,MAX_GEOJSON_TEXT_UNITS=2*1024*1024,MAX_GEOJSON_SERIALIZED_UNITS=4*1024*1024,GEOJSON_BASE_MAP_STYLE={version:8,sources:{},layers:[]};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function assertGeoJsonGraphWithinLimits(root){const tasks=[{value:root,depth:0}],seen=new WeakSet;let graphUnits=0,textUnits=0;const accountGraphUnit=()=>{if(graphUnits++,graphUnits+tasks.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.")},accountText=value=>{if(textUnits+=value.length,textUnits>MAX_GEOJSON_TEXT_UNITS)throw new LyraResourceLimitError("The GeoJSON contains too much text.")};for(;tasks.length>0;){const task=tasks.pop();if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");accountGraphUnit();const value=task.value;if(typeof value=="string"){accountText(value);continue}if(!(value===null||typeof value=="boolean")){if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("invalid JSON number");continue}if(typeof value!="object")throw new Error("invalid JSON value");if(seen.has(value))throw new Error("cyclic JSON graph");if(seen.add(value),Array.isArray(value)){if(graphUnits+tasks.length+value.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=value.length-1;index>=0;index--)tasks.push({value:value[index],depth:task.depth+1});continue}for(const key in value)Object.hasOwn(value,key)&&(accountGraphUnit(),accountText(key),tasks.push({value:value[key],depth:task.depth+1}))}}}function analyzeGeoJson(value){if(assertGeoJsonGraphWithinLimits(value),!isRecord(value))throw new Error("not a GeoJSON object");const root=value,tasks=[{kind:"geo",value,depth:0,mode:"any"}];let processedNodes=0,positionCount=0,bounds=null;const pushTask=task=>{if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(processedNodes+tasks.length>=MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");tasks.push(task)},pushArray=(items,kind,depth)=>{if(processedNodes+tasks.length+items.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=items.length-1;index>=0;index--)pushTask({kind,value:items[index],depth})},requireArray=(candidate,minimum=0)=>{if(!Array.isArray(candidate)||candidate.length<minimum)throw new Error("invalid GeoJSON coordinates");return candidate};for(;tasks.length>0;){const task=tasks.pop();if(processedNodes++,processedNodes>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(task.kind==="position"){const position=requireArray(task.value,2);if(!position.every(coordinate=>typeof coordinate=="number"&&Number.isFinite(coordinate)))throw new Error("invalid GeoJSON position");const[lng,lat]=position;if(lng<-180||lng>180||lat<-90||lat>90)throw new Error("invalid GeoJSON position");if(positionCount++,positionCount>MAX_GEOJSON_POSITIONS)throw new LyraResourceLimitError("The GeoJSON contains too many positions.");const shiftedLng=lng<0?lng+360:lng;bounds?(bounds.minLng=Math.min(bounds.minLng,lng),bounds.maxLng=Math.max(bounds.maxLng,lng),bounds.minShiftedLng=Math.min(bounds.minShiftedLng,shiftedLng),bounds.maxShiftedLng=Math.max(bounds.maxShiftedLng,shiftedLng),bounds.minLat=Math.min(bounds.minLat,lat),bounds.maxLat=Math.max(bounds.maxLat,lat)):bounds={minLng:lng,maxLng:lng,minShiftedLng:shiftedLng,maxShiftedLng:shiftedLng,minLat:lat,maxLat:lat};continue}if(task.kind==="positions"||task.kind==="line"||task.kind==="ring"){const minimum=task.kind==="ring"?4:task.kind==="line"?2:0,positions=requireArray(task.value,minimum);if(task.kind==="ring"){const first=positions[0],last=positions[positions.length-1];if(!Array.isArray(first)||!Array.isArray(last)||first.length!==last.length||first.some((item,index)=>item!==last[index]))throw new Error("GeoJSON polygon rings must be closed")}pushArray(positions,"position",task.depth+1);continue}if(task.kind==="polygon"||task.kind==="multi-line"){const parts=requireArray(task.value);pushArray(parts,task.kind==="polygon"?"ring":"line",task.depth+1);continue}if(task.kind==="multi-polygon"){pushArray(requireArray(task.value),"polygon",task.depth+1);continue}if(task.kind!=="geo")throw new Error("invalid GeoJSON coordinate structure");if(!isRecord(task.value)||typeof task.value.type!="string")throw new Error("invalid GeoJSON member");const member=task.value,type=member.type;if(task.mode==="feature"&&type!=="Feature")throw new Error("FeatureCollection contains a non-Feature");if(task.mode==="geometry"&&!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON geometry");if(type==="Feature"){if(task.mode==="geometry"||!Object.hasOwn(member,"geometry")||!Object.hasOwn(member,"properties"))throw new Error("invalid GeoJSON Feature");if(member.properties!==null&&!isRecord(member.properties))throw new Error("invalid GeoJSON Feature properties");member.geometry!==null&&pushTask({kind:"geo",value:member.geometry,depth:task.depth+1,mode:"geometry"});continue}if(type==="FeatureCollection"){if(task.mode!=="any"||!Array.isArray(member.features))throw new Error("invalid GeoJSON FeatureCollection");for(let index=member.features.length-1;index>=0;index--)pushTask({kind:"geo",value:member.features[index],depth:task.depth+1,mode:"feature"});continue}if(!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON type");if(type==="GeometryCollection"){if(!Array.isArray(member.geometries))throw new Error("invalid GeoJSON GeometryCollection");for(let index=member.geometries.length-1;index>=0;index--)pushTask({kind:"geo",value:member.geometries[index],depth:task.depth+1,mode:"geometry"});continue}if(!Object.hasOwn(member,"coordinates"))throw new Error("GeoJSON geometry has no coordinates");pushTask({kind:{Point:"position",LineString:"line",Polygon:"polygon",MultiPoint:"positions",MultiLineString:"multi-line",MultiPolygon:"multi-polygon"}[type],value:member.coordinates,depth:task.depth+1})}const count=root.type==="FeatureCollection"&&Array.isArray(root.features)?root.features.length:1,metadata=JSON.stringify(root,null,2);if(metadata.length>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.");return{value:root,metadata,featureCount:count,bounds}}const FIT_PADDING=24,MAX_FIT_ZOOM=18;function crossesAntimeridian(bounds){return bounds.maxShiftedLng-bounds.minShiftedLng<bounds.maxLng-bounds.minLng-1e-9}function fitBboxToView(bounds){const crosses=crossesAntimeridian(bounds);let centerLng=crosses?(bounds.minShiftedLng+bounds.maxShiftedLng)/2:(bounds.minLng+bounds.maxLng)/2;centerLng>180&&(centerLng-=360);const center=[centerLng,(bounds.minLat+bounds.maxLat)/2],lngSpan=Math.max(crosses?bounds.maxShiftedLng-bounds.minShiftedLng:bounds.maxLng-bounds.minLng,1e-4),latSpan=Math.max(bounds.maxLat-bounds.minLat,1e-4),span=Math.max(lngSpan,latSpan*2)*1.4,zoom=Math.max(0,Math.min(MAX_FIT_ZOOM,Math.floor(Math.log2(360/span))));return{center,zoom}}class LyraGeoJsonViewerBase extends LyraElement{}class LyraGeoJsonViewer extends TextViewerTarget(LyraGeoJsonViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.mapReady?this.mapCanvas:this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this.maxHeight="",this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.pendingFitBounds=null,this.generation=0,this.lastLoadSrc="",this.registeredMap=null,this.announcements=new ViewerAnnouncementController(this),this.forceMissingMaplibreForTesting=!1}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,geojsonViewFeatureCount:LYRA_DEFAULT_geojsonViewFeatureCount,geojsonViewInvalid:LYRA_DEFAULT_geojsonViewInvalid,geojsonViewLabel:LYRA_DEFAULT_geojsonViewLabel,geojsonViewMissingMapLibrary:LYRA_DEFAULT_geojsonViewMissingMapLibrary,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}textContentRoot(){return this.renderRoot.querySelector('[part="base"]')}stopChildEvent(event){event.stopPropagation()}onMapCanvasReady(map,canvas){if(!this.isConnected||map!==this.registeredMap||this.shadowRoot?.querySelector(tag("map"))!==map||this.loadState.kind!=="loaded"||!this.loadState.peerAvailable||this.src!==this.lastLoadSrc)return;this.mapReady=!0,this.mapCanvas=canvas;const base=this.shadowRoot?.querySelector('[part="base"]');base?.removeAttribute("role"),base?.removeAttribute("aria-label"),this.hostDescription.refresh()}syncMapCanvasReadyCallback(){const next=this.shadowRoot?.querySelector(tag("map"));next!==this.registeredMap&&(this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=next,next&&setMapCanvasReadyCallback(next,canvas=>this.onMapCanvasReady(next,canvas)))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=null,this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}updated(changed){if(super.updated(changed),this.loadState.kind==="loaded"){const peerAvailable=this.loadState.peerAvailable;this.announcements.transition("load",peerAvailable?"loaded":"error",peerAvailable?this.featureCountStatus(this.loadState.featureCount):this.localize("geojsonViewMissingMapLibrary"),peerAvailable?"polite":"assertive")}else this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument"));this.syncMapCanvasReadyCallback(),this.fitLoadedData(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}fitLoadedData(){const bounds=this.pendingFitBounds,map=this.registeredMap;if(!bounds||!map||this.loadState.kind!=="loaded")return;this.pendingFitBounds=null;const crosses=crossesAntimeridian(bounds),west=crosses?bounds.minShiftedLng:bounds.minLng,east=crosses?bounds.maxShiftedLng:bounds.maxLng,fit=()=>{map.fitBounds([[west,bounds.minLat],[east,bounds.maxLat]],{padding:FIT_PADDING,maxZoom:MAX_FIT_ZOOM,animate:!1})};typeof map.fitBounds=="function"?fit():customElements.whenDefined(map.localName).then(fit)}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,this.mapReady=!1,this.mapCanvas=null,!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const parsed=JSON.parse(text),analysis=analyzeGeoJson(parsed),{center,zoom}=analysis.bounds?fitBboxToView(analysis.bounds):{center:[0,0],zoom:1};this.pendingFitBounds=analysis.bounds??null;const maplibre=this.forceMissingMaplibreForTesting?null:await loadMaplibre();if(!this.isConnected||generation!==this.generation)return;this.loadState={kind:"loaded",value:analysis.value,metadata:analysis.metadata,featureCount:analysis.featureCount,center,zoom,peerAvailable:maplibre!==null},maplibre||this.emit("lr-render-error",{error:new LyraUserFacingError(this.localize("geojsonViewMissingMapLibrary"))})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"geojsonViewInvalid")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.loadState={kind:"error",message},this.emit("lr-render-error",{error})}get effectiveLabel(){return hostAriaLabel(this)??(this.name?.trim()?this.name:this.localize("geojsonViewLabel"))}featureCountStatus(featureCount){return this.localize("geojsonViewFeatureCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(featureCount),pluralCount:featureCount})}renderBody(){switch(this.loadState.kind){case"loaded":{const{value,metadata,featureCount,center,zoom,peerAvailable}=this.loadState,statusText=this.featureCountStatus(featureCount);return peerAvailable?html`
|
|
2
2
|
<div part="status">${statusText}</div>
|
|
3
3
|
<pre part="metadata">${metadata}</pre>
|
|
4
4
|
<lr-map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./highlight-layer.styles.js";import{maxPairedAnimationEndMs}from"./highlight-layer-timing.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./highlight-layer.styles.js";import{maxPairedAnimationEndMs}from"./highlight-layer-timing.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_highlightLayerLabel}from"../../../internal/default-strings/viewers.generated.js";function snapshotItems(value){if(!Array.isArray(value))return Object.freeze([]);const output=[],seenIds=new Set,length=Math.min(value.length,1e4);for(let index=0;index<length;index+=1)try{const candidate=value[index];if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const rawId=candidate.id;if(typeof rawId!="string")continue;const id=rawId.trim();if(id.length===0||seenIds.has(id)||!Array.isArray(candidate.rects))continue;seenIds.add(id),output.push(rawId===id?candidate:{...candidate,id})}catch{}return Object.freeze(output)}class LyraHighlightLayer extends LyraElement{constructor(){super(...arguments),this._items=Object.freeze([]),this.activeHighlightId=null,this.withoutInteraction=!1,this.focusedId=null,this.flashingId=null,this.actionList=!1,this.flashGeneration=0,this.pendingFocusId=null}static{this.defaultStrings={...super.defaultStrings,highlightLayerLabel:LYRA_DEFAULT_highlightLayerLabel,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles]}get items(){return this._items}set items(value){const previous=this._items;this._items=snapshotItems(value),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback();const Observer=this.ownerDocument.defaultView?.ResizeObserver;this.sizeObserver=Observer?new Observer(entries=>{this.boxSize=entries.at(-1)?.contentRect??this.boxSize}):void 0,this.sizeObserver?.observe(this)}willUpdate(changed){super.willUpdate(changed);const refocus=this.hasFocusedAction();if(changed.has("items")){const positionOf=(items,id)=>items?.findIndex(item=>item.id===id)??-1,previousItems=changed.get("items");if(this.focusedId!==null&&positionOf(this.items,this.focusedId)<0){const previousIndex=positionOf(previousItems,this.focusedId),nextIndex=this.itemIndexesWithRects(this.items.map(item=>this.safeRects(item))).reduce((nearest,index)=>nearest===null||Math.abs(index-previousIndex)<Math.abs(nearest-previousIndex)?index:nearest,null);this.focusedId=nextIndex===null?null:this.items[nextIndex].id;const previousTargetIndex=positionOf(previousItems,this.focusedId);refocus&&previousTargetIndex>=0&&this.primaryTarget(previousTargetIndex)?.focus()}changed.get("items")!==void 0&&this.clearFlash()}(changed.has("items")||changed.has("boxSize")||changed.has("withoutInteraction"))&&(this.actionList=!this.withoutInteraction&&this.hitAreasOverlap(),refocus&&(this.pendingFocusId=this.focusedId))}updated(changed){super.updated(changed);const pending=this.pendingFocusId;if(this.pendingFocusId=null,pending===null)return;const index=this.items.findIndex(item=>item.id===pending);index>=0&&this.focusRect(index)}disconnectedCallback(){super.disconnectedCallback(),this.sizeObserver?.disconnect(),this.focusedId=null,this.pendingFocusId=null,this.clearFlash()}hasFocusedAction(){return shadowFocusTarget(this)?.matches("[data-item-action]")??!1}hitAreasOverlap(){const view=this.ownerDocument?.defaultView;if(!view)return!1;const{width,height}=this.boxSize??this.getBoundingClientRect(),min=resolveCssTokenLength(view.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim(),{host:this})??0,boxes=this.items.flatMap((item,index)=>this.safeRects(item).map(rect=>{const boxWidth=Math.max(rect.width/100*width,min),boxHeight=Math.max(rect.height/100*height,min),left=(rect.x+rect.width/2)/100*width-boxWidth/2,top=(rect.y+rect.height/2)/100*height-boxHeight/2;return{index,left,top,right:left+boxWidth,bottom:top+boxHeight}})).sort((first,second)=>first.left-second.left);for(let first=0;first<boxes.length;first++){const a=boxes[first];for(let second=first+1;second<boxes.length&&boxes[second].left<a.right;second++){const b=boxes[second];if(b.index!==a.index&&b.top<a.bottom&&a.top<b.bottom)return!0}}return!1}adoptedCallback(){super.adoptedCallback(),this.clearFlash()}flash(id){if(this.clearFlash(),!this.isConnected||!this.items.some(candidate=>candidate.id===id))return;this.flashingId=id;const generation=this.flashGeneration;this.updateComplete.then(()=>{if(generation!==this.flashGeneration||this.flashingId!==id||!this.isConnected)return;const rect=this.primaryVisualRect(this.items.findIndex(candidate=>candidate.id===id));if(!rect){this.flashingId=null;return}const ownerWindow=rect.ownerDocument.defaultView;if(!ownerWindow){this.flashingId=null;return}const computed=ownerWindow.getComputedStyle(rect),durationMs=maxPairedAnimationEndMs(computed.animationName,computed.animationDuration,computed.animationDelay);this.flashTimerWindow=ownerWindow,this.flashTimer=ownerWindow.setTimeout(()=>{generation!==this.flashGeneration||this.flashTimerWindow!==ownerWindow||(this.flashTimer=void 0,this.flashTimerWindow=void 0,this.flashingId=null)},durationMs)})}clearFlash(){this.flashTimer!==void 0&&this.flashTimerWindow?.clearTimeout(this.flashTimer),this.flashTimer=void 0,this.flashTimerWindow=void 0,this.flashGeneration+=1,this.flashingId=null}safeRects(item){return item.rects.map(sanitizePercentRect).filter(rect=>rect!==void 0)}itemIndexesWithRects(rectsByItem){const indexes=[];return rectsByItem.forEach((rects,index)=>{rects.length>0&&indexes.push(index)}),indexes}tabStopIndex(rectsByItem){const renderedIndexes=this.itemIndexesWithRects(rectsByItem);if(renderedIndexes.length===0)return null;if(this.focusedId!==null){const focusedIndex=this.items.findIndex(item=>item.id===this.focusedId);if(renderedIndexes.includes(focusedIndex))return focusedIndex}if(this.activeHighlightId){const activeIndex=this.items.findIndex((item,index)=>item.id===this.activeHighlightId&&rectsByItem[index].length>0);if(activeIndex>=0)return activeIndex}return renderedIndexes[0]}onRectClick(id){this.emit("lr-highlight-activate",{highlightId:id})}onRectFocus(item){this.focusedId=item.id}primaryTarget(itemIndex){return[...this.renderRoot.querySelectorAll("[data-item-action]")].find(target=>target.dataset.itemIndex===String(itemIndex))??null}primaryVisualRect(itemIndex){return[...this.renderRoot.querySelectorAll('[part="rect"][data-primary]')].find(rect=>rect.dataset.itemIndex===String(itemIndex))??null}focusRect(itemIndex){this.primaryTarget(itemIndex)?.focus()}onRectKeyDown(e,itemIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onRectClick(this.items[itemIndex].id);return}const rtl=this.effectiveDirection==="rtl",forward=e.key==="ArrowDown"||(rtl?e.key==="ArrowLeft":e.key==="ArrowRight"),backward=e.key==="ArrowUp"||(rtl?e.key==="ArrowRight":e.key==="ArrowLeft"),renderedIndexes=this.itemIndexesWithRects(this.items.map(item=>this.safeRects(item))),position=renderedIndexes.indexOf(itemIndex);let nextIndex;forward?nextIndex=renderedIndexes[Math.min(renderedIndexes.length-1,position+1)]:backward?nextIndex=renderedIndexes[Math.max(0,position-1)]:e.key==="Home"?nextIndex=renderedIndexes[0]:e.key==="End"&&(nextIndex=renderedIndexes.at(-1)),!(nextIndex===void 0||nextIndex===itemIndex)&&(e.preventDefault(),this.focusedId=this.items[nextIndex].id,this.scheduleAfterUpdate(()=>this.focusRect(nextIndex)))}rectLabel(item,index,total){const numberFormat=getNumberFormat(this.effectiveLocale);return item.label?this.localize("highlightWithLabel",void 0,{label:item.label}):this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}render(){if(this.items.length===0)return nothing;const rectsByItem=this.items.map(item=>this.safeRects(item)),renderedIndexes=this.itemIndexesWithRects(rectsByItem);if(renderedIndexes.length===0)return nothing;const tabStop=this.tabStopIndex(rectsByItem),activeIndex=this.activeHighlightId?this.items.findIndex((item,index)=>item.id===this.activeHighlightId&&rectsByItem[index].length>0):-1,renderedPosition=new Map(renderedIndexes.map((itemIndex,position)=>[itemIndex,position])),interactive=!this.withoutInteraction,useActionList=interactive&&this.actionList,ariaLabel=interactive?hostAriaLabel(this)??this.localize("highlightLayerLabel"):void 0;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
role=${interactive?"group":nothing}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadHtmlSanitizer}from"./dompurify-loader.js";import{styles}from"./html-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadHtmlSanitizer}from"./dompurify-loader.js";import{styles}from"./html-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_htmlViewerLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";class LyraHtmlViewerBase extends LyraElement{}class LyraHtmlViewer extends TextViewerTarget(LyraHtmlViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++,this.beginAbortableLoad(),this.fetchState={kind:"idle"}})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,htmlViewerLabel:LYRA_DEFAULT_htmlViewerLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const sanitizer=await loadHtmlSanitizer();if(!this.isConnected||generation!==this.generation)return;if(!sanitizer)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const raw=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const markup=sanitizePassiveMarkup(sanitizer,raw,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation)return;this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",markup})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}renderBody(){switch(this.fetchState.kind){case"loaded":return html`<div part="html" role=${viewerSemanticRole(this,"document")??nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("htmlViewerLabel"))??nothing}>${unsafeHTML(this.fetchState.markup)}</div>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-html-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraHtmlViewer.prototype,"src",void 0),__decorate([property()],LyraHtmlViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraHtmlViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraHtmlViewer.prototype,"fetchState",void 0);export{LyraHtmlViewer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadHtmlSanitizer}from"../html-viewer/dompurify-loader.js";import{acquireSanitizedIncludeResource,IncludeResourceError,invalidateIncludeResource,MAX_INCLUDE_BYTES}from"./include-resource.js";import{styles}from"./include.styles.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings.generated.js";const INCLUDE_MODE=literalSetConverter(["cors","no-cors","same-origin"],"same-origin");class LyraIncludeBase extends LyraElement{}const ID_REFERENCE_ATTRIBUTES=["aria-activedescendant","aria-controls","aria-describedby","aria-details","aria-errormessage","aria-flowto","aria-labelledby","aria-owns","for","form","headers","list"];let nextClonePrefix=0;function decodedFragment(hash){const encoded=hash.startsWith("#")?hash.slice(1):hash;try{return decodeURIComponent(encoded)}catch{return encoded}}function isTemplateElement(element){return element.localName==="template"&&"content"in element}function allElements(root){const elements=[...root.querySelectorAll("*")];for(const template of elements.filter(isTemplateElement))elements.push(...allElements(template.content));return elements}function elementWithId(root,id){for(const element of allElements(root))if(element.id===id)return element;return null}class LyraInclude extends TextViewerTarget(LyraIncludeBase){constructor(){super(...arguments),this.src="",this._mode="same-origin",this.withoutCache=!1,this.generation=0,this.clonePrefix=`include-fragment-${++nextClonePrefix}`,this.detached=new DeferredTeardown(()=>{this.generation++,this.releaseResourceLease(),this.setAttribute("aria-busy","false")})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}static{this.styles=[LyraElement.styles,styles,srOnly]}get mode(){return this._mode}set mode(next){const normalized=INCLUDE_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this}updated(changed){super.updated(changed),(changed.has("src")||changed.has("mode")||changed.has("withoutCache"))&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),!this.detached.cancel()&&(this.setAttribute("aria-busy","false"),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush()}async reload(){const source=this.resolveSource();source?.kind==="remote"&&invalidateIncludeResource(source.url,this.effectiveMode,source.owner),await this.load()}get effectiveMode(){return this.mode}resolveSource(){const value=this.src.trim();if(!value)return null;if(value.startsWith("#"))return{kind:"same-page",fragment:decodedFragment(value)};const target=resolveOwnerFetchTarget(this,value);if(!target)return null;try{const parsed=new target.view.URL(target.url),fragment=decodedFragment(parsed.hash);return parsed.hash="",{kind:"remote",url:parsed.href,fragment,owner:target.view}}catch{return null}}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async sanitizeSamePage(source,generation){const markup=source.innerHTML;if(new TextEncoder().encode(markup).byteLength>MAX_INCLUDE_BYTES)return this.fail(0,"resource-too-large"),null;const sanitizer=await loadHtmlSanitizer();return!this.isConnected||generation!==this.generation?null:sanitizer?sanitizePassiveMarkup(sanitizer,markup,this.ownerDocument,"transclusion"):(this.fail(0,"missing-sanitizer"),null)}fragmentFromSanitized(markup,fragmentId){const template=this.ownerDocument.createElement("template");template.innerHTML=markup;const output=this.ownerDocument.createDocumentFragment();if(fragmentId){const target=elementWithId(template.content,fragmentId);if(!target)return null;const children=isTemplateElement(target)?target.content.childNodes:target.childNodes;for(const child of children)output.append(child.cloneNode(!0))}else output.append(template.content.cloneNode(!0));return this.rebaseFragmentIds(output),output}rebaseFragmentIds(fragment){const idMap=new Map;let index=0;const elements=allElements(fragment);for(const element of elements){if(element.removeAttribute("name"),!element.id)continue;const original=element.id,next=`${this.clonePrefix}-${++index}`;idMap.has(original)||idMap.set(original,next),element.id=next}for(const element of elements){for(const attribute of ID_REFERENCE_ATTRIBUTES){if(!element.hasAttribute(attribute))continue;const replacements=element.getAttribute(attribute).split(/\s+/).filter(Boolean).map(token=>idMap.get(token)).filter(token=>!!token);replacements.length>0?element.setAttribute(attribute,replacements.join(" ")):element.removeAttribute(attribute)}for(const attribute of["href","xlink:href"]){const value=element.getAttribute(attribute);if(!value)continue;if(!value.startsWith("#")){element.removeAttribute(attribute);continue}const replacement=idMap.get(decodedFragment(value));replacement?element.setAttribute(attribute,`#${replacement}`):element.removeAttribute(attribute)}for(const attribute of element.getAttributeNames()){const value=element.getAttribute(attribute)??"";if(!/url\s*\(/i.test(value))continue;const match=/^\s*url\(\s*(['"]?)#([A-Za-z_][\w:.-]*)\1\s*\)\s*$/i.exec(value),replacement=match?idMap.get(match[2]):void 0;replacement?element.setAttribute(attribute,`url(#${replacement})`):element.removeAttribute(attribute)}}}async load(){const generation=++this.generation;if(this.releaseResourceLease(),this.setAttribute("aria-busy","false"),!this.src.trim()||!this.isConnected)return;const source=this.resolveSource();if(!source){this.emitError({status:0,reason:"blocked-url"});return}this.setAttribute("aria-busy","true");let lease;try{let markup,fragmentId=source.fragment;if(source.kind==="same-page"){const target=this.ownerDocument.getElementById(source.fragment);if(!target){this.fail(0,"missing-fragment");return}markup=await this.sanitizeSamePage(target,generation),fragmentId=""}else lease=acquireSanitizedIncludeResource(source.url,this.effectiveMode,!this.withoutCache,source.owner),this.resourceLease=lease,markup=await lease.promise;if(markup==null||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;const fragment=this.fragmentFromSanitized(markup,fragmentId);if(!fragment){this.fail(0,"missing-fragment");return}if(generation!==this.generation||!this.isConnected||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;this.replaceChildren(fragment),this.requestUpdate(),this.setAttribute("aria-busy","false"),this.emit("lr-load",{src:this.src})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;error instanceof IncludeResourceError?this.fail(error.status,error.reason,error.cause??error):this.fail(0,"network",error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}fail(status,reason,error){this.setAttribute("aria-busy","false"),this.emitError({status,reason,error})}emitError(detail){this.emit("lr-include-error",detail),this.emit("lr-error",detail)}render(){return html`<span part="base"><slot></slot></span>${this.renderAnchorLiveRegion()}`}}__decorate([property({reflect:!0})],LyraInclude.prototype,"src",void 0),__decorate([property({reflect:!0,converter:INCLUDE_MODE})],LyraInclude.prototype,"mode",null),__decorate([property({type:Boolean,attribute:"without-cache"})],LyraInclude.prototype,"withoutCache",void 0);export{LyraInclude};
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadHtmlSanitizer}from"../html-viewer/dompurify-loader.js";import{acquireSanitizedIncludeResource,IncludeResourceError,invalidateIncludeResource,MAX_INCLUDE_BYTES}from"./include-resource.js";import{styles}from"./include.styles.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings/shared.generated.js";const INCLUDE_MODE=literalSetConverter(["cors","no-cors","same-origin"],"same-origin");class LyraIncludeBase extends LyraElement{}const ID_REFERENCE_ATTRIBUTES=["aria-activedescendant","aria-controls","aria-describedby","aria-details","aria-errormessage","aria-flowto","aria-labelledby","aria-owns","for","form","headers","list"];let nextClonePrefix=0;function decodedFragment(hash){const encoded=hash.startsWith("#")?hash.slice(1):hash;try{return decodeURIComponent(encoded)}catch{return encoded}}function isTemplateElement(element){return element.localName==="template"&&"content"in element}function allElements(root){const elements=[...root.querySelectorAll("*")];for(const template of elements.filter(isTemplateElement))elements.push(...allElements(template.content));return elements}function elementWithId(root,id){for(const element of allElements(root))if(element.id===id)return element;return null}class LyraInclude extends TextViewerTarget(LyraIncludeBase){constructor(){super(...arguments),this.src="",this._mode="same-origin",this.withoutCache=!1,this.generation=0,this.clonePrefix=`include-fragment-${++nextClonePrefix}`,this.detached=new DeferredTeardown(()=>{this.generation++,this.releaseResourceLease(),this.setAttribute("aria-busy","false")})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}static{this.styles=[LyraElement.styles,styles,srOnly]}get mode(){return this._mode}set mode(next){const normalized=INCLUDE_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this}updated(changed){super.updated(changed),(changed.has("src")||changed.has("mode")||changed.has("withoutCache"))&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),!this.detached.cancel()&&(this.setAttribute("aria-busy","false"),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush()}async reload(){const source=this.resolveSource();source?.kind==="remote"&&invalidateIncludeResource(source.url,this.effectiveMode,source.owner),await this.load()}get effectiveMode(){return this.mode}resolveSource(){const value=this.src.trim();if(!value)return null;if(value.startsWith("#"))return{kind:"same-page",fragment:decodedFragment(value)};const target=resolveOwnerFetchTarget(this,value);if(!target)return null;try{const parsed=new target.view.URL(target.url),fragment=decodedFragment(parsed.hash);return parsed.hash="",{kind:"remote",url:parsed.href,fragment,owner:target.view}}catch{return null}}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async sanitizeSamePage(source,generation){const markup=source.innerHTML;if(new TextEncoder().encode(markup).byteLength>MAX_INCLUDE_BYTES)return this.fail(0,"resource-too-large"),null;const sanitizer=await loadHtmlSanitizer();return!this.isConnected||generation!==this.generation?null:sanitizer?sanitizePassiveMarkup(sanitizer,markup,this.ownerDocument,"transclusion"):(this.fail(0,"missing-sanitizer"),null)}fragmentFromSanitized(markup,fragmentId){const template=this.ownerDocument.createElement("template");template.innerHTML=markup;const output=this.ownerDocument.createDocumentFragment();if(fragmentId){const target=elementWithId(template.content,fragmentId);if(!target)return null;const children=isTemplateElement(target)?target.content.childNodes:target.childNodes;for(const child of children)output.append(child.cloneNode(!0))}else output.append(template.content.cloneNode(!0));return this.rebaseFragmentIds(output),output}rebaseFragmentIds(fragment){const idMap=new Map;let index=0;const elements=allElements(fragment);for(const element of elements){if(element.removeAttribute("name"),!element.id)continue;const original=element.id,next=`${this.clonePrefix}-${++index}`;idMap.has(original)||idMap.set(original,next),element.id=next}for(const element of elements){for(const attribute of ID_REFERENCE_ATTRIBUTES){if(!element.hasAttribute(attribute))continue;const replacements=element.getAttribute(attribute).split(/\s+/).filter(Boolean).map(token=>idMap.get(token)).filter(token=>!!token);replacements.length>0?element.setAttribute(attribute,replacements.join(" ")):element.removeAttribute(attribute)}for(const attribute of["href","xlink:href"]){const value=element.getAttribute(attribute);if(!value)continue;if(!value.startsWith("#")){element.removeAttribute(attribute);continue}const replacement=idMap.get(decodedFragment(value));replacement?element.setAttribute(attribute,`#${replacement}`):element.removeAttribute(attribute)}for(const attribute of element.getAttributeNames()){const value=element.getAttribute(attribute)??"";if(!/url\s*\(/i.test(value))continue;const match=/^\s*url\(\s*(['"]?)#([A-Za-z_][\w:.-]*)\1\s*\)\s*$/i.exec(value),replacement=match?idMap.get(match[2]):void 0;replacement?element.setAttribute(attribute,`url(#${replacement})`):element.removeAttribute(attribute)}}}async load(){const generation=++this.generation;if(this.releaseResourceLease(),this.setAttribute("aria-busy","false"),!this.src.trim()||!this.isConnected)return;const source=this.resolveSource();if(!source){this.emitError({status:0,reason:"blocked-url"});return}this.setAttribute("aria-busy","true");let lease;try{let markup,fragmentId=source.fragment;if(source.kind==="same-page"){const target=this.ownerDocument.getElementById(source.fragment);if(!target){this.fail(0,"missing-fragment");return}markup=await this.sanitizeSamePage(target,generation),fragmentId=""}else lease=acquireSanitizedIncludeResource(source.url,this.effectiveMode,!this.withoutCache,source.owner),this.resourceLease=lease,markup=await lease.promise;if(markup==null||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;const fragment=this.fragmentFromSanitized(markup,fragmentId);if(!fragment){this.fail(0,"missing-fragment");return}if(generation!==this.generation||!this.isConnected||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;this.replaceChildren(fragment),this.requestUpdate(),this.setAttribute("aria-busy","false"),this.emit("lr-load",{src:this.src})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;error instanceof IncludeResourceError?this.fail(error.status,error.reason,error.cause??error):this.fail(0,"network",error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}fail(status,reason,error){this.setAttribute("aria-busy","false"),this.emitError({status,reason,error})}emitError(detail){this.emit("lr-include-error",detail),this.emit("lr-error",detail)}render(){return html`<span part="base"><slot></slot></span>${this.renderAnchorLiveRegion()}`}}__decorate([property({reflect:!0})],LyraInclude.prototype,"src",void 0),__decorate([property({reflect:!0,converter:INCLUDE_MODE})],LyraInclude.prototype,"mode",null),__decorate([property({type:Boolean,attribute:"without-cache"})],LyraInclude.prototype,"withoutCache",void 0);export{LyraInclude};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{createAnsiParser}from"../../../internal/ansi.js";import{loadNotebookSanitizer}from"./dompurify-loader.js";import{styles}from"./notebook-viewer.styles.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_notebookViewerCodeCell,LYRA_DEFAULT_notebookViewerCollapseOutput,LYRA_DEFAULT_notebookViewerErrorOutput,LYRA_DEFAULT_notebookViewerInPrompt,LYRA_DEFAULT_notebookViewerInPromptEmpty,LYRA_DEFAULT_notebookViewerInvalid,LYRA_DEFAULT_notebookViewerLabel,LYRA_DEFAULT_notebookViewerMarkdownCell,LYRA_DEFAULT_notebookViewerRawCell,LYRA_DEFAULT_notebookViewerShowAllOutput,LYRA_DEFAULT_notebookViewerTooManyCells,LYRA_DEFAULT_notebookViewerUnrenderedOutput,LYRA_DEFAULT_notebookViewerUnsupportedVersion}from"../../../internal/default-strings.generated.js";const MAX_CELLS=2e3,MAX_OUTPUTS=2e4,MAX_JSON_NODES=1e5,SUPPORTED_MAJOR=4,SUPPORTED_MINORS=[0,1,2,3,4,5],MAX_NOTEBOOK_PAINTED_HIGHLIGHTS=100,OMIT_NOTEBOOK_SNAPSHOT=Symbol("omit-notebook-snapshot");function invalidNotebookSnapshot(){return Object.freeze({})}function isNotebookDataRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const parent=Object.getPrototypeOf(prototype),constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(parent===null)return!constructor||"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object";if(constructor)return!1;const parentConstructor=Object.getOwnPropertyDescriptor(parent,"constructor");return!!(Object.getPrototypeOf(parent)===null&&parentConstructor&&"value"in parentConstructor&&typeof parentConstructor.value=="function"&&parentConstructor.value.name==="Object")}catch{return!1}}function snapshotNotebookDocument(value){if(value===null||typeof value!="object"||Array.isArray(value))return OMIT_NOTEBOOK_SNAPSHOT;let remaining=MAX_JSON_NODES;const seen=new WeakSet,created=[],pending=[],createContainer=source=>{let array=!1;try{array=Array.isArray(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}let keys,target;if(array){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(source,"length")}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0||lengthDescriptor.value>remaining)return OMIT_NOTEBOOK_SNAPSHOT;keys=Array.from({length:lengthDescriptor.value},(_,index)=>String(index)),target=new Array(lengthDescriptor.value)}else{if(!isNotebookDataRecord(source))return OMIT_NOTEBOOK_SNAPSHOT;try{keys=Object.keys(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(keys.length>remaining)return OMIT_NOTEBOOK_SNAPSHOT;target={}}return seen.add(source),created.push(target),pending.push({source,target,keys,array}),target};remaining-=1;const root=createContainer(value);if(root===OMIT_NOTEBOOK_SNAPSHOT)return root;for(;pending.length;){const task=pending.pop();for(const key of task.keys){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(task.source,key)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor){if(task.array)continue;return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor.enumerable||!("value"in descriptor)||remaining<=0)return OMIT_NOTEBOOK_SNAPSHOT;remaining-=1;const entry=descriptor.value;let snapshot=entry;if(entry!==null&&(typeof entry=="object"||typeof entry=="function")){if(typeof entry=="function"||seen.has(entry))return OMIT_NOTEBOOK_SNAPSHOT;if(snapshot=createContainer(entry),snapshot===OMIT_NOTEBOOK_SNAPSHOT)return snapshot}Object.defineProperty(task.target,key,{value:snapshot,enumerable:!0,configurable:!1,writable:!1})}}for(let index=created.length-1;index>=0;index-=1)Object.freeze(created[index]);return root}function joinSource(source){return typeof source=="string"?source:source?.join("")??""}function isDenseArray(value){for(let index=0;index<value.length;index++)if(!Object.prototype.hasOwnProperty.call(value,index))return!1;return!0}function joinText(text){return typeof text=="string"?text:Array.isArray(text)&&isDenseArray(text)&&text.every(item=>typeof item=="string")?text.join(""):""}function*notebookSearchTextParts(text){if(typeof text=="string"){yield text;return}if(!(!Array.isArray(text)||!isDenseArray(text)))for(const part of text)typeof part=="string"&&(yield part)}const MARKUP_ENTITIES={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"};function visibleMarkupText(markup){const lower=markup.toLowerCase();let text="",index=0;for(;index<markup.length;){const open=markup.indexOf("<",index);if(open<0){text+=markup.slice(index);break}if(text+=markup.slice(index,open)+" ",lower.startsWith("<!--",open)){const end=markup.indexOf("-->",open+4);index=end<0?markup.length:end+3;continue}const close=markup.indexOf(">",open+1);if(close<0)break;const rawText=lower.startsWith("<script",open)?"<\/script":lower.startsWith("<style",open)?"</style":"";if(rawText){const end=lower.indexOf(rawText,close+1),endClose=end<0?-1:markup.indexOf(">",end);index=endClose<0?markup.length:endClose+1;continue}index=close+1}return text.replace(/&(lt|gt|quot|apos|amp);/g,(_entity,name)=>MARKUP_ENTITIES[name])}function*notebookOutputSearchParts(outputs){for(const output of outputs){yield*notebookSearchTextParts(output.text);const data=output.data;data&&Object.prototype.hasOwnProperty.call(data,"text/plain")&&(yield*notebookSearchTextParts(data["text/plain"]),yield" "),data&&!data["image/png"]&&!data["image/jpeg"]&&(data["image/svg+xml"]?yield visibleMarkupText(joinText(data["image/svg+xml"])):data["text/html"]?yield visibleMarkupText(joinText(data["text/html"])):data["application/json"]&&(yield*notebookSearchTextParts(data["application/json"]))),yield" "}}function isTextValue(value){return typeof value=="string"||Array.isArray(value)&&isDenseArray(value)&&value.every(item=>typeof item=="string")}function isJsonValue(value){const pending=[value];let nodes=0;for(;pending.length;){const current=pending.pop();if(++nodes>MAX_JSON_NODES)return!1;if(!(current===null||typeof current=="string"||typeof current=="boolean")){if(typeof current=="number"){if(!Number.isFinite(current))return!1;continue}if(Array.isArray(current)){if(current.length>MAX_JSON_NODES-nodes-pending.length)return!1;for(let index=current.length-1;index>=0;index--)pending.push(current[index]);continue}if(typeof current!="object")return!1;for(const key in current)if(Object.prototype.hasOwnProperty.call(current,key)){if(pending.length>=MAX_JSON_NODES-nodes)return!1;pending.push(current[key])}}}return!0}function isNotebookOutput(value){if(typeof value!="object"||value===null)return!1;const output=value;if(!["stream","error","display_data","execute_result"].includes(String(output.output_type))||output.text!==void 0&&!isTextValue(output.text)||output.traceback!==void 0&&!isTextValue(output.traceback)||output.ename!==void 0&&typeof output.ename!="string"||output.evalue!==void 0&&typeof output.evalue!="string"||output.name!==void 0&&output.name!=="stdout"&&output.name!=="stderr")return!1;const data=output.data;if(data===void 0)return!0;if(typeof data!="object"||data===null||Array.isArray(data))return!1;const mimeData=data;for(const[mime,payload]of Object.entries(mimeData))if(mime==="application/json"){if(typeof payload=="string")try{if(!isJsonValue(JSON.parse(payload)))return!1}catch{return!1}else if(!isJsonValue(payload))return!1}else if(!isTextValue(payload)&&!isJsonValue(payload))return!1;return!0}function isNotebookShape(value){if(typeof value!="object"||value===null)return!1;const v=value;if(!Number.isInteger(v.nbformat)||!Number.isInteger(v.nbformat_minor)||!Array.isArray(v.cells))return!1;const cells=v.cells;let outputCount=0;for(let index=0;index<cells.length;index++){if(!Object.prototype.hasOwnProperty.call(cells,index))return!1;const value2=cells[index];if(typeof value2!="object"||value2===null)return!1;const cell=value2;if(!["markdown","code","raw"].includes(String(cell.cell_type))||!isTextValue(cell.source)||cell.id!==void 0&&typeof cell.id!="string"||cell.execution_count!==void 0&&cell.execution_count!==null&&(!Number.isInteger(cell.execution_count)||cell.execution_count<0))return!1;if(cell.outputs!==void 0&&(!Array.isArray(cell.outputs)||!isDenseArray(cell.outputs)||(outputCount+=cell.outputs.length,outputCount>MAX_OUTPUTS||!cell.outputs.every(isNotebookOutput))))return!1}return!0}class LyraNotebookViewerBase extends LyraElement{}class LyraNotebookViewer extends DocumentAnchorTarget(LyraNotebookViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.outputCollapseLines=40,this.maxHeight="",this.anchorKinds=["node-path","fragment"],this.loadState={kind:"idle"},this.expandedOutputs=new Set,this.activeCellIndex=null,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1,this.cellKey=(item,index)=>item.id??index,this.highlightedCells=new Map,this.generation=0,this.lastSearchLocale="",this.sanitizerGeneration=0,this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedNotebook()),this.sanitizedOutputCache=new Map,this.sanitizationTasks=new Map,this.renderCell=(cell,index)=>{const c=cell,numberFormat=getNumberFormat(this.effectiveLocale),inCount=c.execution_count==null?this.localize("notebookViewerInPromptEmpty"):this.localize("notebookViewerInPrompt",void 0,{count:numberFormat.format(c.execution_count)}),rowLabel=c.cell_type==="code"?this.localize("notebookViewerCodeCell",void 0,{index:numberFormat.format(index+1)}):c.cell_type==="markdown"?this.localize("notebookViewerMarkdownCell",void 0,{index:numberFormat.format(index+1)}):this.localize("notebookViewerRawCell",void 0,{index:numberFormat.format(index+1)}),active=this.activeCellIndex===index,highlight=this.highlightedCells.get(index),highlighted=highlight!==void 0,parts=["cell"];return active&&parts.push("cell-active"),highlighted&&(parts.push("cell-highlighted",`cell-highlighted-${highlight.tone??"accent"}`),highlight.id===this.activeHighlightId&&parts.push("cell-highlight-active")),html`<div part=${parts.join(" ")} role="group" aria-label=${rowLabel} data-cell-type=${c.cell_type} ?data-active=${active} ?data-highlighted=${highlighted}>
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{createAnsiParser}from"../../../internal/ansi.js";import{loadNotebookSanitizer}from"./dompurify-loader.js";import{styles}from"./notebook-viewer.styles.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_notebookViewerCodeCell,LYRA_DEFAULT_notebookViewerCollapseOutput,LYRA_DEFAULT_notebookViewerErrorOutput,LYRA_DEFAULT_notebookViewerInPrompt,LYRA_DEFAULT_notebookViewerInPromptEmpty,LYRA_DEFAULT_notebookViewerInvalid,LYRA_DEFAULT_notebookViewerLabel,LYRA_DEFAULT_notebookViewerMarkdownCell,LYRA_DEFAULT_notebookViewerRawCell,LYRA_DEFAULT_notebookViewerShowAllOutput,LYRA_DEFAULT_notebookViewerTooManyCells,LYRA_DEFAULT_notebookViewerUnrenderedOutput,LYRA_DEFAULT_notebookViewerUnsupportedVersion}from"../../../internal/default-strings/viewers.generated.js";const MAX_CELLS=2e3,MAX_OUTPUTS=2e4,MAX_JSON_NODES=1e5,SUPPORTED_MAJOR=4,SUPPORTED_MINORS=[0,1,2,3,4,5],MAX_NOTEBOOK_PAINTED_HIGHLIGHTS=100,OMIT_NOTEBOOK_SNAPSHOT=Symbol("omit-notebook-snapshot");function invalidNotebookSnapshot(){return Object.freeze({})}function isNotebookDataRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const parent=Object.getPrototypeOf(prototype),constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(parent===null)return!constructor||"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object";if(constructor)return!1;const parentConstructor=Object.getOwnPropertyDescriptor(parent,"constructor");return!!(Object.getPrototypeOf(parent)===null&&parentConstructor&&"value"in parentConstructor&&typeof parentConstructor.value=="function"&&parentConstructor.value.name==="Object")}catch{return!1}}function snapshotNotebookDocument(value){if(value===null||typeof value!="object"||Array.isArray(value))return OMIT_NOTEBOOK_SNAPSHOT;let remaining=MAX_JSON_NODES;const seen=new WeakSet,created=[],pending=[],createContainer=source=>{let array=!1;try{array=Array.isArray(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}let keys,target;if(array){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(source,"length")}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0||lengthDescriptor.value>remaining)return OMIT_NOTEBOOK_SNAPSHOT;keys=Array.from({length:lengthDescriptor.value},(_,index)=>String(index)),target=new Array(lengthDescriptor.value)}else{if(!isNotebookDataRecord(source))return OMIT_NOTEBOOK_SNAPSHOT;try{keys=Object.keys(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(keys.length>remaining)return OMIT_NOTEBOOK_SNAPSHOT;target={}}return seen.add(source),created.push(target),pending.push({source,target,keys,array}),target};remaining-=1;const root=createContainer(value);if(root===OMIT_NOTEBOOK_SNAPSHOT)return root;for(;pending.length;){const task=pending.pop();for(const key of task.keys){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(task.source,key)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor){if(task.array)continue;return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor.enumerable||!("value"in descriptor)||remaining<=0)return OMIT_NOTEBOOK_SNAPSHOT;remaining-=1;const entry=descriptor.value;let snapshot=entry;if(entry!==null&&(typeof entry=="object"||typeof entry=="function")){if(typeof entry=="function"||seen.has(entry))return OMIT_NOTEBOOK_SNAPSHOT;if(snapshot=createContainer(entry),snapshot===OMIT_NOTEBOOK_SNAPSHOT)return snapshot}Object.defineProperty(task.target,key,{value:snapshot,enumerable:!0,configurable:!1,writable:!1})}}for(let index=created.length-1;index>=0;index-=1)Object.freeze(created[index]);return root}function joinSource(source){return typeof source=="string"?source:source?.join("")??""}function isDenseArray(value){for(let index=0;index<value.length;index++)if(!Object.prototype.hasOwnProperty.call(value,index))return!1;return!0}function joinText(text){return typeof text=="string"?text:Array.isArray(text)&&isDenseArray(text)&&text.every(item=>typeof item=="string")?text.join(""):""}function*notebookSearchTextParts(text){if(typeof text=="string"){yield text;return}if(!(!Array.isArray(text)||!isDenseArray(text)))for(const part of text)typeof part=="string"&&(yield part)}const MARKUP_ENTITIES={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"};function visibleMarkupText(markup){const lower=markup.toLowerCase();let text="",index=0;for(;index<markup.length;){const open=markup.indexOf("<",index);if(open<0){text+=markup.slice(index);break}if(text+=markup.slice(index,open)+" ",lower.startsWith("<!--",open)){const end=markup.indexOf("-->",open+4);index=end<0?markup.length:end+3;continue}const close=markup.indexOf(">",open+1);if(close<0)break;const rawText=lower.startsWith("<script",open)?"<\/script":lower.startsWith("<style",open)?"</style":"";if(rawText){const end=lower.indexOf(rawText,close+1),endClose=end<0?-1:markup.indexOf(">",end);index=endClose<0?markup.length:endClose+1;continue}index=close+1}return text.replace(/&(lt|gt|quot|apos|amp);/g,(_entity,name)=>MARKUP_ENTITIES[name])}function*notebookOutputSearchParts(outputs){for(const output of outputs){yield*notebookSearchTextParts(output.text);const data=output.data;data&&Object.prototype.hasOwnProperty.call(data,"text/plain")&&(yield*notebookSearchTextParts(data["text/plain"]),yield" "),data&&!data["image/png"]&&!data["image/jpeg"]&&(data["image/svg+xml"]?yield visibleMarkupText(joinText(data["image/svg+xml"])):data["text/html"]?yield visibleMarkupText(joinText(data["text/html"])):data["application/json"]&&(yield*notebookSearchTextParts(data["application/json"]))),yield" "}}function isTextValue(value){return typeof value=="string"||Array.isArray(value)&&isDenseArray(value)&&value.every(item=>typeof item=="string")}function isJsonValue(value){const pending=[value];let nodes=0;for(;pending.length;){const current=pending.pop();if(++nodes>MAX_JSON_NODES)return!1;if(!(current===null||typeof current=="string"||typeof current=="boolean")){if(typeof current=="number"){if(!Number.isFinite(current))return!1;continue}if(Array.isArray(current)){if(current.length>MAX_JSON_NODES-nodes-pending.length)return!1;for(let index=current.length-1;index>=0;index--)pending.push(current[index]);continue}if(typeof current!="object")return!1;for(const key in current)if(Object.prototype.hasOwnProperty.call(current,key)){if(pending.length>=MAX_JSON_NODES-nodes)return!1;pending.push(current[key])}}}return!0}function isNotebookOutput(value){if(typeof value!="object"||value===null)return!1;const output=value;if(!["stream","error","display_data","execute_result"].includes(String(output.output_type))||output.text!==void 0&&!isTextValue(output.text)||output.traceback!==void 0&&!isTextValue(output.traceback)||output.ename!==void 0&&typeof output.ename!="string"||output.evalue!==void 0&&typeof output.evalue!="string"||output.name!==void 0&&output.name!=="stdout"&&output.name!=="stderr")return!1;const data=output.data;if(data===void 0)return!0;if(typeof data!="object"||data===null||Array.isArray(data))return!1;const mimeData=data;for(const[mime,payload]of Object.entries(mimeData))if(mime==="application/json"){if(typeof payload=="string")try{if(!isJsonValue(JSON.parse(payload)))return!1}catch{return!1}else if(!isJsonValue(payload))return!1}else if(!isTextValue(payload)&&!isJsonValue(payload))return!1;return!0}function isNotebookShape(value){if(typeof value!="object"||value===null)return!1;const v=value;if(!Number.isInteger(v.nbformat)||!Number.isInteger(v.nbformat_minor)||!Array.isArray(v.cells))return!1;const cells=v.cells;let outputCount=0;for(let index=0;index<cells.length;index++){if(!Object.prototype.hasOwnProperty.call(cells,index))return!1;const value2=cells[index];if(typeof value2!="object"||value2===null)return!1;const cell=value2;if(!["markdown","code","raw"].includes(String(cell.cell_type))||!isTextValue(cell.source)||cell.id!==void 0&&typeof cell.id!="string"||cell.execution_count!==void 0&&cell.execution_count!==null&&(!Number.isInteger(cell.execution_count)||cell.execution_count<0))return!1;if(cell.outputs!==void 0&&(!Array.isArray(cell.outputs)||!isDenseArray(cell.outputs)||(outputCount+=cell.outputs.length,outputCount>MAX_OUTPUTS||!cell.outputs.every(isNotebookOutput))))return!1}return!0}class LyraNotebookViewerBase extends LyraElement{}class LyraNotebookViewer extends DocumentAnchorTarget(LyraNotebookViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.outputCollapseLines=40,this.maxHeight="",this.anchorKinds=["node-path","fragment"],this.loadState={kind:"idle"},this.expandedOutputs=new Set,this.activeCellIndex=null,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1,this.cellKey=(item,index)=>item.id??index,this.highlightedCells=new Map,this.generation=0,this.lastSearchLocale="",this.sanitizerGeneration=0,this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedNotebook()),this.sanitizedOutputCache=new Map,this.sanitizationTasks=new Map,this.renderCell=(cell,index)=>{const c=cell,numberFormat=getNumberFormat(this.effectiveLocale),inCount=c.execution_count==null?this.localize("notebookViewerInPromptEmpty"):this.localize("notebookViewerInPrompt",void 0,{count:numberFormat.format(c.execution_count)}),rowLabel=c.cell_type==="code"?this.localize("notebookViewerCodeCell",void 0,{index:numberFormat.format(index+1)}):c.cell_type==="markdown"?this.localize("notebookViewerMarkdownCell",void 0,{index:numberFormat.format(index+1)}):this.localize("notebookViewerRawCell",void 0,{index:numberFormat.format(index+1)}),active=this.activeCellIndex===index,highlight=this.highlightedCells.get(index),highlighted=highlight!==void 0,parts=["cell"];return active&&parts.push("cell-active"),highlighted&&(parts.push("cell-highlighted",`cell-highlighted-${highlight.tone??"accent"}`),highlight.id===this.activeHighlightId&&parts.push("cell-highlight-active")),html`<div part=${parts.join(" ")} role="group" aria-label=${rowLabel} data-cell-type=${c.cell_type} ?data-active=${active} ?data-highlighted=${highlighted}>
|
|
2
2
|
<div part="cell-gutter">${c.cell_type==="code"?inCount:""}</div>
|
|
3
3
|
<div part="cell-source">
|
|
4
4
|
${c.cell_type==="markdown"?html`<lr-markdown
|
|
@@ -71,4 +71,4 @@ get highlights():readonly LyraHighlight[];set highlights(value:readonly LyraHigh
|
|
|
71
71
|
* attribute value parses to a number; an unresolvable value falls back to the default. */
|
|
72
72
|
thumbWidth:number|string;
|
|
73
73
|
/** Overrides the computed accessible name. */
|
|
74
|
-
label:string;private resolvedPageCount;private thumbnailStates;private allocationWidth;private readonly thumbnailRefs;private readonly thumbnailTargets;private readonly thumbnailHandles;private boundViewer;private digitBuffer;private readonly digitBufferReset;private thumbnailGeneration;private resizeObserver?;private targetObserver?;private readonly ownerFrames;private pendingFocusPage;private focusRepairPending;private focusRepairGeneration;private pageSourceCount;private pageSource;private viewerSnapshotIdentity?;private viewerSnapshotStatus?;private readonly onViewerLoad;private readonly onViewerPageChange;private readonly onViewerStateChange;protected willUpdate(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resolveViewer;private observeForTarget;private unbindViewer;private applyViewerSnapshot;private lookupFor;private get safePageCount();private get safePage();private get safeThumbWidth();private effectivePageCount;private createPageSource;private indexedPages;private thumbnailRef;protected updated(changed:PropertyValues):void;private renderedPageButton;private isCurrentFocusRepair;private focusRepairIndex;private finishFocusRepair;private focusVirtualPage;private invalidateThumbnails;private disposeThumbnailHandle;private disposeThumbnailHandles;private loadThumbnail;private onPageActivate;private cancelDigitTimer;private resetDigitBuffer;private onKeyDown;private renderPageItem;private stopVirtualListEvent;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-page-rail':LyraPageRail;}}
|
|
74
|
+
label:string;private resolvedPageCount;private thumbnailStates;private allocationWidth;private readonly thumbnailRowRefs;private readonly thumbnailRefs;private readonly thumbnailTargets;private readonly thumbnailHandles;private boundViewer;private digitBuffer;private readonly digitBufferReset;private thumbnailGeneration;private resizeObserver?;private targetObserver?;private readonly ownerFrames;private pendingFocusPage;private focusRepairPending;private focusRepairGeneration;private pageSourceCount;private pageSource;private viewerSnapshotIdentity?;private viewerSnapshotStatus?;private readonly onViewerLoad;private readonly onViewerPageChange;private readonly onViewerStateChange;protected willUpdate(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resolveViewer;private observeForTarget;private unbindViewer;private applyViewerSnapshot;private lookupFor;private get safePageCount();private get safePage();private get safeThumbWidth();private effectivePageCount;private createPageSource;private indexedPages;private thumbnailRowRef;private thumbnailRef;protected updated(changed:PropertyValues):void;private renderedPageButton;private isCurrentFocusRepair;private focusRepairIndex;private finishFocusRepair;private focusVirtualPage;private invalidateThumbnails;private disposeThumbnailHandle;private disposeThumbnailHandles;private loadThumbnail;private onPageActivate;private cancelDigitTimer;private resetDigitBuffer;private onKeyDown;private renderPageItem;private stopVirtualListEvent;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-page-rail':LyraPageRail;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{ref}from"lit/directives/ref.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{OwnerAnimationFrameWaiter}from"../../../internal/owner-animation-frame.js";import{tag}from"../../../internal/prefix.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./page-rail.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_pageRailLabel,LYRA_DEFAULT_pageRailPage,LYRA_DEFAULT_pageRailPageHighlighted}from"../../../internal/default-strings.generated.js";import{PageViewerSnapshotController}from"./page-viewer-snapshot.js";const DIGIT_BUFFER_MS=500,MAX_PAGE_COUNT=1e5,DEFAULT_ALLOCATION_WIDTH=320,DEFAULT_THUMB_WIDTH=96,THUMB_WIDTH_CONVERTER={fromAttribute:value=>{if(value===null)return value;const number=Number(value);return Number.isNaN(number)?value:number}};class LyraPageRail extends LyraElement{constructor(){super(...arguments),this.viewer=null,this.for="",this.pageCount=0,this.page=1,this._highlights=snapshotLyraHighlights([]),this.pageTones=new Map,this.thumbWidth=96,this.label="",this.resolvedPageCount=0,this.thumbnailStates=new Map,this.allocationWidth=DEFAULT_ALLOCATION_WIDTH,this.thumbnailRefs=new Map,this.thumbnailTargets=new Map,this.thumbnailHandles=new Map,this.boundViewer=null,this.digitBuffer="",this.digitBufferReset=new DebounceController(DIGIT_BUFFER_MS,()=>{this.digitBuffer=""},()=>this.ownerDocument.defaultView),this.thumbnailGeneration=0,this.ownerFrames=new OwnerAnimationFrameWaiter(this),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration=0,this.pageSourceCount=-1,this.pageSource=this.createPageSource(0),this.onViewerLoad=e=>{this.resolvedPageCount=finiteCount(e.detail?.pageCount??0,0,MAX_PAGE_COUNT),this.invalidateThumbnails()},this.onViewerPageChange=e=>{this.page=e.detail.page},this.onViewerStateChange=event=>{const viewer=this.boundViewer;if(!viewer)return;const eventSnapshot=event.detail?.snapshot;this.applyViewerSnapshot(viewer.pageViewerSnapshot??eventSnapshot)},this.onKeyDown=e=>{const format=getNumberFormat(this.effectiveLocale),digit=/^[0-9]$/.test(e.key)?Number(e.key):Array.from({length:10},(_unused,value)=>format.format(value)).indexOf(e.key);if(e.altKey||e.ctrlKey||e.metaKey||digit<0)return;this.digitBuffer+=digit;const target=Number(this.digitBuffer);this.cancelDigitTimer(),this.ownerDocument.defaultView?this.digitBufferReset.push(void 0):this.digitBuffer="";const count=this.effectivePageCount();target>=1&&target<=count&&(this.boundViewer?this.onPageActivate(target):this.page=target)},this.renderPageItem=pageNumber=>{const number=pageNumber,numberFormat=getNumberFormat(this.effectiveLocale),tones=this.pageTones.get(number)??[],count=tones.length,thumbState=this.thumbnailStates.get(number),name=count===0?this.localize("pageRailPage",void 0,{page:numberFormat.format(number)}):this.localize("pageRailPageHighlighted",void 0,{page:numberFormat.format(number),count:numberFormat.format(count),pluralCount:count}),shownTones=tones.slice(0,3),overflow=tones.length-shownTones.length,isCurrent=this.safePage===number;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{ref}from"lit/directives/ref.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{OwnerAnimationFrameWaiter}from"../../../internal/owner-animation-frame.js";import{tag}from"../../../internal/prefix.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./page-rail.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_pageRailLabel,LYRA_DEFAULT_pageRailPage,LYRA_DEFAULT_pageRailPageHighlighted}from"../../../internal/default-strings/viewers.generated.js";import{PageViewerSnapshotController}from"./page-viewer-snapshot.js";const DIGIT_BUFFER_MS=500,MAX_PAGE_COUNT=1e5,DEFAULT_ALLOCATION_WIDTH=320,DEFAULT_THUMB_WIDTH=96,THUMB_WIDTH_CONVERTER={fromAttribute:value=>{if(value===null)return value;const number=Number(value);return Number.isNaN(number)?value:number}};class LyraPageRail extends LyraElement{constructor(){super(...arguments),this.viewer=null,this.for="",this.pageCount=0,this.page=1,this._highlights=snapshotLyraHighlights([]),this.pageTones=new Map,this.thumbWidth=96,this.label="",this.resolvedPageCount=0,this.thumbnailStates=new Map,this.allocationWidth=DEFAULT_ALLOCATION_WIDTH,this.thumbnailRowRefs=new Map,this.thumbnailRefs=new Map,this.thumbnailTargets=new Map,this.thumbnailHandles=new Map,this.boundViewer=null,this.digitBuffer="",this.digitBufferReset=new DebounceController(DIGIT_BUFFER_MS,()=>{this.digitBuffer=""},()=>this.ownerDocument.defaultView),this.thumbnailGeneration=0,this.ownerFrames=new OwnerAnimationFrameWaiter(this),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration=0,this.pageSourceCount=-1,this.pageSource=this.createPageSource(0),this.onViewerLoad=e=>{this.resolvedPageCount=finiteCount(e.detail?.pageCount??0,0,MAX_PAGE_COUNT),this.invalidateThumbnails()},this.onViewerPageChange=e=>{this.page=e.detail.page},this.onViewerStateChange=event=>{const viewer=this.boundViewer;if(!viewer)return;const eventSnapshot=event.detail?.snapshot;this.applyViewerSnapshot(viewer.pageViewerSnapshot??eventSnapshot)},this.onKeyDown=e=>{const format=getNumberFormat(this.effectiveLocale),digit=/^[0-9]$/.test(e.key)?Number(e.key):Array.from({length:10},(_unused,value)=>format.format(value)).indexOf(e.key);if(e.altKey||e.ctrlKey||e.metaKey||digit<0)return;this.digitBuffer+=digit;const target=Number(this.digitBuffer);this.cancelDigitTimer(),this.ownerDocument.defaultView?this.digitBufferReset.push(void 0):this.digitBuffer="";const count=this.effectivePageCount();target>=1&&target<=count&&(this.boundViewer?this.onPageActivate(target):this.page=target)},this.renderPageItem=pageNumber=>{const number=pageNumber,numberFormat=getNumberFormat(this.effectiveLocale),tones=this.pageTones.get(number)??[],count=tones.length,thumbState=this.thumbnailStates.get(number),name=count===0?this.localize("pageRailPage",void 0,{page:numberFormat.format(number)}):this.localize("pageRailPageHighlighted",void 0,{page:numberFormat.format(number),count:numberFormat.format(count),pluralCount:count}),shownTones=tones.slice(0,3),overflow=tones.length-shownTones.length,isCurrent=this.safePage===number;return html`
|
|
2
2
|
<button
|
|
3
3
|
part=${isCurrent?"page page-current":"page"}
|
|
4
4
|
type="button"
|
|
@@ -6,7 +6,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
6
6
|
aria-current=${isCurrent?"true":"false"}
|
|
7
7
|
@click=${()=>this.onPageActivate(number)}
|
|
8
8
|
>
|
|
9
|
-
<span part="thumbnail">
|
|
9
|
+
<span part="thumbnail" ${ref(this.thumbnailRowRef(number))}>
|
|
10
10
|
${this.boundViewer?thumbState==="unavailable"?html`<lr-file-icon decorative></lr-file-icon>`:html`${keyed(this.thumbnailGeneration,this.boundViewer.renderPageThumbnailToContainer?html`<div part="thumbnail-target" aria-hidden="true" ${ref(this.thumbnailRef(number))}></div>`:html`<canvas part="thumbnail-target" aria-hidden="true" ${ref(this.thumbnailRef(number))}></canvas>`)}${thumbState!=="ready"?html`<lr-skeleton shape="rect" .announce=${!1} aria-hidden="true"></lr-skeleton>`:nothing}`:html`<lr-file-icon decorative></lr-file-icon>`}
|
|
11
11
|
</span>
|
|
12
12
|
<span part="page-number" aria-hidden="true">${numberFormat.format(number)}</span>
|
|
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
15
15
|
${overflow>0?html`<span part="heat-dot heat-dot-overflow" data-overflow="true">+${numberFormat.format(overflow)}</span>`:nothing}
|
|
16
16
|
</span>`:nothing}
|
|
17
17
|
</button>
|
|
18
|
-
`}}static{this.defaultStrings={...super.defaultStrings,pageRailLabel:LYRA_DEFAULT_pageRailLabel,pageRailPage:LYRA_DEFAULT_pageRailPage,pageRailPageHighlighted:LYRA_DEFAULT_pageRailPageHighlighted}}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){if(value===this._highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlightsSource=value,this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("thumbWidth")&&changed.get("thumbWidth")!==void 0&&this.invalidateThumbnails(),changed.has("highlights")){this.pageTones=new Map;for(const{anchor,tone="accent"}of this.highlights){if(!("page"in anchor)||anchor.page===void 0)continue;const tones=this.pageTones.get(anchor.page)??[];tones.push(tone),this.pageTones.set(anchor.page,tones)}}if(changed.has("pageCount")||changed.has("resolvedPageCount")){const list=this.shadowRoot?.querySelector(tag("virtual-list")),focusedRowIndex=(list?shadowFocusTarget(list):null)?.closest("[data-row-index]")?.getAttribute("data-row-index"),focusedIndex=focusedRowIndex==null?-1:finiteInteger(Number(focusedRowIndex),-1,-1),nextCount=this.effectivePageCount();nextCount<=0?this.focusRepairPending&&(this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++):(focusedIndex>=nextCount||this.focusRepairPending)&&(this.pendingFocusPage=nextCount,this.focusRepairPending=!0,this.focusRepairGeneration++)}(!this.hasUpdated||changed.has("viewer")||changed.has("for"))&&(this.resolveViewer(),this.observeForTarget())}connectedCallback(){super.connectedCallback();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;ResizeObserverCtor&&(this.resizeObserver=new ResizeObserverCtor(entries=>{const width=finiteRange(entries.at(-1)?.contentRect.width??DEFAULT_ALLOCATION_WIDTH,DEFAULT_ALLOCATION_WIDTH,0);width!==this.allocationWidth&&(this.allocationWidth=width,this.invalidateThumbnails())}),this.resizeObserver.observe(this)),this.observeForTarget(),this.hasUpdated&&this.resolveViewer()}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.targetObserver?.disconnect(),this.targetObserver=void 0,this.unbindViewer(),this.thumbnailGeneration++,this.disposeThumbnailHandles(),this.ownerFrames.cancel(),this.resetDigitBuffer(),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.targetObserver?.disconnect(),this.targetObserver=void 0,this.ownerFrames.cancel(),this.resetDigitBuffer(),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++,this.unbindViewer(),this.resolvedPageCount=0,this.invalidateThumbnails()}resolveViewer(){const next=this.viewer??this.lookupFor();next!==this.boundViewer&&(this.unbindViewer(),this.resolvedPageCount=0,this.invalidateThumbnails(),this.boundViewer=next,next&&(next.pageViewerSnapshot?(next.addEventListener("lr-page-viewer-state-change",this.onViewerStateChange),this.applyViewerSnapshot(next.pageViewerSnapshot)):(this.page=next.page||this.page,next.addEventListener("lr-load",this.onViewerLoad),next.addEventListener("lr-page-change",this.onViewerPageChange))))}observeForTarget(){this.targetObserver?.disconnect(),this.targetObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;!this.isConnected||!this.for||!MutationObserverCtor||(this.targetObserver=new MutationObserverCtor(()=>this.resolveViewer()),this.targetObserver.observe(this.getRootNode(),{attributes:!0,attributeFilter:["id"],childList:!0,subtree:!0}))}unbindViewer(){this.boundViewer?.removeEventListener("lr-load",this.onViewerLoad),this.boundViewer?.removeEventListener("lr-page-change",this.onViewerPageChange),this.boundViewer?.removeEventListener("lr-page-viewer-state-change",this.onViewerStateChange),this.boundViewer=null,this.viewerSnapshotIdentity=void 0,this.viewerSnapshotStatus=void 0}applyViewerSnapshot(snapshot){if(!snapshot)return;const nextCount=snapshot.status==="ready"?finiteCount(snapshot.pageCount,0,MAX_PAGE_COUNT):0,nextPage=finiteInteger(snapshot.page,1,1,Math.max(1,nextCount)),previousCount=this.resolvedPageCount,documentChanged=this.viewerSnapshotIdentity!==snapshot.identity,statusChanged=this.viewerSnapshotStatus!==snapshot.status;this.viewerSnapshotIdentity=snapshot.identity,this.viewerSnapshotStatus=snapshot.status,this.resolvedPageCount=nextCount,this.page=nextPage,(documentChanged||statusChanged||previousCount!==nextCount)&&this.invalidateThumbnails()}lookupFor(){return this.for?this.getRootNode().getElementById?.(this.for)??null:null}get safePageCount(){return finiteCount(this.pageCount,0,MAX_PAGE_COUNT)}get safePage(){const count=this.effectivePageCount();return finiteInteger(this.page,1,1,Math.max(1,count))}get safeThumbWidth(){const allocation=finiteRange(this.allocationWidth,DEFAULT_ALLOCATION_WIDTH,0),thumbWidth=resolveCssLength(this.thumbWidth,{host:this,percentBase:allocation});return Math.min(finiteRange(thumbWidth??Number.NaN,DEFAULT_THUMB_WIDTH,0),allocation)}effectivePageCount(){return this.boundViewer?this.resolvedPageCount:this.safePageCount}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pageSourceCount&&(this.pageSourceCount=count,this.pageSource=this.createPageSource(count)),this.pageSource}
|
|
18
|
+
`}}static{this.defaultStrings={...super.defaultStrings,pageRailLabel:LYRA_DEFAULT_pageRailLabel,pageRailPage:LYRA_DEFAULT_pageRailPage,pageRailPageHighlighted:LYRA_DEFAULT_pageRailPageHighlighted}}static{this.styles=[LyraElement.styles,styles]}get highlights(){return this._highlights}set highlights(value){if(value===this._highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlightsSource=value,this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("thumbWidth")&&changed.get("thumbWidth")!==void 0&&this.invalidateThumbnails(),changed.has("highlights")){this.pageTones=new Map;for(const{anchor,tone="accent"}of this.highlights){if(!("page"in anchor)||anchor.page===void 0)continue;const tones=this.pageTones.get(anchor.page)??[];tones.push(tone),this.pageTones.set(anchor.page,tones)}}if(changed.has("pageCount")||changed.has("resolvedPageCount")){const list=this.shadowRoot?.querySelector(tag("virtual-list")),focusedRowIndex=(list?shadowFocusTarget(list):null)?.closest("[data-row-index]")?.getAttribute("data-row-index"),focusedIndex=focusedRowIndex==null?-1:finiteInteger(Number(focusedRowIndex),-1,-1),nextCount=this.effectivePageCount();nextCount<=0?this.focusRepairPending&&(this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++):(focusedIndex>=nextCount||this.focusRepairPending)&&(this.pendingFocusPage=nextCount,this.focusRepairPending=!0,this.focusRepairGeneration++)}(!this.hasUpdated||changed.has("viewer")||changed.has("for"))&&(this.resolveViewer(),this.observeForTarget())}connectedCallback(){super.connectedCallback();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;ResizeObserverCtor&&(this.resizeObserver=new ResizeObserverCtor(entries=>{const width=finiteRange(entries.at(-1)?.contentRect.width??DEFAULT_ALLOCATION_WIDTH,DEFAULT_ALLOCATION_WIDTH,0);width!==this.allocationWidth&&(this.allocationWidth=width,this.invalidateThumbnails())}),this.resizeObserver.observe(this)),this.observeForTarget(),this.hasUpdated&&this.resolveViewer()}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.targetObserver?.disconnect(),this.targetObserver=void 0,this.unbindViewer(),this.thumbnailGeneration++,this.disposeThumbnailHandles(),this.ownerFrames.cancel(),this.resetDigitBuffer(),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.targetObserver?.disconnect(),this.targetObserver=void 0,this.ownerFrames.cancel(),this.resetDigitBuffer(),this.pendingFocusPage=null,this.focusRepairPending=!1,this.focusRepairGeneration++,this.unbindViewer(),this.resolvedPageCount=0,this.invalidateThumbnails()}resolveViewer(){const next=this.viewer??this.lookupFor();next!==this.boundViewer&&(this.unbindViewer(),this.resolvedPageCount=0,this.invalidateThumbnails(),this.boundViewer=next,next&&(next.pageViewerSnapshot?(next.addEventListener("lr-page-viewer-state-change",this.onViewerStateChange),this.applyViewerSnapshot(next.pageViewerSnapshot)):(this.page=next.page||this.page,next.addEventListener("lr-load",this.onViewerLoad),next.addEventListener("lr-page-change",this.onViewerPageChange))))}observeForTarget(){this.targetObserver?.disconnect(),this.targetObserver=void 0;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;!this.isConnected||!this.for||!MutationObserverCtor||(this.targetObserver=new MutationObserverCtor(()=>this.resolveViewer()),this.targetObserver.observe(this.getRootNode(),{attributes:!0,attributeFilter:["id"],childList:!0,subtree:!0}))}unbindViewer(){this.boundViewer?.removeEventListener("lr-load",this.onViewerLoad),this.boundViewer?.removeEventListener("lr-page-change",this.onViewerPageChange),this.boundViewer?.removeEventListener("lr-page-viewer-state-change",this.onViewerStateChange),this.boundViewer=null,this.viewerSnapshotIdentity=void 0,this.viewerSnapshotStatus=void 0}applyViewerSnapshot(snapshot){if(!snapshot)return;const nextCount=snapshot.status==="ready"?finiteCount(snapshot.pageCount,0,MAX_PAGE_COUNT):0,nextPage=finiteInteger(snapshot.page,1,1,Math.max(1,nextCount)),previousCount=this.resolvedPageCount,documentChanged=this.viewerSnapshotIdentity!==snapshot.identity,statusChanged=this.viewerSnapshotStatus!==snapshot.status;this.viewerSnapshotIdentity=snapshot.identity,this.viewerSnapshotStatus=snapshot.status,this.resolvedPageCount=nextCount,this.page=nextPage,(documentChanged||statusChanged||previousCount!==nextCount)&&this.invalidateThumbnails()}lookupFor(){return this.for?this.getRootNode().getElementById?.(this.for)??null:null}get safePageCount(){return finiteCount(this.pageCount,0,MAX_PAGE_COUNT)}get safePage(){const count=this.effectivePageCount();return finiteInteger(this.page,1,1,Math.max(1,count))}get safeThumbWidth(){const allocation=finiteRange(this.allocationWidth,DEFAULT_ALLOCATION_WIDTH,0),thumbWidth=resolveCssLength(this.thumbWidth,{host:this,percentBase:allocation});return Math.min(finiteRange(thumbWidth??Number.NaN,DEFAULT_THUMB_WIDTH,0),allocation)}effectivePageCount(){return this.boundViewer?this.resolvedPageCount:this.safePageCount}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pageSourceCount&&(this.pageSourceCount=count,this.pageSource=this.createPageSource(count)),this.pageSource}thumbnailRowRef(pageNumber){let callback=this.thumbnailRowRefs.get(pageNumber);return callback||(callback=element=>{if(element){this.thumbnailRowRefs.set(pageNumber,callback);return}this.thumbnailRowRefs.get(pageNumber)===callback&&(this.thumbnailRowRefs.delete(pageNumber),this.thumbnailRefs.delete(pageNumber),this.thumbnailStates.delete(pageNumber))},this.thumbnailRowRefs.set(pageNumber,callback)),callback}thumbnailRef(pageNumber){let cb=this.thumbnailRefs.get(pageNumber);if(!cb){let mounted;cb=el=>{if(!el){this.thumbnailTargets.get(pageNumber)===mounted&&(this.thumbnailTargets.delete(pageNumber),this.disposeThumbnailHandle(pageNumber)),mounted=void 0;return}mounted=el,this.thumbnailRefs.set(pageNumber,cb),this.thumbnailTargets.set(pageNumber,mounted),this.loadThumbnail(pageNumber,mounted)},this.thumbnailRefs.set(pageNumber,cb)}return cb}updated(changed){super.updated(changed),this.shadowRoot?.querySelector(tag("virtual-list"))?.requestUpdate();const pendingFocusPage=this.pendingFocusPage;this.pendingFocusPage=null,pendingFocusPage!==null&&this.focusVirtualPage(pendingFocusPage,this.focusRepairGeneration)}renderedPageButton(list,index){return list.renderedRows.find(candidate=>finiteInteger(Number(candidate.dataset.rowIndex),-1,-1)===index)?.querySelector('[part~="page"]')??null}isCurrentFocusRepair(list,generation){return this.isConnected&&generation===this.focusRepairGeneration&&this.shadowRoot?.querySelector(tag("virtual-list"))===list}focusRepairIndex(pageNumber){const count=this.effectivePageCount();return count<=0?null:finiteInteger(pageNumber,count,1,count)-1}finishFocusRepair(generation){generation===this.focusRepairGeneration&&(this.focusRepairPending=!1)}async focusVirtualPage(pageNumber,generation){const list=this.shadowRoot?.querySelector(tag("virtual-list"));if(!list){this.finishFocusRepair(generation);return}if(await list.updateComplete,!this.isCurrentFocusRepair(list,generation))return;let index=this.focusRepairIndex(pageNumber);if(index===null){this.finishFocusRepair(generation);return}let button=this.renderedPageButton(list,index);if(button){button.focus(),this.finishFocusRepair(generation);return}list.scrollToIndex(index,{align:"auto",behavior:"auto"});for(let attempt=0;attempt<4;attempt++){if(!await this.ownerFrames.wait()||(await list.updateComplete,!this.isCurrentFocusRepair(list,generation)))return;if(index=this.focusRepairIndex(pageNumber),index===null){this.finishFocusRepair(generation);return}if(button=this.renderedPageButton(list,index),button){button.focus(),this.finishFocusRepair(generation);return}}this.finishFocusRepair(generation)}invalidateThumbnails(){this.thumbnailGeneration++,this.disposeThumbnailHandles(),this.thumbnailStates=new Map,this.pageSourceCount=-1}disposeThumbnailHandle(pageNumber){this.thumbnailHandles.get(pageNumber)?.dispose(),this.thumbnailHandles.delete(pageNumber)}disposeThumbnailHandles(){for(const handle of this.thumbnailHandles.values())handle.dispose();this.thumbnailHandles.clear()}async loadThumbnail(pageNumber,target){const viewer=this.boundViewer;if(!viewer)return;const generation=this.thumbnailGeneration,width=this.safeThumbWidth;this.disposeThumbnailHandle(pageNumber),this.thumbnailStates.set(pageNumber,"pending"),this.requestUpdate();let ok,handle;try{if(viewer.renderPageThumbnailToContainer&&target.localName!=="canvas"){const result=await viewer.renderPageThumbnailToContainer(pageNumber,target,{width});ok=result!==!1,handle=result===!1?void 0:result}else viewer.renderPageThumbnail&&target.localName==="canvas"?ok=await viewer.renderPageThumbnail(pageNumber,target,{width}):ok=!1}catch{ok=!1}if(generation!==this.thumbnailGeneration||viewer!==this.boundViewer||width!==this.safeThumbWidth||this.thumbnailTargets.get(pageNumber)!==target){handle?.dispose();return}handle&&this.thumbnailHandles.set(pageNumber,handle),this.thumbnailStates.set(pageNumber,ok?"ready":"unavailable"),this.requestUpdate()}onPageActivate(pageNumber){this.boundViewer&&(this.boundViewer.page=pageNumber),this.emit("lr-page-select",{page:pageNumber})}cancelDigitTimer(){this.digitBufferReset.cancel()}resetDigitBuffer(){this.cancelDigitTimer(),this.digitBuffer=""}stopVirtualListEvent(event){event.stopPropagation()}render(){const count=this.effectivePageCount();return html`
|
|
19
19
|
<div
|
|
20
20
|
part="base"
|
|
21
21
|
role=${viewerSemanticRole(this,"navigation")??nothing}
|
|
@@ -130,7 +130,7 @@ workerSrc:string;
|
|
|
130
130
|
/** Anchor kinds this viewer resolves. `page` and page-addressed `region` anchors require an
|
|
131
131
|
* integer within the loaded document's range; unlike the public `page` property, anchors are
|
|
132
132
|
* rejected rather than clamped. */
|
|
133
|
-
readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private loadLibrary;private generation;private readonly pageCanvases;private readonly pageRenderTasks;private readonly pageRenderVersions;private pageRenderGeneration;private readonly pageCanvasRefs;private readonly textLayerContainers;private readonly textLayerContainerRefs;private readonly textLayers;private readonly textLayerReadyPromises;private readonly pageTextCache;private readonly pageTextTruncated;private readonly pageSearchIndexes;private readonly mountedPageTextIndexes;private pdfTextScopeBuilds;private readonly thumbnailRenderTasks;private readonly thumbnailRenderVersions;private thumbnailRenderGeneration;private readonly pageHighlightItems;private readonly pageHighlightLayerElements;private readonly highlightLayerRefs;private textSelectionCleanup?;private readonly pendingPageMountWaitCancels;private pdfPageSourceCount;private pdfPageSource;private readonly searchState;private get searchMatches();private set searchMatches(value);private get searchActiveIndex();private set searchActiveIndex(value);private searchGeneration;private textIndexLocale?;private pendingSearchResetEvent;private anchorOperationGeneration;private readonly announcements;
|
|
133
|
+
readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private loadLibrary;private generation;private pendingDocument?;private readonly pageCanvases;private readonly pageRenderTasks;private readonly pageRenderVersions;private pageRenderGeneration;private readonly pageCanvasRefs;private readonly textLayerContainers;private readonly textLayerContainerRefs;private readonly textLayers;private readonly textLayerReadyPromises;private readonly pageTextCache;private readonly pageTextTruncated;private readonly pageSearchIndexes;private readonly mountedPageTextIndexes;private pdfTextScopeBuilds;private readonly thumbnailRenderTasks;private readonly thumbnailRenderVersions;private thumbnailRenderGeneration;private readonly pageHighlightItems;private readonly pageHighlightLayerElements;private readonly highlightLayerRefs;private textSelectionCleanup?;private readonly pendingPageMountWaitCancels;private pdfPageSourceCount;private pdfPageSource;private readonly searchState;private get searchMatches();private set searchMatches(value);private get searchActiveIndex();private set searchActiveIndex(value);private searchGeneration;private textIndexLocale?;private pendingSearchResetEvent;private anchorOperationGeneration;private readonly announcements;
|
|
134
134
|
/**
|
|
135
135
|
* Atomic readonly state for page-rail and other page-addressed integrations. Unlike the legacy
|
|
136
136
|
* `lr-load`/`lr-page-change` pair, a late subscriber can read this immediately, and `identity`
|
|
@@ -142,7 +142,7 @@ get pageViewerSnapshot():LyraPageViewerSnapshot;
|
|
|
142
142
|
* every consumer runs) the moment anything assigns to it, including a stray
|
|
143
143
|
* `.pageViewerSnapshot=${x}` template binding; this no-op keeps that assignment harmless
|
|
144
144
|
* instead of throwing from inside framework internals. */
|
|
145
|
-
set pageViewerSnapshot(_value:LyraPageViewerSnapshot);private focusedToolbarPart;private keepToolbarFocus;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;firstUpdated(changed:PropertyValues):void;private readonly detached;connectedCallback():void;disconnectedCallback():void;private teardownDetachedDocument;adoptedCallback():void;private cancelPendingPageMountWaits;private destroyLoadedDoc;private clampPage;private publishPageViewerSnapshot;private createPageSource;private indexedPages;private load;nextPage():void;previousPage():void;zoomIn():void;zoomOut():void;
|
|
145
|
+
set pageViewerSnapshot(_value:LyraPageViewerSnapshot);private focusedToolbarPart;private keepToolbarFocus;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;firstUpdated(changed:PropertyValues):void;private readonly detached;connectedCallback():void;disconnectedCallback():void;private teardownDetachedDocument;adoptedCallback():void;private cancelPendingPageMountWaits;private destroyLoadedDoc;private retirePendingDocument;private clampPage;private publishPageViewerSnapshot;private createPageSource;private indexedPages;private load;nextPage():void;previousPage():void;zoomIn():void;zoomOut():void;
|
|
146
146
|
/** Sets `page` and resolves once the target page's canvas has actually mounted inside the
|
|
147
147
|
* virtualized list (bounded by a timeout, so a page that somehow never mounts can't hang this
|
|
148
148
|
* promise forever). Resolves `false` without changing `page` for an out-of-range value. */
|