@aceshooting/lyra-ui 30.9.0 → 31.1.1
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 +361 -335
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +2 -2
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.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.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +15 -6
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.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/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 +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- 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/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- 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/table-viewer-shared.js +4 -4
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +26 -9
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +51 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-map.md +33 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-message-feedback.md +38 -3
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +6 -3
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +4 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +46 -4
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +266 -117
- package/locales.json +1 -1
- package/package.json +22 -21
- package/registrations.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{eventCollectionSupport}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{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{eventCollectionSupport}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{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/file-size.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_emailViewerUnnamedAttachment,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_EMAIL_RECIPIENT_POSITIONS=1e4,MAX_EMAIL_RECIPIENT_DEPTH=100,MAX_EMAIL_ATTACHMENT_POSITIONS=1e4;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isSafeRecord(value){if(value===null||typeof value!="object"||isArrayValue(value))return!1;try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function optionalOwnString(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="string"?descriptor.value:void 0}function optionalOwnValue(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectAddressList(value,budget,depth){if(!isArrayValue(value)||budget.positions>=MAX_EMAIL_RECIPIENT_POSITIONS)return[];const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return[];const addresses=[],count=Math.min(length.value,MAX_EMAIL_RECIPIENT_POSITIONS-budget.positions);for(let index=0;index<count;index+=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const address=projectAddress(descriptor.value,budget,depth);address&&addresses.push(address)}return addresses}function projectAddress(value,budget,depth){if(depth>MAX_EMAIL_RECIPIENT_DEPTH||budget.nodes>=MAX_EMAIL_RECIPIENT_POSITIONS||!isSafeRecord(value)||budget.seen.has(value))return;budget.seen.add(value),budget.nodes+=1;const name=optionalOwnString(value,"name"),address=optionalOwnString(value,"address"),groupValue=optionalOwnValue(value,"group"),group=groupValue===void 0?[]:projectAddressList(groupValue,budget,depth+1);if(!(name===void 0&&address===void 0&&group.length===0))return Object.freeze({...name===void 0?{}:{name},...address===void 0?{}:{address},...group.length===0?{}:{group:Object.freeze(group)}})}function normalizeAttachmentContent(content){try{if(typeof content=="string")return new TextEncoder().encode(content);if(content instanceof Uint8Array)return new Uint8Array(content);if(content instanceof ArrayBuffer)return new Uint8Array(content.slice(0))}catch{return}}function projectAttachments(value){if(!isArrayValue(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const attachments=[],count=Math.min(length.value,MAX_EMAIL_ATTACHMENT_POSITIONS);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||!isSafeRecord(entry.value))continue;const content=normalizeAttachmentContent(optionalOwnValue(entry.value,"content"));if(!content)continue;const filename=optionalOwnString(entry.value,"filename")??"",mimeType=optionalOwnString(entry.value,"mimeType")??"";attachments.push(Object.freeze({filename,mimeType,size:content.byteLength,content}))}return Object.freeze(attachments)}function normalizeParsedEmail(value){if(!isSafeRecord(value))return null;const budget={positions:0,nodes:0,seen:new WeakSet},htmlValue=optionalOwnValue(value,"html"),textValue=optionalOwnValue(value,"text"),subjectValue=optionalOwnValue(value,"subject"),dateValue=optionalOwnValue(value,"date"),html2=typeof htmlValue=="string"?htmlValue:void 0,text=typeof textValue=="string"?textValue:void 0,subject=typeof subjectValue=="string"?subjectValue:void 0,date=typeof dateValue=="string"?dateValue:void 0,from=projectAddress(optionalOwnValue(value,"from"),budget,0),to=projectAddressList(optionalOwnValue(value,"to"),budget,0);return Object.freeze({...html2===void 0?{}:{html:html2},...text===void 0?{}:{text},...from===void 0?{}:{from},to:Object.freeze(to),...subject===void 0?{}:{subject},...date===void 0?{}:{date},attachments:projectAttachments(optionalOwnValue(value,"attachments"))})}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
|
|
2
2
|
`),quoted:lines.slice(start).join(`
|
|
3
|
-
`)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);if(!doc)return html2;for(const forged of doc.body.querySelectorAll("[data-quote-toggle], [data-quote-index], [data-email-chrome]"))forged.removeAttribute("data-quote-toggle"),forged.removeAttribute("data-quote-index"),forged.removeAttribute("data-email-chrome");const blocks=doc.body.querySelectorAll(QUOTE_SELECTOR),expandedQuotes=new Set(expandedIndices);return blocks.forEach((block,index)=>{const expanded=expandedQuotes.has(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("data-email-chrome","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&candidate.localName==="button"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.detached=new DeferredTeardown(()=>{this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null}),this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=shadowFocusTarget(this)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,emailViewerUnnamedAttachment:LYRA_DEFAULT_emailViewerUnnamedAttachment,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()&&query.length<=TEXT_QUOTE_LIMITS.maxQueryCodeUnits){const budget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},matchesQuote=block=>createTextQuoteIndex(scopeFromElement(block),this.effectiveLocale).search(query,budget).length>0,{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){this.searchDocument?.html!==bodyHtml&&(this.searchDocument={html:bodyHtml,doc:parseHtmlDocument(bodyHtml,this.ownerDocument)});const next=new Set(this.expandedHtmlQuoteIndices);this.searchDocument.doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{!next.has(index)&&matchesQuote(block)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText),quote=this.ownerDocument.createElement("pre");quote.textContent=split?.quoted??"",split&&!this.textQuoteExpanded&&matchesQuote(quote)&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector('[part="body"]')}buildTextScope(root){return scopeFromElement(root,void 0,element=>this.foldQuotes&&element.localName==="button"&&element.getAttribute("data-email-chrome")==="quote-toggle")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}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()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isCurrentLoad(generation,fetchTarget.view))return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isCurrentLoad(generation,fetchTarget.view))return;const result=await this.parse(buffer,generation,fetchTarget.view);result&&this.isCurrentLoad(generation,fetchTarget.view)&&(this.fetchState={kind:"loaded",...result})}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}async parse(buffer,generation,ownerView){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isCurrentLoad(generation,ownerView))return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const rawParsed=await PostalMime.parse(buffer);if(!this.isCurrentLoad(generation,ownerView))return null;const parsed=normalizeParsedEmail(rawParsed);if(!parsed)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const sanitized=parsed.html!==void 0&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):"",bodyHtml=sanitized.trim()?sanitized:null;if(!this.isCurrentLoad(generation,ownerView))return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));return{...parsed.from===void 0?{}:{fromAddress:parsed.from},toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:[...parsed.attachments]}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
|
|
3
|
+
`)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);if(!doc)return html2;for(const forged of doc.body.querySelectorAll("[data-quote-toggle], [data-quote-index], [data-email-chrome]"))forged.removeAttribute("data-quote-toggle"),forged.removeAttribute("data-quote-index"),forged.removeAttribute("data-email-chrome");const blocks=doc.body.querySelectorAll(QUOTE_SELECTOR),expandedQuotes=new Set(expandedIndices);return blocks.forEach((block,index)=>{const expanded=expandedQuotes.has(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("data-email-chrome","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&candidate.localName==="button"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.detached=new DeferredTeardown(()=>{this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null}),this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=shadowFocusTarget(this)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,emailViewerUnnamedAttachment:LYRA_DEFAULT_emailViewerUnnamedAttachment,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()&&query.length<=TEXT_QUOTE_LIMITS.maxQueryCodeUnits){const budget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},matchesQuote=block=>createTextQuoteIndex(scopeFromElement(block),this.effectiveLocale).search(query,budget).length>0,{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){this.searchDocument?.html!==bodyHtml&&(this.searchDocument={html:bodyHtml,doc:parseHtmlDocument(bodyHtml,this.ownerDocument)});const next=new Set(this.expandedHtmlQuoteIndices);this.searchDocument.doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{!next.has(index)&&matchesQuote(block)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText),quote=this.ownerDocument.createElement("pre");quote.textContent=split?.quoted??"",split&&!this.textQuoteExpanded&&matchesQuote(quote)&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector('[part="body"]')}buildTextScope(root){return scopeFromElement(root,void 0,element=>this.foldQuotes&&element.localName==="button"&&element.getAttribute("data-email-chrome")==="quote-toggle")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.pendingTransportGeneration===void 0)&&this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.pendingTransportGeneration!==void 0&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}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()})}async load(){const generation=++this.generation;this.pendingTransportGeneration=void 0;const signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"},this.pendingTransportGeneration=generation;let acquiringMessage=!0;try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0),acquiringMessage=!1;const result=await this.parse(buffer,generation,fetchTarget.view);result&&this.isCurrentLoad(generation,fetchTarget.view)&&(this.fetchState={kind:"loaded",...result})}catch(error){if(acquiringMessage&&signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}finally{this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0)}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}async parse(buffer,generation,ownerView){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isCurrentLoad(generation,ownerView))return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const rawParsed=await PostalMime.parse(buffer);if(!this.isCurrentLoad(generation,ownerView))return null;const parsed=normalizeParsedEmail(rawParsed);if(!parsed)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const sanitized=parsed.html!==void 0&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):"",bodyHtml=sanitized.trim()?sanitized:null;if(!this.isCurrentLoad(generation,ownerView))return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));return{...parsed.from===void 0?{}:{fromAddress:parsed.from},toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:[...parsed.attachments]}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
|
|
4
4
|
<span part="from-label">${this.localize("emailViewerFrom")}</span><span part="from">${fromAddress?this.formatAddress(fromAddress):email.from}</span>
|
|
5
5
|
<span part="to-label">${this.localize("emailViewerTo")}</span><span part="to">${toAddresses?this.formatAddresses(toAddresses):email.to}</span>
|
|
6
6
|
<span part="subject-label">${this.localize("emailViewerSubject")}</span><span part="subject">${email.subject||this.localize("emailViewerNoSubject")}</span>
|
|
@@ -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{
|
|
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{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"../../../internal/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.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,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(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const sanitizer=await loadHtmlSanitizer();if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!sanitizer)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const raw=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const markup=sanitizePassiveMarkup(sanitizer,raw,this.ownerDocument,"passive-document");if(signal?.aborted||!this.isConnected||generation!==this.generation)return;!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",markup})}catch(error){if(signal?.aborted||!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"../../../internal/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
|
|
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"../../../internal/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{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}engine.setStyle(this.engineStyle());let parsed=!1,contextLost=!1;const publishParsedView=()=>{!current()||contextLost||!parsed||(this.status=engine.positionOf?.(0)===null?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),this.watchEnvironment(current),this.refreshEngine(),!current())return;if(supportsAsyncModelData(engine)){if(await engine.setDataAsync({bytes,format},generation,{signal:controller.signal}),!current())return}else engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){if(!(!this.engine||!this.isConnected))try{this.engine.setStyle(this.engineStyle());const box=this.viewport?.getBoundingClientRect();box&&this.engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready")try{this.acceptCamera(this.engine.fit?.(),!1)}catch(error){this.fail("invalid","error",error)}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation=this.generation;this.fit(),generation===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)});try{this.engine.setCamera(next),this.acceptCamera(next,!0)}catch(error){this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;const generation=this.generation;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){generation===this.generation&&this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}if(engine.setStyle(this.engineStyle()),!current())return;let parsed=!1,contextLost=!1;const publishParsedView=()=>{if(!current()||contextLost||!parsed)return;const empty=engine.positionOf?.(0)===null;!current()||contextLost||(this.status=empty?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),!current()||(this.watchEnvironment(current),this.refreshEngine(),!current()))return;if(supportsAsyncModelData(engine)){if(await engine.setDataAsync({bytes,format},generation,{signal:controller.signal}),!current())return}else engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){const engine=this.engine,generation=this.generation;if(!(!engine||!this.isConnected))try{if(engine.setStyle(this.engineStyle()),generation!==this.generation)return;const box=this.viewport?.getBoundingClientRect();box&&engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready"){const generation=this.generation;try{const camera=this.engine.fit?.();generation===this.generation&&this.status==="ready"&&this.acceptCamera(camera,!1)}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation2=this.generation;this.fit(),generation2===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)}),generation=this.generation;try{this.engine.setCamera(next),generation===this.generation&&this.status==="ready"&&this.acceptCamera(next,!0)}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
|
|
2
2
|
<div part="viewport" role="group" aria-label=${label} aria-busy=${String(this.status==="loading")} tabindex=${ready?"0":"-1"} ?data-ready=${ready} ?hidden=${this.status==="idle"||this.status==="empty"||this.status==="error"} @keydown=${this.keydown}></div>
|
|
3
3
|
<div part="toolbar">${controls.map(([action,label2])=>html`<button part="control" type="button" ?disabled=${!ready} @click=${()=>this.move(action)}>${label2}</button>`)}</div>
|
|
4
4
|
<p part="instructions">${this.localize("modelViewerInstructions")}</p>
|
|
@@ -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-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"../../../internal/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 isNotebookRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}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(!isNotebookRecord(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(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(!isNotebookRecord(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 metadata=v.metadata;if(metadata!==void 0){if(!isNotebookRecord(metadata))return!1;for(const[section,field]of[["language_info","name"],["kernelspec","language"]]){const entry=metadata[section];if(entry===void 0)continue;if(!isNotebookRecord(entry))return!1;const language=entry[field];if(language!==void 0&&typeof language!="string")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(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{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"../../../internal/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 isNotebookRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}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(!isNotebookRecord(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 isMarkupTagBoundary(markup,index){return/[\t\n\f\r />]/.test(markup[index]??"")}function markupTagEnd(markup,start){let quote="",inName=!0,beforeValue=!1,unquotedValue=!1;for(let index=start;index<markup.length;index++){const character=markup[index];if(quote){character===quote&&(quote="");continue}if(character===">")return index;const whitespace=/[\t\n\f\r ]/.test(character);if(inName){(whitespace||character==="/"&&index>start)&&(inName=!1);continue}if(beforeValue){if(whitespace)continue;beforeValue=!1,character==='"'||character==="'"?quote=character:unquotedValue=!0}else unquotedValue?whitespace&&(unquotedValue=!1):character==="="&&(beforeValue=!0)}return-1}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=markupTagEnd(markup,open+1);if(close<0)break;const rawText=lower.startsWith("<script",open)&&isMarkupTagBoundary(lower,open+7)?"<\/script":lower.startsWith("<style",open)&&isMarkupTagBoundary(lower,open+6)?"</style":"";if(rawText){let end=lower.indexOf(rawText,close+1);for(;end>=0&&!isMarkupTagBoundary(lower,end+rawText.length);)end=lower.indexOf(rawText,end+rawText.length);const endClose=end<0?-1:markupTagEnd(markup,end+2);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(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(!isNotebookRecord(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 metadata=v.metadata;if(metadata!==void 0){if(!isNotebookRecord(metadata))return!1;for(const[section,field]of[["language_info","name"],["kernelspec","language"]]){const entry=metadata[section];if(entry===void 0)continue;if(!isNotebookRecord(entry))return!1;const language=entry[field];if(language!==void 0&&typeof language!="string")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(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
|
|
@@ -23,7 +23,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
23
23
|
></lr-code-block>`:html`<pre part="raw-source" tabindex="0">${joinSource(c.source)}</pre>`}
|
|
24
24
|
${c.cell_type==="code"&&c.outputs?.length?html`<div part="outputs">${c.outputs.map((o,i)=>this.renderOutput(index,o,i))}</div>`:nothing}
|
|
25
25
|
</div>
|
|
26
|
-
</div>`}}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,loadingDocument:LYRA_DEFAULT_loadingDocument,notebookViewerCodeCell:LYRA_DEFAULT_notebookViewerCodeCell,notebookViewerCollapseOutput:LYRA_DEFAULT_notebookViewerCollapseOutput,notebookViewerErrorOutput:LYRA_DEFAULT_notebookViewerErrorOutput,notebookViewerInPrompt:LYRA_DEFAULT_notebookViewerInPrompt,notebookViewerInPromptEmpty:LYRA_DEFAULT_notebookViewerInPromptEmpty,notebookViewerInvalid:LYRA_DEFAULT_notebookViewerInvalid,notebookViewerLabel:LYRA_DEFAULT_notebookViewerLabel,notebookViewerMarkdownCell:LYRA_DEFAULT_notebookViewerMarkdownCell,notebookViewerRawCell:LYRA_DEFAULT_notebookViewerRawCell,notebookViewerShowAllOutput:LYRA_DEFAULT_notebookViewerShowAllOutput,notebookViewerTooManyCells:LYRA_DEFAULT_notebookViewerTooManyCells,notebookViewerUnrenderedOutput:LYRA_DEFAULT_notebookViewerUnrenderedOutput,notebookViewerUnsupportedVersion:LYRA_DEFAULT_notebookViewerUnsupportedVersion}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["notebook"])}static{this.identityCollectionObjectProperties=Object.freeze(["notebook"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,viewerLoadingStyles]}get notebook(){return this._notebook}set notebook(value){if(value!==void 0&&(value===this.notebookSource||value===this._notebook))return;this.notebookSource=value;const old=this._notebook,next=typeof value=="string"||value===void 0?value:(()=>{const snapshot=snapshotNotebookDocument(value);return snapshot===OMIT_NOTEBOOK_SNAPSHOT?invalidNotebookSnapshot():snapshot})();Object.is(old,next)||(this._notebook=next,this.requestUpdate("notebook",old),next===void 0?(this.beginSourceTransition(this.src?"loading":"idle"),this.isConnected&&this.scheduleSourceLoad()):this.parseInline())}get source(){return resolveViewerSource(this.src,this._notebook)}set source(_value){}get effectiveOutputCollapseLines(){return finiteCount(this.outputCollapseLines,40)}updated(changed){super.updated(changed),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&this._notebook===void 0&&this.scheduleSourceLoad();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&this._notebook===void 0&&this.beginSourceTransition(this.src?"loading":"idle"),(changed.has("highlights")||changed.has("activeHighlightId")||changed.has("loadState"))&&this.repaintHighlights()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&(this.hasUpdated&&this.src&&this._notebook===void 0&&this.scheduleSourceLoad(),this.hasUpdated&&this._notebook!==void 0&&this.loadState.kind==="loaded"&&this.requestUpdate())}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedNotebook(){this.generation++,this.sanitizerGeneration++,this.beginAbortableLoad(),this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this._notebook===void 0&&(this.loadState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}parseInline(){if(this._notebook===void 0)return;const generation=++this.generation;this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind:"idle"};try{const raw=typeof this._notebook=="string"?JSON.parse(this._notebook):this._notebook;this.setDoc(raw,generation)}catch(error){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error})}}resetParsedState(){const shouldEmitSearchReset=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.activeSearchIndex!==-1;this.sanitizerGeneration++,this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.expandedOutputs=new Set,this.clearSearchState(),this.activeCellIndex=null,shouldEmitSearchReset&&this.emitSearchChange()}beginSourceTransition(kind){this.generation++,this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind}}scheduleSourceLoad(){this.sourceLoadScheduled||(this.sourceLoadScheduled=!0,this.scheduleAfterUpdate(()=>{this.sourceLoadScheduled=!1,this.isConnected&&this._notebook===void 0&&this.loadFromSrc()}))}async loadFromSrc(){if(!this.isConnected||this._notebook!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.emit("lr-render-error",{error});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;this.setDoc(JSON.parse(text),generation)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}setDoc(raw,generation){if(generation!==this.generation)return;if(!isNotebookShape(raw)){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error:new Error("invalid notebook shape")});return}if(raw.nbformat!==SUPPORTED_MAJOR||!SUPPORTED_MINORS.includes(raw.nbformat_minor)){this.loadState={kind:"error",message:this.localize("notebookViewerUnsupportedVersion",void 0,{version:`${raw.nbformat}.${raw.nbformat_minor}`})},this.emit("lr-render-error",{error:new Error("unsupported nbformat version")});return}if(raw.cells.length>MAX_CELLS){this.loadState={kind:"error",message:this.localize("notebookViewerTooManyCells")},this.emit("lr-render-error",{error:new Error("too many cells")});return}this.resetParsedState(),this.loadState={kind:"loaded",doc:raw};const language=raw.metadata?.language_info?.name??raw.metadata?.kernelspec?.language??"";this.emit("lr-load",{cellCount:raw.cells.length,language})}async applyAnchor(anchor){const index=this.resolveAnchorCellIndex(anchor);return index<0?!1:this.activateCell(index,"start")}async activateCell(index,align){const generation=this.generation,ownerDocument=this.ownerDocument;if(this.activeCellIndex=index,!this.isConnected||(await this.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index))return!1;const list=this.virtualListEl;return!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index)?!1:(list.scrollToIndex(index,{align,behavior:"auto"}),await list.updateComplete,this.isConnected&&this.ownerDocument===ownerDocument&&generation===this.generation&&this.activeCellIndex===index)}resolveAnchorCellIndex(anchor){if(this.loadState.kind!=="loaded")return-1;const cells=this.loadState.doc.cells;let index=-1;if(anchor.kind==="node-path"&&Number.isInteger(anchor.path[0]))index=anchor.path[0];else if(anchor.kind==="fragment")index=cells.findIndex(c=>c.id===anchor.id);else return-1;return index<0||index>=cells.length?-1:index}repaintHighlights(){if(this.loadState.kind!=="loaded"){this.highlightedCells.size>0&&(this.highlightedCells=new Map);return}const next=new Map;let considered=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(considered>=MAX_NOTEBOOK_PAINTED_HIGHLIGHTS)break;considered++;const index=this.resolveAnchorCellIndex(highlight.anchor);index<0||next.has(index)||next.set(index,highlight)}this.highlightedCells=next}async search(query2){const boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale),q=boundedQuery.needle;if(this.searchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.searchMatchCountExact=boundedQuery.accepted,this.loadState.kind!=="loaded"||!q||!boundedQuery.accepted)this.searchMatches=[];else{const budget=new ViewerSearchWorkBudget,matches=[];for(let index=0;index<this.loadState.doc.cells.length;index++){const cell=this.loadState.doc.cells[index],sourceParts=typeof cell.source=="string"?[cell.source]:cell.source,sourceMatch=budget.includesJoined(sourceParts,q,this.effectiveLocale),outputMatch=sourceMatch?!1:budget.includesJoined(notebookOutputSearchParts(cell.outputs??[]),q,this.effectiveLocale);if((sourceMatch||outputMatch)&&matches.push(index),!budget.complete){this.searchMatchCountExact=!1;break}}this.searchMatches=matches}return this.activeSearchIndex=this.searchMatches.length?0:-1,await this.activateSearchMatch(),this.emitSearchChange(),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchMatches.length)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}clearSearch(){this.clearSearchState(),this.emitSearchChange()}clearSearchState(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1}async activateSearchMatch(){const index=this.searchMatches[this.activeSearchIndex];index!==void 0&&await this.activateCell(index,"auto")}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.activeSearchIndex})}toggleOutput(index){const next=new Set(this.expandedOutputs);next.has(index)?next.delete(index):next.add(index),this.expandedOutputs=next}renderAnsiText(text){const segments=createAnsiParser().push(text);return html`${segments.map(seg=>html`<span style=${styleMap(this.segmentStyle(seg.styles))}>${seg.text}</span>`)}`}segmentStyle(s){const fg=sanitizeCssColor(s.fg)??"var(--lr-color-text)",bg=sanitizeCssColor(s.bg)??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}renderTextOutput(index,text,tone){const lines=text.split(`
|
|
26
|
+
</div>`}}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,loadingDocument:LYRA_DEFAULT_loadingDocument,notebookViewerCodeCell:LYRA_DEFAULT_notebookViewerCodeCell,notebookViewerCollapseOutput:LYRA_DEFAULT_notebookViewerCollapseOutput,notebookViewerErrorOutput:LYRA_DEFAULT_notebookViewerErrorOutput,notebookViewerInPrompt:LYRA_DEFAULT_notebookViewerInPrompt,notebookViewerInPromptEmpty:LYRA_DEFAULT_notebookViewerInPromptEmpty,notebookViewerInvalid:LYRA_DEFAULT_notebookViewerInvalid,notebookViewerLabel:LYRA_DEFAULT_notebookViewerLabel,notebookViewerMarkdownCell:LYRA_DEFAULT_notebookViewerMarkdownCell,notebookViewerRawCell:LYRA_DEFAULT_notebookViewerRawCell,notebookViewerShowAllOutput:LYRA_DEFAULT_notebookViewerShowAllOutput,notebookViewerTooManyCells:LYRA_DEFAULT_notebookViewerTooManyCells,notebookViewerUnrenderedOutput:LYRA_DEFAULT_notebookViewerUnrenderedOutput,notebookViewerUnsupportedVersion:LYRA_DEFAULT_notebookViewerUnsupportedVersion}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["notebook"])}static{this.identityCollectionObjectProperties=Object.freeze(["notebook"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,viewerLoadingStyles]}get notebook(){return this._notebook}set notebook(value){if(value!==void 0&&(value===this.notebookSource||value===this._notebook))return;this.notebookSource=value;const old=this._notebook,next=typeof value=="string"||value===void 0?value:(()=>{const snapshot=snapshotNotebookDocument(value);return snapshot===OMIT_NOTEBOOK_SNAPSHOT?invalidNotebookSnapshot():snapshot})();Object.is(old,next)||(this._notebook=next,this.requestUpdate("notebook",old),next===void 0?(this.beginSourceTransition(this.src?"loading":"idle"),this.isConnected&&this.scheduleSourceLoad()):this.parseInline())}get source(){return resolveViewerSource(this.src,this._notebook)}set source(_value){}get effectiveOutputCollapseLines(){return finiteCount(this.outputCollapseLines,40)}updated(changed){super.updated(changed),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&this._notebook===void 0&&this.scheduleSourceLoad();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&this._notebook===void 0&&this.beginSourceTransition(this.src?"loading":"idle"),(changed.has("highlights")||changed.has("activeHighlightId")||changed.has("loadState"))&&this.repaintHighlights()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.loadState.kind!=="loading")&&(this.hasUpdated&&this.src&&this._notebook===void 0&&this.scheduleSourceLoad(),this.hasUpdated&&this._notebook!==void 0&&this.loadState.kind==="loaded"&&this.requestUpdate())}disconnectedCallback(){this._notebook===void 0&&this.loadState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedNotebook(){this.generation++,this.sanitizerGeneration++,this.beginAbortableLoad(),this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this._notebook===void 0&&(this.loadState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}parseInline(){if(this._notebook===void 0)return;const generation=++this.generation;this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind:"idle"};try{const raw=typeof this._notebook=="string"?JSON.parse(this._notebook):this._notebook;this.setDoc(raw,generation)}catch(error){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error})}}resetParsedState(){const shouldEmitSearchReset=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.activeSearchIndex!==-1;this.sanitizerGeneration++,this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.expandedOutputs=new Set,this.clearSearchState(),this.activeCellIndex=null,shouldEmitSearchReset&&this.emitSearchChange()}beginSourceTransition(kind){this.generation++,this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind}}scheduleSourceLoad(){this.sourceLoadScheduled||(this.sourceLoadScheduled=!0,this.scheduleAfterUpdate(()=>{this.sourceLoadScheduled=!1,this.isConnected&&this._notebook===void 0&&this.loadFromSrc()}))}async loadFromSrc(){if(!this.isConnected||this._notebook!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.setDoc(JSON.parse(text),generation)}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}setDoc(raw,generation){if(generation!==this.generation)return;if(!isNotebookShape(raw)){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error:new Error("invalid notebook shape")});return}if(raw.nbformat!==SUPPORTED_MAJOR||!SUPPORTED_MINORS.includes(raw.nbformat_minor)){this.loadState={kind:"error",message:this.localize("notebookViewerUnsupportedVersion",void 0,{version:`${raw.nbformat}.${raw.nbformat_minor}`})},this.emit("lr-render-error",{error:new Error("unsupported nbformat version")});return}if(raw.cells.length>MAX_CELLS){this.loadState={kind:"error",message:this.localize("notebookViewerTooManyCells")},this.emit("lr-render-error",{error:new Error("too many cells")});return}this.resetParsedState(),this.loadState={kind:"loaded",doc:raw};const language=raw.metadata?.language_info?.name??raw.metadata?.kernelspec?.language??"";this.emit("lr-load",{cellCount:raw.cells.length,language})}async applyAnchor(anchor){const index=this.resolveAnchorCellIndex(anchor);return index<0?!1:this.activateCell(index,"start")}async activateCell(index,align){const generation=this.generation,ownerDocument=this.ownerDocument;if(this.activeCellIndex=index,!this.isConnected||(await this.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index))return!1;const list=this.virtualListEl;return!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index)?!1:(list.scrollToIndex(index,{align,behavior:"auto"}),await list.updateComplete,this.isConnected&&this.ownerDocument===ownerDocument&&generation===this.generation&&this.activeCellIndex===index)}resolveAnchorCellIndex(anchor){if(this.loadState.kind!=="loaded")return-1;const cells=this.loadState.doc.cells;let index=-1;if(anchor.kind==="node-path"&&Number.isInteger(anchor.path[0]))index=anchor.path[0];else if(anchor.kind==="fragment")index=cells.findIndex(c=>c.id===anchor.id);else return-1;return index<0||index>=cells.length?-1:index}repaintHighlights(){if(this.loadState.kind!=="loaded"){this.highlightedCells.size>0&&(this.highlightedCells=new Map);return}const next=new Map;let considered=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(considered>=MAX_NOTEBOOK_PAINTED_HIGHLIGHTS)break;considered++;const index=this.resolveAnchorCellIndex(highlight.anchor);index<0||next.has(index)||next.set(index,highlight)}this.highlightedCells=next}async search(query2){const boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale),q=boundedQuery.needle;if(this.searchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.searchMatchCountExact=boundedQuery.accepted,this.loadState.kind!=="loaded"||!q||!boundedQuery.accepted)this.searchMatches=[];else{const budget=new ViewerSearchWorkBudget,matches=[];for(let index=0;index<this.loadState.doc.cells.length;index++){const cell=this.loadState.doc.cells[index],sourceParts=typeof cell.source=="string"?[cell.source]:cell.source,sourceMatch=budget.includesJoined(sourceParts,q,this.effectiveLocale),outputMatch=sourceMatch?!1:budget.includesJoined(notebookOutputSearchParts(cell.outputs??[]),q,this.effectiveLocale);if((sourceMatch||outputMatch)&&matches.push(index),!budget.complete){this.searchMatchCountExact=!1;break}}this.searchMatches=matches}return this.activeSearchIndex=this.searchMatches.length?0:-1,await this.activateSearchMatch(),this.emitSearchChange(),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchMatches.length)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}clearSearch(){this.clearSearchState(),this.emitSearchChange()}clearSearchState(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1}async activateSearchMatch(){const index=this.searchMatches[this.activeSearchIndex];index!==void 0&&await this.activateCell(index,"auto")}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.activeSearchIndex})}toggleOutput(index){const next=new Set(this.expandedOutputs);next.has(index)?next.delete(index):next.add(index),this.expandedOutputs=next}renderAnsiText(text){const segments=createAnsiParser().push(text);return html`${segments.map(seg=>html`<span style=${styleMap(this.segmentStyle(seg.styles))}>${seg.text}</span>`)}`}segmentStyle(s){const fg=sanitizeCssColor(s.fg)??"var(--lr-color-text)",bg=sanitizeCssColor(s.bg)??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}renderTextOutput(index,text,tone){const lines=text.split(`
|
|
27
27
|
`),outputCollapseLines=this.effectiveOutputCollapseLines,collapsible=outputCollapseLines>0&&lines.length>outputCollapseLines,expanded=this.expandedOutputs.has(index)||!collapsible,shown=expanded?text:lines.slice(0,outputCollapseLines).join(`
|
|
28
28
|
`);return html`<div part=${tone==="danger"?"output output-error":"output"} data-output-type="stream" data-stream=${tone==="danger"?"stderr":"stdout"}
|
|
29
29
|
>${this.renderAnsiText(shown)}${collapsible?html`<button
|
|
@@ -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 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;
|
|
133
|
+
readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private firstVisiblePage;private loadLibrary;private generation;private pendingTransportGeneration?;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 retirePendingDocument;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 destroyDocumentResource;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. */
|