@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,5 +1,5 @@
|
|
|
1
1
|
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_pdfViewerCurrentZoom,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_loadingDocument,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings/viewers.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,MAX_PDF_CANVAS_PIXELS=16777216,MAX_PDF_CANVAS_DIMENSION=16384,TOOLBAR_FOCUS_TWINS=new Map([["previous-button","next-button"],["next-button","previous-button"],["zoom-out-button","zoom-in-button"],["zoom-in-button","zoom-out-button"]]),PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
|
|
2
|
-
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length,retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function boundedPdfCanvas(canvas,viewport){return resolveBoundedCanvasAllocation({cssWidth:viewport.width,cssHeight:viewport.height,desiredScale:canvas.ownerDocument.defaultView?.devicePixelRatio||1,maxDimension:MAX_PDF_CANVAS_DIMENSION,maxPixels:MAX_PDF_CANVAS_PIXELS})}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerState=new PageViewerSnapshotController,this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchState=new ViewerSearchState(()=>[],detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.focusedToolbarPart=null,this.detached=new DeferredTeardown(()=>this.teardownDetachedDocument()),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
|
|
2
|
+
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length,retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function boundedPdfCanvas(canvas,viewport){return resolveBoundedCanvasAllocation({cssWidth:viewport.width,cssHeight:viewport.height,desiredScale:canvas.ownerDocument.defaultView?.devicePixelRatio||1,maxDimension:MAX_PDF_CANVAS_DIMENSION,maxPixels:MAX_PDF_CANVAS_PIXELS})}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerState=new PageViewerSnapshotController,this.scrollDrivenPage=!1,this.firstVisiblePage=1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchState=new ViewerSearchState(()=>[],detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.focusedToolbarPart=null,this.detached=new DeferredTeardown(()=>this.teardownDetachedDocument()),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
|
|
3
3
|
<canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
|
|
4
4
|
<div part="page-error" hidden></div>
|
|
5
5
|
<lr-highlight-layer
|
|
@@ -8,7 +8,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
8
8
|
@lr-highlight-activate=${this.onHighlightLayerActivate}
|
|
9
9
|
></lr-highlight-layer>
|
|
10
10
|
<div part="text-layer" ${ref(this.textLayerContainerRef(number))}></div>
|
|
11
|
-
</div>`},this.onVisibleRangeChanged=event=>{if(event.stopPropagation(),this.loadState.kind!=="ready")return;const next=this.clampPage(event.detail.start+1);next!==this.page&&(this.scrollDrivenPage=!0,this.page=next)},this.stopInternalEvent=event=>{event.stopPropagation()}}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,loadingDocument:LYRA_DEFAULT_loadingDocument,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,pdfViewerLabel:LYRA_DEFAULT_pdfViewerLabel,pdfViewerMissingLibrary:LYRA_DEFAULT_pdfViewerMissingLibrary,pdfViewerNextPage:LYRA_DEFAULT_pdfViewerNextPage,pdfViewerPageOf:LYRA_DEFAULT_pdfViewerPageOf,pdfViewerPreviousPage:LYRA_DEFAULT_pdfViewerPreviousPage,pdfViewerZoomIn:LYRA_DEFAULT_pdfViewerZoomIn,pdfViewerZoomOut:LYRA_DEFAULT_pdfViewerZoomOut,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}get searchMatches(){return this.searchState.matches}set searchMatches(matches){this.searchState.matches=matches}get searchActiveIndex(){return this.searchState.activeIndex}set searchActiveIndex(index){this.searchState.activeIndex=index}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}keepToolbarFocus(){const part=this.focusedToolbarPart;this.focusedToolbarPart=null;const twin=part===null?void 0:TOOLBAR_FOCUS_TWINS.get(part),root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedToolbarPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("page")&&(this.page=this.clampPage(this.page)),changed.has("page")&&!changed.has("scrollDrivenPage")&&(this.scrollDrivenPage=!1),changed.has("zoom")){this.zoom=clampZoom(this.zoom);for(const[pageNumber,canvas]of this.pageCanvases)this.renderPage(pageNumber,canvas)}changed.has("src")&&(this.pendingSearchResetEvent||=this.searchState.dirty,this.resetSearchState())}updated(changed){super.updated(changed),this.keepToolbarFocus();const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear()),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&(this.scheduleAfterUpdate(()=>{this.load()},"pdf-load"),this.pageHighlightItems.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.searchState.emit())),changed.has("page")&&this.loadState.kind==="ready"&&(changed.get("page")!==this.page&&this.emit("lr-page-change",{page:this.page,pageCount:this.loadState.pageCount}),this.publishPageViewerSnapshot("ready",this.loadState.pageCount)),changed.has("zoom")&&changed.get("zoom")!==void 0&&changed.get("zoom")!==this.zoom&&this.emit("lr-zoom-change",{zoom:this.zoom}),(changed.has("highlights")||changed.has("activeHighlightId")||localeChanged)&&this.resolveMountedPageHighlights(),changed.has("activeHighlightId"))for(const layer of this.pageHighlightLayerElements.values())layer.activeHighlightId=this.activeHighlightId;localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();if(this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}teardownDetachedDocument(){this.generation++,this.retirePendingDocument(),this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits();for(const task of this.pageRenderTasks.values())task.cancel();for(const layer of this.textLayers.values())layer.cancel();for(const task of this.thumbnailRenderTasks.values())task.cancel();this.pageRenderTasks.clear(),this.pageRenderVersions.clear(),this.textLayers.clear(),this.pageCanvases.clear(),this.textLayerContainers.clear(),this.textLayerReadyPromises.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.thumbnailRenderTasks.clear(),this.thumbnailRenderVersions.clear(),this.destroyLoadedDoc(),this.loadState={kind:"idle"},this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.loadState.doc.destroy?.()}retirePendingDocument(){const pending=this.pendingDocument;if(this.pendingDocument=void 0,!(!pending||pending.retired)){pending.retired=!0;try{Promise.resolve(pending.task.destroy?.()).catch(()=>{})}catch{}}}clampPage(value){const pageCount=this.loadState.kind==="ready"?this.loadState.pageCount:1,rounded=Math.round(finiteNumber(value,1));return finiteRange(rounded,1,1,pageCount)}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,this.clampPage(this.page),finiteCount(pageCount,0,MAX_PAGE_COUNT));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pdfPageSourceCount&&(this.pdfPageSourceCount=count,this.pdfPageSource=this.createPageSource(count)),this.pdfPageSource}async load(){const generation=++this.generation;this.retirePendingDocument(),this.pageViewerState.advance();const signal=this.beginAbortableLoad();if(this.destroyLoadedDoc(),!this.src){this.loadState={kind:"idle"},this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"},this.publishPageViewerSnapshot("loading",0);try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const data=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const pdfjsLib=await this.loadLibrary(this.workerSrc||null);if(!this.isConnected||generation!==this.generation)return;if(!pdfjsLib){const error=new LyraUserFacingError(this.localize("pdfViewerMissingLibrary"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}const pending={task:pdfjsLib.getDocument({data}),retired:!1};this.pendingDocument=pending;let doc;try{doc=await pending.task.promise}catch(error){throw this.pendingDocument===pending&&this.retirePendingDocument(),error}if(this.pendingDocument===pending&&(this.pendingDocument=void 0),!this.isConnected||generation!==this.generation){(!pending.retired||!pending.task.destroy)&&await doc.destroy?.();return}const pageCount=finiteCount(doc.numPages,0,MAX_PAGE_COUNT);if(pageCount<1||pageCount!==doc.numPages)throw await doc.destroy?.(),new LyraUserFacingError(this.localize("documentPreviewResourceTooLarge"));this.page=1,this.loadState={kind:"ready",doc,pageCount},this.publishPageViewerSnapshot("ready",pageCount),this.emit("lr-load",{pageCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}nextPage(){this.scrollDrivenPage=!1,this.setPage(this.page+1)}previousPage(){this.scrollDrivenPage=!1,this.setPage(this.page-1)}zoomIn(){this.setZoom(this.zoom+ZOOM_STEP)}zoomOut(){this.setZoom(this.zoom-ZOOM_STEP)}async goToPage(page){return this.loadState.kind!=="ready"||!Number.isInteger(page)||page<1||page>this.loadState.pageCount?!1:page===this.page&&this.pageCanvases.has(page)?!0:(this.scrollDrivenPage=!1,this.page=page,await this.updateComplete,this.waitForPageMount(page))}waitForPageMount(page){if(this.pageCanvases.has(page))return Promise.resolve(!0);const list=this.shadowRoot?.querySelector(tag("virtual-list")),view=this.ownerDocument.defaultView;return!list||!view?Promise.resolve(!1):new Promise(resolve=>{let settled=!1,timeoutId,cancel;const finish=mounted=>{settled||(settled=!0,list.removeEventListener("lr-visible-range-change",onRange),timeoutId!==void 0&&view.clearTimeout(timeoutId),this.pendingPageMountWaitCancels.delete(cancel),resolve(mounted))},onRange=()=>{this.pageCanvases.has(page)&&finish(!0)};cancel=()=>finish(!1),this.pendingPageMountWaitCancels.add(cancel),list.addEventListener("lr-visible-range-change",onRange),timeoutId=view.setTimeout(()=>finish(!1),500)})}setPage(value){const next=this.clampPage(value);next!==this.page&&(this.page=next)}setZoom(value){const next=clampZoom(value);next!==this.zoom&&(this.zoom=next)}async scrollToAnchor(target){return this.anchorOperationGeneration++,super.scrollToAnchor(target)}async applyAnchor(anchor){if(this.loadState.kind!=="ready")return!1;const doc=this.loadState.doc,operation=this.anchorOperationGeneration;switch(anchor.kind){case"page":return!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,this.isCurrentAnchorOperation(operation,doc)&&this.pageCanvases.has(anchor.page));case"text-quote":return this.applyTextQuoteAnchor(anchor,operation,doc);case"region":return this.applyRegionAnchor(anchor,operation,doc);default:return!1}}isCurrentAnchorOperation(operation,doc){return operation===this.anchorOperationGeneration&&this.loadState.kind==="ready"&&this.loadState.doc===doc}*pageSearchOrder(hint,pageCount){if(hint==null){for(let page=1;page<=pageCount;page++)yield page;return}const clampedHint=Math.min(pageCount,Math.max(1,Math.round(hint)));yield clampedHint;for(let delta=1;delta<pageCount;delta++)clampedHint-delta>=1&&(yield clampedHint-delta),clampedHint+delta<=pageCount&&(yield clampedHint+delta)}async applyTextQuoteAnchor(anchor,operation,doc){if(!this.isCurrentAnchorOperation(operation,doc)||this.loadState.kind!=="ready"||anchor.quote.length>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.prefix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.suffix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||!normalizeQuoteText(anchor.quote))return!1;const order=this.pageSearchOrder(anchor.page,this.loadState.pageCount);let matchedPage,inspectedPages=0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(const pageNumber of order){if(inspectedPages++>=MAX_SEARCH_PAGES||remainingCorpus<=0||remainingNormalizationWork<=0||workBudget.remainingCodeUnits<=0)break;let pageIndex=this.mountedPageTextIndex(pageNumber);if(!pageIndex){let text;try{text=await this.getPageText(pageNumber)}catch{continue}if(!this.isCurrentAnchorOperation(operation,doc))return!1;pageIndex=this.rawPageTextIndex(pageNumber,text,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits)),remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits}if(!this.isCurrentAnchorOperation(operation,doc))return!1;if(pageIndex.index.resolve(anchor,workBudget)){matchedPage=pageNumber;break}if(pageIndex.scope.truncated)break}if(matchedPage==null||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==matchedPage&&(this.scrollDrivenPage=!1,this.page=matchedPage),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)||!this.pageCanvases.has(matchedPage))||(await this.textLayerReadyPromises.get(matchedPage),!this.isCurrentAnchorOperation(operation,doc)))return!1;const range=this.resolveQuoteRangeOnPage(matchedPage,anchor);return!range||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollRangeIntoView(range),!0)}resolveQuoteRangeOnPage(pageNumber,anchor){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const match=mounted.index.resolve(anchor);return match?rangeFromTextQuoteMatch(mounted.scope,match):null}async applyRegionAnchor(anchor,operation,doc){const rect=sanitizePercentRect(anchor.rect);if(!rect||this.loadState.kind!=="ready"||anchor.page==null||!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)))return!1;const canvas=this.pageCanvases.get(anchor.page);return!canvas||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollPercentRectIntoView(canvas,rect),!0)}virtualListScrollContainer(){return this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot?.querySelector('[part="base"]')??null}scrollRangeIntoView(range){const rect=range.getClientRects()[0],scrollContainer=this.virtualListScrollContainer();if(!rect||!scrollContainer)return;const containerRect=scrollContainer.getBoundingClientRect(),offset=rect.top-containerRect.top-containerRect.height/2+rect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}scrollPercentRectIntoView(pageEl,rect){const scrollContainer=this.virtualListScrollContainer();if(!scrollContainer)return;const pageRect=pageEl.getBoundingClientRect(),containerRect=scrollContainer.getBoundingClientRect(),offset=pageRect.top+rect.y/100*pageRect.height-containerRect.top-containerRect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}computeSelectionAnchor(range){const pageNumber=this.pageForNode(range.startContainer);if(pageNumber==null)return null;const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const anchor=buildQuoteAnchor(range,mounted.scope);return anchor.kind==="text-quote"?{...anchor,page:pageNumber}:anchor}pageForNode(node){for(const[pageNumber,container]of this.textLayerContainers)if(container.contains(node))return pageNumber;return null}selectionShadowRoots(contentRoot){const roots=super.selectionShadowRoots(contentRoot),nested=this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot;return nested&&!roots.includes(nested)&&roots.push(nested),roots}bindTextSelection(contentRoot){super.bindTextSelection(contentRoot),this.textSelectionCleanup=()=>this.unbindTextSelection()}async getPageText(page){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)throw new Error(`Page ${page} is out of range (1-${pageCount}).`);const cached=this.pageTextCache.get(page);if(cached)return this.pageTextCache.delete(page),this.pageTextCache.set(page,cached),(await cached.promise).text;const entry={cancelled:!1,promise:Promise.resolve({text:"",truncated:!1})};if(this.pageTextCache.set(page,entry),this.pageTextCache.size>PAGE_TEXT_CACHE_LIMIT){const oldestKey=this.pageTextCache.keys().next().value;oldestKey!==void 0&&this.evictPageTextCacheEntry(oldestKey)}return entry.promise=this.loadPageText(page,entry),entry.promise.then(result=>{this.pageTextCache.get(page)===entry&&(result.truncated?this.pageTextTruncated.add(page):this.pageTextTruncated.delete(page))},()=>{this.pageTextCache.get(page)===entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page))}),(await entry.promise).text}evictPageTextCacheEntry(page){const entry=this.pageTextCache.get(page);entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page),entry.cancelled=!0,entry.reader?.cancel().catch(()=>{}))}clearPageTextCache(){for(const entry of this.pageTextCache.values())entry.cancelled=!0,entry.reader?.cancel().catch(()=>{});this.pageTextCache.clear(),this.pageTextTruncated.clear()}async loadPageText(page,entry){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const doc=this.loadState.doc,pdfPage=await doc.getPage(page),DOMExceptionCtor=this.ownerDocument.defaultView?.DOMException??DOMException;if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");const accumulator={chunks:[],length:0,inspectedItems:0,truncated:!1},source=pdfPage.streamTextContent?.();if(!isReadablePdfTextStream(source))throw new Error("PDF text streaming is unavailable.");const reader=source.getReader();entry.reader=reader;let inspectedChunks=0;try{for(;inspectedChunks++<MAX_PDF_TEXT_CHUNKS;){const result=await reader.read();if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw reader.cancel().catch(()=>{}),new DOMExceptionCtor("Superseded","AbortError");if(result.done)break;const value=result.value;if(appendPdfTextItems(value&&typeof value=="object"&&"items"in value?value.items:void 0,accumulator),accumulator.truncated){reader.cancel().catch(()=>{});break}}inspectedChunks>MAX_PDF_TEXT_CHUNKS&&(accumulator.truncated=!0,reader.cancel().catch(()=>{}))}finally{entry.reader===reader&&(entry.reader=void 0),reader.releaseLock()}if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");return{text:accumulator.chunks.join(""),truncated:accumulator.truncated}}async renderPageThumbnail(page,canvas,options){if(this.loadState.kind!=="ready")return!1;const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)return!1;const width=options?.width??DEFAULT_THUMBNAIL_WIDTH;if(!Number.isFinite(width)||width<=0||width>MAX_THUMBNAIL_WIDTH)return!1;this.thumbnailRenderTasks.get(canvas)?.cancel(),this.thumbnailRenderTasks.delete(canvas);const version=++this.thumbnailRenderGeneration;this.thumbnailRenderVersions.set(canvas,version);const doc=this.loadState.doc;let renderTask;try{const pdfPage=await doc.getPage(page);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc||this.thumbnailRenderVersions.get(canvas)!==version)return!1;const unscaledViewport=pdfPage.getViewport({scale:1});if(!Number.isFinite(unscaledViewport.width)||unscaledViewport.width<=0)return!1;const scale=width/unscaledViewport.width,viewport=pdfPage.getViewport({scale}),allocation=boundedPdfCanvas(canvas,viewport);canvas.width=allocation.pixelWidth,canvas.height=allocation.pixelHeight,canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(allocation.scaleX,0,0,allocation.scaleY,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(!ref2)return;const pageIndex=await doc.getPageIndex(ref2);return typeof pageIndex=="number"?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;const textNode=node,element=textNode.parentElement??container;items.push({text:textNode.data,element,node:textNode,joinBefore:items.length===0||run!==previousRun}),previousRun=run}const scope=scopeFromItems(items);return traversalTruncated&&(scope.truncated=!0),this.pdfTextScopeBuilds++,scope}mountedPageTextIndex(pageNumber,forceMappingRefresh=!1){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;const cached=this.mountedPageTextIndexes.get(pageNumber);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&!cached.mappingDirty&&!forceMappingRefresh)return cached;const scope=this.buildMountedPageScope(container);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&cached.index.rebindScope(scope))return cached.scope=scope,cached.mappingDirty=!1,cached;const created={scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceWorkCodeUnits:scope.text.length,container,mappingDirty:!1};return this.mountedPageTextIndexes.set(pageNumber,created),created}pdfTextScopeBuildCount(){return this.pdfTextScopeBuilds}pdfTextQuoteScanCount(pageNumber){return this.mountedPageTextIndexes.get(pageNumber)?.index.scanCount??0}async search(query){invalidateLyraLocaleCache(this);const generation=++this.searchGeneration;if(this.searchState.query=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchState.publish(void 0,!1),0;const trimmedQuery=query.trim();if(this.loadState.kind!=="ready"||!trimmedQuery)return this.searchState.publish(),0;const{pageCount}=this.loadState,matches=[];let matchCountExact=!0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const searchBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},inspectedPages=Math.min(pageCount,MAX_SEARCH_PAGES);pageCount>inspectedPages&&(matchCountExact=!1);for(let page=1;page<=inspectedPages;page++){if(generation!==this.searchGeneration)return this.searchMatches.length;if(remainingCorpus<=0||remainingNormalizationWork<=0||searchBudget.remainingCodeUnits<=0){matchCountExact=!1;break}let raw;try{raw=await this.getPageText(page)}catch{matchCountExact=!1;continue}if(generation!==this.searchGeneration)return this.searchMatches.length;const fullPageFits=raw.length<=remainingNormalizationWork,pageIndex=this.rawPageTextIndex(page,raw,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits));remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits;const pageMatches=pageIndex.index.search(trimmedQuery,searchBudget);pageMatches.matchCountExact||(matchCountExact=!1);const retainedBeforePage=matches.length;for(const match of pageMatches){if(matches.length>=MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({page,start:match.start,length:match.end-match.start})}if(matches.length>=MAX_SEARCH_MATCHES&&pageMatches.length>0){const retainedOnPage=matches.length-retainedBeforePage;if(pageMatches.length>retainedOnPage){matchCountExact=!1;break}}if(!fullPageFits||pageIndex.scope.truncated||!pageMatches.scanComplete){matchCountExact=!1;break}}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchState.publish(matches,matchCountExact),this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length)}async searchNext(){return this.searchState.step(1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}async searchPrevious(){return this.searchState.step(-1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.searchState.emit()}resetSearchState(){this.searchGeneration++,this.searchState.reset()}async focusSearchMatch(index){const match=this.searchMatches[index];match&&(await this.goToPage(match.page),await this.textLayerReadyPromises.get(match.page),this.paintSearchMatches(match.page))}clearSearchPaint(container){const containers=container?[container]:this.textLayerContainers.values();for(const target of containers){target.querySelectorAll('mark[part~="search-match"]').forEach(mark=>{unwrapTextMark(mark)});for(const cached of this.mountedPageTextIndexes.values())cached.container===target&&(cached.mappingDirty=!0)}}paintSearchMatches(page){const container=this.textLayerContainers.get(page);if(!container)return;this.clearSearchPaint(container);const count=Math.min(this.searchMatches.length,MAX_PAINTED_SEARCH_MATCHES),half=MAX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchActiveIndex<0?0:this.searchActiveIndex,start=Math.max(0,Math.min(centre-half,this.searchMatches.length-count)),pageMatches=[];for(let matchIndex=start;matchIndex<start+count;matchIndex++){const match=this.searchMatches[matchIndex];match?.page===page&&pageMatches.push({match,matchIndex})}if(pageMatches.length===0)return;const active=pageMatches.find(({matchIndex})=>matchIndex===this.searchActiveIndex),nonOverlapping=[];for(const candidate of active?[active,...pageMatches.filter(entry=>entry!==active)]:pageMatches){const candidateEnd=candidate.match.start+candidate.match.length;nonOverlapping.some(({match})=>candidate.match.start<match.start+match.length&&match.start<candidateEnd)||nonOverlapping.push(candidate)}const mounted=this.mountedPageTextIndex(page);if(!mounted)return;const materialized=rangesFromTextQuoteMatches(mounted.scope,nonOverlapping.map(({match})=>({start:match.start,end:match.start+match.length}))),ranges=[];for(let position=0;position<nonOverlapping.length;position++){const{match,matchIndex}=nonOverlapping[position],range=materialized[position]??null;range&&ranges.push({matchIndex,match,range})}ranges.sort((a,b)=>b.match.start-a.match.start);const budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:this.remainingSearchMarkBudget(container)};let painted=!1;for(const{matchIndex,range}of ranges){const part=matchIndex===this.searchActiveIndex?"search-match search-match-active":"search-match";wrapPdfSearchRange(range,part,budget).length>0&&(painted=!0)}painted&&(mounted.mappingDirty=!0)}remainingSearchMarkBudget(except){let remaining=MAX_PAINTED_SEARCH_MARKS;for(const container of this.textLayerContainers.values()){if(container===except)continue;const count=container.querySelectorAll('mark[part~="search-match"]').length;if(remaining-=Math.min(remaining,count),remaining<=0)return 0}return remaining}resolveMountedPageHighlights(){const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),pages=[...this.pageCanvases.keys()].filter(pageNumber=>this.textLayerContainers.has(pageNumber)).sort((left,right)=>left-right),active=this.activeHighlightId?candidates.find(highlight=>highlight.id===this.activeHighlightId):void 0,activePage=active?.anchor.kind==="page"?active.anchor.page:active?.anchor.kind==="region"?active.anchor.page??this.page:active?.anchor.kind==="text-quote"?active.anchor.page:void 0;activePage!==void 0&&pages.sort((left,right)=>+(right===activePage)-+(left===activePage));for(const layer of this.pageHighlightLayerElements.values())layer.items=[];this.pageHighlightItems.clear();const results=new Map;for(const pageNumber of pages)results.set(pageNumber,[]);const textIndexes=new Map,searchPaintPages=new Set,budget={work:{remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},remainingResolutionAttempts:MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS,remainingItems:MAX_PAINTED_HIGHLIGHTS,remainingRects:MAX_HIGHLIGHT_RECTS},plans=[],textOptionsByPage=new Map,pageRects=new Map;for(const highlight of candidates){const options=[];for(const pageNumber of this.mountedPagesForHighlight(highlight.anchor,pages)){const container=this.textLayerContainers.get(pageNumber),canvas=this.pageCanvases.get(pageNumber);if(!container||!canvas||this.loadState.kind!=="ready")continue;let pageRect=pageRects.get(pageNumber);pageRect||(pageRect=canvas.getBoundingClientRect(),pageRects.set(pageNumber,pageRect));let textIndex;if(highlight.anchor.kind==="text-quote"){if(budget.remainingResolutionAttempts<=0)break;if(textIndexes.has(pageNumber)||(container.querySelector('mark[part~="search-match"]')&&(searchPaintPages.add(pageNumber),this.clearSearchPaint(container)),textIndexes.set(pageNumber,this.mountedPageTextIndex(pageNumber))),textIndex=textIndexes.get(pageNumber)??void 0,!textIndex)continue;budget.remainingResolutionAttempts--;const match=textIndex.index.resolve(highlight.anchor,budget.work);if(!match)continue;const option={pageNumber,pageRect,textIndex,match};options.push(option);const pageOptions=textOptionsByPage.get(pageNumber)??[];pageOptions.push(option),textOptionsByPage.set(pageNumber,pageOptions);continue}options.push({pageNumber,pageRect})}plans.push({highlight,options})}for(const[pageNumber,options]of textOptionsByPage){const textIndex=textIndexes.get(pageNumber);if(!textIndex)continue;const ranges=rangesFromTextQuoteMatches(textIndex.scope,options.map(({match})=>match));for(let position=0;position<options.length;position++)options[position].range=ranges[position]??null}candidateLoop:for(const{highlight,options}of plans){if(budget.remainingItems<=0||budget.remainingRects<=0)break;for(const{pageNumber,pageRect,range}of options){const rects=this.resolveHighlightRectsForPage(highlight.anchor,pageNumber,pageRect,budget,range);if(rects.length!==0){results.get(pageNumber).push({id:highlight.id,rects,label:highlight.label,tone:highlight.tone}),budget.remainingItems--;continue candidateLoop}}}for(const[pageNumber,pageItems]of results){this.pageHighlightItems.set(pageNumber,pageItems);const layer=this.pageHighlightLayerElements.get(pageNumber);layer&&(layer.items=pageItems)}for(const pageNumber of searchPaintPages)this.paintSearchMatches(pageNumber)}*mountedPagesForHighlight(anchor,mountedPages){const addressedPage=anchor.kind==="page"?anchor.page:anchor.kind==="region"?anchor.page??this.page:anchor.kind==="text-quote"?anchor.page:void 0;if(addressedPage!==void 0){mountedPages.includes(addressedPage)&&(yield addressedPage);return}if(anchor.kind==="text-quote")for(const pageNumber of mountedPages)yield pageNumber}resolveHighlightRectsForPage(anchor,pageNumber,pageRect,budget,range){if(anchor.kind==="page"&&anchor.page===pageNumber)return budget.remainingRects<=0?[]:(budget.remainingRects--,[{x:0,y:0,width:100,height:100}]);if(anchor.kind==="region"&&(anchor.page??pageNumber)===pageNumber){const rect=sanitizePercentRect(anchor.rect);return!rect||budget.remainingRects<=0?[]:(budget.remainingRects--,[rect])}if(anchor.kind==="text-quote"&&range&&(anchor.page==null||anchor.page===pageNumber)){if(!(pageRect.width>0)||!(pageRect.height>0))return[];const rects=[];for(const rect of range.getClientRects()){if(rects.length>=budget.remainingRects)return[];rects.push({x:(rect.left-pageRect.left)/pageRect.width*100,y:(rect.top-pageRect.top)/pageRect.height*100,width:rect.width/pageRect.width*100,height:rect.height/pageRect.height*100})}return budget.remainingRects-=rects.length,rects}return[]}highlightLayerRef(pageNumber){let callback=this.highlightLayerRefs.get(pageNumber);return callback||(callback=element=>{if(!element){this.pageHighlightLayerElements.delete(pageNumber),this.pageHighlightItems.delete(pageNumber),this.highlightLayerRefs.delete(pageNumber);return}const layer=element;this.pageHighlightLayerElements.set(pageNumber,layer),layer.items=this.pageHighlightItems.get(pageNumber)??[],layer.activeHighlightId=this.activeHighlightId;const canvas=this.pageCanvases.get(pageNumber);canvas?.style.width&&(layer.style.width=canvas.style.width,layer.style.height=canvas.style.height)},this.highlightLayerRefs.set(pageNumber,callback)),callback}onPageClick(pageNumber,e){const canvas=this.pageCanvases.get(pageNumber),selection=canvas?.ownerDocument.defaultView?.getSelection();if(selection&&!selection.isCollapsed)return;const items=this.pageHighlightItems.get(pageNumber);if(!canvas||!items||items.length===0)return;const pageRect=canvas.getBoundingClientRect(),xPct=(e.clientX-pageRect.left)/pageRect.width*100,yPct=(e.clientY-pageRect.top)/pageRect.height*100;for(let i=items.length-1;i>=0;i--){const item=items[i];if(!item)continue;if(item.rects.some(rect=>xPct>=rect.x&&xPct<=rect.x+rect.width&&yPct>=rect.y&&yPct<=rect.y+rect.height)){this.emit("lr-highlight-activate",{highlightId:item.id});return}}}renderToolbar(){if(this.loadState.kind!=="ready")return html``;const{pageCount}=this.loadState,numberFormat=getNumberFormat(this.effectiveLocale),formattedZoom=numberFormat.format(Math.round(this.zoom*100));return html`<div part="toolbar">
|
|
11
|
+
</div>`},this.onVisibleRangeChanged=event=>{if(event.stopPropagation(),this.loadState.kind!=="ready")return;const next=this.clampPage(event.detail.start+1);next!==this.firstVisiblePage&&(this.firstVisiblePage=next,next!==this.page&&(this.scrollDrivenPage=!0,this.page=next))},this.stopInternalEvent=event=>{event.stopPropagation()}}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,loadingDocument:LYRA_DEFAULT_loadingDocument,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,pdfViewerLabel:LYRA_DEFAULT_pdfViewerLabel,pdfViewerMissingLibrary:LYRA_DEFAULT_pdfViewerMissingLibrary,pdfViewerNextPage:LYRA_DEFAULT_pdfViewerNextPage,pdfViewerPageOf:LYRA_DEFAULT_pdfViewerPageOf,pdfViewerPreviousPage:LYRA_DEFAULT_pdfViewerPreviousPage,pdfViewerZoomIn:LYRA_DEFAULT_pdfViewerZoomIn,pdfViewerZoomOut:LYRA_DEFAULT_pdfViewerZoomOut,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}get searchMatches(){return this.searchState.matches}set searchMatches(matches){this.searchState.matches=matches}get searchActiveIndex(){return this.searchState.activeIndex}set searchActiveIndex(index){this.searchState.activeIndex=index}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}keepToolbarFocus(){const part=this.focusedToolbarPart;this.focusedToolbarPart=null;const twin=part===null?void 0:TOOLBAR_FOCUS_TWINS.get(part),root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedToolbarPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("page")&&(this.page=this.clampPage(this.page)),changed.has("page")&&!changed.has("scrollDrivenPage")&&(this.scrollDrivenPage=!1),changed.has("zoom")){this.zoom=clampZoom(this.zoom);for(const[pageNumber,canvas]of this.pageCanvases)this.renderPage(pageNumber,canvas)}changed.has("src")&&(this.pendingSearchResetEvent||=this.searchState.dirty,this.resetSearchState())}updated(changed){super.updated(changed),this.keepToolbarFocus();const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear()),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&(this.scheduleAfterUpdate(()=>{this.load()},"pdf-load"),this.pageHighlightItems.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.searchState.emit())),changed.has("page")&&this.loadState.kind==="ready"&&(changed.get("page")!==this.page&&this.emit("lr-page-change",{page:this.page,pageCount:this.loadState.pageCount}),this.publishPageViewerSnapshot("ready",this.loadState.pageCount)),changed.has("zoom")&&changed.get("zoom")!==void 0&&changed.get("zoom")!==this.zoom&&this.emit("lr-zoom-change",{zoom:this.zoom}),(changed.has("highlights")||changed.has("activeHighlightId")||localeChanged)&&this.resolveMountedPageHighlights(),changed.has("activeHighlightId"))for(const layer of this.pageHighlightLayerElements.values())layer.activeHighlightId=this.activeHighlightId;localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();if(this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&(!moved||this.pendingTransportGeneration!==void 0)&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.pendingTransportGeneration!==void 0&&this.generation++,this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}teardownDetachedDocument(){this.generation++,this.retirePendingDocument(),this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits();for(const task of this.pageRenderTasks.values())task.cancel();for(const layer of this.textLayers.values())layer.cancel();for(const task of this.thumbnailRenderTasks.values())task.cancel();this.pageRenderTasks.clear(),this.pageRenderVersions.clear(),this.textLayers.clear(),this.pageCanvases.clear(),this.textLayerContainers.clear(),this.textLayerReadyPromises.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.thumbnailRenderTasks.clear(),this.thumbnailRenderVersions.clear(),this.destroyLoadedDoc(),this.loadState={kind:"idle"},this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.destroyDocumentResource(this.loadState.doc)}retirePendingDocument(){const pending=this.pendingDocument;this.pendingDocument=void 0,!(!pending||pending.retired)&&(pending.retired=!0,this.destroyDocumentResource(pending.task))}destroyDocumentResource(resource){try{Promise.resolve(resource.destroy?.()).catch(()=>{})}catch{}}clampPage(value){const pageCount=this.loadState.kind==="ready"?this.loadState.pageCount:1,rounded=Math.round(finiteNumber(value,1));return finiteRange(rounded,1,1,pageCount)}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,this.clampPage(this.page),finiteCount(pageCount,0,MAX_PAGE_COUNT));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pdfPageSourceCount&&(this.pdfPageSourceCount=count,this.pdfPageSource=this.createPageSource(count)),this.pdfPageSource}async load(){const generation=++this.generation;this.pendingTransportGeneration=void 0,this.firstVisiblePage=1,this.retirePendingDocument(),this.pageViewerState.advance();const signal=this.beginAbortableLoad();if(this.destroyLoadedDoc(),!this.src){this.loadState={kind:"idle"},this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.pendingTransportGeneration=generation,this.loadState={kind:"loading"},this.publishPageViewerSnapshot("loading",0);let acquiringDocument=!0;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 data=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const pdfjsLib=await this.loadLibrary(this.workerSrc||null);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!pdfjsLib){const error=new LyraUserFacingError(this.localize("pdfViewerMissingLibrary"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}const pending={task:pdfjsLib.getDocument({data}),retired:!1};signal?.aborted||!this.isConnected||generation!==this.generation?(pending.retired=!0,this.destroyDocumentResource(pending.task)):this.pendingDocument=pending,acquiringDocument=!1,this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0);let doc;try{doc=await pending.task.promise}catch(error){throw this.pendingDocument===pending&&this.retirePendingDocument(),error}if(this.pendingDocument===pending&&(this.pendingDocument=void 0),pending.retired||!this.isConnected||generation!==this.generation){(!pending.retired||!pending.task.destroy)&&await doc.destroy?.();return}const pageCount=finiteCount(doc.numPages,0,MAX_PAGE_COUNT);if(pageCount<1||pageCount!==doc.numPages)throw await doc.destroy?.(),new LyraUserFacingError(this.localize("documentPreviewResourceTooLarge"));this.page=1,this.loadState={kind:"ready",doc,pageCount},this.publishPageViewerSnapshot("ready",pageCount),this.emit("lr-load",{pageCount})}catch(error){if(acquiringDocument&&signal?.aborted||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}finally{this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0)}}nextPage(){this.scrollDrivenPage=!1,this.setPage(this.page+1)}previousPage(){this.scrollDrivenPage=!1,this.setPage(this.page-1)}zoomIn(){this.setZoom(this.zoom+ZOOM_STEP)}zoomOut(){this.setZoom(this.zoom-ZOOM_STEP)}async goToPage(page){return this.loadState.kind!=="ready"||!Number.isInteger(page)||page<1||page>this.loadState.pageCount?!1:page===this.page&&this.pageCanvases.has(page)?!0:(this.scrollDrivenPage=!1,this.page=page,await this.updateComplete,this.waitForPageMount(page))}waitForPageMount(page){if(this.pageCanvases.has(page))return Promise.resolve(!0);const list=this.shadowRoot?.querySelector(tag("virtual-list")),view=this.ownerDocument.defaultView;return!list||!view?Promise.resolve(!1):new Promise(resolve=>{let settled=!1,timeoutId,cancel;const finish=mounted=>{settled||(settled=!0,list.removeEventListener("lr-visible-range-change",onRange),timeoutId!==void 0&&view.clearTimeout(timeoutId),this.pendingPageMountWaitCancels.delete(cancel),resolve(mounted))},onRange=()=>{this.pageCanvases.has(page)&&finish(!0)};cancel=()=>finish(!1),this.pendingPageMountWaitCancels.add(cancel),list.addEventListener("lr-visible-range-change",onRange),timeoutId=view.setTimeout(()=>finish(!1),500)})}setPage(value){const next=this.clampPage(value);next!==this.page&&(this.page=next)}setZoom(value){const next=clampZoom(value);next!==this.zoom&&(this.zoom=next)}async scrollToAnchor(target){return this.anchorOperationGeneration++,super.scrollToAnchor(target)}async applyAnchor(anchor){if(this.loadState.kind!=="ready")return!1;const doc=this.loadState.doc,operation=this.anchorOperationGeneration;switch(anchor.kind){case"page":return!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,this.isCurrentAnchorOperation(operation,doc)&&this.pageCanvases.has(anchor.page));case"text-quote":return this.applyTextQuoteAnchor(anchor,operation,doc);case"region":return this.applyRegionAnchor(anchor,operation,doc);default:return!1}}isCurrentAnchorOperation(operation,doc){return operation===this.anchorOperationGeneration&&this.loadState.kind==="ready"&&this.loadState.doc===doc}*pageSearchOrder(hint,pageCount){if(hint==null){for(let page=1;page<=pageCount;page++)yield page;return}const clampedHint=Math.min(pageCount,Math.max(1,Math.round(hint)));yield clampedHint;for(let delta=1;delta<pageCount;delta++)clampedHint-delta>=1&&(yield clampedHint-delta),clampedHint+delta<=pageCount&&(yield clampedHint+delta)}async applyTextQuoteAnchor(anchor,operation,doc){if(!this.isCurrentAnchorOperation(operation,doc)||this.loadState.kind!=="ready"||anchor.quote.length>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.prefix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.suffix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||!normalizeQuoteText(anchor.quote))return!1;const order=this.pageSearchOrder(anchor.page,this.loadState.pageCount);let matchedPage,inspectedPages=0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(const pageNumber of order){if(inspectedPages++>=MAX_SEARCH_PAGES||remainingCorpus<=0||remainingNormalizationWork<=0||workBudget.remainingCodeUnits<=0)break;let pageIndex=this.mountedPageTextIndex(pageNumber);if(!pageIndex){let text;try{text=await this.getPageText(pageNumber)}catch{continue}if(!this.isCurrentAnchorOperation(operation,doc))return!1;pageIndex=this.rawPageTextIndex(pageNumber,text,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits)),remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits}if(!this.isCurrentAnchorOperation(operation,doc))return!1;if(pageIndex.index.resolve(anchor,workBudget)){matchedPage=pageNumber;break}if(pageIndex.scope.truncated)break}if(matchedPage==null||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==matchedPage&&(this.scrollDrivenPage=!1,this.page=matchedPage),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)||!this.pageCanvases.has(matchedPage))||(await this.textLayerReadyPromises.get(matchedPage),!this.isCurrentAnchorOperation(operation,doc)))return!1;const range=this.resolveQuoteRangeOnPage(matchedPage,anchor);return!range||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollRangeIntoView(range),!0)}resolveQuoteRangeOnPage(pageNumber,anchor){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const match=mounted.index.resolve(anchor);return match?rangeFromTextQuoteMatch(mounted.scope,match):null}async applyRegionAnchor(anchor,operation,doc){const rect=sanitizePercentRect(anchor.rect);if(!rect||this.loadState.kind!=="ready"||anchor.page==null||!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)))return!1;const canvas=this.pageCanvases.get(anchor.page);return!canvas||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollPercentRectIntoView(canvas,rect),!0)}virtualListScrollContainer(){return this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot?.querySelector('[part="base"]')??null}scrollRangeIntoView(range){const rect=range.getClientRects()[0],scrollContainer=this.virtualListScrollContainer();if(!rect||!scrollContainer)return;const containerRect=scrollContainer.getBoundingClientRect(),offset=rect.top-containerRect.top-containerRect.height/2+rect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}scrollPercentRectIntoView(pageEl,rect){const scrollContainer=this.virtualListScrollContainer();if(!scrollContainer)return;const pageRect=pageEl.getBoundingClientRect(),containerRect=scrollContainer.getBoundingClientRect(),offset=pageRect.top+rect.y/100*pageRect.height-containerRect.top-containerRect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}computeSelectionAnchor(range){const pageNumber=this.pageForNode(range.startContainer);if(pageNumber==null)return null;const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const anchor=buildQuoteAnchor(range,mounted.scope);return anchor.kind==="text-quote"?{...anchor,page:pageNumber}:anchor}pageForNode(node){for(const[pageNumber,container]of this.textLayerContainers)if(container.contains(node))return pageNumber;return null}selectionShadowRoots(contentRoot){const roots=super.selectionShadowRoots(contentRoot),nested=this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot;return nested&&!roots.includes(nested)&&roots.push(nested),roots}bindTextSelection(contentRoot){super.bindTextSelection(contentRoot),this.textSelectionCleanup=()=>this.unbindTextSelection()}async getPageText(page){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)throw new Error(`Page ${page} is out of range (1-${pageCount}).`);const cached=this.pageTextCache.get(page);if(cached)return this.pageTextCache.delete(page),this.pageTextCache.set(page,cached),(await cached.promise).text;const entry={cancelled:!1,promise:Promise.resolve({text:"",truncated:!1})};if(this.pageTextCache.set(page,entry),this.pageTextCache.size>PAGE_TEXT_CACHE_LIMIT){const oldestKey=this.pageTextCache.keys().next().value;oldestKey!==void 0&&this.evictPageTextCacheEntry(oldestKey)}return entry.promise=this.loadPageText(page,entry),entry.promise.then(result=>{this.pageTextCache.get(page)===entry&&(result.truncated?this.pageTextTruncated.add(page):this.pageTextTruncated.delete(page))},()=>{this.pageTextCache.get(page)===entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page))}),(await entry.promise).text}evictPageTextCacheEntry(page){const entry=this.pageTextCache.get(page);entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page),entry.cancelled=!0,entry.reader?.cancel().catch(()=>{}))}clearPageTextCache(){for(const entry of this.pageTextCache.values())entry.cancelled=!0,entry.reader?.cancel().catch(()=>{});this.pageTextCache.clear(),this.pageTextTruncated.clear()}async loadPageText(page,entry){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const doc=this.loadState.doc,pdfPage=await doc.getPage(page),DOMExceptionCtor=this.ownerDocument.defaultView?.DOMException??DOMException;if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");const accumulator={chunks:[],length:0,inspectedItems:0,truncated:!1},source=pdfPage.streamTextContent?.();if(!isReadablePdfTextStream(source))throw new Error("PDF text streaming is unavailable.");const reader=source.getReader();entry.reader=reader;let inspectedChunks=0;try{for(;inspectedChunks++<MAX_PDF_TEXT_CHUNKS;){const result=await reader.read();if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw reader.cancel().catch(()=>{}),new DOMExceptionCtor("Superseded","AbortError");if(result.done)break;const value=result.value;if(appendPdfTextItems(value&&typeof value=="object"&&"items"in value?value.items:void 0,accumulator),accumulator.truncated){reader.cancel().catch(()=>{});break}}inspectedChunks>MAX_PDF_TEXT_CHUNKS&&(accumulator.truncated=!0,reader.cancel().catch(()=>{}))}finally{entry.reader===reader&&(entry.reader=void 0),reader.releaseLock()}if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");return{text:accumulator.chunks.join(""),truncated:accumulator.truncated}}async renderPageThumbnail(page,canvas,options){if(this.loadState.kind!=="ready")return!1;const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)return!1;const width=options?.width??DEFAULT_THUMBNAIL_WIDTH;if(!Number.isFinite(width)||width<=0||width>MAX_THUMBNAIL_WIDTH)return!1;this.thumbnailRenderTasks.get(canvas)?.cancel(),this.thumbnailRenderTasks.delete(canvas);const version=++this.thumbnailRenderGeneration;this.thumbnailRenderVersions.set(canvas,version);const doc=this.loadState.doc;let renderTask;try{const pdfPage=await doc.getPage(page);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc||this.thumbnailRenderVersions.get(canvas)!==version)return!1;const unscaledViewport=pdfPage.getViewport({scale:1});if(!Number.isFinite(unscaledViewport.width)||unscaledViewport.width<=0)return!1;const scale=width/unscaledViewport.width,viewport=pdfPage.getViewport({scale}),allocation=boundedPdfCanvas(canvas,viewport);canvas.width=allocation.pixelWidth,canvas.height=allocation.pixelHeight,canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(allocation.scaleX,0,0,allocation.scaleY,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(ref2==null)return;const pageIndex=typeof ref2=="number"?ref2:await doc.getPageIndex(ref2);return Number.isInteger(pageIndex)&&pageIndex>=0&&pageIndex<doc.numPages?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;const textNode=node,element=textNode.parentElement??container;items.push({text:textNode.data,element,node:textNode,joinBefore:items.length===0||run!==previousRun}),previousRun=run}const scope=scopeFromItems(items);return traversalTruncated&&(scope.truncated=!0),this.pdfTextScopeBuilds++,scope}mountedPageTextIndex(pageNumber,forceMappingRefresh=!1){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;const cached=this.mountedPageTextIndexes.get(pageNumber);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&!cached.mappingDirty&&!forceMappingRefresh)return cached;const scope=this.buildMountedPageScope(container);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&cached.index.rebindScope(scope))return cached.scope=scope,cached.mappingDirty=!1,cached;const created={scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceWorkCodeUnits:scope.text.length,container,mappingDirty:!1};return this.mountedPageTextIndexes.set(pageNumber,created),created}pdfTextScopeBuildCount(){return this.pdfTextScopeBuilds}pdfTextQuoteScanCount(pageNumber){return this.mountedPageTextIndexes.get(pageNumber)?.index.scanCount??0}async search(query){invalidateLyraLocaleCache(this);const generation=++this.searchGeneration;if(this.searchState.query=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchState.publish(void 0,!1),0;const trimmedQuery=query.trim();if(this.loadState.kind!=="ready"||!trimmedQuery)return this.searchState.publish(),0;const{pageCount}=this.loadState,matches=[];let matchCountExact=!0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const searchBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},inspectedPages=Math.min(pageCount,MAX_SEARCH_PAGES);pageCount>inspectedPages&&(matchCountExact=!1);for(let page=1;page<=inspectedPages;page++){if(generation!==this.searchGeneration)return this.searchMatches.length;if(remainingCorpus<=0||remainingNormalizationWork<=0||searchBudget.remainingCodeUnits<=0){matchCountExact=!1;break}let raw;try{raw=await this.getPageText(page)}catch{matchCountExact=!1;continue}if(generation!==this.searchGeneration)return this.searchMatches.length;const fullPageFits=raw.length<=remainingNormalizationWork,pageIndex=this.rawPageTextIndex(page,raw,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits));remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits;const pageMatches=pageIndex.index.search(trimmedQuery,searchBudget);pageMatches.matchCountExact||(matchCountExact=!1);const retainedBeforePage=matches.length;for(const match of pageMatches){if(matches.length>=MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({page,start:match.start,length:match.end-match.start})}if(matches.length>=MAX_SEARCH_MATCHES&&pageMatches.length>0){const retainedOnPage=matches.length-retainedBeforePage;if(pageMatches.length>retainedOnPage){matchCountExact=!1;break}}if(!fullPageFits||pageIndex.scope.truncated||!pageMatches.scanComplete){matchCountExact=!1;break}}return generation!==this.searchGeneration?this.searchMatches.length:this.searchState.publish(matches,matchCountExact)?(this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length):0}async searchNext(){return this.searchState.step(1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}async searchPrevious(){return this.searchState.step(-1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.searchState.emit()}resetSearchState(){this.searchGeneration++,this.searchState.reset()}async focusSearchMatch(index){const match=this.searchMatches[index];match&&(await this.goToPage(match.page),await this.textLayerReadyPromises.get(match.page),this.paintSearchMatches(match.page))}clearSearchPaint(container){const containers=container?[container]:this.textLayerContainers.values();for(const target of containers){target.querySelectorAll('mark[part~="search-match"]').forEach(mark=>{unwrapTextMark(mark)});for(const cached of this.mountedPageTextIndexes.values())cached.container===target&&(cached.mappingDirty=!0)}}paintSearchMatches(page){const container=this.textLayerContainers.get(page);if(!container)return;this.clearSearchPaint(container);const count=Math.min(this.searchMatches.length,MAX_PAINTED_SEARCH_MATCHES),half=MAX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchActiveIndex<0?0:this.searchActiveIndex,start=Math.max(0,Math.min(centre-half,this.searchMatches.length-count)),pageMatches=[];for(let matchIndex=start;matchIndex<start+count;matchIndex++){const match=this.searchMatches[matchIndex];match?.page===page&&pageMatches.push({match,matchIndex})}if(pageMatches.length===0)return;const active=pageMatches.find(({matchIndex})=>matchIndex===this.searchActiveIndex),nonOverlapping=[];for(const candidate of active?[active,...pageMatches.filter(entry=>entry!==active)]:pageMatches){const candidateEnd=candidate.match.start+candidate.match.length;nonOverlapping.some(({match})=>candidate.match.start<match.start+match.length&&match.start<candidateEnd)||nonOverlapping.push(candidate)}const mounted=this.mountedPageTextIndex(page);if(!mounted)return;const materialized=rangesFromTextQuoteMatches(mounted.scope,nonOverlapping.map(({match})=>({start:match.start,end:match.start+match.length}))),ranges=[];for(let position=0;position<nonOverlapping.length;position++){const{match,matchIndex}=nonOverlapping[position],range=materialized[position]??null;range&&ranges.push({matchIndex,match,range})}ranges.sort((a,b)=>b.match.start-a.match.start);const budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:this.remainingSearchMarkBudget(container)};let painted=!1;for(const{matchIndex,range}of ranges){const part=matchIndex===this.searchActiveIndex?"search-match search-match-active":"search-match";wrapPdfSearchRange(range,part,budget).length>0&&(painted=!0)}painted&&(mounted.mappingDirty=!0)}remainingSearchMarkBudget(except){let remaining=MAX_PAINTED_SEARCH_MARKS;for(const container of this.textLayerContainers.values()){if(container===except)continue;const count=container.querySelectorAll('mark[part~="search-match"]').length;if(remaining-=Math.min(remaining,count),remaining<=0)return 0}return remaining}resolveMountedPageHighlights(){const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),pages=[...this.pageCanvases.keys()].filter(pageNumber=>this.textLayerContainers.has(pageNumber)).sort((left,right)=>left-right),active=this.activeHighlightId?candidates.find(highlight=>highlight.id===this.activeHighlightId):void 0,activePage=active?.anchor.kind==="page"?active.anchor.page:active?.anchor.kind==="region"?active.anchor.page??this.page:active?.anchor.kind==="text-quote"?active.anchor.page:void 0;activePage!==void 0&&pages.sort((left,right)=>+(right===activePage)-+(left===activePage));for(const layer of this.pageHighlightLayerElements.values())layer.items=[];this.pageHighlightItems.clear();const results=new Map;for(const pageNumber of pages)results.set(pageNumber,[]);const textIndexes=new Map,searchPaintPages=new Set,budget={work:{remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},remainingResolutionAttempts:MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS,remainingItems:MAX_PAINTED_HIGHLIGHTS,remainingRects:MAX_HIGHLIGHT_RECTS},plans=[],textOptionsByPage=new Map,pageRects=new Map;for(const highlight of candidates){const options=[];for(const pageNumber of this.mountedPagesForHighlight(highlight.anchor,pages)){const container=this.textLayerContainers.get(pageNumber),canvas=this.pageCanvases.get(pageNumber);if(!container||!canvas||this.loadState.kind!=="ready")continue;let pageRect=pageRects.get(pageNumber);pageRect||(pageRect=canvas.getBoundingClientRect(),pageRects.set(pageNumber,pageRect));let textIndex;if(highlight.anchor.kind==="text-quote"){if(budget.remainingResolutionAttempts<=0)break;if(textIndexes.has(pageNumber)||(container.querySelector('mark[part~="search-match"]')&&(searchPaintPages.add(pageNumber),this.clearSearchPaint(container)),textIndexes.set(pageNumber,this.mountedPageTextIndex(pageNumber))),textIndex=textIndexes.get(pageNumber)??void 0,!textIndex)continue;budget.remainingResolutionAttempts--;const match=textIndex.index.resolve(highlight.anchor,budget.work);if(!match)continue;const option={pageNumber,pageRect,textIndex,match};options.push(option);const pageOptions=textOptionsByPage.get(pageNumber)??[];pageOptions.push(option),textOptionsByPage.set(pageNumber,pageOptions);continue}options.push({pageNumber,pageRect})}plans.push({highlight,options})}for(const[pageNumber,options]of textOptionsByPage){const textIndex=textIndexes.get(pageNumber);if(!textIndex)continue;const ranges=rangesFromTextQuoteMatches(textIndex.scope,options.map(({match})=>match));for(let position=0;position<options.length;position++)options[position].range=ranges[position]??null}candidateLoop:for(const{highlight,options}of plans){if(budget.remainingItems<=0||budget.remainingRects<=0)break;for(const{pageNumber,pageRect,range}of options){const rects=this.resolveHighlightRectsForPage(highlight.anchor,pageNumber,pageRect,budget,range);if(rects.length!==0){results.get(pageNumber).push({id:highlight.id,rects,label:highlight.label,tone:highlight.tone}),budget.remainingItems--;continue candidateLoop}}}for(const[pageNumber,pageItems]of results){this.pageHighlightItems.set(pageNumber,pageItems);const layer=this.pageHighlightLayerElements.get(pageNumber);layer&&(layer.items=pageItems)}for(const pageNumber of searchPaintPages)this.paintSearchMatches(pageNumber)}*mountedPagesForHighlight(anchor,mountedPages){const addressedPage=anchor.kind==="page"?anchor.page:anchor.kind==="region"?anchor.page??this.page:anchor.kind==="text-quote"?anchor.page:void 0;if(addressedPage!==void 0){mountedPages.includes(addressedPage)&&(yield addressedPage);return}if(anchor.kind==="text-quote")for(const pageNumber of mountedPages)yield pageNumber}resolveHighlightRectsForPage(anchor,pageNumber,pageRect,budget,range){if(anchor.kind==="page"&&anchor.page===pageNumber)return budget.remainingRects<=0?[]:(budget.remainingRects--,[{x:0,y:0,width:100,height:100}]);if(anchor.kind==="region"&&(anchor.page??pageNumber)===pageNumber){const rect=sanitizePercentRect(anchor.rect);return!rect||budget.remainingRects<=0?[]:(budget.remainingRects--,[rect])}if(anchor.kind==="text-quote"&&range&&(anchor.page==null||anchor.page===pageNumber)){if(!(pageRect.width>0)||!(pageRect.height>0))return[];const rects=[];for(const rect of range.getClientRects()){if(rects.length>=budget.remainingRects)return[];rects.push({x:(rect.left-pageRect.left)/pageRect.width*100,y:(rect.top-pageRect.top)/pageRect.height*100,width:rect.width/pageRect.width*100,height:rect.height/pageRect.height*100})}return budget.remainingRects-=rects.length,rects}return[]}highlightLayerRef(pageNumber){let callback=this.highlightLayerRefs.get(pageNumber);return callback||(callback=element=>{if(!element){this.pageHighlightLayerElements.delete(pageNumber),this.pageHighlightItems.delete(pageNumber),this.highlightLayerRefs.delete(pageNumber);return}const layer=element;this.pageHighlightLayerElements.set(pageNumber,layer),layer.items=this.pageHighlightItems.get(pageNumber)??[],layer.activeHighlightId=this.activeHighlightId;const canvas=this.pageCanvases.get(pageNumber);canvas?.style.width&&(layer.style.width=canvas.style.width,layer.style.height=canvas.style.height)},this.highlightLayerRefs.set(pageNumber,callback)),callback}onPageClick(pageNumber,e){const canvas=this.pageCanvases.get(pageNumber),selection=canvas?.ownerDocument.defaultView?.getSelection();if(selection&&!selection.isCollapsed)return;const items=this.pageHighlightItems.get(pageNumber);if(!canvas||!items||items.length===0)return;const pageRect=canvas.getBoundingClientRect(),xPct=(e.clientX-pageRect.left)/pageRect.width*100,yPct=(e.clientY-pageRect.top)/pageRect.height*100;for(let i=items.length-1;i>=0;i--){const item=items[i];if(!item)continue;if(item.rects.some(rect=>xPct>=rect.x&&xPct<=rect.x+rect.width&&yPct>=rect.y&&yPct<=rect.y+rect.height)){this.emit("lr-highlight-activate",{highlightId:item.id});return}}}renderToolbar(){if(this.loadState.kind!=="ready")return html``;const{pageCount}=this.loadState,numberFormat=getNumberFormat(this.effectiveLocale),formattedZoom=numberFormat.format(Math.round(this.zoom*100));return html`<div part="toolbar">
|
|
12
12
|
<button type="button" part="previous-button" data-action="previous" ?disabled=${this.page<=1} @click=${this.previousPage}>${this.localize("pdfViewerPreviousPage")}</button>
|
|
13
13
|
<span part="page-indicator">${this.localize("pdfViewerPageOf",void 0,{page:numberFormat.format(this.page),total:numberFormat.format(pageCount)})}</span>
|
|
14
14
|
<button type="button" part="next-button" data-action="next" ?disabled=${this.page>=pageCount} @click=${this.nextPage}>${this.localize("pdfViewerNextPage")}</button>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{adaptPptxViewer,getPptxRenderer}from"./pptx-loader.js";import{assertPptxArchiveWithinLimits}from"./pptx-resource-guard.js";import{styles}from"./pptx-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_pptxViewerFidelityNotice,LYRA_DEFAULT_pptxViewerLabel,LYRA_DEFAULT_pptxViewerMissingLibrary,LYRA_DEFAULT_pptxViewerNextSlide,LYRA_DEFAULT_pptxViewerPreviousSlide,LYRA_DEFAULT_pptxViewerRenderError,LYRA_DEFAULT_pptxViewerSlideOf}from"../../../internal/default-strings/viewers.generated.js";const MAX_PPTX_SEARCH_MATCHES=1e4,MAX_PPTX_THUMBNAIL_WIDTH=2048;class LyraPptxViewerBase extends LyraElement{}class LyraPptxViewer extends TextViewerTarget(LyraPptxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.maxHeight="",this.phase="idle",this.errorMessage="",this.slideCount=0,this.currentSlideIndex=0,this.loadRenderer=getPptxRenderer,this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.pptxSearchQuery="",this.lastSearchLocale="",this.pptxSearchMatches=[],this.pendingSearchResetEvent=!1,this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.pptxSearchGeneration=0,this.pageViewerState=new PageViewerSnapshotController,this.anchorKinds=["text-quote","fragment","page"],this.onViewerEvent=event=>{if(event.kind==="slide-change"){this.commitSlide(event.index);return}this.reportPeerDiagnostic(event.code,event.cause,{page:event.page,nodeId:event.nodeId},event.fatal)},this.focusedPagerPart=null,this.detached=new DeferredTeardown(()=>this.releaseDetachedPresentation())}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,pptxViewerFidelityNotice:LYRA_DEFAULT_pptxViewerFidelityNotice,pptxViewerLabel:LYRA_DEFAULT_pptxViewerLabel,pptxViewerMissingLibrary:LYRA_DEFAULT_pptxViewerMissingLibrary,pptxViewerNextSlide:LYRA_DEFAULT_pptxViewerNextSlide,pptxViewerPreviousSlide:LYRA_DEFAULT_pptxViewerPreviousSlide,pptxViewerRenderError:LYRA_DEFAULT_pptxViewerRenderError,pptxViewerSlideOf:LYRA_DEFAULT_pptxViewerSlideOf}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}async search(query2){const generation=++this.pptxSearchGeneration,viewer=this.viewer,boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale);if(this.pptxSearchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.disposeSearchHighlight(),viewer?.clearSearchHighlights(),!boundedQuery.accepted)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;if(!viewer||!boundedQuery.needle)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;try{const raw=viewer.searchText(query2.trim(),{matchCase:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer)return this.pptxSearchMatches.length;const normalized=this.normalizeSearchResults(raw,viewer.slideCount);return this.pptxSearchMatches=normalized.matches,this.pptxSearchMatchCountExact=normalized.matchCountExact,this.pptxSearchActiveIndex=this.pptxSearchMatches.length>0?0:-1,this.emitPptxSearchChange(),this.pptxSearchActiveIndex>=0&&await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),this.pptxSearchMatches.length}catch(cause){return generation!==this.pptxSearchGeneration||viewer!==this.viewer||(this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.reportPeerDiagnostic("pptx-search-error",cause),this.emitPptxSearchChange()),0}}async searchNext(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex+1)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}async searchPrevious(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex-1+this.pptxSearchMatches.length)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}clearSearch(){this.pptxSearchGeneration++,this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.emitPptxSearchChange()}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}textContentRoot(){return this.renderRoot.querySelector('[part="container"]')??this.renderRoot.querySelector('[part="base"]')}async applyAnchor(anchor){const viewer=this.viewer;if(anchor.kind==="page"){const index=anchor.page-1;return!viewer||!Number.isInteger(anchor.page)||index<0||index>=this.slideCount?!1:(await this.goToSlide(index),viewer===this.viewer&&this.currentSlideIndex===index)}if(anchor.kind==="text-quote"&&viewer){const slideIndex=this.slideForTextQuote(viewer,anchor);if(slideIndex>=0&&slideIndex!==this.currentSlideIndex){if(await this.goToSlide(slideIndex),viewer!==this.viewer||this.currentSlideIndex!==slideIndex)return!1;await this.updateComplete}}return this.applyMountedAnchor(anchor)}applyMountedAnchor(anchor){return Object.getPrototypeOf(LyraPptxViewer.prototype).applyAnchor.call(this,anchor)}slideForTextQuote(viewer,anchor){const quote=anchor.quote.trim(),bounded=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!bounded.accepted||!bounded.needle)return-1;let matches;try{matches=this.normalizeSearchResults(viewer.searchText(quote,{matchCase:!1}),viewer.slideCount).matches}catch(cause){return this.reportPeerDiagnostic("pptx-search-error",cause),-1}let best,bestScore=-1;for(const match of matches){const score=textQuoteContextScore(match.text,match.matchStart,match.matchEnd,anchor.prefix,anchor.suffix);score>bestScore&&(best=match,bestScore=score)}return best?.slideIndex??-1}keepPagerFocus(){const part=this.focusedPagerPart;this.focusedPagerPart=null;const twin=part==="previous-button"?"next-button":part==="next-button"?"previous-button":void 0,root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}updated(changed){if(super.updated(changed),this.keepPagerFocus(),this.announcements.transition("load",this.phase,this.phase==="error"?this.errorMessage:this.localize("loading")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.mount()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitPptxSearchChange()),changed.has("page")&&this.viewer&&this.page-1!==this.currentSlideIndex){const page=this.page;this.scheduleAfterUpdate(()=>{this.page===page&&this.goToSlide(page-1)},"page-navigation")}const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.pptxSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.pptxSearchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);this.focusedPagerPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasPptxSearchState(),this.resetPptxSearchState()),(changed.has("page")||changed.has("slideCount"))&&(this.page=finiteInteger(this.page,1,1,Math.max(1,this.slideCount)))}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.mount()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPresentation(){this.teardown(),this.phase="idle",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async goToSlide(index){const viewer=this.viewer;if(!viewer||!Number.isSafeInteger(index)||index<0||index>=viewer.slideCount)return;const generation=this.generation;try{await viewer.goToSlide(index)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||viewer!==this.viewer)return;this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}viewer===this.viewer&&viewer.currentSlideIndex!==this.currentSlideIndex&&this.commitSlide(viewer.currentSlideIndex)}async renderPageThumbnailToContainer(page,container,options){const viewer=this.viewer,generation=this.generation,width=options?.width??96;if(!viewer||!Number.isSafeInteger(page)||page<1||page>viewer.slideCount||!Number.isFinite(width)||width<=0||width>MAX_PPTX_THUMBNAIL_WIDTH)return!1;const previousChildren=[...container.childNodes],restorePreviousChildren=()=>{container.replaceChildren(...previousChildren)};let handle;try{handle=viewer.renderThumbnailToContainer(page-1,container,{width})}catch{return restorePreviousChildren(),!1}if(!handle)return restorePreviousChildren(),!1;try{await handle.ready}catch{return handle.dispose(),restorePreviousChildren(),!1}if(generation!==this.generation||viewer!==this.viewer||!container.isConnected)return handle.dispose(),restorePreviousChildren(),!1;for(const child of previousChildren)child.parentNode===container&&child.remove();return handle}isValidSlideIndex(index){return Number.isSafeInteger(index)&&index>=0&&index<this.slideCount}commitSlide(index){if(!this.isValidSlideIndex(index))return;const changed=index!==this.currentSlideIndex;this.currentSlideIndex=index,this.page=index+1,this.publishPageViewerSnapshot("ready",this.slideCount),changed&&this.emit("lr-slide-change",{index,count:this.slideCount})}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,finiteInteger(this.page,1,1,Math.max(1,pageCount)),finiteInteger(pageCount,0,0,Number.MAX_SAFE_INTEGER));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}teardown(){const shouldEmitSearchReset=this.hasPptxSearchState();this.generation++,this.viewerUnsubscribe?.(),this.viewerUnsubscribe=void 0,this.viewer?.destroy(),this.viewer=void 0,this.resetPptxSearchState(),shouldEmitSearchReset&&this.emitPptxSearchChange()}hasPptxSearchState(){return this.pptxSearchQuery!==""||this.pptxSearchMatches.length>0||!this.pptxSearchMatchCountExact||this.pptxSearchActiveIndex!==-1}resetPptxSearchState(){this.pptxSearchGeneration++,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1}normalizeSearchResults(value,slideCount){if(!Array.isArray(value))throw new TypeError("PPTX search returned a non-array result.");const matches=[],work=new ViewerSearchWorkBudget;let matchCountExact=!0;for(const candidate of value){if(!work.consume("")){matchCountExact=!1;break}if(!candidate||typeof candidate!="object")continue;const result=candidate;if(!(!Number.isSafeInteger(result.slideIndex)||result.slideIndex<0||result.slideIndex>=slideCount||typeof result.nodeId!="string"||typeof result.text!="string"||!Number.isSafeInteger(result.matchStart)||!Number.isSafeInteger(result.matchEnd)||result.matchStart<0||result.matchEnd<result.matchStart||result.matchEnd>result.text.length)){if(!work.consume(result.nodeId)||!work.consume(result.text)){matchCountExact=!1;break}if(matches.length===MAX_PPTX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push(candidate)}}return{matches,matchCountExact:matchCountExact&&work.complete}}async focusPptxSearchMatch(index,generation,viewer){const match=this.pptxSearchMatches[index];if(match){this.disposeSearchHighlight(),viewer.clearSearchHighlights();try{if(await viewer.goToSlide(match.slideIndex),generation!==this.pptxSearchGeneration||viewer!==this.viewer)return;const highlight=await viewer.highlightSearchResult(match,{scrollIntoView:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer){highlight?.dispose();return}this.searchHighlight=highlight??void 0}catch(cause){generation===this.pptxSearchGeneration&&viewer===this.viewer&&this.reportPeerDiagnostic("pptx-search-error",cause,{page:match.slideIndex+1})}}}disposeSearchHighlight(){this.searchHighlight?.dispose(),this.searchHighlight=void 0}emitPptxSearchChange(){this.emit("lr-search-change",{query:this.pptxSearchQuery,matchCount:this.pptxSearchMatches.length,matchCountExact:this.pptxSearchMatchCountExact,activeIndex:this.pptxSearchActiveIndex})}reportPeerDiagnostic(code,cause,location={},fatal=!1){this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code,severity:"error",fatal,source:"pptx-renderer",cause,...location})}),fatal&&(this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error:cause}))}async mount(){this.teardown(),this.pageViewerState.advance();const signal=this.beginAbortableLoad(),generation=this.generation;if(this.slideCount=0,this.currentSlideIndex=0,this.page=1,!this.src){this.phase="idle",this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.phase="loading",this.publishPageViewerSnapshot("loading",0);let module,response;try{[module,response]=await Promise.all([this.loadRenderer(),fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0)])}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!this.isConnected||generation!==this.generation)return;if(!module||!response.ok){response.body?.cancel().catch(()=>{});const error=new LyraUserFacingError(this.localize(module?"documentPreviewFailedToLoad":"pptxViewerMissingLibrary"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}let buffer;try{if(buffer=await readResponseArrayBuffer(response),!this.isConnected||generation!==this.generation)return;await assertPptxArchiveWithinLimits(buffer,{signal})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!(!this.isConnected||generation!==this.generation)&&(this.phase="mounted",await this.updateComplete,!(!this.isConnected||generation!==this.generation||!this.containerEl)))try{const openedViewer=await module.PptxViewer.open(buffer,this.containerEl,{externalMedia:"block",zipLimits:module.RECOMMENDED_ZIP_LIMITS,listOptions:{windowed:!0}});if(!this.isConnected||generation!==this.generation){openedViewer.destroy();return}const viewer=adaptPptxViewer(openedViewer);if(!viewer)throw openedViewer.destroy(),new TypeError("The PPTX renderer did not expose the required viewer capabilities.");this.viewer=viewer,this.viewerUnsubscribe=viewer.subscribe(this.onViewerEvent),this.slideCount=viewer.slideCount,this.isValidSlideIndex(viewer.currentSlideIndex)&&(this.currentSlideIndex=viewer.currentSlideIndex,this.page=viewer.currentSlideIndex+1),this.publishPageViewerSnapshot("ready",viewer.slideCount),this.emit("lr-load",{slideCount:viewer.slideCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}renderBody(){return this.phase==="loading"?renderViewerLoading(this.localize("loading")):this.phase==="error"?html`<div part="error">${this.errorMessage}</div>`:this.phase!=="mounted"?nothing:html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{adaptPptxViewer,getPptxRenderer}from"./pptx-loader.js";import{assertPptxArchiveWithinLimits}from"./pptx-resource-guard.js";import{styles}from"./pptx-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_pptxViewerFidelityNotice,LYRA_DEFAULT_pptxViewerLabel,LYRA_DEFAULT_pptxViewerMissingLibrary,LYRA_DEFAULT_pptxViewerNextSlide,LYRA_DEFAULT_pptxViewerPreviousSlide,LYRA_DEFAULT_pptxViewerRenderError,LYRA_DEFAULT_pptxViewerSlideOf}from"../../../internal/default-strings/viewers.generated.js";const MAX_PPTX_SEARCH_MATCHES=1e4,MAX_PPTX_THUMBNAIL_WIDTH=2048;class LyraPptxViewerBase extends LyraElement{}class LyraPptxViewer extends TextViewerTarget(LyraPptxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.maxHeight="",this.phase="idle",this.errorMessage="",this.slideCount=0,this.currentSlideIndex=0,this.loadRenderer=getPptxRenderer,this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.pptxSearchQuery="",this.lastSearchLocale="",this.pptxSearchMatches=[],this.pendingSearchResetEvent=!1,this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.pptxSearchGeneration=0,this.pageViewerState=new PageViewerSnapshotController,this.anchorKinds=["text-quote","fragment","page"],this.onViewerEvent=event=>{if(event.kind==="slide-change"){this.commitSlide(event.index);return}this.reportPeerDiagnostic(event.code,event.cause,{page:event.page,nodeId:event.nodeId},event.fatal)},this.focusedPagerPart=null,this.detached=new DeferredTeardown(()=>this.releaseDetachedPresentation())}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,pptxViewerFidelityNotice:LYRA_DEFAULT_pptxViewerFidelityNotice,pptxViewerLabel:LYRA_DEFAULT_pptxViewerLabel,pptxViewerMissingLibrary:LYRA_DEFAULT_pptxViewerMissingLibrary,pptxViewerNextSlide:LYRA_DEFAULT_pptxViewerNextSlide,pptxViewerPreviousSlide:LYRA_DEFAULT_pptxViewerPreviousSlide,pptxViewerRenderError:LYRA_DEFAULT_pptxViewerRenderError,pptxViewerSlideOf:LYRA_DEFAULT_pptxViewerSlideOf}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}async search(query2){const generation=++this.pptxSearchGeneration,viewer=this.viewer,boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale);if(this.pptxSearchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.disposeSearchHighlight(),viewer?.clearSearchHighlights(),!boundedQuery.accepted)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;if(!viewer||!boundedQuery.needle)return this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.emitPptxSearchChange(),0;try{const raw=viewer.searchText(query2.trim(),{matchCase:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer)return this.pptxSearchMatches.length;const normalized=this.normalizeSearchResults(raw,viewer.slideCount);return this.pptxSearchMatches=normalized.matches,this.pptxSearchMatchCountExact=normalized.matchCountExact,this.pptxSearchActiveIndex=this.pptxSearchMatches.length>0?0:-1,this.emitPptxSearchChange(),this.pptxSearchActiveIndex>=0&&await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),this.pptxSearchMatches.length}catch(cause){return generation!==this.pptxSearchGeneration||viewer!==this.viewer||(this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!1,this.pptxSearchActiveIndex=-1,this.reportPeerDiagnostic("pptx-search-error",cause),this.emitPptxSearchChange()),0}}async searchNext(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex+1)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}async searchPrevious(){const viewer=this.viewer;if(!viewer||this.pptxSearchMatches.length===0)return!1;const generation=++this.pptxSearchGeneration;return this.pptxSearchActiveIndex=(this.pptxSearchActiveIndex-1+this.pptxSearchMatches.length)%this.pptxSearchMatches.length,this.emitPptxSearchChange(),await this.focusPptxSearchMatch(this.pptxSearchActiveIndex,generation,viewer),generation===this.pptxSearchGeneration}clearSearch(){this.pptxSearchGeneration++,this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.emitPptxSearchChange()}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}textContentRoot(){return this.renderRoot.querySelector('[part="container"]')??this.renderRoot.querySelector('[part="base"]')}async applyAnchor(anchor){const viewer=this.viewer;if(anchor.kind==="page"){const index=anchor.page-1;return!viewer||!Number.isInteger(anchor.page)||index<0||index>=this.slideCount?!1:(await this.goToSlide(index),viewer===this.viewer&&this.currentSlideIndex===index)}if(anchor.kind==="text-quote"&&viewer){const slideIndex=this.slideForTextQuote(viewer,anchor);if(slideIndex>=0&&slideIndex!==this.currentSlideIndex){if(await this.goToSlide(slideIndex),viewer!==this.viewer||this.currentSlideIndex!==slideIndex)return!1;await this.updateComplete}}return this.applyMountedAnchor(anchor)}applyMountedAnchor(anchor){return Object.getPrototypeOf(LyraPptxViewer.prototype).applyAnchor.call(this,anchor)}slideForTextQuote(viewer,anchor){const quote=anchor.quote.trim(),bounded=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!bounded.accepted||!bounded.needle)return-1;let matches;try{matches=this.normalizeSearchResults(viewer.searchText(quote,{matchCase:!1}),viewer.slideCount).matches}catch(cause){return this.reportPeerDiagnostic("pptx-search-error",cause),-1}let best,bestScore=-1;for(const match of matches){const score=textQuoteContextScore(match.text,match.matchStart,match.matchEnd,anchor.prefix,anchor.suffix);score>bestScore&&(best=match,bestScore=score)}return best?.slideIndex??-1}keepPagerFocus(){const part=this.focusedPagerPart;this.focusedPagerPart=null;const twin=part==="previous-button"?"next-button":part==="next-button"?"previous-button":void 0,root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}updated(changed){if(super.updated(changed),this.keepPagerFocus(),this.announcements.transition("load",this.phase,this.phase==="error"?this.errorMessage:this.localize("loading")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.mount()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitPptxSearchChange()),changed.has("page")&&this.viewer&&this.page-1!==this.currentSlideIndex){const page=this.page;this.scheduleAfterUpdate(()=>{this.page===page&&this.goToSlide(page-1)},"page-navigation")}const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.pptxSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.pptxSearchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);this.focusedPagerPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasPptxSearchState(),this.resetPptxSearchState()),(changed.has("page")||changed.has("slideCount"))&&(this.page=finiteInteger(this.page,1,1,Math.max(1,this.slideCount)))}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&(!moved||this.phase==="loading")&&this.scheduleAfterUpdate(()=>{this.mount()})}disconnectedCallback(){this.phase==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPresentation(){this.teardown(),this.phase="idle",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async goToSlide(index){const viewer=this.viewer;if(!viewer||!Number.isSafeInteger(index)||index<0||index>=viewer.slideCount)return;const generation=this.generation;try{await viewer.goToSlide(index)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||viewer!==this.viewer)return;this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}viewer===this.viewer&&viewer.currentSlideIndex!==this.currentSlideIndex&&this.commitSlide(viewer.currentSlideIndex)}async renderPageThumbnailToContainer(page,container,options){const viewer=this.viewer,generation=this.generation,width=options?.width??96;if(!viewer||!Number.isSafeInteger(page)||page<1||page>viewer.slideCount||!Number.isFinite(width)||width<=0||width>MAX_PPTX_THUMBNAIL_WIDTH)return!1;const previousChildren=[...container.childNodes],restorePreviousChildren=()=>{container.replaceChildren(...previousChildren)};let handle;try{handle=viewer.renderThumbnailToContainer(page-1,container,{width})}catch{return restorePreviousChildren(),!1}if(!handle)return restorePreviousChildren(),!1;try{await handle.ready}catch{return handle.dispose(),restorePreviousChildren(),!1}if(generation!==this.generation||viewer!==this.viewer||!container.isConnected)return handle.dispose(),restorePreviousChildren(),!1;for(const child of previousChildren)child.parentNode===container&&child.remove();return handle}isValidSlideIndex(index){return Number.isSafeInteger(index)&&index>=0&&index<this.slideCount}commitSlide(index){if(!this.isValidSlideIndex(index))return;const changed=index!==this.currentSlideIndex;this.currentSlideIndex=index,this.page=index+1,this.publishPageViewerSnapshot("ready",this.slideCount),changed&&this.emit("lr-slide-change",{index,count:this.slideCount})}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,finiteInteger(this.page,1,1,Math.max(1,pageCount)),finiteInteger(pageCount,0,0,Number.MAX_SAFE_INTEGER));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}teardown(){const shouldEmitSearchReset=this.hasPptxSearchState();this.generation++,this.viewerUnsubscribe?.(),this.viewerUnsubscribe=void 0,this.viewer?.destroy(),this.viewer=void 0,this.resetPptxSearchState(),shouldEmitSearchReset&&this.emitPptxSearchChange()}hasPptxSearchState(){return this.pptxSearchQuery!==""||this.pptxSearchMatches.length>0||!this.pptxSearchMatchCountExact||this.pptxSearchActiveIndex!==-1}resetPptxSearchState(){this.pptxSearchGeneration++,this.disposeSearchHighlight(),this.viewer?.clearSearchHighlights(),this.pptxSearchQuery="",this.pptxSearchMatches=[],this.pptxSearchMatchCountExact=!0,this.pptxSearchActiveIndex=-1}normalizeSearchResults(value,slideCount){if(!Array.isArray(value))throw new TypeError("PPTX search returned a non-array result.");const matches=[],work=new ViewerSearchWorkBudget;let matchCountExact=!0;for(const candidate of value){if(!work.consume("")){matchCountExact=!1;break}if(!candidate||typeof candidate!="object")continue;const result=candidate;if(!(!Number.isSafeInteger(result.slideIndex)||result.slideIndex<0||result.slideIndex>=slideCount||typeof result.nodeId!="string"||typeof result.text!="string"||!Number.isSafeInteger(result.matchStart)||!Number.isSafeInteger(result.matchEnd)||result.matchStart<0||result.matchEnd<result.matchStart||result.matchEnd>result.text.length)){if(!work.consume(result.nodeId)||!work.consume(result.text)){matchCountExact=!1;break}if(matches.length===MAX_PPTX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push(candidate)}}return{matches,matchCountExact:matchCountExact&&work.complete}}async focusPptxSearchMatch(index,generation,viewer){const match=this.pptxSearchMatches[index];if(match){this.disposeSearchHighlight(),viewer.clearSearchHighlights();try{if(await viewer.goToSlide(match.slideIndex),generation!==this.pptxSearchGeneration||viewer!==this.viewer)return;const highlight=await viewer.highlightSearchResult(match,{scrollIntoView:!1});if(generation!==this.pptxSearchGeneration||viewer!==this.viewer){highlight?.dispose();return}this.searchHighlight=highlight??void 0}catch(cause){generation===this.pptxSearchGeneration&&viewer===this.viewer&&this.reportPeerDiagnostic("pptx-search-error",cause,{page:match.slideIndex+1})}}}disposeSearchHighlight(){this.searchHighlight?.dispose(),this.searchHighlight=void 0}emitPptxSearchChange(){this.emit("lr-search-change",{query:this.pptxSearchQuery,matchCount:this.pptxSearchMatches.length,matchCountExact:this.pptxSearchMatchCountExact,activeIndex:this.pptxSearchActiveIndex})}reportPeerDiagnostic(code,cause,location={},fatal=!1){this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code,severity:"error",fatal,source:"pptx-renderer",cause,...location})}),fatal&&(this.teardown(),this.phase="error",this.slideCount=0,this.currentSlideIndex=0,this.page=1,this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error:cause}))}async mount(){this.teardown(),this.pageViewerState.advance();const signal=this.beginAbortableLoad(),generation=this.generation;if(this.slideCount=0,this.currentSlideIndex=0,this.page=1,!this.src){this.phase="idle",this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.phase="loading",this.publishPageViewerSnapshot("loading",0);let module,response;try{[module,response]=await Promise.all([this.loadRenderer(),fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0)])}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!module||!response.ok){response.body?.cancel().catch(()=>{});const error=new LyraUserFacingError(this.localize(module?"documentPreviewFailedToLoad":"pptxViewerMissingLibrary"));this.phase="error",this.errorMessage=error.message,this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}let buffer;try{if(buffer=await readResponseArrayBuffer(response),signal?.aborted||!this.isConnected||generation!==this.generation)return;await assertPptxArchiveWithinLimits(buffer,{signal})}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}if(!(signal?.aborted||!this.isConnected||generation!==this.generation)&&(this.phase="mounted",await this.updateComplete,!(!this.isConnected||generation!==this.generation||!this.containerEl)))try{const openedViewer=await module.PptxViewer.open(buffer,this.containerEl,{externalMedia:"block",zipLimits:module.RECOMMENDED_ZIP_LIMITS,listOptions:{windowed:!0}});if(!this.isConnected||generation!==this.generation){openedViewer.destroy();return}const viewer=adaptPptxViewer(openedViewer);if(!viewer)throw openedViewer.destroy(),new TypeError("The PPTX renderer did not expose the required viewer capabilities.");this.viewer=viewer,this.viewerUnsubscribe=viewer.subscribe(this.onViewerEvent),this.slideCount=viewer.slideCount,this.isValidSlideIndex(viewer.currentSlideIndex)&&(this.currentSlideIndex=viewer.currentSlideIndex,this.page=viewer.currentSlideIndex+1),this.publishPageViewerSnapshot("ready",viewer.slideCount),this.emit("lr-load",{slideCount:viewer.slideCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.phase="error",this.errorMessage=this.localize("pptxViewerRenderError"),this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}renderBody(){return this.phase==="loading"?renderViewerLoading(this.localize("loading")):this.phase==="error"?html`<div part="error">${this.errorMessage}</div>`:this.phase!=="mounted"?nothing:html`
|
|
2
2
|
<div part="nav" ?hidden=${this.slideCount<=1}>
|
|
3
3
|
${renderViewerPagerButton("previous",this.localize("pptxViewerPreviousSlide"),this.currentSlideIndex<=0,()=>{this.goToSlide(this.currentSlideIndex-1)})}
|
|
4
4
|
<span part="slide-count">${this.localize("pptxViewerSlideOf",void 0,{current:getNumberFormat(this.effectiveLocale).format(this.currentSlideIndex+1),total:getNumberFormat(this.effectiveLocale).format(this.slideCount)})}</span>
|
|
@@ -21,7 +21,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
|
|
|
21
21
|
.items=${guard([sheet.body],()=>sheet.body.length<=1e4?sheet.body:nothing)}
|
|
22
22
|
.source=${this.table.indexedSource(sheet.body)}
|
|
23
23
|
.renderItem=${this.table.rowRenderer(sheet,[this.table.columnWindow(sheet.name,count).columns,this.activeHighlightId,this.strings],(row,bodyIndex)=>this.renderRow(row,count,"data-row",bodyIndex+2,sheet.name))}
|
|
24
|
-
.keyFunction=${this.virtualListKeyFunction}
|
|
24
|
+
.keyFunction=${sheet.body.length<=1e4?this.virtualListKeyFunction:void 0}
|
|
25
25
|
.activeItemId=${index===this.activeRowSheet?this.table.activeRowKey:""}
|
|
26
26
|
item-role="row"
|
|
27
27
|
row-index-offset="1"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{loadSvgSanitizer}from"./dompurify-loader.js";import{styles}from"./svg-viewer.styles.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizePassiveMarkup}from"../passive-markup.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_documentPreviewTypeImage,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_svgViewerLabel}from"../../../internal/default-strings/viewers.generated.js";function sameRegionAnchor(a,b){return a.kind==="region"&&b.kind==="region"&&sameRegionRect(a,b)}function sanitizeInlineSvg(sanitizer,raw,ownerDocument){const markup=sanitizePassiveMarkup(sanitizer,raw,ownerDocument,"passive-svg"),template=ownerDocument.createElement("template");if(template.innerHTML=markup,!template.content.querySelector("svg"))throw new Error("SVG sanitizer did not return an SVG document.");return markup}const MAX_PAINTED_HIGHLIGHTS=100;class LyraSvgViewerBase extends LyraElement{}class LyraSvgViewer extends DocumentAnchorTarget(LyraSvgViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.zoomable=!1,this.anchorKinds=["region"],this.fetchState={kind:"idle"},this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++,this.beginAbortableLoad(),this.fetchState={kind:"idle"}})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,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,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,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,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,svgViewerLabel:LYRA_DEFAULT_svgViewerLabel}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,viewerLoadingStyles,srOnly]}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const sanitizer=await loadSvgSanitizer();if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!sanitizer)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const raw=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const markup=sanitizeInlineSvg(sanitizer,raw,this.ownerDocument);!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",markup})}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const message=error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}}renderBody(regionHighlights){switch(this.fetchState.kind){case"loaded":return this.renderZoomableWrapper(html`<div part="svg">${unsafeSVG(this.fetchState.markup)}</div>`,regionHighlights);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("documentPreviewTypeImage")})}</p>`}}stopPanZoomEvent(event){event.stopPropagation()}renderZoomableWrapper(content,regionHighlights){const inner=html`<div class="zoom-content">
|
|
2
2
|
${content}${this.renderHighlightLayer(regionHighlights,regionHighlights.length===1)}
|
|
3
3
|
</div>`,frame=this.zoomable?html`<lr-pan-zoom
|
|
4
4
|
exportparts="viewport:frame-viewport, content:frame-content, controls:frame-controls, zoom-in:frame-zoom-in, zoom-out:frame-zoom-out, reset:frame-reset"
|
|
@@ -13,10 +13,10 @@ import{SourceRequestController,sourceCount,sourceRevision}from"../../internal/so
|
|
|
13
13
|
>
|
|
14
14
|
${text}
|
|
15
15
|
</button>
|
|
16
|
-
</div>`}columnWindow(key,count,limit=count){if(this.geometryWidth===void 0){const view=this.host.ownerDocument.defaultView,token=view?.getComputedStyle(this.host).getPropertyValue("--lr-size-8rem").trim()||"8rem";if(this.geometryWidth=Math.max(1,resolveCssTokenLength(token,{host:this.host})??1),this.hooks.pageScroll?.()&&view){const rect=this.host.getBoundingClientRect(),leading=view.getComputedStyle(this.host).direction==="rtl"?view.innerWidth-rect.right:rect.left;this.geometryAllocation=Math.max(0,view.innerWidth-Math.max(0,leading)),this.pageOffset=Math.max(0,-leading)}else this.geometryAllocation=this.host.clientWidth}const width=this.geometryWidth,allocation=this.geometryAllocation??0;let window=this.windows.get(key);const offset=this.hooks.pageScroll?.()?this.forcedPageOffset??this.pageOffset:window?.offset??0,start=Math.min(Math.max(0,count-1),Math.max(0,Math.floor(offset/width)-2)),end=Math.min(count,start+Math.max(1,limit),Math.max(start+1,Math.ceil((offset+allocation)/width)+4));return(!window||window.count!==count||window.width!==width||window.start!==start||window.end!==end)&&(window={start,end,count,width,offset,columns:Array.from({length:end-start},(_,index)=>start+index),style:`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr));min-inline-size:calc(${count} * var(--lr-size-8rem))`},this.windows.set(key,window)),window}scrollColumns(key,target){this.setColumnOffset(key,Math.abs(target.scrollLeft))}setColumnOffset(key,offset){const window=this.windows.get(key);if(!window||window.offset===offset)return;window.offset=offset;const previous=window.columns;this.columnWindow(key,window.count).columns!==previous&&this.hooks.repaint()}async showColumn(key,col,scroller){const window=this.windows.get(key);if(!(!window||!scroller)&&(col<window.start||col>=window.end)){const rtl=this.host.ownerDocument.defaultView?.getComputedStyle(this.host).direction==="rtl";scroller.scrollLeft=(rtl?-1:1)*col*window.width,this.hooks.pageScroll?.()?(this.forcedPageOffset=col*window.width,this.setColumnOffset(key,this.forcedPageOffset)):this.scrollColumns(key,scroller),await this.host.updateComplete}}rowRenderer(key,inputs,render){const dependencies=[...inputs,this.highlights,this.hooks.locale(),this.hooks.localize("highlightWithLabel"),this.hooks.localize("cellHighlightWithLabel")],existing=this.renderers.get(key);if(existing&&dependencies.length===existing.inputs.length&&dependencies.every((value,index)=>value===existing.inputs[index]))return existing.render;const rows=new Map,memo=(row,index)=>{const existing2=rows.get(index);if(existing2&&existing2.row===row)return existing2.result;const result=render(row,index);return rows.set(index,{row,result}),rows.size>256&&rows.delete(rows.keys().next().value),result};return this.renderers.set(key,{inputs:dependencies,render:memo}),memo}revealCell(target){return this.scroll.reveal(target),!!target}scrollColumnIntoView(root,selector,col){return this.scroll.scrollColumnIntoView(root.querySelector(selector),col)}async runSearch(query,loaded,scan,source=scan){this.search.query=query;const locale=this.hooks.locale();this.lastLocale=locale;const bounded=boundedViewerSearchQuery(query,locale),matches=[];let exact=bounded.accepted;if(loaded&&bounded.accepted&&bounded.needle){let corpus=this.searchCorpus;if(!corpus||corpus.source!==source||corpus.locale!==locale){const budget=new ViewerSearchWorkBudget,fields=[];scan((text,match)=>(fields.push({text:budget.prepare(text,locale),match}),budget.complete)),corpus={source,locale,fields,exact:budget.complete},this.searchCorpus=corpus}exact=corpus.exact;for(const field of corpus.fields)if(field.text?.includes(bounded.needle)){if(matches.length===MAX_TABLE_SEARCH_MATCHES){exact=!1;break}matches.push(field.match)}}return this.search.publish(matches,exact),matches.length>0&&await this.hooks.jump(matches[0]),matches.length}async step(direction){return this.search.step(direction)?await this.hooks.jump(this.search.matches[this.search.activeIndex])!==!1:!1}clearSearch(){this.activeRowKey="",this.search.clear()}}const TABLE_VIEWER_SOURCE_MESSAGE_KEYS={documentPreviewResourceTooLarge:"documentPreviewResourceTooLarge",documentPreviewFailedToLoad:"documentPreviewFailedToLoad",noData:"noData",loadingDocument:"loadingDocument",sourceSearchUnavailable:"sourceSearchUnavailable"};class TableViewerSourceController{constructor(host,chrome,hooks){this.host=host,this.chrome=chrome,this.hooks=hooks,this.locale="",this.limit=0,this.dirty=!0,this.bindingIntent=0,this.sheets=[],this.sheetIndex=0,this.rows=0,this.columns=0,this.slots=[],this.physicalReads=0,this.epoch=0,this.paint=0,this.firstRow=0,this.visibleRows=0,this.windowIntent=0,this.activeRow="",this.windowColumns=[],this.labels=[],this.columnStart=0,this.labelUnits=0,this.loaded=!1,this.pendingPaint=!1,this.sourceRows=this.makeRows(),this.searchRunning=!1,this.onRange=event=>{if(event.stopPropagation(),!this.loaded||event.currentTarget.source!==this.sourceRows)return;const start=Math.min(this.rows,event.detail.start),row=Math.max(0,start-6),visible=Math.max(0,Math.min(this.rows,event.detail.end)-start);row===this.firstRow&&visible===this.visibleRows||(this.visibleRows=visible,this.firstRow=row,this.requestWindow(),this.notify())},this.searchState=new ViewerSearchState(()=>[],detail=>hooks.emitSearch(detail),()=>hooks.repaint()),this.authority=new SourceRequestController(host,{channels:["cells0","cells1","search","reveal"],onReset:()=>this.reset()}),host.addController(this)}get enabled(){return this.hooks.source()!==void 0}get busy(){return this.enabled&&!this.failure&&this.slots.some(slot=>slot.state!=="ready")}makeRows(){return{count:this.rows,itemAt:index=>index,keyAt:index=>index,indexOfKey:key=>typeof key=="number"&&Number.isSafeInteger(key)&&key>=0&&key<this.rows?key:-1}}notify(){if(this.pendingPaint)return;this.pendingPaint=!0;const document=this.host.ownerDocument;queueMicrotask(()=>{this.pendingPaint=!1,this.host.isConnected&&this.host.ownerDocument===document&&this.hooks.repaint()})}reset(){this.epoch++,this.dirty=!0;for(const slot of this.slots)slot.settle(!1);this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.failure=void 0,this.loaded=!1,this.firstRow=0,this.visibleRows=0,this.paint++,this.queuedSearch=void 0,this.notify()}refresh(){this.bindingIntent++,this.hooks.cancelAnchor(),this.authority.refresh()}hostConnected(){this.dirty=!0,this.notify()}hostDisconnected(){this.dirty=!0}adopted(){this.hooks.cancelAnchor(),this.authority.adopted()}update(){const source=this.hooks.source(),intent=this.bindingIntent,locale=this.hooks.locale(),limit=this.hooks.columnLimit();if(!(source===this.bound&&this.failure&&!this.dirty&&locale===this.locale&&limit===this.limit))try{const revision=source===void 0?void 0:sourceRevision(source.revision);if(source===this.bound&&revision===this.revision&&locale===this.locale&&limit===this.limit&&!this.dirty||source!==this.hooks.source()||intent!==this.bindingIntent||(source===this.bound&&(revision!==this.revision||locale!==this.locale||limit!==this.limit)&&this.hooks.cancelAnchor(),this.authority.setSource(source,revision),source!==this.hooks.source()||intent!==this.bindingIntent))return;source===this.bound&&revision===this.revision&&(locale!==this.locale||limit!==this.limit)&&this.authority.refresh();const epoch=this.epoch;if(this.bound=source,this.revision=revision,this.locale=locale,this.limit=limit,this.dirty=!1,this.failure=void 0,this.sheetIndex=0,this.firstRow=0,this.activeRow="",this.searchState.dirty&&this.searchState.clear(),source===void 0){this.theme&&(this.theme.hostDisconnected(),this.host.removeController(this.theme),this.theme=void 0),this.sheets=[],this.sheet=void 0;return}this.theme??=new ThemeWatcher(this.host,()=>this.notify());let sheets;if(this.hooks.workbook){const raw=source.sheets;if(!Array.isArray(raw)||raw.length>256)throw new LyraResourceLimitError;const keys=new Set,names=new Set;sheets=raw.map(entry=>{if(!entry||typeof entry.key!="string"||!entry.key||typeof entry.name!="string"||!entry.name||keys.has(entry.key)||names.has(entry.name))throw new TypeError("Invalid source sheet");if(entry.key.length>65536||entry.name.length>65536)throw new LyraResourceLimitError;return keys.add(entry.key),names.add(entry.name),Object.freeze({key:entry.key,name:entry.name,data:entry.data})})}else sheets=[{key:"",name:"",data:source}];if(!this.current(epoch))return;this.sheets=Object.freeze(sheets),this.selectSheet(0)}catch(error){if(this.hooks.source()!==source)return;this.bound=source,this.locale=locale,this.limit=limit,this.dirty=!1,this.fail(error)}}current(epoch){return epoch===this.epoch&&this.hooks.source()===this.bound&&this.host.isConnected}fail(error){this.failure!==error&&(this.failure=error,this.hooks.error(error),this.notify())}selectSheet(index){this.authority.invalidate("cells0"),this.authority.invalidate("cells1"),this.authority.invalidate("reveal");for(const slot of this.slots)slot.settle(!1);if(this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.firstRow=0,this.visibleRows=0,this.activeRow="",this.sheetIndex=index,this.sheet=this.sheets[index],this.paint++,!this.sheet){this.rows=this.columns=0,this.sourceRows=this.makeRows();return}const data=this.sheet.data,epoch=this.epoch,revision=sourceRevision(data.revision),rows=sourceCount(data.rowCount),columns=sourceCount(data.columnCount);if(rows>=Number.MAX_SAFE_INTEGER||columns>this.limit)throw new LyraResourceLimitError;if(typeof data.columnAt!="function"||typeof data.cellAt=="function"==(typeof data.readCells=="function"))throw new TypeError("Invalid cell source");this.current(epoch)&&(this.sheetRevision=revision,this.rows=rows,this.columns=columns,this.sourceRows=this.makeRows(),this.loaded=!0,this.host.shadowRoot?.querySelector(tag("virtual-list"))?.scrollToIndex(0,{align:"start",behavior:"auto"}))}scalar(value){if(value!=null&&typeof value!="string"&&typeof value!="boolean"&&(typeof value!="number"||!Number.isFinite(value)))throw new TypeError("Invalid source cell");const text=this.hooks.format(value);if(text.length>65536)throw new LyraResourceLimitError;return text}prepareColumns(columns){if(this.windowColumns===columns||!this.sheet)return;const epoch=this.epoch,sheet=this.sheet,labels=[];let units=0;for(const index of columns){const column=sheet.data.columnAt(index);if(!this.current(epoch)||this.sheet!==sheet)return;if(!column||typeof column.key!="string"||!column.key||typeof column.label!="string")throw new TypeError("Invalid source column");if(column.key.length>65536||column.label.length>65536)throw new LyraResourceLimitError;if(units+=column.key.length+column.label.length,units>2e6)throw new LyraResourceLimitError;labels.push(Object.freeze({key:column.key,label:column.label}))}this.labels=labels,this.labelUnits=units,this.windowColumns=columns,this.columnStart=columns[0]??0,this.paint++,this.requestWindow()}requestWindow(){if(!this.sheet||!this.loaded||!this.windowColumns.length||!this.rows||this.failure)return;const epoch=this.epoch,intent=++this.windowIntent,maximum=Math.min(500,Math.floor(1e4/this.windowColumns.length)),first=Math.min(this.firstRow,this.rows-1),demand=Math.min(this.rows-first,this.visibleRows+12),block=Math.min(maximum,Math.max(64,demand));if(demand>maximum*2){this.fail(new LyraResourceLimitError);return}const aligned=Math.floor(first/block)*block,row=first-aligned+demand<=block*2?aligned:first,starts=row+block<this.rows?[row,row+block]:[row],keys=starts.map(start=>`${this.sheetIndex}:${start}:${block}:${this.columnStart}:${this.windowColumns.length}`),previous=this.slots;this.slots=previous.filter(slot=>keys.includes(slot.key));for(const slot of previous)if(!this.slots.includes(slot)&&(slot.settle(!1),this.authority.invalidate(slot.channel),!this.current(epoch)||intent!==this.windowIntent))return;for(let index=0;index<starts.length;index++){if(this.slots.some(slot2=>slot2.key===keys[index]))continue;const channel=this.slots.some(slot2=>slot2.channel==="cells0")?"cells1":"cells0",lease=this.authority.begin(channel,this.locale);if(!lease||!this.current(epoch)||intent!==this.windowIntent)return;let settle;const promise=new Promise(resolve=>{settle=resolve}),slot={key:keys[index],channel,row:starts[index],rows:Math.min(block,this.rows-starts[index]),column:this.columnStart,columns:this.windowColumns.length,lease,source:this.sheet.data,promise,settle,state:"queued",units:0};lease.context.signal.addEventListener("abort",()=>slot.settle(!1),{once:!0}),this.slots.push(slot)}this.paint++,queueMicrotask(()=>this.pump())}pump(){for(;this.physicalReads<2;){const slot=this.slots.find(value=>value.state==="queued"&&value.lease.isCurrent());if(!slot)return;slot.state="loading",this.physicalReads++,this.read(slot)}}async read(slot){try{const source=slot.source,result=source.readCells?await source.readCells(Object.freeze({...slot.lease.context,revision:this.sheetRevision,row:slot.row,rowCount:slot.rows,column:slot.column,columnCount:slot.columns})):void 0;if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;if(result!==void 0&&(!Array.isArray(result)||result.length!==slot.rows))throw new TypeError("Invalid source rectangle");const values=[];let units=this.labelUnits+this.slots.reduce((sum,other)=>sum+(other===slot?0:other.units),0);const initialUnits=units;for(let row=0;row<slot.rows;row++){const input=result?.[row];if(result!==void 0&&(!Array.isArray(input)||input.length!==slot.columns))throw new TypeError("Invalid source rectangle row");const cells=[];for(let col=0;col<slot.columns;col++){const value=result!==void 0?input[col]:source.cellAt(slot.row+row,slot.column+col);if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;const text=this.scalar(value);if(units+=text.length,units>2e6)throw new LyraResourceLimitError;cells.push(text)}values.push(cells)}slot.values=values,slot.units=units-initialUnits,slot.state="ready",slot.settle(!0),this.paint++,this.notify()}catch(error){slot.lease.isCurrent()&&this.slots.includes(slot)&&this.fail(error),slot.settle(!1)}finally{this.physicalReads--,this.pump()}}scrollColumns(target){this.chrome.scrollColumns(this,target)}row(index,style,height){const slot=this.slots.find(value=>index>=value.row&&index<value.row+value.rows&&value.state==="ready"),rawRow=index+1+Number(this.hooks.header()),highlights=this.chrome.highlightsForRow(rawRow,this.hooks.workbook?this.sheet?.name:void 0);return html`<div part="data-row" role="presentation" aria-busy=${slot?"false":"true"} style=${`${style};height:${height}px;overflow:hidden`}>
|
|
16
|
+
</div>`}columnWindow(key,count,limit=count){if(this.geometryWidth===void 0){const view=this.host.ownerDocument.defaultView,token=view?.getComputedStyle(this.host).getPropertyValue("--lr-size-8rem").trim()||"8rem";if(this.geometryWidth=Math.max(1,resolveCssTokenLength(token,{host:this.host})??1),this.hooks.pageScroll?.()&&view){const rect=this.host.getBoundingClientRect(),leading=view.getComputedStyle(this.host).direction==="rtl"?view.innerWidth-rect.right:rect.left;this.geometryAllocation=Math.max(0,view.innerWidth-Math.max(0,leading)),this.pageOffset=Math.max(0,-leading)}else this.geometryAllocation=this.host.clientWidth}const width=this.geometryWidth,allocation=this.geometryAllocation??0;let window=this.windows.get(key);const offset=this.hooks.pageScroll?.()?this.forcedPageOffset??this.pageOffset:window?.offset??0,start=Math.min(Math.max(0,count-1),Math.max(0,Math.floor(offset/width)-2)),end=Math.min(count,start+Math.max(1,limit),Math.max(start+1,Math.ceil((offset+allocation)/width)+4));return(!window||window.count!==count||window.width!==width||window.start!==start||window.end!==end)&&(window={start,end,count,width,offset,columns:Array.from({length:end-start},(_,index)=>start+index),style:`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr));min-inline-size:calc(${count} * var(--lr-size-8rem))`},this.windows.set(key,window)),window}scrollColumns(key,target){this.setColumnOffset(key,Math.abs(target.scrollLeft))}setColumnOffset(key,offset){const window=this.windows.get(key);if(!window||window.offset===offset)return;window.offset=offset;const previous=window.columns;this.columnWindow(key,window.count).columns!==previous&&this.hooks.repaint()}async showColumn(key,col,scroller){const window=this.windows.get(key);if(!(!window||!scroller)&&(col<window.start||col>=window.end)){const rtl=this.host.ownerDocument.defaultView?.getComputedStyle(this.host).direction==="rtl";scroller.scrollLeft=(rtl?-1:1)*col*window.width,this.hooks.pageScroll?.()?(this.forcedPageOffset=col*window.width,this.setColumnOffset(key,this.forcedPageOffset)):this.scrollColumns(key,scroller),await this.host.updateComplete}}rowRenderer(key,inputs,render){const dependencies=[...inputs,this.highlights,this.hooks.locale(),this.hooks.localize("highlightWithLabel"),this.hooks.localize("cellHighlightWithLabel")],existing=this.renderers.get(key);if(existing&&dependencies.length===existing.inputs.length&&dependencies.every((value,index)=>value===existing.inputs[index]))return existing.render;const rows=new Map,memo=(row,index)=>{const existing2=rows.get(index);if(existing2&&existing2.row===row)return existing2.result;const result=render(row,index);return rows.set(index,{row,result}),rows.size>256&&rows.delete(rows.keys().next().value),result};return this.renderers.set(key,{inputs:dependencies,render:memo}),memo}revealCell(target){return this.scroll.reveal(target),!!target}scrollColumnIntoView(root,selector,col){return this.scroll.scrollColumnIntoView(root.querySelector(selector),col)}async runSearch(query,loaded,scan,source=scan){this.search.query=query;const locale=this.hooks.locale();this.lastLocale=locale;const bounded=boundedViewerSearchQuery(query,locale),matches=[];let exact=bounded.accepted;if(loaded&&bounded.accepted&&bounded.needle){let corpus=this.searchCorpus;if(!corpus||corpus.source!==source||corpus.locale!==locale){const budget=new ViewerSearchWorkBudget,fields=[];scan((text,match)=>(fields.push({text:budget.prepare(text,locale),match}),budget.complete)),corpus={source,locale,fields,exact:budget.complete},this.searchCorpus=corpus}exact=corpus.exact;for(const field of corpus.fields)if(field.text?.includes(bounded.needle)){if(matches.length===MAX_TABLE_SEARCH_MATCHES){exact=!1;break}matches.push(field.match)}}return this.search.publish(matches,exact)?(matches.length>0&&await this.hooks.jump(matches[0]),matches.length):0}async step(direction){return this.search.step(direction)?await this.hooks.jump(this.search.matches[this.search.activeIndex])!==!1:!1}clearSearch(){this.activeRowKey="",this.search.clear()}}const TABLE_VIEWER_SOURCE_MESSAGE_KEYS={documentPreviewResourceTooLarge:"documentPreviewResourceTooLarge",documentPreviewFailedToLoad:"documentPreviewFailedToLoad",noData:"noData",loadingDocument:"loadingDocument",sourceSearchUnavailable:"sourceSearchUnavailable"};class TableViewerSourceController{constructor(host,chrome,hooks){this.host=host,this.chrome=chrome,this.hooks=hooks,this.locale="",this.limit=0,this.dirty=!0,this.bindingIntent=0,this.sheetIntent=0,this.sheets=[],this.sheetIndex=0,this.rows=0,this.columns=0,this.slots=[],this.physicalReads=0,this.epoch=0,this.paint=0,this.firstRow=0,this.visibleRows=0,this.windowIntent=0,this.activeRow="",this.windowColumns=[],this.labels=[],this.columnStart=0,this.labelUnits=0,this.loaded=!1,this.pendingPaint=!1,this.sourceRows=this.makeRows(),this.searchRunning=!1,this.searchIntent=0,this.onRange=event=>{if(event.stopPropagation(),!this.loaded||event.currentTarget.source!==this.sourceRows)return;const start=Math.min(this.rows,event.detail.start),row=Math.max(0,start-6),visible=Math.max(0,Math.min(this.rows,event.detail.end)-start);row===this.firstRow&&visible===this.visibleRows||(this.visibleRows=visible,this.firstRow=row,this.requestWindow(),this.notify())},this.searchState=new ViewerSearchState(()=>[],detail=>hooks.emitSearch(detail),()=>hooks.repaint()),this.authority=new SourceRequestController(host,{channels:["cells0","cells1","search","reveal"],onReset:()=>this.reset()}),host.addController(this)}get enabled(){return this.hooks.source()!==void 0}get busy(){return this.enabled&&!this.failure&&this.slots.some(slot=>slot.state!=="ready")}makeRows(){return{count:this.rows,itemAt:index=>index,keyAt:index=>index,indexOfKey:key=>typeof key=="number"&&Number.isSafeInteger(key)&&key>=0&&key<this.rows?key:-1}}notify(){if(this.pendingPaint)return;this.pendingPaint=!0;const document=this.host.ownerDocument;queueMicrotask(()=>{this.pendingPaint=!1,this.host.isConnected&&this.host.ownerDocument===document&&this.hooks.repaint()})}reset(){this.epoch++,this.searchIntent++,this.dirty=!0;for(const slot of this.slots)slot.settle(!1);this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.failure=void 0,this.loaded=!1,this.firstRow=0,this.visibleRows=0,this.paint++,this.queuedSearch=void 0,this.notify()}refresh(){this.bindingIntent++,this.hooks.cancelAnchor(),this.authority.refresh()}hostConnected(){this.dirty=!0,this.notify()}hostDisconnected(){this.dirty=!0}adopted(){this.hooks.cancelAnchor(),this.authority.adopted()}update(){const source=this.hooks.source(),intent=this.bindingIntent,locale=this.hooks.locale(),limit=this.hooks.columnLimit();if(!(source===this.bound&&this.failure&&!this.dirty&&locale===this.locale&&limit===this.limit))try{const revision=source===void 0?void 0:sourceRevision(source.revision);if(source===this.bound&&revision===this.revision&&locale===this.locale&&limit===this.limit&&!this.dirty||source!==this.hooks.source()||intent!==this.bindingIntent||(source===this.bound&&(revision!==this.revision||locale!==this.locale||limit!==this.limit)&&this.hooks.cancelAnchor(),this.authority.setSource(source,revision),source!==this.hooks.source()||intent!==this.bindingIntent))return;source===this.bound&&revision===this.revision&&(locale!==this.locale||limit!==this.limit)&&this.authority.refresh();const epoch=this.epoch;if(this.bound=source,this.revision=revision,this.locale=locale,this.limit=limit,this.dirty=!1,this.failure=void 0,this.sheetIndex=0,this.firstRow=0,this.activeRow="",this.searchState.dirty&&this.searchState.clear(),source===void 0){this.theme&&(this.theme.hostDisconnected(),this.host.removeController(this.theme),this.theme=void 0),this.sheets=[],this.sheet=void 0;return}this.theme??=new ThemeWatcher(this.host,()=>this.notify());let sheets;if(this.hooks.workbook){const raw=source.sheets;if(!Array.isArray(raw)||raw.length>256)throw new LyraResourceLimitError;const keys=new Set,names=new Set;sheets=raw.map(entry=>{if(!entry||typeof entry.key!="string"||!entry.key||typeof entry.name!="string"||!entry.name||keys.has(entry.key)||names.has(entry.name))throw new TypeError("Invalid source sheet");if(entry.key.length>65536||entry.name.length>65536)throw new LyraResourceLimitError;return keys.add(entry.key),names.add(entry.name),Object.freeze({key:entry.key,name:entry.name,data:entry.data})})}else sheets=[{key:"",name:"",data:source}];if(!this.current(epoch))return;this.sheets=Object.freeze(sheets),this.selectSheet(0)}catch(error){if(this.hooks.source()!==source)return;this.bound=source,this.locale=locale,this.limit=limit,this.dirty=!1,this.fail(error)}}current(epoch){return epoch===this.epoch&&this.hooks.source()===this.bound&&this.host.isConnected}fail(error){this.failure!==error&&(this.failure=error,this.hooks.error(error),this.notify())}selectSheet(index){const intent=++this.sheetIntent,epoch=this.epoch,current=()=>intent===this.sheetIntent&&this.current(epoch);for(const channel of["cells0","cells1","reveal"])if(this.authority.invalidate(channel),!current())return!1;for(const slot of this.slots)slot.settle(!1);if(this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.firstRow=0,this.visibleRows=0,this.activeRow="",this.sheetIndex=index,this.sheet=this.sheets[index],this.paint++,!this.sheet)return this.rows=this.columns=0,this.sourceRows=this.makeRows(),!0;const data=this.sheet.data;try{const revision=sourceRevision(data.revision);if(!current())return!1;const rows=sourceCount(data.rowCount);if(!current())return!1;const columns=sourceCount(data.columnCount);if(!current())return!1;if(rows>=Number.MAX_SAFE_INTEGER||columns>this.limit)throw new LyraResourceLimitError;const columnAt=data.columnAt;if(!current())return!1;const cellAt=data.cellAt;if(!current())return!1;const readCells=data.readCells;if(!current())return!1;if(typeof columnAt!="function"||typeof cellAt=="function"==(typeof readCells=="function"))throw new TypeError("Invalid cell source");return this.sheetRevision=revision,this.rows=rows,this.columns=columns,this.sourceRows=this.makeRows(),this.loaded=!0,this.host.shadowRoot?.querySelector(tag("virtual-list"))?.scrollToIndex(0,{align:"start",behavior:"auto"}),current()}catch(error){if(current())throw error;return!1}}scalar(value){if(value!=null&&typeof value!="string"&&typeof value!="boolean"&&(typeof value!="number"||!Number.isFinite(value)))throw new TypeError("Invalid source cell");const text=this.hooks.format(value);if(text.length>65536)throw new LyraResourceLimitError;return text}prepareColumns(columns){if(this.windowColumns===columns||!this.sheet)return;const epoch=this.epoch,sheet=this.sheet,intent=this.sheetIntent,current=()=>this.current(epoch)&&this.sheet===sheet&&this.sheetIntent===intent,labels=[];let units=0;for(const index of columns){const column=sheet.data.columnAt(index);if(!current())return;if(!column)throw new TypeError("Invalid source column");const key=column.key;if(!current())return;const label=column.label;if(!current())return;if(typeof key!="string"||!key||typeof label!="string")throw new TypeError("Invalid source column");if(key.length>65536||label.length>65536)throw new LyraResourceLimitError;if(units+=key.length+label.length,units>2e6)throw new LyraResourceLimitError;labels.push(Object.freeze({key,label}))}this.labels=labels,this.labelUnits=units,this.windowColumns=columns,this.columnStart=columns[0]??0,this.paint++,this.requestWindow()}requestWindow(){if(!this.sheet||!this.loaded||!this.windowColumns.length||!this.rows||this.failure)return;const epoch=this.epoch,intent=++this.windowIntent,maximum=Math.min(500,Math.floor(1e4/this.windowColumns.length)),first=Math.min(this.firstRow,this.rows-1),demand=Math.min(this.rows-first,this.visibleRows+12),block=Math.min(maximum,Math.max(64,demand));if(demand>maximum*2){this.fail(new LyraResourceLimitError);return}const aligned=Math.floor(first/block)*block,row=first-aligned+demand<=block*2?aligned:first,starts=row+block<this.rows?[row,row+block]:[row],keys=starts.map(start=>`${this.sheetIndex}:${start}:${block}:${this.columnStart}:${this.windowColumns.length}`),previous=this.slots;this.slots=previous.filter(slot=>keys.includes(slot.key));for(const slot of previous)if(!this.slots.includes(slot)&&(slot.settle(!1),this.authority.invalidate(slot.channel),!this.current(epoch)||intent!==this.windowIntent))return;for(let index=0;index<starts.length;index++){if(this.slots.some(slot2=>slot2.key===keys[index]))continue;const channel=this.slots.some(slot2=>slot2.channel==="cells0")?"cells1":"cells0",lease=this.authority.begin(channel,this.locale);if(!lease||!this.current(epoch)||intent!==this.windowIntent)return;let settle;const promise=new Promise(resolve=>{settle=resolve}),slot={key:keys[index],channel,row:starts[index],rows:Math.min(block,this.rows-starts[index]),column:this.columnStart,columns:this.windowColumns.length,lease,source:this.sheet.data,promise,settle,state:"queued",units:0};lease.context.signal.addEventListener("abort",()=>slot.settle(!1),{once:!0}),this.slots.push(slot)}this.paint++,queueMicrotask(()=>this.pump())}pump(){for(;this.physicalReads<2;){const slot=this.slots.find(value=>value.state==="queued"&&value.lease.isCurrent());if(!slot)return;slot.state="loading",this.physicalReads++,this.read(slot)}}async read(slot){try{const source=slot.source,result=source.readCells?await source.readCells(Object.freeze({...slot.lease.context,revision:this.sheetRevision,row:slot.row,rowCount:slot.rows,column:slot.column,columnCount:slot.columns})):void 0;if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;if(result!==void 0&&(!Array.isArray(result)||result.length!==slot.rows))throw new TypeError("Invalid source rectangle");const values=[];let units=this.labelUnits+this.slots.reduce((sum,other)=>sum+(other===slot?0:other.units),0);const initialUnits=units;for(let row=0;row<slot.rows;row++){const input=result?.[row];if(result!==void 0&&(!Array.isArray(input)||input.length!==slot.columns))throw new TypeError("Invalid source rectangle row");const cells=[];for(let col=0;col<slot.columns;col++){const value=result!==void 0?input[col]:source.cellAt(slot.row+row,slot.column+col);if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;const text=this.scalar(value);if(units+=text.length,units>2e6)throw new LyraResourceLimitError;cells.push(text)}values.push(cells)}slot.values=values,slot.units=units-initialUnits,slot.state="ready",slot.settle(!0),this.paint++,this.notify()}catch(error){slot.lease.isCurrent()&&this.slots.includes(slot)&&this.fail(error),slot.settle(!1)}finally{this.physicalReads--,this.pump()}}scrollColumns(target){this.chrome.scrollColumns(this,target)}row(index,style,height){const slot=this.slots.find(value=>index>=value.row&&index<value.row+value.rows&&value.state==="ready"),rawRow=index+1+Number(this.hooks.header()),highlights=this.chrome.highlightsForRow(rawRow,this.hooks.workbook?this.sheet?.name:void 0);return html`<div part="data-row" role="presentation" aria-busy=${slot?"false":"true"} style=${`${style};height:${height}px;overflow:hidden`}>
|
|
17
17
|
${this.windowColumns.map((column,position)=>this.chrome.renderCell(slot?.values?.[index-slot.row]?.[position]??"",column,highlights,"cell","cell",this.hooks.colorVar,this.hooks.activeHighlight()))}
|
|
18
|
-
</div>`}render(){if(this.failure)return html`<div part="error">${this.hooks.localize(isResourceLimitError(this.failure)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`;if(!this.loaded||!this.sheet||!this.columns)return html`<p class="empty-note">${this.hooks.localize("noData")}</p>`;
|
|
19
|
-
${this.hooks.workbook&&this.sheets.length>1?this.hooks.renderSheetTabs?.(this.sheets.map(sheet=>sheet.name),this.sheetIndex,index=>{if(Number.isInteger(index)&&index>=0&&index<this.sheets.length&&index!==this.sheetIndex)try{this.selectSheet(index)
|
|
18
|
+
</div>`}render(){if(this.failure)return html`<div part="error">${this.hooks.localize(isResourceLimitError(this.failure)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`;if(!this.loaded||!this.sheet||!this.columns)return html`<p class="empty-note">${this.hooks.localize("noData")}</p>`;const epoch=this.epoch,intent=this.sheetIntent,current=()=>this.current(epoch)&&this.sheetIntent===intent;try{const window=this.chrome.columnWindow(this,this.columns,100);if(this.prepareColumns(window.columns),!current())return html``;if(this.failure)return html`<div part="error">${this.hooks.localize("documentPreviewFailedToLoad")}</div>`;const view=this.host.ownerDocument.defaultView,height=Math.max(1,resolveCssTokenLength(view?.getComputedStyle(this.host).getPropertyValue("--lr-size-3rem").trim()||"3rem",{host:this.host})??48),header=this.hooks.header(),search=this.hooks.workbook?this.bound.search:this.sheet.data.search;return html`
|
|
19
|
+
${this.hooks.workbook&&this.sheets.length>1?this.hooks.renderSheetTabs?.(this.sheets.map(sheet=>sheet.name),this.sheetIndex,index=>{if(Number.isInteger(index)&&index>=0&&index<this.sheets.length&&index!==this.sheetIndex){this.hooks.cancelAnchor();try{this.selectSheet(index)&&this.notify()}catch(error){this.fail(error)}}})??nothing:nothing}
|
|
20
20
|
${this.busy?html`<p part="spinner" class="empty-note">${this.hooks.localize("loadingDocument")}</p>`:nothing}
|
|
21
21
|
${typeof search!="function"?html`<p part="search-status" class="empty-note">${this.hooks.localize("sourceSearchUnavailable")}</p>`:nothing}
|
|
22
22
|
<div part=${this.hooks.headerPart==="header-cell"?"table":"sheet"} role="table" aria-label=${this.hooks.workbook?this.sheet.name:this.hooks.label(this.rows)} aria-rowcount=${this.rows+Number(header)} aria-colcount=${this.columns}
|
|
@@ -28,4 +28,4 @@ import{SourceRequestController,sourceCount,sourceRevision}from"../../internal/so
|
|
|
28
28
|
.scrollElement=${this.hooks.pageScroll?.()?view??void 0:void 0}
|
|
29
29
|
@lr-visible-range-change=${this.onRange} @lr-virtual-scroll=${event=>event.stopPropagation()} @lr-load-more=${event=>event.stopPropagation()}
|
|
30
30
|
></lr-virtual-list>
|
|
31
|
-
</div>`}catch(error){return this.fail(error),html`<div part="error">${this.hooks.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`}}async revealAnchor(anchor){if(anchor.kind!=="cell-range")return!1;const range=parseCellRange(anchor.range);if(!range)return!1;const name=anchor.sheet??range.sheet;if(!this.hooks.workbook&&name)return!1;const index=name?this.sheets.findIndex(sheet=>sheet.name===name):this.sheetIndex;return this.reveal(index,range.startRow-Number(this.hooks.header()),range.startCol)}async reveal(sheetIndex,row,column){if(this.failure||sheetIndex<0||sheetIndex>=this.sheets.length)return!1;if(sheetIndex!==this.sheetIndex)try{this.selectSheet(sheetIndex)
|
|
31
|
+
</div>`}catch(error){return current()?(this.fail(error),html`<div part="error">${this.hooks.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`):html``}}async revealAnchor(anchor){if(anchor.kind!=="cell-range")return!1;const range=parseCellRange(anchor.range);if(!range)return!1;const name=anchor.sheet??range.sheet;if(!this.hooks.workbook&&name)return!1;const index=name?this.sheets.findIndex(sheet=>sheet.name===name):this.sheetIndex;return this.reveal(index,range.startRow-Number(this.hooks.header()),range.startCol)}async reveal(sheetIndex,row,column){if(this.failure||sheetIndex<0||sheetIndex>=this.sheets.length)return!1;if(sheetIndex!==this.sheetIndex)try{if(!this.selectSheet(sheetIndex))return!1;this.notify()}catch(error){return this.fail(error),!1}if(!Number.isSafeInteger(row)||row<(this.hooks.header()?-1:0)||row>=this.rows||!Number.isSafeInteger(column)||column<0||column>=this.columns)return!1;const lease=this.authority.begin("reveal",this.locale);if(!lease||(await this.host.updateComplete,!lease.isCurrent())||(await this.chrome.showColumn(this,column,this.hooks.scrollContainer?.()??this.host.shadowRoot?.querySelector('[part="sheet"]')??null),!lease.isCurrent()))return!1;if(row<0)return this.chrome.revealCell(this.host.shadowRoot?.querySelector(`[part="header-row"] [aria-colindex="${column+1}"]`));const previousRow=this.firstRow,sheet=this.sheet,epoch=this.epoch;this.firstRow=row,this.activeRow=row,this.requestWindow(),this.notify();const abandon=()=>(this.firstRow===row&&this.sheet===sheet&&this.current(epoch)&&(this.firstRow=previousRow,this.requestWindow(),this.notify()),!1);if(await this.host.updateComplete,!lease.isCurrent())return abandon();const list=this.host.shadowRoot?.querySelector(tag("virtual-list"));if(!list)return abandon();if(list.scrollToIndex(row,{align:"start",behavior:"auto"}),await list.updateComplete,!lease.isCurrent())return!1;const slot=this.slots.find(value=>row>=value.row&&row<value.row+value.rows&&column>=value.column&&column<value.column+value.columns);if(!slot||!await slot.promise||!lease.isCurrent()||(await this.host.updateComplete,await list.updateComplete,!lease.isCurrent()))return!1;const target=list.shadowRoot?.querySelector(`[data-row-index="${row}"] [aria-colindex="${column+1}"]`);return this.chrome.revealCell(target)&&lease.isCurrent()}beginSearchChange(){const intent=++this.searchIntent;this.hooks.cancelAnchor();for(const channel of["search","reveal"]){if(intent!==this.searchIntent)return;this.authority.invalidate(channel)}return intent===this.searchIntent?intent:void 0}async search(query){const intent=this.beginSearchChange();if(intent===void 0)return 0;this.searchState.query=query;const bounded=boundedViewerSearchQuery(query,this.locale);if(!bounded.needle||!bounded.accepted)return this.searchState.publish([],bounded.accepted),0;const source=this.bound,search=this.hooks.workbook?source?.search:this.sheet?.data.search;if(intent!==this.searchIntent)return 0;if(!source||!search||this.failure)return this.searchState.publish([],!1),0;const lease=this.authority.begin("search",this.locale);return lease?new Promise(resolve=>{lease.context.signal.addEventListener("abort",()=>resolve(0),{once:!0});const run=async()=>{if(!lease.isCurrent()){resolve(0);return}this.searchRunning=!0;try{const result=await search.call(source,Object.freeze({...lease.context,query,limit:MAX_TABLE_SEARCH_MATCHES}));if(!lease.isCurrent())return;if(!result||!Array.isArray(result.hits)||result.hits.length>MAX_TABLE_SEARCH_MATCHES||typeof result.exhaustive!="boolean"||result.total!==null&&sourceCount(result.total)<result.hits.length)throw new TypeError("Invalid source search result");if(result.exhaustive&&result.total!==null&&result.total!==result.hits.length)throw new TypeError("Inconsistent source search total");let exact=result.exhaustive;const hits=[];for(const hit of result.hits){const index=this.hooks.workbook?this.sheets.findIndex(sheet=>sheet.key===hit.sheetKey):0;if(index<0||!Number.isSafeInteger(hit.row)||hit.row<-1||!Number.isSafeInteger(hit.column)||hit.column<0)throw new TypeError("Invalid source search hit");const data=this.sheets[index].data;if(hit.row>=sourceCount(data.rowCount)||hit.column>=sourceCount(data.columnCount)||hit.column>=this.limit)throw new TypeError("Source search hit is out of bounds");if(!lease.isCurrent())return;if(hit.row===-1&&!this.hooks.header()){exact=!1;continue}hits.push({sheetIndex:index,row:hit.row,col:hit.column})}if(!lease.isCurrent())return;if(!this.searchState.publish(hits,exact)||!lease.isCurrent()){resolve(0);return}hits.length&&await this.reveal(hits[0].sheetIndex,hits[0].row,hits[0].col),lease.isCurrent()&&resolve(hits.length)}catch(error){lease.isCurrent()&&(this.fail(error),this.searchState.publish([],!1),resolve(0))}finally{this.searchRunning=!1;const next=this.queuedSearch;this.queuedSearch=void 0,next&&next()}};this.searchRunning?this.queuedSearch=run:run()}):0}async step(direction){const intent=this.searchIntent;if(!this.searchState.step(direction)||intent!==this.searchIntent)return!1;const hit=this.searchState.matches[this.searchState.activeIndex];return this.reveal(hit.sheetIndex,hit.row,hit.col)}clearSearch(){this.beginSearchChange()!==void 0&&(this.activeRow="",this.searchState.clear(),this.notify())}}export{TABLE_VIEWER_SOURCE_MESSAGE_KEYS,TableViewerController,TableViewerScrollController,TableViewerSourceController,collectTableSearchMatches,tableHighlightsForColumn,tableHighlightsForRow};
|