@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 +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{srOnly}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/file-size.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.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_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_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=Number.POSITIVE_INFINITY;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=(item,index)=>`${item.name}\0${index}`,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++}),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,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,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector(tag("virtual-list"))}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot(),listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector(tag("virtual-list"));index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}activeArchiveMatchKey(){if(this.fetchState.kind!=="loaded")return"";const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return"";const index=this.fetchState.entries.indexOf(match);return index>=0?this.archiveEntryKey(match,index):""}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.activeArchiveMatchKey()} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;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>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
|
|
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{srOnly}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/file-size.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.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_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_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=Number.POSITIVE_INFINITY;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=(item,index)=>`${item.name}\0${index}`,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++}),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,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,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&(!moved||this.fetchState.kind==="loading")&&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()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector(tag("virtual-list"))}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot(),listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector(tag("virtual-list"));index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}activeArchiveMatchKey(){if(this.fetchState.kind!=="loaded")return"";const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return"";const index=this.fetchState.entries.indexOf(match);return index>=0?this.archiveEntryKey(match,index):""}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.activeArchiveMatchKey()} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;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>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadIcal}from"./calendar-loader.js";import{styles}from"./calendar-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.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_calendarViewerEmpty,LYRA_DEFAULT_calendarViewerLabel,LYRA_DEFAULT_calendarViewerMissingParser,LYRA_DEFAULT_calendarViewerNoSummary,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeCalendar,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_CALENDAR_EVENTS=250,MAX_CALENDAR_RENDERED_CHARS=2*1024*1024;function formatEventTime(event,locale){if(!event.start)return"";if(event.startKind==="date"){const formatter2=getDateTimeFormat(locale,{dateStyle:"medium",timeZone:"UTC"});if(!event.end||event.endKind!=="date")return formatter2.format(event.start);const inclusiveEnd=new Date(event.end.getTime());return inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate()-1),inclusiveEnd.getTime()<=event.start.getTime()?formatter2.format(event.start):formatter2.formatRange(event.start,inclusiveEnd)}const formatter=getDateTimeFormat(locale,{dateStyle:"medium",timeStyle:"short"});return event.end&&event.endKind==="date-time"?formatter.formatRange(event.start,event.end):formatter.format(event.start)}function parseCalendarTime(time){if(!time)return null;let value;if(time.isDate===!0&&Number.isInteger(time.year)&&Number.isInteger(time.month)&&Number.isInteger(time.day)){if(value=utcDate(time.year,time.month-1,time.day),value.getUTCFullYear()!==time.year||value.getUTCMonth()+1!==time.month||value.getUTCDate()!==time.day)throw new Error("Invalid all-day calendar date.")}else value=time.toJSDate();if(!Number.isFinite(value.getTime()))throw new Error("Invalid calendar date.");return{value,kind:time.isDate===!0?"date":"date-time"}}function eventTime(read){try{return parseCalendarTime(read())}catch{return null}}class LyraCalendarViewerBase extends LyraElement{}class LyraCalendarViewer extends TextViewerTarget(LyraCalendarViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,calendarViewerEmpty:LYRA_DEFAULT_calendarViewerEmpty,calendarViewerLabel:LYRA_DEFAULT_calendarViewerLabel,calendarViewerMissingParser:LYRA_DEFAULT_calendarViewerMissingParser,calendarViewerNoSummary:LYRA_DEFAULT_calendarViewerNoSummary,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeCalendar:LYRA_DEFAULT_documentPreviewTypeCalendar,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&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()}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(){this.lastLoadSrc=this.src;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 source=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const events=await this.parse(source,generation,signal);if(signal?.aborted||!this.isConnected||generation!==this.generation||!events)return;!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",events})}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})}}async parse(source,generation,signal){const ical=await loadIcal();if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!ical)throw new LyraUserFacingError(this.localize("calendarViewerMissingParser"));if((source.match(/^BEGIN:VEVENT\r?$/gim)?.length??0)>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");const subcomponents=new ical.Component(ical.parse(source)).getAllSubcomponents("vevent");if(subcomponents.length>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");let renderedChars=0;return subcomponents.map(subcomponent=>{const event=new ical.Event(subcomponent),parsedStart=eventTime(()=>event.startDate),parsedEnd=eventTime(()=>event.endDate),end=parsedStart&&parsedEnd&&(parsedStart.kind!==parsedEnd.kind||parsedEnd.value.getTime()<parsedStart.value.getTime())?null:parsedEnd,uid=event.uid??"",summary=event.summary??"",location=event.location??"",description=event.description??"";if(renderedChars+=uid.length+summary.length+location.length+description.length,renderedChars>MAX_CALENDAR_RENDERED_CHARS)throw new LyraResourceLimitError("The calendar contains too much rendered text.");return{uid,summary,start:parsedStart?.value??null,end:end?.value??null,startKind:parsedStart?.kind??null,endKind:end?.kind??null,location,description}})}renderEvent(event){return html`<li part="event"><span part="event-summary">${event.summary||this.localize("calendarViewerNoSummary")}</span><span part="event-time">${formatEventTime(event,this.effectiveLocale)}</span>${event.location?html`<span part="event-location">${event.location}</span>`:nothing}${event.description?html`<p part="event-description">${event.description}</p>`:nothing}</li>`}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.events.length?html`<ul part="event-list">${this.fetchState.events.map(event=>this.renderEvent(event))}</ul>`:html`<p class="empty-note">${this.localize("calendarViewerEmpty")}</p>`;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("documentPreviewTypeCalendar")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"&&this.fetchState.events.length>0?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${viewerSemanticRole(this,"region")??nothing} style=${maxHeight?styleMap({"--lr-calendar-viewer-max-height":maxHeight}):nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("calendarViewerLabel"))??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraCalendarViewer.prototype,"src",void 0),__decorate([property()],LyraCalendarViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraCalendarViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraCalendarViewer.prototype,"fetchState",void 0);export{LyraCalendarViewer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{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{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{getListFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{parseVCards}from"./vcard.js";import{styles}from"./contact-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.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_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_contactViewerAddressFormat,LYRA_DEFAULT_contactViewerAddressLabel,LYRA_DEFAULT_contactViewerEmailLabel,LYRA_DEFAULT_contactViewerLabel,LYRA_DEFAULT_contactViewerNoContacts,LYRA_DEFAULT_contactViewerOrganization,LYRA_DEFAULT_contactViewerPhoneLabel,LYRA_DEFAULT_contactViewerTypeCell,LYRA_DEFAULT_contactViewerTypeFax,LYRA_DEFAULT_contactViewerTypeHome,LYRA_DEFAULT_contactViewerTypeInternet,LYRA_DEFAULT_contactViewerTypePreferred,LYRA_DEFAULT_contactViewerTypeVoice,LYRA_DEFAULT_contactViewerTypeWork,LYRA_DEFAULT_contactViewerTypedValue,LYRA_DEFAULT_contactViewerUnnamedContact,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";class LyraContactViewerBase extends LyraElement{}class LyraContactViewer extends TextViewerTarget(LyraContactViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.headingLevel="3",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,contactViewerAddressFormat:LYRA_DEFAULT_contactViewerAddressFormat,contactViewerAddressLabel:LYRA_DEFAULT_contactViewerAddressLabel,contactViewerEmailLabel:LYRA_DEFAULT_contactViewerEmailLabel,contactViewerLabel:LYRA_DEFAULT_contactViewerLabel,contactViewerNoContacts:LYRA_DEFAULT_contactViewerNoContacts,contactViewerOrganization:LYRA_DEFAULT_contactViewerOrganization,contactViewerPhoneLabel:LYRA_DEFAULT_contactViewerPhoneLabel,contactViewerTypeCell:LYRA_DEFAULT_contactViewerTypeCell,contactViewerTypeFax:LYRA_DEFAULT_contactViewerTypeFax,contactViewerTypeHome:LYRA_DEFAULT_contactViewerTypeHome,contactViewerTypeInternet:LYRA_DEFAULT_contactViewerTypeInternet,contactViewerTypePreferred:LYRA_DEFAULT_contactViewerTypePreferred,contactViewerTypeVoice:LYRA_DEFAULT_contactViewerTypeVoice,contactViewerTypeWork:LYRA_DEFAULT_contactViewerTypeWork,contactViewerTypedValue:LYRA_DEFAULT_contactViewerTypedValue,contactViewerUnnamedContact:LYRA_DEFAULT_contactViewerUnnamedContact,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeContact:LYRA_DEFAULT_documentPreviewTypeContact,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}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()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&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()}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(){this.lastLoadSrc=this.src;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 source=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}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})}}formatList(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(values)}formatAddress(address){return this.localize("contactViewerAddressFormat",void 0,{poBox:address.poBox,extendedAddress:address.extendedAddress,streetAddress:address.streetAddress,locality:address.locality,region:address.region,postalCode:address.postalCode,country:address.country}).split(/\r\n|\r|\n/).map(line=>line.replace(/\s+/g," ").trim()).filter(Boolean).join(`
|
|
2
2
|
`)}formatType(type){const key={home:"contactViewerTypeHome",work:"contactViewerTypeWork",cell:"contactViewerTypeCell",voice:"contactViewerTypeVoice",fax:"contactViewerTypeFax",internet:"contactViewerTypeInternet",pref:"contactViewerTypePreferred",preferred:"contactViewerTypePreferred"}[type.toLowerCase()];return key?this.localize(key):type}formatTypedValue(value,types){return types.length?this.localize("contactViewerTypedValue",void 0,{value,types:this.formatList(types.map(type=>this.formatType(type)))}):value}renderContact(contact){const headingLevel=resolveHeadingLevel(this.headingLevel);return html`<article part="contact">
|
|
3
3
|
<div
|
|
4
4
|
part="contact-name"
|
|
@@ -19,7 +19,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
|
|
|
19
19
|
.items=${body.length<=1e4?body:nothing}
|
|
20
20
|
.source=${this.table.indexedSource(body)}
|
|
21
21
|
.renderItem=${renderItem}
|
|
22
|
-
.keyFunction=${indexKeyFunction}
|
|
22
|
+
.keyFunction=${body.length<=1e4?indexKeyFunction:void 0}
|
|
23
23
|
.activeItemId=${this.table.activeRowKey}
|
|
24
24
|
item-role="row"
|
|
25
25
|
row-index-offset=${hasHeaderRow?"1":"0"}
|
|
@@ -16,7 +16,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
|
|
|
16
16
|
.items=${guard([rows],()=>rows.length<=1e4?rows:nothing)}
|
|
17
17
|
.source=${this.tableController.indexedSource(rows)}
|
|
18
18
|
.renderItem=${this.tableController.rowRenderer(rows,[fields,window.columns,this.activeHighlightId,this.strings],(row,index)=>this.renderRow(row,index,fields))}
|
|
19
|
-
.keyFunction=${this.virtualListKeyFunction}
|
|
19
|
+
.keyFunction=${rows.length<=1e4?this.virtualListKeyFunction:void 0}
|
|
20
20
|
.activeItemId=${this.tableController.activeRowKey}
|
|
21
21
|
.scrollElement=${this.scrollMode==="page"?this.ownerDocument.defaultView??void 0:void 0}
|
|
22
22
|
item-role="row"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./document-preview.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{snapshotLyraHighlightAnchorKind,snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_convertingDocument,LYRA_DEFAULT_documentPreviewAlt,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewNotAvailable,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const IDLE_TEXT_FETCH={kind:"idle"};function classifyFormat(mimeType){const mt=(mimeType??"").split(";",1)[0].trim().toLowerCase();return mt.startsWith("text/")||mt==="application/json"?"text":mt.startsWith("image/")?"image":"generic"}const EMPTY_REGION_HIGHLIGHTS=Object.freeze([]);function projectRegionAnchor(value,knownRegionKind=!1){try{if(value===null||typeof value!="object"||Array.isArray(value))return;if(!knownRegionKind){const kind=getOwnDataDescriptor(value,"kind");if(kind===MISSING_OWN_DATA_DESCRIPTOR||kind===UNSAFE_OWN_DATA_DESCRIPTOR||kind.value!=="region")return}const rectDescriptor=getOwnDataDescriptor(value,"rect");if(rectDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rectDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const rect=sanitizePercentRect(rectDescriptor.value);if(!rect)return;const pageDescriptor=getOwnDataDescriptor(value,"page"),page=pageDescriptor===MISSING_OWN_DATA_DESCRIPTOR||pageDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:pageDescriptor.value;return Object.freeze({rect,...typeof page=="number"&&Number.isFinite(page)?{page}:{}})}catch{return}}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function downloadIcon(){return icon(svg`
|
|
2
2
|
<path d="M12 3v12"></path>
|
|
3
3
|
<polyline points="7 11 12 16 17 11"></polyline>
|
|
4
4
|
<path d="M4 18v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"></path>
|
|
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
|
|
|
15
15
|
aria-hidden="true"
|
|
16
16
|
focusable="false"
|
|
17
17
|
>${paths}</svg>
|
|
18
|
-
`}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedPreview()),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,convertingDocument:LYRA_DEFAULT_convertingDocument,details:LYRA_DEFAULT_details,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly]}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;this.highlightsSource=value;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"
|
|
18
|
+
`}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedPreview()),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,convertingDocument:LYRA_DEFAULT_convertingDocument,details:LYRA_DEFAULT_details,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly]}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;this.highlightsSource=value;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"&&(!moved||this.textFetch.kind==="loading")&&(this.textFetch=IDLE_TEXT_FETCH,this.scheduleAfterUpdate(()=>{const url=safeFetchUrl(this.src);url&&this.status!=="converting"&&this.status!=="error"&&this.fetchText(url)}))}disconnectedCallback(){this.textFetch.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPreview(){this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")),this.textFetch.kind!=="idle"&&(classifyFormat(this.mimeType)!=="text"||safeFetchUrl(this.src)===null||this.status==="converting"||this.status==="error")&&(this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH)}updated(changed){super.updated(changed),this.syncAnnouncementState();const safeTextSrc=safeFetchUrl(this.src);classifyFormat(this.mimeType)==="text"&&safeTextSrc!==null&&this.status!=="converting"&&this.status!=="error"&&(changed.has("src")||changed.has("mimeType")||changed.has("status")&&this.textFetch.kind==="idle")&&this.scheduleAfterUpdate(()=>{this.fetchText(safeTextSrc)})}syncAnnouncementState(){if(this.status==="converting"){if(this.progress!=null&&Number.isFinite(this.progress)){this.announcements.transition("preview","progress");return}this.announcements.transition("preview","loading",this.localize("convertingDocument"));return}if(this.status==="error"){this.announcements.transition("preview","error",this.errorText||this.localize("documentPreviewGenericError"));return}if(classifyFormat(this.mimeType)!=="text"||this.src===""){this.announcements.transition("preview","idle");return}if(safeFetchUrl(this.src)===null){this.announcements.transition("preview","error",this.localize("documentPreviewUrlNotAllowed"));return}if(this.textFetch.kind==="error"){this.announcements.transition("preview","error",this.textFetch.message);return}if(this.textFetch.kind==="loaded"){this.announcements.transition("preview","loaded");return}this.announcements.transition("preview","loading",this.localize("loadingDocument"))}async fetchText(url){const generation=++this.generation,signal=this.beginAbortableLoad(),fetchTarget=resolveOwnerFetchTarget(this,url);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.textFetch={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.textFetch={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.textFetch={kind:"loaded",text}}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const message=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.textFetch={kind:"error",message},this.emit("lr-render-error",{error})}}renderSpinner(label,progressValue){if(progressValue!=null&&Number.isFinite(progressValue)){const clamped=finiteRange(progressValue,0,0,100),rounded=Math.round(clamped),formatted=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:0}).format(clamped/100);return html`
|
|
19
19
|
<div
|
|
20
20
|
part="spinner"
|
|
21
21
|
role="progressbar"
|
|
@@ -88,7 +88,7 @@ name:string;
|
|
|
88
88
|
/** A CSS `max-height` that caps the scrollable document body; invalid values are ignored.*/
|
|
89
89
|
maxHeight:string;
|
|
90
90
|
/** Anchor kinds this viewer resolves via `scrollToAnchor()`. Readonly.*/
|
|
91
|
-
readonly anchorKinds:readonly['fragment','text-quote'];private fetchState;private readonly searchState;private resolvedHighlightActions;private generation;private lastLoadSrc;private loadLibrary;private readonly announcements;private headingTree;private highlightHandle?;private resolvedHighlightRanges;private pendingResolvedHighlightActions;private resolvedHighlightActionSyncPending;private paintedSearchMarks;private textIndexCache;private textIndexMappingDirty;private textIndexLocale?;private readonly detached;connectedCallback():void;disconnectedCallback():void;private releaseDetachedDocument;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private contentRoot;private resetSearchForContentChange;private load;private failWithLocalizedMessage;private stampHeadings;
|
|
91
|
+
readonly anchorKinds:readonly['fragment','text-quote'];private fetchState;private readonly searchState;private resolvedHighlightActions;private generation;private pendingTransportGeneration?;private lastLoadSrc;private loadLibrary;private readonly announcements;private headingTree;private highlightHandle?;private resolvedHighlightRanges;private pendingResolvedHighlightActions;private resolvedHighlightActionSyncPending;private paintedSearchMarks;private textIndexCache;private textIndexMappingDirty;private textIndexLocale?;private readonly detached;connectedCallback():void;disconnectedCallback():void;private releaseDetachedDocument;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private contentRoot;private resetSearchForContentChange;private load;private failWithLocalizedMessage;private stampHeadings;
|
|
92
92
|
/** A document-ordered, flattened heading outline -- empty until a document has finished loading.*/
|
|
93
93
|
getHeadingTree():DocxHeadingItem[];protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private applyFragmentAnchor;private applyTextQuoteAnchor;
|
|
94
94
|
/** Overrides `DocumentAnchorTarget`'s default (whole render-root) selection scope -- only
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}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_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.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 null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}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,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();root&&this.bindTextSelection(root);return}this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"},this.headingTree=[];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.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"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})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}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_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.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 null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}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,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();if(root&&this.bindTextSelection(root),this.pendingTransportGeneration===void 0)return}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()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}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"},this.headingTree=[];return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.pendingTransportGeneration=generation,this.fetchState={kind:"loading"};let acquiringDocument=!0;try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}acquiringDocument=!1,this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0);const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(acquiringDocument&&signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"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})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
|
|
2
2
|
<div part="highlight-actions">
|
|
3
3
|
${highlights.map(highlight=>{const label=this.highlightActionLabel(highlight);return html`
|
|
4
4
|
<button
|
|
@@ -9,7 +9,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
9
9
|
>${highlight.label||label}</button>
|
|
10
10
|
`})}
|
|
11
11
|
</div>
|
|
12
|
-
`}getTextIndex(root){const locale=this.effectiveLocale;if(!this.textIndexCache||this.textIndexCache.locale!==locale){const scope=scopeFromElement(root);this.textIndexCache={scope,index:createTextQuoteIndex(scope,locale,{maxMatches:MAX_DOCX_SEARCH_MATCHES}),locale},this.textIndexMappingDirty=!1}return this.textIndexCache}currentTextIndex(root){const cached=this.getTextIndex(root);if(!this.textIndexMappingDirty)return cached;const scope=scopeFromElement(root);return cached.index.rebindScope(scope)?(cached.scope=scope,this.textIndexMappingDirty=!1,cached):(this.textIndexCache=null,this.textIndexMappingDirty=!1,this.getTextIndex(root))}async search(query){if(invalidateLyraLocaleCache(this),this.searchState.query=query,!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.clearSearchPaint(),this.searchState.publish(void 0,!1),0;const root=this.contentRoot(),trimmed=query.trim();if(!root||!trimmed)return this.clearSearchPaint(),this.searchState.publish(),0;const{index}=this.getTextIndex(root),matches=index.search(trimmed,index.createWorkBudget());return this.searchState.publish(matches,matches.matchCountExact)
|
|
12
|
+
`}getTextIndex(root){const locale=this.effectiveLocale;if(!this.textIndexCache||this.textIndexCache.locale!==locale){const scope=scopeFromElement(root);this.textIndexCache={scope,index:createTextQuoteIndex(scope,locale,{maxMatches:MAX_DOCX_SEARCH_MATCHES}),locale},this.textIndexMappingDirty=!1}return this.textIndexCache}currentTextIndex(root){const cached=this.getTextIndex(root);if(!this.textIndexMappingDirty)return cached;const scope=scopeFromElement(root);return cached.index.rebindScope(scope)?(cached.scope=scope,this.textIndexMappingDirty=!1,cached):(this.textIndexCache=null,this.textIndexMappingDirty=!1,this.getTextIndex(root))}async search(query){if(invalidateLyraLocaleCache(this),this.searchState.query=query,!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.clearSearchPaint(),this.searchState.publish(void 0,!1),0;const root=this.contentRoot(),trimmed=query.trim();if(!root||!trimmed)return this.clearSearchPaint(),this.searchState.publish(),0;const{index}=this.getTextIndex(root),matches=index.search(trimmed,index.createWorkBudget());return this.searchState.publish(matches,matches.matchCountExact)?(this.paintSearchMatches(),this.searchState.activeIndex>=0&&this.scrollToActiveSearchMatch(),matches.length):0}async searchNext(){return this.stepSearch(1)}async searchPrevious(){return this.stepSearch(-1)}stepSearch(direction){return this.searchState.step(direction)?(this.paintSearchMatches(),this.scrollToActiveSearchMatch(),!0):!1}clearSearch(){this.clearSearchPaint(),this.searchState.clear()}scrollToActiveSearchMatch(){this.renderRoot.querySelector('mark[part~="search-match-active"]')?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"})}clearSearchPaint(){this.paintedSearchMarks.length>0&&(this.textIndexMappingDirty=!0);for(const mark of this.paintedSearchMarks)unwrapTextMark(mark);this.paintedSearchMarks=[]}paintSearchMatches(){this.clearSearchPaint();const root=this.contentRoot();if(!root||this.searchState.matches.length===0)return;const{scope}=this.currentTextIndex(root),marks=[],count=Math.min(this.searchState.matches.length,MAX_DOCX_PAINTED_SEARCH_MATCHES),half=MAX_DOCX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchState.activeIndex<0?0:this.searchState.activeIndex,start=Math.max(0,Math.min(centre-half,this.searchState.matches.length-count)),budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:MAX_DOCX_PAINTED_SEARCH_MATCHES},window=[];for(let i=start+count-1;i>=start;i--){const match=this.searchState.matches.at(i);match&&window.push({index:i,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,window.map(({match})=>match)),ranges=[];for(let position=0;position<window.length;position++){const range=resolvedRanges[position];range&&ranges.push({index:window[position].index,range})}for(const{index,range}of ranges){const part=index===this.searchState.activeIndex?"search-match search-match-active":"search-match";marks.push(...wrapRangeInSearchMarks(range,part,budget))}this.paintedSearchMarks=marks,marks.length>0&&(this.textIndexMappingDirty=!0)}renderBody(){switch(this.fetchState.kind){case"loaded":return html`
|
|
13
13
|
<div
|
|
14
14
|
part="content"
|
|
15
15
|
role=${viewerSemanticRole(this,"document")??nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DEFAULT_CANVAS_COLOR}from"../../../internal/canvas-color.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{guardEpubUnloadListener}from"./epub-unload-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerMissingLibrary,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_FIND_RESULTS=1e4,MAX_PAINTED_HIGHLIGHTS=100,MAX_PEER_PROTOTYPES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function inheritedDataDescriptor(value,key){let current=value;for(let depth=0;current&&depth<MAX_PEER_PROTOTYPES;depth+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(current,key)}catch{return}if(descriptor)return"value"in descriptor?descriptor:void 0;try{current=Object.getPrototypeOf(current)}catch{return}}}function inheritedDataValue(value,key){return isObjectValue(value)?inheritedDataDescriptor(value,key)?.value:void 0}function savedCallable(value,key){if(!isObjectValue(value))return;const candidate=inheritedDataDescriptor(value,key)?.value;if(typeof candidate=="function")return(...args)=>Reflect.apply(candidate,value,args)}function savedThenable(value){const then=savedCallable(value,"then");if(then)return new Promise((resolve,reject)=>{try{then(()=>resolve(),reject)}catch(error){reject(error)}})}function taskFrom(call,...args){try{return savedThenable(call(...args))??Promise.resolve()}catch(error){return Promise.reject(error)}}function awaitPeerResult(value){const then=savedCallable(value,"then"),wrap=resolved=>Object.freeze({value:resolved});return then?new Promise((resolve,reject)=>{try{then(resolved=>resolve(wrap(resolved)),reject)}catch(error){reject(error)}}):Promise.resolve(wrap(value))}function quoteContextScore(excerpt,quote,prefix,suffix){const text=excerpt.replace(/\s+/g," ").toLowerCase(),needle=quote.replace(/\s+/g," ").toLowerCase();let best=0;for(let at=text.indexOf(needle);at>=0;at=text.indexOf(needle,at+1))best=Math.max(best,textQuoteContextScore(text,at,at+needle.length,prefix,suffix));return best}const EPUB_CHAPTER_CONTENT_SECURITY_POLICY="default-src 'none'; img-src blob: data:; media-src blob: data:; font-src blob: data:; style-src blob: 'unsafe-inline'";function silenceChapterNetwork(chapter){const root=chapter.documentElement;if(!root)return;for(const node of[...chapter.childNodes])node.nodeType===Node.PROCESSING_INSTRUCTION_NODE&&chapter.removeChild(node);for(const element of[...chapter.querySelectorAll("link, meta")]){const rel=` ${(element.getAttribute("rel")??"").toLowerCase()} `;(/ (?:dns-prefetch|preconnect) /.test(rel)||(element.getAttribute("http-equiv")??"").trim().toLowerCase()==="refresh")&&element.remove()}const namespace=root.namespaceURI??"http://www.w3.org/1999/xhtml";let head=chapter.querySelector("head");head||(head=chapter.createElementNS(namespace,"head"),root.insertBefore(head,root.firstChild));const policy=chapter.createElementNS(namespace,"meta");policy.setAttribute("http-equiv","Content-Security-Policy"),policy.setAttribute("content",EPUB_CHAPTER_CONTENT_SECURITY_POLICY),head.insertBefore(policy,head.firstChild)}function registerNetworkSilentChapters(book){const contentHooks=inheritedDataValue(inheritedDataValue(book.spine,"hooks"),"content");savedCallable(contentHooks,"register")?.(silenceChapterNetwork)}function normalizeBook(value){if(!isObjectValue(value))return;const ready=savedThenable(inheritedDataValue(value,"ready")),renderTo=savedCallable(value,"renderTo"),destroy=savedCallable(value,"destroy");if(!ready||!renderTo||!destroy)return;let navigationCaptured=!1,navigation;const getNavigation=()=>(navigationCaptured||(navigationCaptured=!0,navigation=inheritedDataValue(value,"navigation")),navigation),spine=inheritedDataValue(value,"spine"),load=savedCallable(value,"load");return Object.freeze({ready,...spine===void 0?{}:{spine},...load===void 0?{}:{load},getNavigation,renderTo:(element,options)=>renderTo(element,options),destroy:()=>{destroy()}})}function normalizeRendition(value){if(!isObjectValue(value))return;const display=savedCallable(value,"display"),prev=savedCallable(value,"prev"),next=savedCallable(value,"next"),on=savedCallable(value,"on"),annotationsValue=inheritedDataValue(value,"annotations"),highlight=savedCallable(annotationsValue,"highlight"),remove=savedCallable(annotationsValue,"remove");if(!(!display||!prev||!next||!on||!highlight||!remove))return Object.freeze({display:target=>taskFrom(display,target),prev:()=>taskFrom(prev),next:()=>taskFrom(next),on:(type,callback)=>{on(type,callback)},annotations:Object.freeze({highlight:(cfi,data,callback,className,styles2)=>highlight(cfi,data,callback,className,styles2),remove:(cfi,type)=>{remove(cfi,type)}})})}function normalizeSpineItem(value){const load=savedCallable(value,"load"),find=savedCallable(value,"find"),unload=savedCallable(value,"unload");if(!(!load||!find||!unload))return Object.freeze({load:request=>load(request),find:query=>find(query),unload:()=>{unload()}})}function projectSpineItems(book){const spineItems=inheritedDataValue(book.spine,"spineItems");if(!isArrayValue(spineItems))return Object.freeze({items:Object.freeze([]),exact:spineItems===void 0});const length=getOwnDataDescriptor(spineItems,"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({items:Object.freeze([]),exact:!1});const items=[];let exact=length.value<=MAX_SEARCH_SPINE_ITEMS;const count=Math.min(length.value,MAX_SEARCH_SPINE_ITEMS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(spineItems,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){exact=!1;continue}const item=normalizeSpineItem(descriptor.value);if(!item){exact=!1;continue}items.push(item)}return Object.freeze({items:Object.freeze(items),exact})}function projectFindResults(value,work){if(!isArrayValue(value))return Object.freeze({matches:Object.freeze([]),exact:!1});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({matches:Object.freeze([]),exact:!1});const matches=[];let exact=length.value<=MAX_FIND_RESULTS;const count=Math.min(length.value,MAX_FIND_RESULTS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(descriptor.value)){exact=!1;continue}const cfi=getOwnDataDescriptor(descriptor.value,"cfi"),excerpt=getOwnDataDescriptor(descriptor.value,"excerpt");if(cfi===MISSING_OWN_DATA_DESCRIPTOR||cfi===UNSAFE_OWN_DATA_DESCRIPTOR||typeof cfi.value!="string"){exact=!1;continue}if(!work.canConsume(cfi.value)||!work.consume(cfi.value)||cfi.value.trim()===""){exact=!1;continue}let excerptValue="";excerpt!==MISSING_OWN_DATA_DESCRIPTOR&&(excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"||!work.canConsume(excerpt.value)||!work.consume(excerpt.value)?exact=!1:excerptValue=excerpt.value),matches.push({cfi:cfi.value,excerpt:excerptValue})}return Object.freeze({matches:Object.freeze(matches),exact})}function pushTocEntries(value,level,budget,stack){if(!isArrayValue(value)||budget.positions>=MAX_TOC_ITEMS)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 count=Math.min(length.value,MAX_TOC_ITEMS-budget.positions);for(let index=count-1;index>=0;index-=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||stack.push({value:descriptor.value,level})}}function projectToc(value){const budget={positions:0,nodes:0,seen:new WeakSet},stack=[];pushTocEntries(value,1,budget,stack);const items=[];for(;stack.length>0&&budget.nodes<MAX_TOC_ITEMS;){const current=stack.pop();if(!isObjectValue(current.value)||budget.seen.has(current.value))continue;budget.seen.add(current.value),budget.nodes+=1;const href=getOwnDataDescriptor(current.value,"href"),id=getOwnDataDescriptor(current.value,"id"),label=getOwnDataDescriptor(current.value,"label"),children=getOwnDataDescriptor(current.value,"subitems");if(href!==MISSING_OWN_DATA_DESCRIPTOR&&href!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof href.value=="string"){const idValue=id!==MISSING_OWN_DATA_DESCRIPTOR&&id!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof id.value=="string"&&id.value!==""?id.value:href.value,labelValue=label!==MISSING_OWN_DATA_DESCRIPTOR&&label!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof label.value=="string"?label.value.trim():"";items.push({id:idValue,label:labelValue,href:href.value,level:current.level})}current.level<MAX_TOC_DEPTH&&children!==MISSING_OWN_DATA_DESCRIPTOR&&children!==UNSAFE_OWN_DATA_DESCRIPTOR&&pushTocEntries(children.value,current.level+1,budget,stack)}return Object.freeze(items)}const TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:DEFAULT_CANVAS_COLOR};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerMissingLibrary:LYRA_DEFAULT_ebookViewerMissingLibrary,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}constructor(){super(),this.src="",this.name="",this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.failedGeneration=-1,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.chapterButtonFocused=!1,this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.chapterButtonFocused&&this.ebookState.kind!=="ready"&&this.shadowRoot?.querySelector('[part="mount"]')?.focus(),this.chapterButtonFocused=!1,this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();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);const active=shadowFocusTarget(this);this.chapterButtonFocused=active?.localName==="button"&&!active.disabled&&active.getAttribute("part")?.endsWith("-button")===!0,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}connectedMoveCallback(){}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.destroyBook(this.book),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}destroyBook(book){try{book?.destroy()}catch{}}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}isCurrentBookRendition(generation,ownerView,book,rendition){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView&&this.book===book&&this.rendition===rendition}failCurrentLoad(error,message=this.localize("ebookViewerLoadError")){this.failedGeneration!==this.generation&&(this.failedGeneration=this.generation,this.ebookState={kind:"error",message},this.emit("lr-render-error",{error}))}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isCurrentLoad(generation,fetchTarget.view)||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isCurrentLoad(generation,fetchTarget.view)))return}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error,this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError"));return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerMissingLibrary"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=normalizeBook(factory(data));if(!book)throw new Error("EPUB peer returned an unusable book.");candidateBook=book,registerNetworkSilentChapters(book);const rawRendition=book.renderTo(mount,{width:"100%",height:"100%"});guardEpubUnloadListener({settings:inheritedDataValue(rawRendition,"settings"),requireManager:savedCallable(rawRendition,"requireManager")});const rendition=normalizeRendition(rawRendition);if(!rendition)throw new Error("EPUB peer returned an unusable rendition.");if(await book.ready,!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}if(book.getNavigation(),await rendition.display(this.location||void 0),!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}rendition.on("relocated",loc=>{if(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition))return;const start=inheritedDataValue(loc,"start"),cfi=inheritedDataValue(start,"cfi"),href=inheritedDataValue(start,"href");typeof cfi!="string"||cfi.trim()===""||!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href:typeof href=="string"?href:""}))}),rendition.on("selected",(cfiRange,contents)=>{if(!(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition)||typeof cfiRange!="string"))try{const contentsWindow=inheritedDataValue(contents,"window"),selection=savedCallable(contentsWindow,"getSelection")?.(),range=this.selectedRange(selection);if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contentsWindow);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}catch{}}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(this.destroyBook(candidateBook),isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error)}}selectedRange(selection){const prototype=this.ownerDocument.defaultView?.Selection.prototype;if(prototype)try{const count2=Object.getOwnPropertyDescriptor(prototype,"rangeCount")?.get?.call(selection);if(typeof count2=="number")return count2>0?prototype.getRangeAt.call(selection,0):null}catch{}const count=inheritedDataValue(selection,"rangeCount"),getRangeAt=savedCallable(selection,"getRangeAt");return typeof count=="number"&&count>0&&getRangeAt?getRangeAt(0):null}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.failCurrentLoad(error,message)}reportRenditionFailure(error,rendition,generation,ownerView=this.ownerDocument.defaultView){!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==ownerView||rendition!==this.rendition||this.failCurrentLoad(error)}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&¤t!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async getToc(){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!book||!ownerView)return[];try{await book.ready}catch{return[]}return!this.isCurrentLoad(generation,ownerView)||this.book!==book?[]:[...projectToc(inheritedDataValue(book.getNavigation(),"toc"))]}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView,book=this.book,rendition=this.rendition;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){return operation!==this.anchorOperationGeneration||!ownerView||!this.isCurrentLoad(generation,ownerView)||this.book!==book||this.rendition!==rendition||(rendition&&this.reportRenditionFailure(error,rendition,generation,ownerView),this.emit("lr-anchor-result",{found:!1})),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!rendition||!ownerView)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor);return!cfi||operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition)}return!1}async findTextQuoteCfi(anchor){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,quote=anchor.quote.trim(),boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!ownerView||!boundedQuery.accepted||!boundedQuery.needle)return null;const fullContextScore=(anchor.prefix?.trim()?1:0)+(anchor.suffix?.trim()?1:0);let bestMatch=null,bestScore=-1;const work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);for(const item of spine.items){if(!work.consume(""))return bestMatch;let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;const{value:rawResults}=await awaitPeerResult(item.find(quote)),results=projectFindResults(rawResults,work);if(!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;for(const result of results.matches){if(!work.consume(""))return bestMatch;const score=fullContextScore===0?0:quoteContextScore(result.excerpt,quote,anchor.prefix,anchor.suffix);if(score===fullContextScore)return result.cfi;score>bestScore&&(bestMatch=result.cfi,bestScore=score)}}catch{continue}finally{if(loaded)try{item.unload()}catch{}}}return bestMatch}repaintHighlights(){const rendition=this.rendition;if(!rendition)return;const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;const fillCache=new Map,resolveFill=pair=>{let value=fillCache.get(pair.token);return value===void 0&&(value=this.resolveHighlightFill(pair).fill,fillCache.set(pair.token,value)),value};for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2={fill:resolveFill(TONE_FILL_TOKEN[tone])};if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":resolveFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN),styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}rendition.annotations.highlight(cfi,{id:highlight.id},()=>{!book||!ownerView||!this.isCurrentBookRendition(generation,ownerView,book,rendition)||this.emit("lr-highlight-activate",{highlightId:highlight.id})},active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,ownerView=this.ownerDocument.defaultView,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!ownerView||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);spine.exact||(matchCountExact=!1);for(const item of spine.items){if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;const{value:rawResults}=await awaitPeerResult(item.find(query.trim())),results=projectFindResults(rawResults,work);if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;results.exact||(matchCountExact=!1);for(const r of results.matches){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push(r)}}catch{matchCountExact=!1;continue}finally{if(loaded)try{item.unload()}catch{matchCountExact=!1}}if(matchCeilingExceeded)break}return generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation,ownerView),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){const cfi=this.searchAnnotationCfi;this.searchAnnotationCfi=void 0;const rendition=this.rendition,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!(!cfi||!rendition||!ownerView))try{rendition.annotations.remove(cfi,"highlight")}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async showSearchMatch(index,generation=this.searchGeneration,ownerView=this.ownerDocument.defaultView){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration||!ownerView||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.ownerDocument.defaultView===ownerView&&this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?renderViewerLoading(this.localize("loadingDocument")):this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const maxHeight=sanitizeCssLength(this.maxHeight),disabled=this.ebookState.kind!=="ready";return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DEFAULT_CANVAS_COLOR}from"../../../internal/canvas-color.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{guardEpubUnloadListener}from"./epub-unload-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerMissingLibrary,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_FIND_RESULTS=1e4,MAX_PAINTED_HIGHLIGHTS=100,MAX_PEER_PROTOTYPES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function inheritedDataDescriptor(value,key){let current=value;for(let depth=0;current&&depth<MAX_PEER_PROTOTYPES;depth+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(current,key)}catch{return}if(descriptor)return"value"in descriptor?descriptor:void 0;try{current=Object.getPrototypeOf(current)}catch{return}}}function inheritedDataValue(value,key){return isObjectValue(value)?inheritedDataDescriptor(value,key)?.value:void 0}function savedCallable(value,key){if(!isObjectValue(value))return;const candidate=inheritedDataDescriptor(value,key)?.value;if(typeof candidate=="function")return(...args)=>Reflect.apply(candidate,value,args)}function savedThenable(value){const then=savedCallable(value,"then");if(then)return new Promise((resolve,reject)=>{try{then(()=>resolve(),reject)}catch(error){reject(error)}})}function taskFrom(call,...args){try{return savedThenable(call(...args))??Promise.resolve()}catch(error){return Promise.reject(error)}}function awaitPeerResult(value){const then=savedCallable(value,"then"),wrap=resolved=>Object.freeze({value:resolved});return then?new Promise((resolve,reject)=>{try{then(resolved=>resolve(wrap(resolved)),reject)}catch(error){reject(error)}}):Promise.resolve(wrap(value))}function quoteContextScore(excerpt,quote,prefix,suffix){const text=excerpt.replace(/\s+/g," ").toLowerCase(),needle=quote.replace(/\s+/g," ").toLowerCase();let best=0;for(let at=text.indexOf(needle);at>=0;at=text.indexOf(needle,at+1))best=Math.max(best,textQuoteContextScore(text,at,at+needle.length,prefix,suffix));return best}const EPUB_CHAPTER_CONTENT_SECURITY_POLICY="default-src 'none'; img-src blob: data:; media-src blob: data:; font-src blob: data:; style-src blob: 'unsafe-inline'";function silenceChapterNetwork(chapter){const root=chapter.documentElement;if(!root)return;for(const node of[...chapter.childNodes])node.nodeType===Node.PROCESSING_INSTRUCTION_NODE&&chapter.removeChild(node);for(const element of[...chapter.querySelectorAll("link, meta")]){const rel=` ${(element.getAttribute("rel")??"").toLowerCase()} `;(/ (?:dns-prefetch|preconnect) /.test(rel)||(element.getAttribute("http-equiv")??"").trim().toLowerCase()==="refresh")&&element.remove()}const namespace=root.namespaceURI??"http://www.w3.org/1999/xhtml";let head=chapter.querySelector("head");head||(head=chapter.createElementNS(namespace,"head"),root.insertBefore(head,root.firstChild));const policy=chapter.createElementNS(namespace,"meta");policy.setAttribute("http-equiv","Content-Security-Policy"),policy.setAttribute("content",EPUB_CHAPTER_CONTENT_SECURITY_POLICY),head.insertBefore(policy,head.firstChild)}function registerNetworkSilentChapters(book){const contentHooks=inheritedDataValue(inheritedDataValue(book.spine,"hooks"),"content");savedCallable(contentHooks,"register")?.(silenceChapterNetwork)}function normalizeBook(value){if(!isObjectValue(value))return;const ready=savedThenable(inheritedDataValue(value,"ready")),renderTo=savedCallable(value,"renderTo"),destroy=savedCallable(value,"destroy");if(!ready||!renderTo||!destroy)return;let navigationCaptured=!1,navigation;const getNavigation=()=>(navigationCaptured||(navigationCaptured=!0,navigation=inheritedDataValue(value,"navigation")),navigation),spine=inheritedDataValue(value,"spine"),load=savedCallable(value,"load");return Object.freeze({ready,...spine===void 0?{}:{spine},...load===void 0?{}:{load},getNavigation,renderTo:(element,options)=>renderTo(element,options),destroy:()=>{destroy()}})}function normalizeRendition(value){if(!isObjectValue(value))return;const display=savedCallable(value,"display"),prev=savedCallable(value,"prev"),next=savedCallable(value,"next"),on=savedCallable(value,"on"),annotationsValue=inheritedDataValue(value,"annotations"),highlight=savedCallable(annotationsValue,"highlight"),remove=savedCallable(annotationsValue,"remove");if(!(!display||!prev||!next||!on||!highlight||!remove))return Object.freeze({display:target=>taskFrom(display,target),prev:()=>taskFrom(prev),next:()=>taskFrom(next),on:(type,callback)=>{on(type,callback)},annotations:Object.freeze({highlight:(cfi,data,callback,className,styles2)=>highlight(cfi,data,callback,className,styles2),remove:(cfi,type)=>{remove(cfi,type)}})})}function normalizeSpineItem(value){const load=savedCallable(value,"load"),find=savedCallable(value,"find"),unload=savedCallable(value,"unload");if(!(!load||!find||!unload))return Object.freeze({load:request=>load(request),find:query=>find(query),unload:()=>{unload()}})}function projectSpineItems(book){const spineItems=inheritedDataValue(book.spine,"spineItems");if(!isArrayValue(spineItems))return Object.freeze({items:Object.freeze([]),exact:spineItems===void 0});const length=getOwnDataDescriptor(spineItems,"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({items:Object.freeze([]),exact:!1});const items=[];let exact=length.value<=MAX_SEARCH_SPINE_ITEMS;const count=Math.min(length.value,MAX_SEARCH_SPINE_ITEMS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(spineItems,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){exact=!1;continue}const item=normalizeSpineItem(descriptor.value);if(!item){exact=!1;continue}items.push(item)}return Object.freeze({items:Object.freeze(items),exact})}function projectFindResults(value,work){if(!isArrayValue(value))return Object.freeze({matches:Object.freeze([]),exact:!1});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({matches:Object.freeze([]),exact:!1});const matches=[];let exact=length.value<=MAX_FIND_RESULTS;const count=Math.min(length.value,MAX_FIND_RESULTS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(descriptor.value)){exact=!1;continue}const cfi=getOwnDataDescriptor(descriptor.value,"cfi"),excerpt=getOwnDataDescriptor(descriptor.value,"excerpt");if(cfi===MISSING_OWN_DATA_DESCRIPTOR||cfi===UNSAFE_OWN_DATA_DESCRIPTOR||typeof cfi.value!="string"){exact=!1;continue}if(!work.canConsume(cfi.value)||!work.consume(cfi.value)||cfi.value.trim()===""){exact=!1;continue}let excerptValue="";excerpt!==MISSING_OWN_DATA_DESCRIPTOR&&(excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"||!work.canConsume(excerpt.value)||!work.consume(excerpt.value)?exact=!1:excerptValue=excerpt.value),matches.push({cfi:cfi.value,excerpt:excerptValue})}return Object.freeze({matches:Object.freeze(matches),exact})}function pushTocEntries(value,level,budget,stack){if(!isArrayValue(value)||budget.positions>=MAX_TOC_ITEMS)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 count=Math.min(length.value,MAX_TOC_ITEMS-budget.positions);for(let index=count-1;index>=0;index-=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||stack.push({value:descriptor.value,level})}}function projectToc(value){const budget={positions:0,nodes:0,seen:new WeakSet},stack=[];pushTocEntries(value,1,budget,stack);const items=[];for(;stack.length>0&&budget.nodes<MAX_TOC_ITEMS;){const current=stack.pop();if(!isObjectValue(current.value)||budget.seen.has(current.value))continue;budget.seen.add(current.value),budget.nodes+=1;const href=getOwnDataDescriptor(current.value,"href"),id=getOwnDataDescriptor(current.value,"id"),label=getOwnDataDescriptor(current.value,"label"),children=getOwnDataDescriptor(current.value,"subitems");if(href!==MISSING_OWN_DATA_DESCRIPTOR&&href!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof href.value=="string"){const idValue=id!==MISSING_OWN_DATA_DESCRIPTOR&&id!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof id.value=="string"&&id.value!==""?id.value:href.value,labelValue=label!==MISSING_OWN_DATA_DESCRIPTOR&&label!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof label.value=="string"?label.value.trim():"";items.push({id:idValue,label:labelValue,href:href.value,level:current.level})}current.level<MAX_TOC_DEPTH&&children!==MISSING_OWN_DATA_DESCRIPTOR&&children!==UNSAFE_OWN_DATA_DESCRIPTOR&&pushTocEntries(children.value,current.level+1,budget,stack)}return Object.freeze(items)}const TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:DEFAULT_CANVAS_COLOR};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerMissingLibrary:LYRA_DEFAULT_ebookViewerMissingLibrary,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}constructor(){super(),this.src="",this.name="",this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.failedGeneration=-1,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.chapterButtonFocused=!1,this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.chapterButtonFocused&&this.ebookState.kind!=="ready"&&this.shadowRoot?.querySelector('[part="mount"]')?.focus(),this.chapterButtonFocused=!1,this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();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);const active=shadowFocusTarget(this);this.chapterButtonFocused=active?.localName==="button"&&!active.disabled&&active.getAttribute("part")?.endsWith("-button")===!0,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src?.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}connectedMoveCallback(){}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.destroyBook(this.book),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}destroyBook(book){try{book?.destroy()}catch{}}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}isCurrentBookRendition(generation,ownerView,book,rendition){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView&&this.book===book&&this.rendition===rendition}failCurrentLoad(error,message=this.localize("ebookViewerLoadError")){this.failedGeneration!==this.generation&&(this.failedGeneration=this.generation,this.ebookState={kind:"error",message},this.emit("lr-render-error",{error}))}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src?.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isCurrentLoad(generation,fetchTarget.view)||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isCurrentLoad(generation,fetchTarget.view)))return}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error,this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError"));return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerMissingLibrary"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=normalizeBook(factory(data));if(!book)throw new Error("EPUB peer returned an unusable book.");candidateBook=book,registerNetworkSilentChapters(book);const rawRendition=book.renderTo(mount,{width:"100%",height:"100%"});guardEpubUnloadListener({settings:inheritedDataValue(rawRendition,"settings"),requireManager:savedCallable(rawRendition,"requireManager")});const rendition=normalizeRendition(rawRendition);if(!rendition)throw new Error("EPUB peer returned an unusable rendition.");if(await book.ready,!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}if(book.getNavigation(),await rendition.display(this.location||void 0),!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}rendition.on("relocated",loc=>{if(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition))return;const start=inheritedDataValue(loc,"start"),cfi=inheritedDataValue(start,"cfi"),href=inheritedDataValue(start,"href");typeof cfi!="string"||cfi.trim()===""||!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href:typeof href=="string"?href:""}))}),rendition.on("selected",(cfiRange,contents)=>{if(!(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition)||typeof cfiRange!="string"))try{const contentsWindow=inheritedDataValue(contents,"window"),selection=savedCallable(contentsWindow,"getSelection")?.(),range=this.selectedRange(selection);if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contentsWindow);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}catch{}}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(this.destroyBook(candidateBook),isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error)}}selectedRange(selection){const prototype=this.ownerDocument.defaultView?.Selection.prototype;if(prototype)try{const count2=Object.getOwnPropertyDescriptor(prototype,"rangeCount")?.get?.call(selection);if(typeof count2=="number")return count2>0?prototype.getRangeAt.call(selection,0):null}catch{}const count=inheritedDataValue(selection,"rangeCount"),getRangeAt=savedCallable(selection,"getRangeAt");return typeof count=="number"&&count>0&&getRangeAt?getRangeAt(0):null}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.failCurrentLoad(error,message)}reportRenditionFailure(error,rendition,generation,ownerView=this.ownerDocument.defaultView){!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==ownerView||rendition!==this.rendition||this.failCurrentLoad(error)}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&¤t!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async getToc(){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!book||!ownerView)return[];try{await book.ready}catch{return[]}return!this.isCurrentLoad(generation,ownerView)||this.book!==book?[]:[...projectToc(inheritedDataValue(book.getNavigation(),"toc"))]}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView,book=this.book,rendition=this.rendition;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){return operation!==this.anchorOperationGeneration||!ownerView||!this.isCurrentLoad(generation,ownerView)||this.book!==book||this.rendition!==rendition||(rendition&&this.reportRenditionFailure(error,rendition,generation,ownerView),this.emit("lr-anchor-result",{found:!1})),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!rendition||!ownerView)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor);return!cfi||operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition)}return!1}async findTextQuoteCfi(anchor){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,quote=anchor.quote.trim(),boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!ownerView||!boundedQuery.accepted||!boundedQuery.needle)return null;const fullContextScore=(anchor.prefix?.trim()?1:0)+(anchor.suffix?.trim()?1:0);let bestMatch=null,bestScore=-1;const work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);for(const item of spine.items){if(!work.consume(""))return bestMatch;let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;const{value:rawResults}=await awaitPeerResult(item.find(quote)),results=projectFindResults(rawResults,work);if(!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;for(const result of results.matches){if(!work.consume(""))return bestMatch;const score=fullContextScore===0?0:quoteContextScore(result.excerpt,quote,anchor.prefix,anchor.suffix);if(score===fullContextScore)return result.cfi;score>bestScore&&(bestMatch=result.cfi,bestScore=score)}}catch{continue}finally{if(loaded)try{item.unload()}catch{}}}return bestMatch}repaintHighlights(){const rendition=this.rendition;if(!rendition)return;const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;const fillCache=new Map,resolveFill=pair=>{let value=fillCache.get(pair.token);return value===void 0&&(value=this.resolveHighlightFill(pair).fill,fillCache.set(pair.token,value)),value};for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2={fill:resolveFill(TONE_FILL_TOKEN[tone])};if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":resolveFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN),styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}rendition.annotations.highlight(cfi,{id:highlight.id},()=>{!book||!ownerView||!this.isCurrentBookRendition(generation,ownerView,book,rendition)||this.emit("lr-highlight-activate",{highlightId:highlight.id})},active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,ownerView=this.ownerDocument.defaultView,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!ownerView||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);spine.exact||(matchCountExact=!1);for(const item of spine.items){if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;const{value:rawResults}=await awaitPeerResult(item.find(query.trim())),results=projectFindResults(rawResults,work);if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;results.exact||(matchCountExact=!1);for(const r of results.matches){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push(r)}}catch{matchCountExact=!1;continue}finally{if(loaded)try{item.unload()}catch{matchCountExact=!1}}if(matchCeilingExceeded)break}return generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation,ownerView),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){const cfi=this.searchAnnotationCfi;this.searchAnnotationCfi=void 0;const rendition=this.rendition,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!(!cfi||!rendition||!ownerView))try{rendition.annotations.remove(cfi,"highlight")}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async showSearchMatch(index,generation=this.searchGeneration,ownerView=this.ownerDocument.defaultView){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration||!ownerView||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.ownerDocument.defaultView===ownerView&&this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?renderViewerLoading(this.localize("loadingDocument")):this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const maxHeight=sanitizeCssLength(this.maxHeight),disabled=this.ebookState.kind!=="ready";return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
|
|
@@ -81,4 +81,4 @@ foldQuotes:boolean;
|
|
|
81
81
|
/** Shared text search and anchor-target API for message body text. Searching for text
|
|
82
82
|
* inside a folded quote reveals matching quotes before navigating the active match, using the
|
|
83
83
|
* same bounded Unicode/whitespace normalization and locale matching as the shared text index. */
|
|
84
|
-
search(query:string):Promise<number>;searchNext():Promise<boolean>;searchPrevious():Promise<boolean>;clearSearch():void;private searchDocument?;private fetchState;private textQuoteExpanded;private expandedHtmlQuoteIndices;private generation;private lastLoadSrc;private readonly announcements;private foldedHtmlCache;protected textContentRoot():Element|null;protected buildTextScope(root:Element):ReturnType<typeof scopeFromElement>;connectedCallback():void;private readonly detached;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private load;private failWithLocalizedMessage;private isCurrentLoad;private parse;private formatAddress;private formatAddresses;private formatDate;private renderHeaders;private renderAttachments;private renderTextBody;private onBodyClick;private getFoldedHtml;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-email-viewer':LyraEmailViewer;}}export{};
|
|
84
|
+
search(query:string):Promise<number>;searchNext():Promise<boolean>;searchPrevious():Promise<boolean>;clearSearch():void;private searchDocument?;private fetchState;private textQuoteExpanded;private expandedHtmlQuoteIndices;private generation;private pendingTransportGeneration;private lastLoadSrc;private readonly announcements;private foldedHtmlCache;protected textContentRoot():Element|null;protected buildTextScope(root:Element):ReturnType<typeof scopeFromElement>;connectedCallback():void;private readonly detached;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private load;private failWithLocalizedMessage;private isCurrentLoad;private parse;private formatAddress;private formatAddresses;private formatDate;private renderHeaders;private renderAttachments;private renderTextBody;private onBodyClick;private getFoldedHtml;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-email-viewer':LyraEmailViewer;}}export{};
|