@aceshooting/lyra-ui 31.0.0 → 31.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +149 -0
- package/dist/autoloader-cdn.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/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +18 -8
- 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/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/prompt-input/prompt-input.class.d.ts +6 -3
- 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/thread-list/thread-list.class.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- 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/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/timeline/timeline.class.js +1 -1
- package/dist/components/data/tree/tree-data-expansion.js +1 -0
- package/dist/components/data/tree/tree-item.class.d.ts +10 -4
- package/dist/components/data/tree/tree-item.class.js +5 -2
- package/dist/components/data/tree/tree-item.styles.js +1 -1
- package/dist/components/data/tree/tree-owner-controller.js +1 -1
- package/dist/components/data/tree/tree-pointer-reorder.js +1 -0
- package/dist/components/data/tree/tree-types.d.ts +5 -1
- package/dist/components/data/tree/tree.class.d.ts +27 -9
- package/dist/components/data/tree/tree.class.js +5 -3
- package/dist/components/data/tree/tree.styles.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/select/select.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/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/virtual-list/virtual-list.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.class.d.ts +10 -1
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.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/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +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/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/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +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 +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/notebook-viewer/notebook-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +18 -4
- package/dist/framework-types.d.ts +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/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- 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/sizes.styles.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/lyra.d.ts +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-budget-meter.md +31 -0
- package/llms/components/lr-chat-composer.md +13 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +34 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-map.md +33 -0
- package/llms/components/lr-message-feedback.md +38 -3
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +5 -2
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- package/llms/components/lr-tree-item.md +1 -1
- package/llms/components/lr-tree.md +59 -7
- package/llms/components/lr-virtual-list.md +3 -1
- package/llms/peers.md +2 -2
- package/llms/shared/ai-and-peers.md +10 -1
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +25 -0
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +255 -114
- package/locales.json +1 -1
- package/package.json +9 -9
- package/registrations.json +1 -1
|
@@ -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.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.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.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.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.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==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">
|
|
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>
|
|
@@ -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"
|
|
@@ -1,4 +1,4 @@
|
|
|
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{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isAbortError,isResourceLimitError,readResponseText,LyraResourceLimitError,LyraUserFacingError,resolveOwnerFetchTarget,yieldViewerTask}from"../../../internal/resource-loader.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{styles}from"./xml-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_expand,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchMatchCount}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_xmlViewerChildCount,LYRA_DEFAULT_xmlViewerCollapseNode,LYRA_DEFAULT_xmlViewerCopyDocument,LYRA_DEFAULT_xmlViewerCopyNode,LYRA_DEFAULT_xmlViewerExpandNode,LYRA_DEFAULT_xmlViewerLabel,LYRA_DEFAULT_xmlViewerLimit,LYRA_DEFAULT_xmlViewerParseError,LYRA_DEFAULT_xmlViewerTooManyNodes}from"../../../internal/default-strings/viewers.generated.js";const MAX_NODES=5e4,MAX_RENDERED_ROWS=5e3,MAX_DEPTH=256,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_HIGHLIGHTS=100;function attrKey(pathKey,attrName){return`${pathKey}\0${attrName}`}const EMPTY_SEARCH={matches:new Set,tagMatches:new Set,attrMatches:new Set,textMatches:new Set,forceExpand:new Set,paths:new Set,ordered:[],matchCountExact:!0};function elementChildren(node){return Array.from(node.children)}function findParserError(doc){const root=doc.documentElement,onRoot=root?.tagName==="parsererror",onFirstChild=root?.firstElementChild?.tagName==="parsererror",errorEl=onRoot?root:onFirstChild?root.firstElementChild:null;return errorEl?errorEl.textContent??"XML parse error":null}class XmlDoctypeError extends Error{constructor(){super("XML document type declarations are not supported."),this.name="XmlDoctypeError"}}function preflightXml(raw,maxBytes=26214400,maxNodes=MAX_NODES){if(raw.length>maxBytes||new TextEncoder().encode(raw).byteLength>maxBytes)throw new LyraResourceLimitError;let nodes=1,depth=0;const count=()=>{if(++nodes>maxNodes)throw new LyraResourceLimitError};for(let offset=0;offset<raw.length;){const open=raw.indexOf("<",offset);if(open<0){depth>0&&offset<raw.length&&count();break}if(depth>0&&open>offset&&count(),raw.startsWith("<!--",open)||raw.startsWith("<![CDATA[",open)||raw.startsWith("<?",open)){const comment=raw.startsWith("<!--",open),cdata=raw.startsWith("<![CDATA[",open),terminator=comment?"-->":cdata?"]]>":"?>";(comment||cdata||!/^<\?xml(?:\s|\?)/.test(raw.slice(open,open+8)))&&count();const end2=raw.indexOf(terminator,open+(comment?4:cdata?9:2));if(end2<0)break;offset=end2+terminator.length;continue}if(raw.slice(open,open+9).toUpperCase()==="<!DOCTYPE")throw new XmlDoctypeError;let quote="",end=open+1;for(;end<raw.length;end++){const character=raw[end];if(quote)character===quote&&(quote="");else if(character==='"'||character==="'")quote=character;else{if(character==="<")throw new Error("Invalid XML markup");if(character===">")break}}if(end===raw.length)break;if(raw[open+1]==="/")depth=Math.max(0,depth-1);else{if(count(),depth+1>MAX_DEPTH)throw new LyraResourceLimitError;raw[end-1]!=="/"&&depth++}offset=end+1}}function parseXmlDocument(raw,ownerDocument,maxBytes,maxNodes,prepared=!1){prepared||preflightXml(raw,maxBytes,maxNodes);const DOMParserCtor=ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)throw new Error("DOMParser is unavailable without a browsing context.");return new DOMParserCtor().parseFromString(raw,"application/xml")}function isRenderedXmlChild(node){return node.nodeType===Node.ELEMENT_NODE||node.nodeType===Node.TEXT_NODE&&!!(node.textContent??"").trim()||node.nodeType===Node.COMMENT_NODE||node.nodeType===Node.CDATA_SECTION_NODE||node.nodeType===Node.PROCESSING_INSTRUCTION_NODE}function validateDocumentComplexity(node,maxNodes){const childCounts=new WeakMap,pending=[{node,depth:0}];let count=0;for(;pending.length;){const current=pending.pop();if(count++,count>maxNodes||current.depth>MAX_DEPTH)throw new LyraResourceLimitError;let child=current.node.lastChild,children=0;for(;child;){if(isRenderedXmlChild(child)&&children++,count+pending.length>=maxNodes)throw new LyraResourceLimitError;pending.push({node:child,depth:current.depth+1}),child=child.previousSibling}childCounts.set(current.node,children)}return childCounts}function resolvePath(root,path,budget){if(!Array.isArray(path)||budget&&budget.remaining--<=0)return null;let current=root;for(let i=0;i<path.length;i++){if(budget&&budget.remaining--<=0)return null;const segment=path[i];if(typeof segment=="string"){if(!segment.startsWith("@")||i!==path.length-1)return null;const attr=segment.slice(1);return!attr||!current.hasAttribute(attr)?null:{element:current,attr}}const children=current.children;if(!Number.isInteger(segment)||segment<0||segment>=children.length)return null;const child=children.item(segment);if(!child)return null;current=child}return{element:current}}class LyraXmlViewerBase extends LyraElement{}class LyraXmlViewer extends DocumentAnchorTarget(LyraXmlViewerBase){constructor(){super(...arguments),this.maxNodes=5e4,this.maxRows=5e3,this.maxBytes=26214400,this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.src="",this.name="",this.copyable=!1,this.maxHeight="",this.anchorKinds=["node-path"],this.childCounts=new WeakMap,this.xmlState={kind:"idle"},this.expandedOverrides=new Map,this.activePath=null,this.activeAttr=null,this.activeSearchIndex=-1,this.searchQuery="",this.renderedHighlights=new Map,this.searchState=EMPTY_SEARCH,this.lastSearchLocale="",this.pendingSearchStateEvent=!1,this.generation=0,this.explicitRefresh=0,this.nodeElements=new Map,this.attributeElements=new Map,this.cursorElements=[],this.announcements=new ViewerAnnouncementController(this),this.copyFeedback=null,this.copyGeneration=0,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.cancelSourceAnchor=()=>{this.treeSource!==void 0&&(this.cancelPendingAnchor(),this.sourceNavigationIntent++,this.sourceAnchorTask&&(this.sourceAnchorTask=void 0,this.hierarchy.cancelPending()))}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,expand:LYRA_DEFAULT_expand,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,xmlViewerChildCount:LYRA_DEFAULT_xmlViewerChildCount,xmlViewerCollapseNode:LYRA_DEFAULT_xmlViewerCollapseNode,xmlViewerCopyDocument:LYRA_DEFAULT_xmlViewerCopyDocument,xmlViewerCopyNode:LYRA_DEFAULT_xmlViewerCopyNode,xmlViewerExpandNode:LYRA_DEFAULT_xmlViewerExpandNode,xmlViewerLabel:LYRA_DEFAULT_xmlViewerLabel,xmlViewerLimit:LYRA_DEFAULT_xmlViewerLimit,xmlViewerParseError:LYRA_DEFAULT_xmlViewerParseError,xmlViewerTooManyNodes:LYRA_DEFAULT_xmlViewerTooManyNodes}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,specialistTokens,styles,viewerLoadingStyles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.cancelPendingAnchor(),this.generation++,this.beginAbortableLoad(),this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.sourceAnchorTask=void 0,this.cancelPendingAnchor(),this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.searchQuery??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.cancelPendingAnchor(),this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.searchQuery??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceAnchorTask=void 0,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.resetCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.searchQuery??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.activeSearchIndex=this.sourceHitKeys.size?0:-1,this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),this.sourceHits?.isCurrent()&&this.activeSearchIndex>=0&&await this.hierarchy.reveal(this.sourceHits.value.hits[0].key),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent;this.sourceAnchorTask=void 0,this.cancelPendingAnchor();const hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.resetCopyFeedback();const result=await this.hierarchy.copy(key,scope,this.effectiveMaxBytes);if(!current()||result.status==="stale")return;const feedback=key??"document";if(result.status!=="ready"){this.showSourceCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.announcements.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showSourceCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.announcements.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.announcements.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("xmlViewerCopyNode",void 0,{name:node.name}):this.localize("xmlViewerCopyDocument");return html`<button part="copy-button" type="button" aria-label=${this.copyButtonLabel(key??"document",label)}
|
|
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{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isResourceLimitError,readResponseText,LyraResourceLimitError,LyraUserFacingError,resolveOwnerFetchTarget,yieldViewerTask}from"../../../internal/resource-loader.js";import{chevronIcon}from"../../../internal/icons.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{styles}from"./xml-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_expand,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchMatchCount}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_xmlViewerChildCount,LYRA_DEFAULT_xmlViewerCollapseNode,LYRA_DEFAULT_xmlViewerCopyDocument,LYRA_DEFAULT_xmlViewerCopyNode,LYRA_DEFAULT_xmlViewerExpandNode,LYRA_DEFAULT_xmlViewerLabel,LYRA_DEFAULT_xmlViewerLimit,LYRA_DEFAULT_xmlViewerParseError,LYRA_DEFAULT_xmlViewerTooManyNodes}from"../../../internal/default-strings/viewers.generated.js";const MAX_NODES=5e4,MAX_RENDERED_ROWS=5e3,MAX_DEPTH=256,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_HIGHLIGHTS=100;function attrKey(pathKey,attrName){return`${pathKey}\0${attrName}`}const EMPTY_SEARCH={matches:new Set,tagMatches:new Set,attrMatches:new Set,textMatches:new Set,forceExpand:new Set,paths:new Set,ordered:[],matchCountExact:!0};function elementChildren(node){return Array.from(node.children)}function findParserError(doc){const root=doc.documentElement,onRoot=root?.tagName==="parsererror",onFirstChild=root?.firstElementChild?.tagName==="parsererror",errorEl=onRoot?root:onFirstChild?root.firstElementChild:null;return errorEl?errorEl.textContent??"XML parse error":null}class XmlDoctypeError extends Error{constructor(){super("XML document type declarations are not supported."),this.name="XmlDoctypeError"}}function preflightXml(raw,maxBytes=26214400,maxNodes=MAX_NODES){if(raw.length>maxBytes||new TextEncoder().encode(raw).byteLength>maxBytes)throw new LyraResourceLimitError;let nodes=1,depth=0;const count=()=>{if(++nodes>maxNodes)throw new LyraResourceLimitError};for(let offset=0;offset<raw.length;){const open=raw.indexOf("<",offset);if(open<0){depth>0&&offset<raw.length&&count();break}if(depth>0&&open>offset&&count(),raw.startsWith("<!--",open)||raw.startsWith("<![CDATA[",open)||raw.startsWith("<?",open)){const comment=raw.startsWith("<!--",open),cdata=raw.startsWith("<![CDATA[",open),terminator=comment?"-->":cdata?"]]>":"?>";(comment||cdata||!/^<\?xml(?:\s|\?)/.test(raw.slice(open,open+8)))&&count();const end2=raw.indexOf(terminator,open+(comment?4:cdata?9:2));if(end2<0)break;offset=end2+terminator.length;continue}if(raw.slice(open,open+9).toUpperCase()==="<!DOCTYPE")throw new XmlDoctypeError;let quote="",end=open+1;for(;end<raw.length;end++){const character=raw[end];if(quote)character===quote&&(quote="");else if(character==='"'||character==="'")quote=character;else{if(character==="<")throw new Error("Invalid XML markup");if(character===">")break}}if(end===raw.length)break;if(raw[open+1]==="/")depth=Math.max(0,depth-1);else{if(count(),depth+1>MAX_DEPTH)throw new LyraResourceLimitError;raw[end-1]!=="/"&&depth++}offset=end+1}}function parseXmlDocument(raw,ownerDocument,maxBytes,maxNodes,prepared=!1){prepared||preflightXml(raw,maxBytes,maxNodes);const DOMParserCtor=ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)throw new Error("DOMParser is unavailable without a browsing context.");return new DOMParserCtor().parseFromString(raw,"application/xml")}function isRenderedXmlChild(node){return node.nodeType===Node.ELEMENT_NODE||node.nodeType===Node.TEXT_NODE&&!!(node.textContent??"").trim()||node.nodeType===Node.COMMENT_NODE||node.nodeType===Node.CDATA_SECTION_NODE||node.nodeType===Node.PROCESSING_INSTRUCTION_NODE}function validateDocumentComplexity(node,maxNodes){const childCounts=new WeakMap,pending=[{node,depth:0}];let count=0;for(;pending.length;){const current=pending.pop();if(count++,count>maxNodes||current.depth>MAX_DEPTH)throw new LyraResourceLimitError;let child=current.node.lastChild,children=0;for(;child;){if(isRenderedXmlChild(child)&&children++,count+pending.length>=maxNodes)throw new LyraResourceLimitError;pending.push({node:child,depth:current.depth+1}),child=child.previousSibling}childCounts.set(current.node,children)}return childCounts}function resolvePath(root,path,budget){if(!Array.isArray(path)||budget&&budget.remaining--<=0)return null;let current=root;for(let i=0;i<path.length;i++){if(budget&&budget.remaining--<=0)return null;const segment=path[i];if(typeof segment=="string"){if(!segment.startsWith("@")||i!==path.length-1)return null;const attr=segment.slice(1);return!attr||!current.hasAttribute(attr)?null:{element:current,attr}}const children=current.children;if(!Number.isInteger(segment)||segment<0||segment>=children.length)return null;const child=children.item(segment);if(!child)return null;current=child}return{element:current}}class LyraXmlViewerBase extends LyraElement{}class LyraXmlViewer extends DocumentAnchorTarget(LyraXmlViewerBase){constructor(){super(...arguments),this.maxNodes=5e4,this.maxRows=5e3,this.maxBytes=26214400,this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.src="",this.name="",this.copyable=!1,this.maxHeight="",this.anchorKinds=["node-path"],this.childCounts=new WeakMap,this.xmlState={kind:"idle"},this.expandedOverrides=new Map,this.activePath=null,this.activeAttr=null,this.activeSearchIndex=-1,this.searchQuery="",this.renderedHighlights=new Map,this.searchState=EMPTY_SEARCH,this.lastSearchLocale="",this.pendingSearchStateEvent=!1,this.generation=0,this.explicitRefresh=0,this.nodeElements=new Map,this.attributeElements=new Map,this.cursorElements=[],this.announcements=new ViewerAnnouncementController(this),this.copyFeedback=null,this.copyGeneration=0,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.cancelSourceAnchor=()=>{this.treeSource!==void 0&&(this.cancelPendingAnchor(),this.sourceNavigationIntent++,this.sourceAnchorTask&&(this.sourceAnchorTask=void 0,this.hierarchy.cancelPending()))}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,expand:LYRA_DEFAULT_expand,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,xmlViewerChildCount:LYRA_DEFAULT_xmlViewerChildCount,xmlViewerCollapseNode:LYRA_DEFAULT_xmlViewerCollapseNode,xmlViewerCopyDocument:LYRA_DEFAULT_xmlViewerCopyDocument,xmlViewerCopyNode:LYRA_DEFAULT_xmlViewerCopyNode,xmlViewerExpandNode:LYRA_DEFAULT_xmlViewerExpandNode,xmlViewerLabel:LYRA_DEFAULT_xmlViewerLabel,xmlViewerLimit:LYRA_DEFAULT_xmlViewerLimit,xmlViewerParseError:LYRA_DEFAULT_xmlViewerParseError,xmlViewerTooManyNodes:LYRA_DEFAULT_xmlViewerTooManyNodes}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,specialistTokens,styles,viewerLoadingStyles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.cancelPendingAnchor(),this.generation++,this.beginAbortableLoad(),this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.sourceAnchorTask=void 0,this.cancelPendingAnchor(),this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.searchQuery??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.cancelPendingAnchor(),this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.searchQuery??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceAnchorTask=void 0,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.resetCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.searchQuery??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.activeSearchIndex=this.sourceHitKeys.size?0:-1,this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),this.sourceHits?.isCurrent()&&this.activeSearchIndex>=0&&await this.hierarchy.reveal(this.sourceHits.value.hits[0].key),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent;this.sourceAnchorTask=void 0,this.cancelPendingAnchor();const hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.resetCopyFeedback();const result=await this.hierarchy.copy(key,scope,this.effectiveMaxBytes);if(!current()||result.status==="stale")return;const feedback=key??"document";if(result.status!=="ready"){this.showSourceCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.announcements.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showSourceCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.announcements.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.announcements.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("xmlViewerCopyNode",void 0,{name:node.name}):this.localize("xmlViewerCopyDocument");return html`<button part="copy-button" type="button" aria-label=${this.copyButtonLabel(key??"document",label)}
|
|
2
2
|
@keydown=${event=>event.stopPropagation()}
|
|
3
3
|
@click=${event=>{event.stopPropagation();const button=event.currentTarget;button.isConnected&&button.getRootNode()===this.renderRoot&&!this.hierarchy.loading&&projection===this.hierarchy.projection&&source===this.treeSource&&epoch===this.hierarchy.epoch&&this.copySource(key,node?node.kind==="object"||node.kind==="array"||node.kind==="element"?"subtree":"node":"document")}}>${this.copyButtonLabel(key??"document",this.localize("copy"))}</button>`}showSourceCopyFeedback(key,success){const owner=this.ownerDocument.defaultView;owner&&this.showCopyFeedback(key,success?"success":"error",this.copyGeneration,owner)}renderSourceNode(node){const match=this.sourceHits?.isCurrent()&&this.sourceHitKeys.has(node.path),active=this.sourceHits?.value.hits[this.activeSearchIndex]?.key===node.path,highlight=this.renderedHighlights.get(node.path),source=this.treeSource,epoch=this.hierarchy.epoch,projection=this.hierarchy.projection,highlights=this.highlights,part=node.kind==="element"?"tag":node.kind==="attribute"?"attribute":node.kind==="comment"?"comment":node.kind==="processing-instruction"?"pi":"text";return html`<span part=${part} ?data-match=${match} ?data-active-match=${active}
|
|
4
4
|
?data-active=${this.activePath===node.path}
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
11
11
|
${this.copyable&&this.hasSourceCopy()?html`<div part="toolbar">${this.sourceCopyButton()}</div>`:nothing}
|
|
12
12
|
${hierarchySourceView(this.hierarchy,{label:hostAriaLabel(this)??(this.name||this.localize("xmlViewerLabel")),rtl:this.effectiveDirection==="rtl",multiple:!1,loading:this.localize("loading"),error:this.localize("treeSourceError"),empty:this.localize("noData"),retry:this.localize("retry"),expand:this.localize("expand"),collapse:this.localize("collapse"),summary:this.sourceSummary(),name:node=>node.name,content:node=>this.renderSourceNode(node),select:()=>{}})}
|
|
13
13
|
${partial?html`<div part="search-status">${this.sourceSearchUnavailable?this.localize("sourceSearchUnavailable"):this.localize("viewerSearchMatchCount",void 0,{count:`≥${getNumberFormat(this.effectiveLocale).format(count)}`,pluralCount:count})}</div>`:nothing}
|
|
14
|
-
</div>`}get effectiveMaxNodes(){return Math.max(1,finiteCount(this.maxNodes,MAX_NODES,5e5))}get effectiveMaxRows(){return Math.max(1,finiteCount(this.maxRows,MAX_RENDERED_ROWS,5e4))}get effectiveMaxBytes(){return Math.max(1,finiteCount(this.maxBytes,26214400,262144e3))}get xml(){return this._xml}set xml(value){if(value===this._xml)return;const old=this._xml;this._xml=value,this.requestUpdate("xml",old),value!==void 0&&this.parseInline(value)}get source(){return resolveViewerSource(this.src,this._xml)}set source(_value){}requestUpdate(...args){this._treeSource!==void 0&&args[0]===void 0&&(this.invalidateSourceSearch(),this.syncSource(!0)),args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}syncCursors(){const next=[this.activePath===null?void 0:this.nodeElements.get(this.activePath),this.activeAttr===null?void 0:this.attributeElements.get(this.activeAttr),this.nodeElements.get(this.searchState.ordered[this.activeSearchIndex]??"")],attributes=["data-active","data-active","data-active-match"];next.forEach((element,index)=>{this.cursorElements[index]!==element&&this.cursorElements[index]?.removeAttribute(attributes[index]),element?.setAttribute(attributes[index],"")}),this.cursorElements=next}get safeExpandDepth(){return this.expandDepth===void 0?void 0:finiteCount(this.expandDepth)}willUpdate(changed){const wasSource=this.sourceMode;if(this.syncSource(),super.willUpdate(changed),this.treeSource!==void 0){this.sourceMode=!0,this.treeMemo=void 0,(changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml!==void 0&&this.parseInline(this._xml),this.sourceSearchDirty&&(this.sourceSearchTask=this.searchSource());return}this.sourceMode=!1,wasSource&&(this.resetSearchForSourceReplacement(),this._xml!==void 0?this.parseInline(this._xml):this.scheduleAfterUpdate(()=>{this.loadFromSrc()})),(changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml!==void 0&&this.parseInline(this._xml),this.hasUpdated&&(changed.has("src")||changed.has("xml"))&&this.resetCopyFeedback(),(changed.has("src")||changed.has("xml"))&&(this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement());const locale=this.effectiveLocale;this.lastSearchLocale&&locale!==this.lastSearchLocale&&this.xmlState.kind==="loaded"&&(this.searchState=this.computeSearch(this.xmlState.doc),this.activeSearchIndex=this.searchState.ordered.length?Math.min(Math.max(0,this.activeSearchIndex),this.searchState.ordered.length-1):-1,this.searchQuery!==""&&(this.pendingSearchStateEvent=!0)),this.lastSearchLocale=locale}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const source=this.treeSource,epoch=this.hierarchy.epoch,binding=this.sourceBinding,owner=this.ownerDocument,current=()=>this.isConnected&&this.ownerDocument===owner&&source===this.treeSource&&epoch===this.hierarchy.epoch&&binding===this.sourceBinding,error=this.hierarchy.error||this.hierarchy.rowError,message=error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();if(!current()||(this.announcements.transition("source",error?"error":this.hierarchy.loading?"loading":"loaded",message),!current()))return;error&&this.sourceAnnouncement!==message&&this.emit("lr-render-error",{error}),current()&&(this.sourceAnnouncement=error?message:void 0);return}this.syncCursors(),this.announcements.transition("load",this.xmlState.kind,this.xmlState.kind==="error"?this.xmlState.message:this.localize("loadingDocument")),(changed.has("src")||changed.has("xml")||changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml===void 0&&this.scheduleAfterUpdate(()=>{this.loadFromSrc()}),this.pendingSearchStateEvent&&(this.pendingSearchStateEvent=!1,this.emitSearchChange())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.sourceBinding=void 0,this.requestUpdate("sourceReconnect",null),this.renderRoot.addEventListener("click",this.cancelSourceAnchor,!0),this.renderRoot.addEventListener("keydown",this.cancelSourceAnchor,!0);const moved=this.detached.cancel();this.hasUpdated&&this.src&&this._xml===void 0&&!moved&&this.scheduleAfterUpdate(()=>{this.loadFromSrc()})}disconnectedCallback(){this.invalidateSourceSearch(),this.sourceBinding=void 0,this.renderRoot.removeEventListener("click",this.cancelSourceAnchor,!0),this.renderRoot.removeEventListener("keydown",this.cancelSourceAnchor,!0),this.announcements.disconnect(),this.resetCopyFeedback(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.beginAbortableLoad(),this._xml===void 0&&(this.xmlState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.invalidateSourceSearch(),this.sourceBinding=void 0,this.hierarchy.adopted(),this.detached.flush(),this.announcements.adopted(),this.resetCopyFeedback()}parseInline(raw){const generation=++this.generation;this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement();try{this.setDoc(parseXmlDocument(raw,this.ownerDocument,this.effectiveMaxBytes,this.effectiveMaxNodes),generation)}catch(error){this.xmlState={kind:"error",message:this.localize(isResourceLimitError(error)?"xmlViewerTooManyNodes":"xmlViewerParseError")},this.emit("lr-render-error",{error})}}async loadFromSrc(){if(this.treeSource!==void 0||this._xml!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement(),!this.src){this.xmlState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.xmlState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.xmlState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response,this.effectiveMaxBytes);if(!this.isConnected||generation!==this.generation)return;preflightXml(text,this.effectiveMaxBytes,this.effectiveMaxNodes),await yieldViewerTask(this.ownerDocument.defaultView,()=>this.isConnected&&generation===this.generation),this.setDoc(parseXmlDocument(text,this.ownerDocument,this.effectiveMaxBytes,this.effectiveMaxNodes,!0),generation)}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.xmlState={kind:"error",message:this.localize(error instanceof XmlDoctypeError?"xmlViewerParseError":isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}resetSearchForSourceReplacement(){if(this.treeSource!==void 0)return!1;const changed=this.searchQuery!==""||this.searchState.ordered.length>0||!this.searchState.matchCountExact||this.activeSearchIndex!==-1;return this.searchQuery="",this.searchState=EMPTY_SEARCH,this.activeSearchIndex=-1,changed}setDoc(doc,generation){if(generation!==this.generation)return;const parseError=findParserError(doc);if(parseError){this.xmlState={kind:"error",message:this.localize("xmlViewerParseError")},this.emit("lr-render-error",{error:new Error(parseError)});return}try{this.childCounts=validateDocumentComplexity(doc,this.effectiveMaxNodes)}catch(error){this.xmlState={kind:"error",message:this.localize("xmlViewerTooManyNodes")},this.emit("lr-render-error",{error});return}if(this.xmlState={kind:"loaded",doc},this.treeSource!==void 0)return;const next=this.computeSearch(doc);if(this.searchState=next,this.searchQuery.trim()&&(this.activeSearchIndex=next.ordered.length?Math.min(Math.max(this.activeSearchIndex,0),next.ordered.length-1):-1,this.emitSearchChange()),this.expandedOverrides.size){let pruned=null;for(const key of this.expandedOverrides.keys())next.paths.has(key)||(pruned??=new Map(this.expandedOverrides),pruned.delete(key));pruned&&(this.expandedOverrides=pruned)}}computeSearch(doc){const locale=this.effectiveLocale,boundedQuery=boundedViewerSearchQuery(this.searchQuery,locale),query=boundedQuery.needle,budget=new ViewerSearchWorkBudget,matches=new Set,tagMatches=new Set,attrMatches=new Set,textMatches=new Set,forceExpand=new Set,paths=new Set,ordered=[];let matchCountExact=boundedQuery.accepted;const markAncestors=path=>{for(let i=path.length-1;i>=0;i--)forceExpand.add(JSON.stringify(path.slice(0,i)))},walk=(el,path)=>{const pathKey=JSON.stringify(path);if(paths.add(pathKey),query&&matchCountExact){let hit=!1;budget.includes(el.tagName,query,locale)&&(tagMatches.add(pathKey),hit=!0);for(const attr of el.attributes)if((budget.includes(attr.name,query,locale)||budget.includes(attr.value,query,locale))&&(attrMatches.add(attrKey(pathKey,attr.name)),hit=!0),!budget.complete)break;const ownTextParts=function*(){for(const child of el.childNodes)child.nodeType===Node.TEXT_NODE&&(yield child.textContent??"")};if(budget.complete&&budget.includesJoined(ownTextParts(),query,locale)&&(textMatches.add(pathKey),hit=!0),budget.complete||(matchCountExact=!1),hit)if(ordered.length===MAX_SEARCH_MATCHES){matchCountExact=!1,tagMatches.delete(pathKey),textMatches.delete(pathKey);for(const attr of el.attributes)attrMatches.delete(attrKey(pathKey,attr.name))}else matches.add(pathKey),ordered.push(pathKey),forceExpand.add(pathKey),markAncestors(path)}elementChildren(el).forEach((child,i)=>walk(child,[...path,i]))};return doc.documentElement&&walk(doc.documentElement,[]),{matches,tagMatches,attrMatches,textMatches,forceExpand,paths,ordered,matchCountExact}}sourcePathKey(path){if(!Array.isArray(path)||path.length>MAX_DEPTH)return;const segments=[];for(let index=0;index<path.length;index++){const segment=hierarchyField(path,String(index));if(typeof segment=="number"&&Number.isSafeInteger(segment)&&segment>=0)segments.push(segment);else if(typeof segment=="string"&&index===path.length-1&&segment.startsWith("@")&&segment.length>1&&segment.length<=65536)segments.push(segment);else return}const key=JSON.stringify(segments);return key.length<=65536?key:void 0}async applyAnchor(anchor){if(this.treeSource!==void 0){const key=anchor.kind==="node-path"?this.sourcePathKey(anchor.path):void 0;if(key===void 0)return!1;const task={};this.sourceAnchorTask=task;try{return!await this.hierarchy.reveal(key)||this.sourceAnchorTask!==task?!1:(this.activePath=key,await this.updateComplete,this.sourceAnchorTask===task)}finally{this.sourceAnchorTask===task&&(this.sourceAnchorTask=void 0)}}if(anchor.kind!=="node-path"||this.xmlState.kind!=="loaded"||!this.xmlState.doc.documentElement)return!1;const resolved=resolvePath(this.xmlState.doc.documentElement,anchor.path);if(!resolved?.element)return!1;const numericPath=anchor.path.filter(s=>typeof s=="number");this.expandAncestors(anchor.path);const pathKey=JSON.stringify(numericPath);return this.activePath=pathKey,this.activeAttr=resolved.attr?attrKey(pathKey,resolved.attr):null,await this.updateComplete,this.renderRoot.querySelector('[part="node"][data-active]')!==null}resolveHighlights(){const byPath=new Map;if(this.treeSource!==void 0){const admitted=[],seen2=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(seen2.has(highlight.id))continue;seen2.add(highlight.id);const key=highlight.anchor.kind==="node-path"?this.sourcePathKey(highlight.anchor.path):void 0;if(key!==void 0&&admitted.push({highlight,key}),admitted.length>=MAX_PAINTED_HIGHLIGHTS)break}return admitted.forEach(({highlight,key},index)=>{byPath.has(key)||byPath.set(key,{highlight,index,total:admitted.length})}),byPath}if(this.xmlState.kind!=="loaded")return byPath;const root=this.xmlState.doc.documentElement;if(!root)return byPath;const seen=new Set,resolved=[],candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolutionBudget={remaining:this.effectiveMaxNodes};for(const highlight of candidates)if(!seen.has(highlight.id)&&(seen.add(highlight.id),highlight.anchor.kind==="node-path"&&resolvePath(root,highlight.anchor.path,resolutionBudget)&&(resolved.push({highlight,pathKey:JSON.stringify(highlight.anchor.path.filter(s=>typeof s=="number"))}),resolved.length>=MAX_PAINTED_HIGHLIGHTS)))break;return resolved.forEach(({highlight,pathKey},index)=>{byPath.has(pathKey)||byPath.set(pathKey,{highlight,index,total:resolved.length})}),byPath}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}expandAncestors(path,includeSelf=!1){let next;const expand=(key,depth)=>{this.isExpanded(key,depth)||(next??=new Map(this.expandedOverrides),next.set(key,!0))};for(let i=0;i<path.length;i++)typeof path[i]=="number"&&expand(JSON.stringify(path.slice(0,i)),i);includeSelf&&expand(JSON.stringify(path),path.length),next&&(this.expandedOverrides=next)}async search(query){if(this.treeSource!==void 0){this.cancelPendingAnchor(),this.searchQuery=query,this.invalidateSourceSearch(),this.syncSource();const intent=this.sourceSearchIntent;return this.requestUpdate("sourceSearchIntent",null),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceSearchTask:0}return this.searchQuery=query,this.searchState=this.xmlState.kind==="loaded"?this.computeSearch(this.xmlState.doc):EMPTY_SEARCH,this.activeSearchIndex=this.searchState.ordered.length?0:-1,this.requestUpdate(),this.emitSearchChange(),this.activeSearchIndex>=0&&await this.scrollActiveMatchIntoView(),this.searchState.ordered.length}async searchNext(){return this.treeSource!==void 0?this.stepSourceSearch(1):this.searchState.ordered.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchState.ordered.length,this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0):!1}async searchPrevious(){return this.treeSource!==void 0?this.stepSourceSearch(-1):this.searchState.ordered.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchState.ordered.length)%this.searchState.ordered.length,this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0):!1}clearSearch(){if(this.cancelPendingAnchor(),this.treeSource!==void 0){this.searchQuery="",this.hierarchy.cancelSearch(),this.invalidateSourceSearch(),this.syncSource(),this.requestUpdate("sourceSearchIntent",null);return}this.searchQuery="",this.searchState=this.xmlState.kind==="loaded"?this.computeSearch(this.xmlState.doc):EMPTY_SEARCH,this.activeSearchIndex=-1,this.requestUpdate(),this.emitSearchChange()}async scrollActiveMatchIntoView(){const pathKey=this.searchState.ordered[this.activeSearchIndex];if(pathKey===void 0)return;this.expandAncestors(JSON.parse(pathKey),!0),await this.updateComplete,this.renderRoot.querySelector("[data-active-match]")?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.treeSource!==void 0?this.sourceHitKeys.size:this.searchState.ordered.length,matchCountExact:this.treeSource!==void 0?this.sourceSearchExact:this.searchState.matchCountExact,activeIndex:this.activeSearchIndex})}toggleNode(pathKey,expanded){const next=new Map(this.expandedOverrides);next.set(pathKey,!expanded),this.expandedOverrides=next}isExpanded(pathKey,depth){const override=this.expandedOverrides.get(pathKey);if(override!==void 0)return override;if(this.searchState.forceExpand.has(pathKey))return!0;const expandDepth=this.safeExpandDepth;return!(expandDepth!==void 0&&depth>=expandDepth)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration++,this.cancelCopyTimer(),this.copyFeedback=null}showCopyFeedback(key,status,generation,owner){this.copyFeedback={key,status},this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||this.copyTimer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.copyFeedback=null)},1500),this.copyTimer={owner,handle,generation}}async copyText(text,key){if(this.treeSource!==void 0)return;const owner=this.isConnected?this.ownerDocument.defaultView:null,generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyFeedback=null;const outcome=await writeClipboardText(owner,text);if(!(!owner||!this.isConnected||generation!==this.copyGeneration||this.ownerDocument.defaultView!==owner)){if(outcome.ok){this.showCopyFeedback(key,"success",generation,owner),this.emit("lr-copy",outcome);return}this.showCopyFeedback(key,"error",generation,owner),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}}serializeXml(node){const XMLSerializerCtor=this.isConnected?this.ownerDocument.defaultView?.XMLSerializer:void 0;return XMLSerializerCtor?new XMLSerializerCtor().serializeToString(node):null}copySerializedXml(node,key){const text=this.serializeXml(node);text!==null&&this.copyText(text,key)}copyButtonLabel(key,rest){const feedback=this.copyFeedback?.key===key?this.copyFeedback.status:void 0;return feedback==="success"?this.localize("copied"):feedback==="error"?this.localize("copyFailed"):rest}renderCopyButton(getNode,name,key){if(!this.copyable)return nothing;const label=this.copyButtonLabel(key,this.localize("xmlViewerCopyNode",void 0,{name}));return html`
|
|
14
|
+
</div>`}get effectiveMaxNodes(){return Math.max(1,finiteCount(this.maxNodes,MAX_NODES,5e5))}get effectiveMaxRows(){return Math.max(1,finiteCount(this.maxRows,MAX_RENDERED_ROWS,5e4))}get effectiveMaxBytes(){return Math.max(1,finiteCount(this.maxBytes,26214400,262144e3))}get xml(){return this._xml}set xml(value){if(value===this._xml)return;const old=this._xml;this._xml=value,this.requestUpdate("xml",old),value!==void 0&&this.parseInline(value)}get source(){return resolveViewerSource(this.src,this._xml)}set source(_value){}requestUpdate(...args){this._treeSource!==void 0&&args[0]===void 0&&(this.invalidateSourceSearch(),this.syncSource(!0)),args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}syncCursors(){const next=[this.activePath===null?void 0:this.nodeElements.get(this.activePath),this.activeAttr===null?void 0:this.attributeElements.get(this.activeAttr),this.nodeElements.get(this.searchState.ordered[this.activeSearchIndex]??"")],attributes=["data-active","data-active","data-active-match"];next.forEach((element,index)=>{this.cursorElements[index]!==element&&this.cursorElements[index]?.removeAttribute(attributes[index]),element?.setAttribute(attributes[index],"")}),this.cursorElements=next}get safeExpandDepth(){return this.expandDepth===void 0?void 0:finiteCount(this.expandDepth)}willUpdate(changed){const wasSource=this.sourceMode;if(this.syncSource(),super.willUpdate(changed),this.treeSource!==void 0){this.sourceMode=!0,this.treeMemo=void 0,(changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml!==void 0&&this.parseInline(this._xml),this.sourceSearchDirty&&(this.sourceSearchTask=this.searchSource());return}this.sourceMode=!1,wasSource&&(this.resetSearchForSourceReplacement(),this._xml!==void 0?this.parseInline(this._xml):this.scheduleAfterUpdate(()=>{this.loadFromSrc()})),(changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml!==void 0&&this.parseInline(this._xml),this.hasUpdated&&(changed.has("src")||changed.has("xml"))&&this.resetCopyFeedback(),(changed.has("src")||changed.has("xml"))&&(this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement());const locale=this.effectiveLocale;this.lastSearchLocale&&locale!==this.lastSearchLocale&&this.xmlState.kind==="loaded"&&(this.searchState=this.computeSearch(this.xmlState.doc),this.activeSearchIndex=this.searchState.ordered.length?Math.min(Math.max(0,this.activeSearchIndex),this.searchState.ordered.length-1):-1,this.searchQuery!==""&&(this.pendingSearchStateEvent=!0)),this.lastSearchLocale=locale}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const source=this.treeSource,epoch=this.hierarchy.epoch,binding=this.sourceBinding,owner=this.ownerDocument,current=()=>this.isConnected&&this.ownerDocument===owner&&source===this.treeSource&&epoch===this.hierarchy.epoch&&binding===this.sourceBinding,error=this.hierarchy.error||this.hierarchy.rowError,message=error?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();if(!current()||(this.announcements.transition("source",error?"error":this.hierarchy.loading?"loading":"loaded",message),!current()))return;error&&this.sourceAnnouncement!==message&&this.emit("lr-render-error",{error}),current()&&(this.sourceAnnouncement=error?message:void 0);return}this.syncCursors(),this.announcements.transition("load",this.xmlState.kind,this.xmlState.kind==="error"?this.xmlState.message:this.localize("loadingDocument")),(changed.has("src")||changed.has("xml")||changed.has("maxNodes")||changed.has("maxBytes"))&&this._xml===void 0&&this.scheduleAfterUpdate(()=>{this.loadFromSrc()}),this.pendingSearchStateEvent&&(this.pendingSearchStateEvent=!1,this.emitSearchChange())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.sourceBinding=void 0,this.requestUpdate("sourceReconnect",null),this.renderRoot.addEventListener("click",this.cancelSourceAnchor,!0),this.renderRoot.addEventListener("keydown",this.cancelSourceAnchor,!0);const moved=this.detached.cancel();this.hasUpdated&&this.src&&this._xml===void 0&&(!moved||this.xmlState.kind==="loading")&&this.scheduleAfterUpdate(()=>{this.loadFromSrc()})}disconnectedCallback(){this.xmlState.kind==="loading"&&this.generation++,this.invalidateSourceSearch(),this.sourceBinding=void 0,this.renderRoot.removeEventListener("click",this.cancelSourceAnchor,!0),this.renderRoot.removeEventListener("keydown",this.cancelSourceAnchor,!0),this.announcements.disconnect(),this.resetCopyFeedback(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.beginAbortableLoad(),this._xml===void 0&&(this.xmlState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.invalidateSourceSearch(),this.sourceBinding=void 0,this.hierarchy.adopted(),this.detached.flush(),this.announcements.adopted(),this.resetCopyFeedback()}parseInline(raw){const generation=++this.generation;this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement();try{this.setDoc(parseXmlDocument(raw,this.ownerDocument,this.effectiveMaxBytes,this.effectiveMaxNodes),generation)}catch(error){this.xmlState={kind:"error",message:this.localize(isResourceLimitError(error)?"xmlViewerTooManyNodes":"xmlViewerParseError")},this.emit("lr-render-error",{error})}}async loadFromSrc(){if(this.treeSource!==void 0||this._xml!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(this.pendingSearchStateEvent||=this.resetSearchForSourceReplacement(),!this.src){this.xmlState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.xmlState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.xmlState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response,this.effectiveMaxBytes);if(signal?.aborted||!this.isConnected||generation!==this.generation||(preflightXml(text,this.effectiveMaxBytes,this.effectiveMaxNodes),await yieldViewerTask(this.ownerDocument.defaultView,()=>!signal?.aborted&&this.isConnected&&generation===this.generation),signal?.aborted||!this.isConnected||generation!==this.generation))return;this.setDoc(parseXmlDocument(text,this.ownerDocument,this.effectiveMaxBytes,this.effectiveMaxNodes,!0),generation)}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.xmlState={kind:"error",message:this.localize(error instanceof XmlDoctypeError?"xmlViewerParseError":isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}resetSearchForSourceReplacement(){if(this.treeSource!==void 0)return!1;const changed=this.searchQuery!==""||this.searchState.ordered.length>0||!this.searchState.matchCountExact||this.activeSearchIndex!==-1;return this.searchQuery="",this.searchState=EMPTY_SEARCH,this.activeSearchIndex=-1,changed}setDoc(doc,generation){if(generation!==this.generation)return;const parseError=findParserError(doc);if(parseError){this.xmlState={kind:"error",message:this.localize("xmlViewerParseError")},this.emit("lr-render-error",{error:new Error(parseError)});return}try{this.childCounts=validateDocumentComplexity(doc,this.effectiveMaxNodes)}catch(error){this.xmlState={kind:"error",message:this.localize("xmlViewerTooManyNodes")},this.emit("lr-render-error",{error});return}if(this.xmlState={kind:"loaded",doc},this.treeSource!==void 0)return;const next=this.computeSearch(doc);if(this.searchState=next,this.searchQuery.trim()&&(this.activeSearchIndex=next.ordered.length?Math.min(Math.max(this.activeSearchIndex,0),next.ordered.length-1):-1,this.emitSearchChange()),this.expandedOverrides.size){let pruned=null;for(const key of this.expandedOverrides.keys())next.paths.has(key)||(pruned??=new Map(this.expandedOverrides),pruned.delete(key));pruned&&(this.expandedOverrides=pruned)}}computeSearch(doc){const locale=this.effectiveLocale,boundedQuery=boundedViewerSearchQuery(this.searchQuery,locale),query=boundedQuery.needle,budget=new ViewerSearchWorkBudget,matches=new Set,tagMatches=new Set,attrMatches=new Set,textMatches=new Set,forceExpand=new Set,paths=new Set,ordered=[];let matchCountExact=boundedQuery.accepted;const markAncestors=path=>{for(let i=path.length-1;i>=0;i--)forceExpand.add(JSON.stringify(path.slice(0,i)))},walk=(el,path)=>{const pathKey=JSON.stringify(path);if(paths.add(pathKey),query&&matchCountExact){let hit=!1;budget.includes(el.tagName,query,locale)&&(tagMatches.add(pathKey),hit=!0);for(const attr of el.attributes)if((budget.includes(attr.name,query,locale)||budget.includes(attr.value,query,locale))&&(attrMatches.add(attrKey(pathKey,attr.name)),hit=!0),!budget.complete)break;const ownTextParts=function*(){for(const child of el.childNodes)child.nodeType===Node.TEXT_NODE&&(yield child.textContent??"")};if(budget.complete&&budget.includesJoined(ownTextParts(),query,locale)&&(textMatches.add(pathKey),hit=!0),budget.complete||(matchCountExact=!1),hit)if(ordered.length===MAX_SEARCH_MATCHES){matchCountExact=!1,tagMatches.delete(pathKey),textMatches.delete(pathKey);for(const attr of el.attributes)attrMatches.delete(attrKey(pathKey,attr.name))}else matches.add(pathKey),ordered.push(pathKey),forceExpand.add(pathKey),markAncestors(path)}elementChildren(el).forEach((child,i)=>walk(child,[...path,i]))};return doc.documentElement&&walk(doc.documentElement,[]),{matches,tagMatches,attrMatches,textMatches,forceExpand,paths,ordered,matchCountExact}}sourcePathKey(path){if(!Array.isArray(path)||path.length>MAX_DEPTH)return;const segments=[];for(let index=0;index<path.length;index++){const segment=hierarchyField(path,String(index));if(typeof segment=="number"&&Number.isSafeInteger(segment)&&segment>=0)segments.push(segment);else if(typeof segment=="string"&&index===path.length-1&&segment.startsWith("@")&&segment.length>1&&segment.length<=65536)segments.push(segment);else return}const key=JSON.stringify(segments);return key.length<=65536?key:void 0}async applyAnchor(anchor){if(this.treeSource!==void 0){const key=anchor.kind==="node-path"?this.sourcePathKey(anchor.path):void 0;if(key===void 0)return!1;const task={};this.sourceAnchorTask=task;try{return!await this.hierarchy.reveal(key)||this.sourceAnchorTask!==task?!1:(this.activePath=key,await this.updateComplete,this.sourceAnchorTask===task)}finally{this.sourceAnchorTask===task&&(this.sourceAnchorTask=void 0)}}if(anchor.kind!=="node-path"||this.xmlState.kind!=="loaded"||!this.xmlState.doc.documentElement)return!1;const resolved=resolvePath(this.xmlState.doc.documentElement,anchor.path);if(!resolved?.element)return!1;const numericPath=anchor.path.filter(s=>typeof s=="number");this.expandAncestors(anchor.path);const pathKey=JSON.stringify(numericPath);return this.activePath=pathKey,this.activeAttr=resolved.attr?attrKey(pathKey,resolved.attr):null,await this.updateComplete,this.renderRoot.querySelector('[part="node"][data-active]')!==null}resolveHighlights(){const byPath=new Map;if(this.treeSource!==void 0){const admitted=[],seen2=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(seen2.has(highlight.id))continue;seen2.add(highlight.id);const key=highlight.anchor.kind==="node-path"?this.sourcePathKey(highlight.anchor.path):void 0;if(key!==void 0&&admitted.push({highlight,key}),admitted.length>=MAX_PAINTED_HIGHLIGHTS)break}return admitted.forEach(({highlight,key},index)=>{byPath.has(key)||byPath.set(key,{highlight,index,total:admitted.length})}),byPath}if(this.xmlState.kind!=="loaded")return byPath;const root=this.xmlState.doc.documentElement;if(!root)return byPath;const seen=new Set,resolved=[],candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolutionBudget={remaining:this.effectiveMaxNodes};for(const highlight of candidates)if(!seen.has(highlight.id)&&(seen.add(highlight.id),highlight.anchor.kind==="node-path"&&resolvePath(root,highlight.anchor.path,resolutionBudget)&&(resolved.push({highlight,pathKey:JSON.stringify(highlight.anchor.path.filter(s=>typeof s=="number"))}),resolved.length>=MAX_PAINTED_HIGHLIGHTS)))break;return resolved.forEach(({highlight,pathKey},index)=>{byPath.has(pathKey)||byPath.set(pathKey,{highlight,index,total:resolved.length})}),byPath}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}expandAncestors(path,includeSelf=!1){let next;const expand=(key,depth)=>{this.isExpanded(key,depth)||(next??=new Map(this.expandedOverrides),next.set(key,!0))};for(let i=0;i<path.length;i++)typeof path[i]=="number"&&expand(JSON.stringify(path.slice(0,i)),i);includeSelf&&expand(JSON.stringify(path),path.length),next&&(this.expandedOverrides=next)}async search(query){if(this.treeSource!==void 0){this.cancelPendingAnchor(),this.searchQuery=query,this.invalidateSourceSearch(),this.syncSource();const intent=this.sourceSearchIntent;return this.requestUpdate("sourceSearchIntent",null),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceSearchTask:0}return this.searchQuery=query,this.searchState=this.xmlState.kind==="loaded"?this.computeSearch(this.xmlState.doc):EMPTY_SEARCH,this.activeSearchIndex=this.searchState.ordered.length?0:-1,this.requestUpdate(),this.emitSearchChange(),this.activeSearchIndex>=0&&await this.scrollActiveMatchIntoView(),this.searchState.ordered.length}async searchNext(){return this.treeSource!==void 0?this.stepSourceSearch(1):this.searchState.ordered.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchState.ordered.length,this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0):!1}async searchPrevious(){return this.treeSource!==void 0?this.stepSourceSearch(-1):this.searchState.ordered.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchState.ordered.length)%this.searchState.ordered.length,this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0):!1}clearSearch(){if(this.cancelPendingAnchor(),this.treeSource!==void 0){this.searchQuery="",this.hierarchy.cancelSearch(),this.invalidateSourceSearch(),this.syncSource(),this.requestUpdate("sourceSearchIntent",null);return}this.searchQuery="",this.searchState=this.xmlState.kind==="loaded"?this.computeSearch(this.xmlState.doc):EMPTY_SEARCH,this.activeSearchIndex=-1,this.requestUpdate(),this.emitSearchChange()}async scrollActiveMatchIntoView(){const pathKey=this.searchState.ordered[this.activeSearchIndex];if(pathKey===void 0)return;this.expandAncestors(JSON.parse(pathKey),!0),await this.updateComplete,this.renderRoot.querySelector("[data-active-match]")?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.treeSource!==void 0?this.sourceHitKeys.size:this.searchState.ordered.length,matchCountExact:this.treeSource!==void 0?this.sourceSearchExact:this.searchState.matchCountExact,activeIndex:this.activeSearchIndex})}toggleNode(pathKey,expanded){const next=new Map(this.expandedOverrides);next.set(pathKey,!expanded),this.expandedOverrides=next}isExpanded(pathKey,depth){const override=this.expandedOverrides.get(pathKey);if(override!==void 0)return override;if(this.searchState.forceExpand.has(pathKey))return!0;const expandDepth=this.safeExpandDepth;return!(expandDepth!==void 0&&depth>=expandDepth)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration++,this.cancelCopyTimer(),this.copyFeedback=null}showCopyFeedback(key,status,generation,owner){this.copyFeedback={key,status},this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||this.copyTimer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.copyFeedback=null)},1500),this.copyTimer={owner,handle,generation}}async copyText(text,key){if(this.treeSource!==void 0)return;const owner=this.isConnected?this.ownerDocument.defaultView:null,generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyFeedback=null;const outcome=await writeClipboardText(owner,text);if(!(!owner||!this.isConnected||generation!==this.copyGeneration||this.ownerDocument.defaultView!==owner)){if(outcome.ok){this.showCopyFeedback(key,"success",generation,owner),this.emit("lr-copy",outcome);return}this.showCopyFeedback(key,"error",generation,owner),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}}serializeXml(node){const XMLSerializerCtor=this.isConnected?this.ownerDocument.defaultView?.XMLSerializer:void 0;return XMLSerializerCtor?new XMLSerializerCtor().serializeToString(node):null}copySerializedXml(node,key){const text=this.serializeXml(node);text!==null&&this.copyText(text,key)}copyButtonLabel(key,rest){const feedback=this.copyFeedback?.key===key?this.copyFeedback.status:void 0;return feedback==="success"?this.localize("copied"):feedback==="error"?this.localize("copyFailed"):rest}renderCopyButton(getNode,name,key){if(!this.copyable)return nothing;const label=this.copyButtonLabel(key,this.localize("xmlViewerCopyNode",void 0,{name}));return html`
|
|
15
15
|
<button
|
|
16
16
|
part="copy-button"
|
|
17
17
|
type="button"
|
package/dist/data-sources.d.ts
CHANGED
|
@@ -32,3 +32,13 @@ readonly state:string;readonly total:number;readonly rows:LyraHierarchyView<Lyra
|
|
|
32
32
|
export interface LyraHierarchySource<T,Q,Summary=undefined>{readonly revision:LyraSourceRevision;project(request:LyraHierarchyRequest<Q>):Promise<LyraHierarchyProjection<T,Summary>>;search?(request:LyraSourceSearchRequest):Promise<LyraSourceSearchResult<{readonly key:string;}>>;copy?(request:LyraSourceContext&{readonly key:string|null;readonly scope:'node'|'subtree'|'document';readonly maxBytes:number;}):Promise<string>;}export interface LyraInspectionNode{readonly name:string;readonly kind:'object'|'array'|'scalar'|'element'|'attribute'|'text'|'comment'|'processing-instruction';readonly value?:string;readonly path:string;}export interface LyraHierarchyQuery{readonly search:string;readonly hiddenKinds:readonly string[];}export interface LyraTraceSourceSummary{readonly startMs:number;readonly endMs:number;}export interface LyraTaskSourceSummary{readonly total:number;readonly completed:number;}export interface LyraSourceBounds{readonly x:number;readonly y:number;readonly width:number;readonly height:number;}export interface LyraGraphSourceQuery{readonly kind:'nodes'|'edges';readonly search:string;readonly centerKey:string|null;readonly direction:'in'|'out'|'both';readonly nodeTypes:readonly string[];}export type LyraGraphRecord<N,E> ={readonly kind:'node';readonly value:N;}|{readonly kind:'edge';readonly value:E;};export interface LyraGraphSourceSummary{readonly nodes:number;readonly edges:number;}export interface LyraGraphSceneRequest extends LyraSourceContext{readonly mode:'neighborhood'|'viewport';readonly centerKey:string|null;readonly bounds:LyraSourceBounds|null;readonly nodeLimit:number;readonly edgeLimit:number;readonly includeKeys:readonly string[];}export interface LyraGraphScene<N,E>{readonly nodes:readonly{readonly key:string;readonly value:N;readonly position?:{readonly x:number;readonly y:number;readonly z?:number;};}[];readonly edges:readonly{readonly key:string;readonly value:E;readonly source:string;readonly target:string;}[];readonly total:LyraGraphSourceSummary;readonly coverage:'complete'|'neighborhood'|'aggregate';readonly worldBounds:LyraSourceBounds|null;}export interface LyraGraphOverview{readonly bounds:LyraSourceBounds;readonly bins:readonly{readonly bounds:LyraSourceBounds;readonly count:number;}[];}
|
|
33
33
|
/** Full-source record navigation with separately bounded diagram and aggregate queries.*/
|
|
34
34
|
export interface LyraGraphSource<N,E>{readonly revision:LyraSourceRevision;readonly records:LyraPageSource<LyraGraphRecord<N,E>,LyraGraphSourceQuery,LyraGraphSourceSummary>;scene(request:LyraGraphSceneRequest):Promise<LyraGraphScene<N,E>>;overview?(request:LyraSourceContext&{readonly limit:number;}):Promise<LyraGraphOverview>;}
|
|
35
|
+
/** One stable-key row in a bounded cursor result.*/
|
|
36
|
+
export interface LyraCursorRecord<T>{readonly key:string;readonly value:T;}
|
|
37
|
+
/** A provider-owned query with an opaque continuation; null starts the query.*/
|
|
38
|
+
export interface LyraCursorRequest<Q>extends LyraSourceContext{readonly scope:string;readonly query:Q;readonly cursor:string|null;readonly limit:number;}export interface LyraCursorResult<T>{readonly rows:readonly LyraCursorRecord<T>[];
|
|
39
|
+
/** Null is the only end marker; a token does not promise another row or an exact total.*/
|
|
40
|
+
readonly nextCursor:string|null;}
|
|
41
|
+
/** Bounded continuation navigation without a total, numeric order, or lookup requirement.*/
|
|
42
|
+
export interface LyraCursorSource<T,Q>{readonly revision:LyraSourceRevision;
|
|
43
|
+
/** Identity namespace and listing scope; changing it invalidates retained row identity.*/
|
|
44
|
+
readonly scope:string;query(request:LyraCursorRequest<Q>):Promise<LyraCursorResult<T>>;}export type LyraCursorSourceStatus='idle'|'loading'|'ready'|'error';export interface LyraCursorNavigationState{readonly status:LyraCursorSourceStatus;readonly canGoBack:boolean;readonly canGoForward:boolean;readonly atEnd:boolean;readonly historyTruncated:boolean;}
|