@aceshooting/lyra-ui 12.0.0 → 12.1.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 +19 -0
- package/custom-elements.json +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
- package/dist/components/charts/chart/histogram-bin.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
- package/dist/components/charts/chart/lite-chart.class.js +6 -6
- package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +4 -1
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/table/table.class.d.ts +18 -4
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +2 -1
- package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
- package/dist/components/data/timeline/timeline-cluster.js +1 -0
- package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
- package/dist/components/data/timeline/timeline-item.class.js +13 -2
- package/dist/components/data/timeline/timeline-item.styles.js +65 -0
- package/dist/components/data/timeline/timeline.class.d.ts +83 -27
- package/dist/components/data/timeline/timeline.class.js +3 -3
- package/dist/components/data/timeline/timeline.d.ts +1 -0
- package/dist/components/data/timeline/timeline.js +1 -1
- package/dist/components/data/timeline/timeline.styles.js +14 -0
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
- package/dist/components/forms/combobox/combobox.class.js +3 -2
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/time-input-shared.d.ts +2 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
- package/dist/components/forms/radio/radio-button.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +0 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +0 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +0 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +0 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
- package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
- package/dist/components/layout/details/accordion-owner.d.ts +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/av-player/av-metadata.d.ts +0 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +0 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +4 -1
- package/dist/components/media/map/map.class.d.ts +50 -12
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/utility/format/format-options.d.ts +0 -2
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon-resource.d.ts +0 -2
- package/dist/components/utility/icon/icon-resource.js +1 -1
- package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
- package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
- package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
- package/dist/custom-elements-jsx.d.ts +4 -4
- package/dist/events.d.ts +15 -0
- package/dist/internal/accessibility-visibility.d.ts +1 -1
- package/dist/internal/anchor-target.d.ts +1 -3
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
- package/dist/internal/anchored-overlay-runtime.js +1 -0
- package/dist/internal/announcement-text.d.ts +1 -1
- package/dist/internal/ansi.d.ts +0 -4
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/aria-ownership.d.ts +2 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/focus-navigation.d.ts +3 -2
- package/dist/internal/form-associated.d.ts +0 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.d.ts +0 -3
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +0 -13
- package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
- package/dist/internal/nonmodal-overlay-manager.js +1 -0
- package/dist/internal/overlay-manager.d.ts +4 -20
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.d.ts +66 -0
- package/dist/internal/overlay-stack.js +1 -0
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/lyra.d.ts +2 -3
- package/dist/svelte.d.ts +4 -4
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/utilities/localization.js +1 -1
- package/dist/vue.d.ts +4 -4
- package/llms/components/lr-combobox.md +42 -0
- package/llms/components/lr-heatmap.md +4 -1
- package/llms/components/lr-lite-chart.md +20 -8
- package/llms/components/lr-map.md +51 -21
- package/llms/components/lr-option.md +42 -0
- package/llms/components/lr-popover.md +39 -0
- package/llms/components/lr-table.md +7 -3
- package/llms/components/lr-timeline-item.md +49 -24
- package/llms/components/lr-timeline.md +49 -24
- package/llms-full.txt +220 -56
- package/package.json +3 -4
- package/vscode-css-data.json +21 -0
- package/vscode-html-data.json +12 -6
- package/web-types.json +47 -16
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedSelectionRects,boundedSelectionText,normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
|
|
2
|
-
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length
|
|
2
|
+
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length,retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
|
|
3
3
|
<canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
|
|
4
4
|
<div part="page-error" hidden></div>
|
|
5
5
|
<lr-highlight-layer
|
|
@@ -8,7 +8,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
8
8
|
@lr-highlight-activate=${this.onHighlightLayerActivate}
|
|
9
9
|
></lr-highlight-layer>
|
|
10
10
|
<div part="text-layer" ${ref(this.textLayerContainerRef(number))}></div>
|
|
11
|
-
</div>`},this.onVisibleRangeChanged=event=>{if(event.stopPropagation(),this.loadState.kind!=="ready")return;const next=this.clampPage(event.detail.start+1);next!==this.page&&(this.scrollDrivenPage=!0,this.page=next)}}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}}static{this.styles=[LyraElement.styles,styles,srOnly]}get pageViewerSnapshot(){return this.pageViewerSnapshotValue}willUpdate(changed){if(super.willUpdate(changed),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.hasSearchState(),this.resetSearchState())}updated(changed){super.updated(changed);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.emitSearchChange())),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.searchQuery.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.generation++,this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits(),this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0;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.pageViewerIdentity++,this.pageViewerSnapshotValue=Object.freeze({identity:this.pageViewerIdentity,status:"idle",page:1,pageCount:0}),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.loadState.doc.destroy?.()}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=Object.freeze({identity:this.pageViewerIdentity,status,page:status==="ready"?this.clampPage(this.page):1,pageCount:status==="ready"?finiteCount(pageCount,0,MAX_PAGE_COUNT):0}),previous=this.pageViewerSnapshotValue;previous.identity===snapshot.identity&&previous.status===snapshot.status&&previous.page===snapshot.page&&previous.pageCount===snapshot.pageCount||(this.pageViewerSnapshotValue=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.pageViewerIdentity++;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 doc=await pdfjsLib.getDocument({data}).promise;if(!this.isConnected||generation!==this.generation){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("lr-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("lr-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.ownerDocument.defaultView)?"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.ownerDocument.defaultView)?"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}bindTextSelection(contentRoot){this.textSelectionCleanup?.();const ownerDocument=contentRoot.ownerDocument,view=ownerDocument.defaultView;if(!view){this.textSelectionCleanup=void 0;return}const resolveSelectionRange=()=>{const hostShadowRoot=this.shadowRoot,listShadowRoot=this.shadowRoot?.querySelector("lr-virtual-list")?.shadowRoot??null,globalSelection=view.getSelection();if(globalSelection?.getComposedRanges&&hostShadowRoot){const shadowRoots=listShadowRoot?[hostShadowRoot,listShadowRoot]:[hostShadowRoot],[composed]=globalSelection.getComposedRanges({shadowRoots});if(!composed||composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)return null;const range=ownerDocument.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}const selection=listShadowRoot?.getSelection?.()??globalSelection;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)},onSelectionEnd=()=>{const range=resolveSelectionRange();if(!range||!containsAcrossShadowBoundaries(contentRoot,range.commonAncestorContainer)&&range.commonAncestorContainer!==contentRoot)return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};let debounceHandle;const onSelectionChange=()=>{debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle),debounceHandle=view.requestAnimationFrame(()=>{debounceHandle=void 0,onSelectionEnd()})};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd),ownerDocument.addEventListener("selectionchange",onSelectionChange),this.textSelectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),ownerDocument.removeEventListener("selectionchange",onSelectionChange),debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle)}}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}),dpr=canvas.ownerDocument.defaultView?.devicePixelRatio||1;canvas.width=Math.floor(viewport.width*dpr),canvas.height=Math.floor(viewport.height*dpr),canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(dpr,0,0,dpr,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(!ref2)return;const pageIndex=await doc.getPageIndex(ref2);return typeof pageIndex=="number"?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;if(items.length>=TEXT_QUOTE_LIMITS.maxNodes){traversalTruncated=!0;break}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.searchQuery=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(this.loadState.kind!=="ready")return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const trimmedQuery=query.trim();if(!trimmedQuery)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),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.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length)}async searchNext(){return this.searchMatches.length===0?!1:(this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),await this.focusSearchMatch(this.searchActiveIndex),!0)}async searchPrevious(){return this.searchMatches.length===0?!1:(this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),await this.focusSearchMatch(this.searchActiveIndex),!0)}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}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=>{unwrapPdfSearchMark(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.page&&(this.scrollDrivenPage=!0,this.page=next)}}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}}static{this.styles=[LyraElement.styles,styles,srOnly]}get pageViewerSnapshot(){return this.pageViewerSnapshotValue}willUpdate(changed){if(super.willUpdate(changed),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.hasSearchState(),this.resetSearchState())}updated(changed){super.updated(changed);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.emitSearchChange())),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.searchQuery.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.generation++,this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits(),this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0;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.pageViewerIdentity++,this.pageViewerSnapshotValue=Object.freeze({identity:this.pageViewerIdentity,status:"idle",page:1,pageCount:0}),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.loadState.doc.destroy?.()}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=Object.freeze({identity:this.pageViewerIdentity,status,page:status==="ready"?this.clampPage(this.page):1,pageCount:status==="ready"?finiteCount(pageCount,0,MAX_PAGE_COUNT):0}),previous=this.pageViewerSnapshotValue;previous.identity===snapshot.identity&&previous.status===snapshot.status&&previous.page===snapshot.page&&previous.pageCount===snapshot.pageCount||(this.pageViewerSnapshotValue=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.pageViewerIdentity++;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 doc=await pdfjsLib.getDocument({data}).promise;if(!this.isConnected||generation!==this.generation){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("lr-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("lr-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.ownerDocument.defaultView)?"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.ownerDocument.defaultView)?"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}bindTextSelection(contentRoot){this.textSelectionCleanup?.();const ownerDocument=contentRoot.ownerDocument,view=ownerDocument.defaultView;if(!view){this.textSelectionCleanup=void 0;return}const resolveSelectionRange=()=>{const hostShadowRoot=this.shadowRoot,listShadowRoot=this.shadowRoot?.querySelector("lr-virtual-list")?.shadowRoot??null,globalSelection=view.getSelection();if(globalSelection?.getComposedRanges&&hostShadowRoot){const shadowRoots=listShadowRoot?[hostShadowRoot,listShadowRoot]:[hostShadowRoot],[composed]=globalSelection.getComposedRanges({shadowRoots});if(!composed||composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)return null;const range=ownerDocument.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}const selection=listShadowRoot?.getSelection?.()??globalSelection;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)},onSelectionEnd=()=>{const range=resolveSelectionRange();if(!range||!containsAcrossShadowBoundaries(contentRoot,range.commonAncestorContainer)&&range.commonAncestorContainer!==contentRoot)return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};let debounceHandle;const onSelectionChange=()=>{debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle),debounceHandle=view.requestAnimationFrame(()=>{debounceHandle=void 0,onSelectionEnd()})};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd),ownerDocument.addEventListener("selectionchange",onSelectionChange),this.textSelectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),ownerDocument.removeEventListener("selectionchange",onSelectionChange),debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle)}}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}),dpr=canvas.ownerDocument.defaultView?.devicePixelRatio||1;canvas.width=Math.floor(viewport.width*dpr),canvas.height=Math.floor(viewport.height*dpr),canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(dpr,0,0,dpr,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(!ref2)return;const pageIndex=await doc.getPageIndex(ref2);return typeof pageIndex=="number"?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;const textNode=node,element=textNode.parentElement??container;items.push({text:textNode.data,element,node:textNode,joinBefore:items.length===0||run!==previousRun}),previousRun=run}const scope=scopeFromItems(items);return traversalTruncated&&(scope.truncated=!0),this.pdfTextScopeBuilds++,scope}mountedPageTextIndex(pageNumber,forceMappingRefresh=!1){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;const cached=this.mountedPageTextIndexes.get(pageNumber);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&!cached.mappingDirty&&!forceMappingRefresh)return cached;const scope=this.buildMountedPageScope(container);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&cached.index.rebindScope(scope))return cached.scope=scope,cached.mappingDirty=!1,cached;const created={scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceWorkCodeUnits:scope.text.length,container,mappingDirty:!1};return this.mountedPageTextIndexes.set(pageNumber,created),created}pdfTextScopeBuildCount(){return this.pdfTextScopeBuilds}pdfTextQuoteScanCount(pageNumber){return this.mountedPageTextIndexes.get(pageNumber)?.index.scanCount??0}async search(query){invalidateLyraLocaleCache(this);const generation=++this.searchGeneration;if(this.searchQuery=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(this.loadState.kind!=="ready")return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const trimmedQuery=query.trim();if(!trimmedQuery)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),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.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length)}async searchNext(){return this.searchMatches.length===0?!1:(this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),await this.focusSearchMatch(this.searchActiveIndex),!0)}async searchPrevious(){return this.searchMatches.length===0?!1:(this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),await this.focusSearchMatch(this.searchActiveIndex),!0)}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}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=>{unwrapPdfSearchMark(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} aria-label=${this.localize("pdfViewerPreviousPage")} @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} aria-label=${this.localize("pdfViewerNextPage")} @click=${this.nextPage}>${this.localize("pdfViewerNextPage")}</button>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertZipArchiveWithinLimits}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_PPTX_ENTRIES=4e3,DEFAULT_MAX_PPTX_UNCOMPRESSED_BYTES=256*1024*1024;function assertPptxArchiveWithinLimits(source,options={}){return assertZipArchiveWithinLimits(source,{description:"PPTX",maxEntries:options.maxEntries??DEFAULT_MAX_PPTX_ENTRIES,maxUncompressedBytes:options.maxUncompressedBytes??DEFAULT_MAX_PPTX_UNCOMPRESSED_BYTES,signal:options.signal})}export{
|
|
1
|
+
import{assertZipArchiveWithinLimits}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_PPTX_ENTRIES=4e3,DEFAULT_MAX_PPTX_UNCOMPRESSED_BYTES=256*1024*1024;function assertPptxArchiveWithinLimits(source,options={}){return assertZipArchiveWithinLimits(source,{description:"PPTX",maxEntries:options.maxEntries??DEFAULT_MAX_PPTX_ENTRIES,maxUncompressedBytes:options.maxUncompressedBytes??DEFAULT_MAX_PPTX_UNCOMPRESSED_BYTES,signal:options.signal})}export{assertPptxArchiveWithinLimits};
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
export declare const DEFAULT_MAX_XLSX_ENTRIES = 10000;
|
|
2
|
-
export declare const DEFAULT_MAX_XLSX_UNCOMPRESSED_BYTES: number;
|
|
3
|
-
export declare const DEFAULT_MAX_XLSX_XML_NODES = 1000000;
|
|
4
|
-
export declare const DEFAULT_MAX_XLSX_ROWS = 10000;
|
|
5
|
-
export declare const DEFAULT_MAX_XLSX_CELLS = 1000000;
|
|
6
1
|
export interface XlsxResourceGuardOptions {
|
|
7
2
|
signal?: AbortSignal;
|
|
8
3
|
maxXmlNodes?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_XLSX_ENTRIES=1e4,DEFAULT_MAX_XLSX_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_XLSX_XML_NODES=1e6,DEFAULT_MAX_XLSX_ROWS=1e4,DEFAULT_MAX_XLSX_CELLS=1e6;function assertXlsxArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_XLSX_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_XLSX_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"spreadsheet",maxEntries,maxUncompressedBytes,allowNonZip:!0,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.xml$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_XLSX_XML_NODES,maxRows:options.maxRows??DEFAULT_MAX_XLSX_ROWS,maxCells:options.maxCells??DEFAULT_MAX_XLSX_CELLS})})}export{
|
|
1
|
+
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_XLSX_ENTRIES=1e4,DEFAULT_MAX_XLSX_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_XLSX_XML_NODES=1e6,DEFAULT_MAX_XLSX_ROWS=1e4,DEFAULT_MAX_XLSX_CELLS=1e6;function assertXlsxArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_XLSX_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_XLSX_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"spreadsheet",maxEntries,maxUncompressedBytes,allowNonZip:!0,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.xml$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_XLSX_XML_NODES,maxRows:options.maxRows??DEFAULT_MAX_XLSX_ROWS,maxCells:options.maxCells??DEFAULT_MAX_XLSX_CELLS})})}export{assertXlsxArchiveWithinLimits};
|
|
@@ -102,7 +102,7 @@ import type { LyraSparkline } from './components/data/sparkline/sparkline.class.
|
|
|
102
102
|
import type { LyraStat } from './components/data/stat/stat.class.js';
|
|
103
103
|
import type { LyraTable, LyraTableEventMap } from './components/data/table/table.class.js';
|
|
104
104
|
import type { LyraTimelineItem } from './components/data/timeline/timeline-item.class.js';
|
|
105
|
-
import type { LyraTimeline } from './components/data/timeline/timeline.class.js';
|
|
105
|
+
import type { LyraTimeline, LyraTimelineEventMap } from './components/data/timeline/timeline.class.js';
|
|
106
106
|
import type { LyraTreeItem, LyraTreeItemEventMap } from './components/data/tree/tree-item.class.js';
|
|
107
107
|
import type { LyraTree, LyraTreeEventMap } from './components/data/tree/tree.class.js';
|
|
108
108
|
import type { LyraWordCloud, LyraWordCloudEventMap } from './components/data/word-cloud/word-cloud.class.js';
|
|
@@ -1202,7 +1202,7 @@ export type LyraLocalePickerReactProps = LyraReactElementProps<LyraLocalePicker,
|
|
|
1202
1202
|
'show-flags'?: LyraLocalePicker['showFlags'];
|
|
1203
1203
|
'value'?: LyraLocalePicker['defaultValue'];
|
|
1204
1204
|
}>;
|
|
1205
|
-
export type LyraMapReactProps = LyraReactElementProps<LyraMap, 'center' | 'choropleth' | 'dataLayers' | 'label' | 'legend' | 'legendGradient' | 'legendGradientHiLabel' | 'legendGradientLoLabel' | 'locale' | 'mapStyle' | 'markers' | 'maxBounds' | 'strings' | 'zoom', {}, LyraMapEventMap, 'lr-map-click' | 'lr-map-load', '--lr-map-choropleth-fill-opacity' | '--lr-map-popup-close-button-active-bg' | '--lr-map-popup-close-button-active-color' | '--lr-map-popup-close-button-hover-bg' | '--lr-map-popup-close-button-hover-color', {
|
|
1205
|
+
export type LyraMapReactProps = LyraReactElementProps<LyraMap, 'center' | 'choropleth' | 'dataLayers' | 'label' | 'legend' | 'legendGradient' | 'legendGradientHiLabel' | 'legendGradientLoLabel' | 'locale' | 'mapStyle' | 'markers' | 'maxBounds' | 'renderWorldCopies' | 'strings' | 'zoom', {}, LyraMapEventMap, 'lr-map-click' | 'lr-map-load' | 'lr-map-marker-activate', '--lr-map-choropleth-fill-opacity' | '--lr-map-popup-close-button-active-bg' | '--lr-map-popup-close-button-active-color' | '--lr-map-popup-close-button-hover-bg' | '--lr-map-popup-close-button-hover-color', {
|
|
1206
1206
|
'legend-gradient-hi-label'?: LyraMap['legendGradientHiLabel'];
|
|
1207
1207
|
'legend-gradient-lo-label'?: LyraMap['legendGradientLoLabel'];
|
|
1208
1208
|
}>;
|
|
@@ -1865,10 +1865,10 @@ export type LyraTimeRangeReactProps = LyraReactElementProps<LyraTimeRange, 'cust
|
|
|
1865
1865
|
'end-label'?: LyraTimeRange['endLabel'];
|
|
1866
1866
|
'start-label'?: LyraTimeRange['startLabel'];
|
|
1867
1867
|
}>;
|
|
1868
|
-
export type LyraTimelineReactProps = LyraReactElementProps<LyraTimeline, 'accessibleLabel' | 'collision' | 'locale' | 'orientation' | 'rangeEnd' | 'rangeStart' | 'scale' | 'strings', {},
|
|
1868
|
+
export type LyraTimelineReactProps = LyraReactElementProps<LyraTimeline, 'accessibleLabel' | 'collision' | 'locale' | 'orientation' | 'rangeEnd' | 'rangeStart' | 'scale' | 'strings', {}, LyraTimelineEventMap, 'lr-cluster-activate', '--lr-scroll-fade-size' | '--lr-timeline-cluster-bg' | '--lr-timeline-cluster-color' | '--lr-timeline-cluster-size' | '--lr-timeline-collision-offset' | '--lr-timeline-gap' | '--lr-timeline-time-extent', {
|
|
1869
1869
|
'aria-label'?: LyraTimeline['accessibleLabel'];
|
|
1870
1870
|
}>;
|
|
1871
|
-
export type LyraTimelineItemReactProps = LyraReactElementProps<LyraTimelineItem, 'active' | 'locale' | 'strings' | 'sync' | 'timestamp' | 'variant', {}, {}, never, '--lr-timeline-active-ring-color' | '--lr-timeline-marker-color' | '--lr-timeline-marker-size' | '--lr-timeline-rail-color' | '--lr-timeline-rail-width', {}>;
|
|
1871
|
+
export type LyraTimelineItemReactProps = LyraReactElementProps<LyraTimelineItem, 'active' | 'locale' | 'strings' | 'sync' | 'timestamp' | 'variant', {}, {}, never, '--lr-timeline-active-ring-color' | '--lr-timeline-cluster-bg' | '--lr-timeline-cluster-color' | '--lr-timeline-cluster-size' | '--lr-timeline-marker-color' | '--lr-timeline-marker-size' | '--lr-timeline-rail-color' | '--lr-timeline-rail-width', {}>;
|
|
1872
1872
|
export type LyraToastReactProps = LyraReactElementProps<LyraToast, 'locale' | 'placement' | 'strings', {}, LyraToastEventMap, 'lr-toast-overflow', '--gap' | '--lr-toast-accent-color' | '--lr-toast-accent-width' | '--lr-toast-font-size' | '--lr-toast-gap' | '--lr-toast-hide-duration' | '--lr-toast-padding' | '--lr-toast-show-duration' | '--lr-toast-width' | '--width', {}>;
|
|
1873
1873
|
export type LyraToastItemReactProps = LyraReactElementProps<LyraToastItem, 'duration' | 'locale' | 'size' | 'strings' | 'variant' | 'withIcon', {}, LyraToastItemEventMap, 'lr-after-hide' | 'lr-after-show' | 'lr-hide' | 'lr-show', '--accent-width' | '--hide-duration' | '--lr-toast-accent-color' | '--lr-toast-accent-width' | '--lr-toast-close-button-active-bg' | '--lr-toast-close-button-active-color' | '--lr-toast-close-button-hover-bg' | '--lr-toast-close-button-hover-color' | '--lr-toast-font-size' | '--lr-toast-hide-duration' | '--lr-toast-item-gap' | '--lr-toast-item-radius' | '--lr-toast-padding' | '--lr-toast-show-duration' | '--padding' | '--show-duration', {
|
|
1874
1874
|
'with-icon'?: LyraToastItem['withIcon'];
|
package/dist/events.d.ts
CHANGED
|
@@ -73,6 +73,7 @@ import type { LyraHeatmapEventMap } from './components/data/heatmap/heatmap.clas
|
|
|
73
73
|
import type { LyraPaginationEventMap } from './components/data/pagination/pagination.class.js';
|
|
74
74
|
import type { LyraSequenceStripEventMap } from './components/data/sequence-strip/sequence-strip.class.js';
|
|
75
75
|
import type { LyraTableEventMap } from './components/data/table/table.class.js';
|
|
76
|
+
import type { LyraTimelineEventMap } from './components/data/timeline/timeline.class.js';
|
|
76
77
|
import type { LyraTreeItemEventMap } from './components/data/tree/tree-item.class.js';
|
|
77
78
|
import type { LyraTreeEventMap } from './components/data/tree/tree.class.js';
|
|
78
79
|
import type { LyraWordCloudEventMap } from './components/data/word-cloud/word-cloud.class.js';
|
|
@@ -570,6 +571,12 @@ export type LyraClearEvent = LyraComboboxEventMap['lr-clear'] | LyraDateInputEve
|
|
|
570
571
|
* one component's exact detail, index its own map — e.g. `LyraCalloutEventMap['lr-close']`.
|
|
571
572
|
*/
|
|
572
573
|
export type LyraCloseEvent = LyraCalloutEventMap['lr-close'] | LyraCommandPaletteEventMap['lr-close'] | LyraDialogEventMap['lr-close'] | LyraDocumentViewerEventMap['lr-close'] | LyraResponsivePanelEventMap['lr-close'] | LyraTabEventMap['lr-close'] | LyraToolApprovalDialogEventMap['lr-close'] | LyraToolResultDialogEventMap['lr-close'] | LyraToolSelectDialogEventMap['lr-close'];
|
|
574
|
+
/**
|
|
575
|
+
* `lr-cluster-activate` — dispatched by `<lr-timeline>`.
|
|
576
|
+
*
|
|
577
|
+
* Detail type: `LyraTimelineEventMap['lr-cluster-activate']`.
|
|
578
|
+
*/
|
|
579
|
+
export type LyraClusterActivateEvent = LyraTimelineEventMap['lr-cluster-activate'];
|
|
573
580
|
/**
|
|
574
581
|
* `lr-collapse` — dispatched by 3 components: `<lr-accordion>`, `<lr-tree-item>`, `<lr-tree>`.
|
|
575
582
|
*
|
|
@@ -1303,6 +1310,12 @@ export type LyraMapClickEvent = LyraMapEventMap['lr-map-click'];
|
|
|
1303
1310
|
* Detail type: `LyraMapEventMap['lr-map-load']`.
|
|
1304
1311
|
*/
|
|
1305
1312
|
export type LyraMapLoadEvent = LyraMapEventMap['lr-map-load'];
|
|
1313
|
+
/**
|
|
1314
|
+
* `lr-map-marker-activate` — dispatched by `<lr-map>`.
|
|
1315
|
+
*
|
|
1316
|
+
* Detail type: `LyraMapEventMap['lr-map-marker-activate']`.
|
|
1317
|
+
*/
|
|
1318
|
+
export type LyraMapMarkerActivateEvent = LyraMapEventMap['lr-map-marker-activate'];
|
|
1306
1319
|
/**
|
|
1307
1320
|
* `lr-matrix-geometry-change` — dispatched by `<lr-heatmap>`.
|
|
1308
1321
|
*
|
|
@@ -2629,6 +2642,7 @@ export interface LyraGlobalEventMap {
|
|
|
2629
2642
|
'lr-claim-select': LyraClaimSelectEvent;
|
|
2630
2643
|
'lr-clear': LyraClearEvent;
|
|
2631
2644
|
'lr-close': LyraCloseEvent;
|
|
2645
|
+
'lr-cluster-activate': LyraClusterActivateEvent;
|
|
2632
2646
|
'lr-collapse': LyraCollapseEvent;
|
|
2633
2647
|
'lr-collapse-change': LyraCollapseChangeEvent;
|
|
2634
2648
|
'lr-collapse-request': LyraCollapseRequestEvent;
|
|
@@ -2733,6 +2747,7 @@ export interface LyraGlobalEventMap {
|
|
|
2733
2747
|
'lr-location-change': LyraLocationChangeEvent;
|
|
2734
2748
|
'lr-map-click': LyraMapClickEvent;
|
|
2735
2749
|
'lr-map-load': LyraMapLoadEvent;
|
|
2750
|
+
'lr-map-marker-activate': LyraMapMarkerActivateEvent;
|
|
2736
2751
|
'lr-matrix-geometry-change': LyraMatrixGeometryChangeEvent;
|
|
2737
2752
|
'lr-maximize-change': LyraMaximizeChangeEvent;
|
|
2738
2753
|
'lr-mcp-log': LyraMcpLogEvent;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { composedParentElement } from './active-element.js';
|
|
2
|
-
|
|
2
|
+
type AccessibilityTextTruncationReason = 'ancestors' | 'characters' | 'depth' | 'nodes';
|
|
3
3
|
export interface ComposedAccessibilityTextOptions {
|
|
4
4
|
/** Whether a top-level Text node starts visible. Element visibility is resolved from CSS. */
|
|
5
5
|
inheritedTextVisible?: boolean;
|
|
@@ -2,9 +2,7 @@ import { LyraElement } from './lyra-element.js';
|
|
|
2
2
|
import type { LyraAnchor, LyraAnchorKind, LyraHighlight, HighlightActivateDetail, TextSelectDetail, AnchorResultDetail } from '../components/viewers/document-viewer/anchors.js';
|
|
3
3
|
type PublicConstructor<T> = new (...args: never[]) => T;
|
|
4
4
|
type MixedConstructor<Base extends PublicConstructor<object>, Added> = Base & (new (...args: ConstructorParameters<Base>) => InstanceType<Base> & Added);
|
|
5
|
-
export
|
|
6
|
-
export declare const ANCHOR_TIMEOUT_MS = 5000;
|
|
7
|
-
export { HIGHLIGHT_SNAPSHOT_LIMIT, snapshotLyraHighlights, } from './highlight-collection.js';
|
|
5
|
+
export { HIGHLIGHT_SNAPSHOT_LIMIT, } from './highlight-collection.js';
|
|
8
6
|
/** Maximum records a capped highlight renderer receives from one retained snapshot. */
|
|
9
7
|
export declare const HIGHLIGHT_CANDIDATE_LIMIT = 1000;
|
|
10
8
|
export interface LyraAnchorTargetEventMap {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"./announcer.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";import"./lyra-element.js";import{snapshotLyraHighlights}from"./highlight-collection.js";import{boundedSelectionRects,boundedSelectionText,scopeFromElement,buildQuoteAnchor}from"./text-quote.js";const ANCHOR_RETRY_INTERVAL_MS=250,ANCHOR_TIMEOUT_MS=5e3;import{HIGHLIGHT_SNAPSHOT_LIMIT
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"./announcer.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";import"./lyra-element.js";import{snapshotLyraHighlights}from"./highlight-collection.js";import{boundedSelectionRects,boundedSelectionText,scopeFromElement,buildQuoteAnchor}from"./text-quote.js";const ANCHOR_RETRY_INTERVAL_MS=250,ANCHOR_TIMEOUT_MS=5e3;import{HIGHLIGHT_SNAPSHOT_LIMIT}from"./highlight-collection.js";const HIGHLIGHT_CANDIDATE_LIMIT=1e3;function prioritizedHighlightCandidates(highlights,activeHighlightId){const ordinary=[];let active;for(let index=0;index<highlights.length;index++){const highlight=highlights[index];activeHighlightId!==null&&highlight.id===activeHighlightId?active??=highlight:ordinary.length<HIGHLIGHT_CANDIDATE_LIMIT&&ordinary.push(highlight)}return active&&(ordinary.length>=HIGHLIGHT_CANDIDATE_LIMIT&&(ordinary.length=HIGHLIGHT_CANDIDATE_LIMIT-1),ordinary.unshift(active)),ordinary}function selectionRange(root){const document=root.ownerDocument,view=document.defaultView,renderRoot=root.renderRoot,shadowRoot=renderRoot?.nodeType===11&&renderRoot.host===root?renderRoot:void 0,globalSelection=view?.getSelection()??null;if(globalSelection?.getComposedRanges&&shadowRoot){const[composed]=globalSelection.getComposedRanges({shadowRoots:[shadowRoot]});if(!composed||composed.startContainer===composed.endContainer&&composed.startOffset===composed.endOffset)return null;const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}const selection=shadowRoot?.getSelection?.()??globalSelection;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}function DocumentAnchorTarget(Base){class DocumentAnchorTargetElement extends Base{constructor(){super(...arguments),this._highlights=snapshotLyraHighlights([]),this.activeHighlightId=null,this.anchor=null,this.anchorKinds=[],this.anchorRetryIntervalMs=ANCHOR_RETRY_INTERVAL_MS,this.anchorTimeoutMs=ANCHOR_TIMEOUT_MS,this.anchorAnnouncementText="",this.anchorGeneration=0}static{this.ownedCollectionProperties=Object.freeze(["anchor"])}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get highlights(){return this._highlights}set highlights(value){const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.anchorAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&this.anchor!==null&&this.scrollToAnchor(this.anchor).catch(()=>{})}disconnectedCallback(){this.anchorGeneration++,this.cancelAnchorRetry(),this.unbindTextSelection(),this.anchorAnnouncementSink?.release(),this.anchorAnnouncementSink=void 0,super.disconnectedCallback()}async applyAnchor(_anchor){return!1}computeSelectionAnchor(range,_text){const scope=scopeFromElement(this.renderRoot);return buildQuoteAnchor(range,scope)}cancelAnchorRetry(){this.anchorRetryHandle!==void 0&&(this.anchorRetryOwner?.clearTimeout(this.anchorRetryHandle),this.anchorRetryHandle=void 0),this.anchorRetryOwner=void 0;const resolveWait=this.anchorRetryResolve;resolveWait&&(this.anchorRetryResolve=void 0,resolveWait())}async scrollToAnchor(target){const generation=++this.anchorGeneration;try{return await this.performScrollToAnchor(target,generation)}catch{return generation!==this.anchorGeneration||(this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1})),!1}}async performScrollToAnchor(target,generation=++this.anchorGeneration){if(this.cancelAnchorRetry(),await this.updateComplete,generation!==this.anchorGeneration)return!1;const highlightId=typeof target=="string"?target:void 0,anchor=typeof target=="string"?this.highlights.find(h=>h.id===target)?.anchor:target;if(!anchor)return this.announceAnchorResult(void 0,!1),this.emit("lr-anchor-result",{found:!1}),!1;const ok=await this.resolveWithRetry(anchor,generation);return generation!==this.anchorGeneration?!1:(ok&&highlightId&&(this.activeHighlightId=highlightId),this.announceAnchorResult(anchor,ok),this.emit("lr-anchor-result",{found:ok}),ok)}async resolveWithRetry(anchor,generation){const deadline=Date.now()+this.anchorTimeoutMs;for(;;){if(generation!==this.anchorGeneration)return!1;const ok=await this.applyAnchor(anchor);if(generation!==this.anchorGeneration)return!1;if(ok)return!0;if(Date.now()>=deadline)return!1;const view=this.ownerDocument.defaultView;if(!view)return!1;await new Promise(resolve=>{this.anchorRetryResolve=resolve,this.anchorRetryOwner=view;let handle;handle=view.setTimeout(()=>{this.anchorRetryHandle===handle&&this.anchorRetryOwner===view&&(this.anchorRetryHandle=void 0,this.anchorRetryOwner=void 0),this.anchorRetryResolve===resolve&&(this.anchorRetryResolve=void 0),resolve()},this.anchorRetryIntervalMs),this.anchorRetryHandle=handle})}}announceAnchorResult(anchor,found){if(!found||!anchor){this.announce(this.localize("anchorNotFound"));return}const page="page"in anchor?anchor.page:void 0;this.announce(page!=null?this.localize("anchorJumpedToPage",void 0,{page}):this.localize("anchorJumped"))}announce(text){isAccessibilityVisible(this)&&this.anchorAnnouncementSink?.announce(text),this.anchorAnnouncementText=text}renderAnchorLiveRegion(){return html`<div
|
|
2
2
|
part="anchor-live-region"
|
|
3
3
|
class="sr-only"
|
|
4
4
|
aria-hidden="true"
|
|
5
|
-
>${this.anchorAnnouncementText}</div>`}bindTextSelection(contentRoot){this.unbindTextSelection();const document=contentRoot.ownerDocument,view=document.defaultView,onSelectionEnd=()=>{const range=selectionRange(this);if(!range||!contentRoot.contains(range.commonAncestorContainer)&&range.commonAncestorContainer!==contentRoot)return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range,text),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};let debounceHandle;const onSelectionChange=()=>{if(!view){onSelectionEnd();return}debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle),debounceHandle=view.requestAnimationFrame(()=>{debounceHandle=void 0,onSelectionEnd()})};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd),document.addEventListener("selectionchange",onSelectionChange),this.selectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),document.removeEventListener("selectionchange",onSelectionChange),debounceHandle!==void 0&&view?.cancelAnimationFrame(debounceHandle)}}unbindTextSelection(){this.selectionCleanup?.(),this.selectionCleanup=void 0}}return __decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],DocumentAnchorTargetElement.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1,hasChanged:()=>!0})],DocumentAnchorTargetElement.prototype,"anchor",void 0),__decorate([state()],DocumentAnchorTargetElement.prototype,"anchorAnnouncementText",void 0),DocumentAnchorTargetElement}export{
|
|
5
|
+
>${this.anchorAnnouncementText}</div>`}bindTextSelection(contentRoot){this.unbindTextSelection();const document=contentRoot.ownerDocument,view=document.defaultView,onSelectionEnd=()=>{const range=selectionRange(this);if(!range||!contentRoot.contains(range.commonAncestorContainer)&&range.commonAncestorContainer!==contentRoot)return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range,text),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};let debounceHandle;const onSelectionChange=()=>{if(!view){onSelectionEnd();return}debounceHandle!==void 0&&view.cancelAnimationFrame(debounceHandle),debounceHandle=view.requestAnimationFrame(()=>{debounceHandle=void 0,onSelectionEnd()})};contentRoot.addEventListener("pointerup",onSelectionEnd),contentRoot.addEventListener("keyup",onSelectionEnd),document.addEventListener("selectionchange",onSelectionChange),this.selectionCleanup=()=>{contentRoot.removeEventListener("pointerup",onSelectionEnd),contentRoot.removeEventListener("keyup",onSelectionEnd),document.removeEventListener("selectionchange",onSelectionChange),debounceHandle!==void 0&&view?.cancelAnimationFrame(debounceHandle)}}unbindTextSelection(){this.selectionCleanup?.(),this.selectionCleanup=void 0}}return __decorate([property({attribute:!1})],DocumentAnchorTargetElement.prototype,"highlights",null),__decorate([property({attribute:"active-highlight-id"})],DocumentAnchorTargetElement.prototype,"activeHighlightId",void 0),__decorate([property({attribute:!1,hasChanged:()=>!0})],DocumentAnchorTargetElement.prototype,"anchor",void 0),__decorate([state()],DocumentAnchorTargetElement.prototype,"anchorAnnouncementText",void 0),DocumentAnchorTargetElement}export{DocumentAnchorTarget,HIGHLIGHT_CANDIDATE_LIMIT,HIGHLIGHT_SNAPSHOT_LIMIT,prioritizedHighlightCandidates};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { place } from './positioner.js';
|
|
2
|
+
/** The positioning capability loaded on the first anchored surface open. */
|
|
3
|
+
export interface AnchoredOverlayRuntime {
|
|
4
|
+
place: typeof place;
|
|
5
|
+
}
|
|
6
|
+
/** Loads and caches the positioning runtime shared by every deferred anchored surface. */
|
|
7
|
+
export declare function loadAnchoredOverlayRuntime(): Promise<AnchoredOverlayRuntime>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const defaultRuntimeLoader=()=>import("./positioner.js");let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader();let cached;return cached=pending.catch(error=>{throw runtimePromise===cached&&(runtimePromise=void 0),error}),runtimePromise=cached,runtimePromise}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}export{__setAnchoredOverlayRuntimeLoaderForTesting,loadAnchoredOverlayRuntime};
|
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* The implementation lives with the visibility predicates it consumes so label, announcement,
|
|
5
5
|
* typeahead and semantic-owner paths cannot drift into separate recursive walkers.
|
|
6
6
|
*/
|
|
7
|
-
export { composedAccessibilityText, composedAccessibilityTextResult,
|
|
7
|
+
export { composedAccessibilityText, composedAccessibilityTextResult, } from './accessibility-visibility.js';
|
package/dist/internal/ansi.d.ts
CHANGED
|
@@ -32,8 +32,4 @@ export interface AnsiParser {
|
|
|
32
32
|
/** Clears style state and any buffered partial sequence — call alongside a full scrollback reset. */
|
|
33
33
|
reset(): void;
|
|
34
34
|
}
|
|
35
|
-
/** ANSI control sequences are small; this generous ceiling prevents a truncated OSC/CSI from
|
|
36
|
-
* retaining and repeatedly rescanning an unbounded streamed suffix, and prevents a terminated
|
|
37
|
-
* sequence from allocating or interpreting an unbounded payload. */
|
|
38
|
-
export declare const MAX_ANSI_SEQUENCE_LENGTH = 4096;
|
|
39
35
|
export declare function createAnsiParser(): AnsiParser;
|
package/dist/internal/ansi.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const RESET_STYLES={bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},ANSI_16_VAR_NAMES=["black","red","green","yellow","blue","magenta","cyan","white","bright-black","bright-red","bright-green","bright-yellow","bright-blue","bright-magenta","bright-cyan","bright-white"];function ansiVar(index){return`var(--lr-terminal-color-${ANSI_16_VAR_NAMES[index]})`}function ansiBgVar(index){return`var(--lr-terminal-bg-${ANSI_16_VAR_NAMES[index]})`}const FG_VARS={},BG_VARS={};for(let i=0;i<8;i++)FG_VARS[30+i]=ansiVar(i),FG_VARS[90+i]=ansiVar(8+i),BG_VARS[40+i]=ansiBgVar(i),BG_VARS[100+i]=ansiBgVar(8+i);const CUBE_LEVELS=[0,95,135,175,215,255];function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):0}function ansi256ToColor(n,role="fg"){const named=role==="bg"?ansiBgVar:ansiVar;if(!Number.isInteger(n)||n<0)return named(0);if(n<16)return named(n);if(n<=231){const i=n-16,r=CUBE_LEVELS[Math.floor(i/36)%6],g=CUBE_LEVELS[Math.floor(i/6)%6],b=CUBE_LEVELS[i%6];return`rgb(${r}, ${g}, ${b})`}if(n<=255){const v=8+(n-232)*10;return`rgb(${v}, ${v}, ${v})`}return named(0)}const CSI_FINAL_BYTE=/[\x40-\x7e]/,MAX_ANSI_SEQUENCE_LENGTH=4096,MAX_SGR_PARAMETERS=64;function parseSgrParameters(input,start,end){if(start===end)return[0];const params=[];let value=0,hasTokenContent=!1,valid=!0;for(let index=start;index<=end;index++){const code=index===end?59:input.charCodeAt(index);if(code>=48&&code<=57){hasTokenContent=!0;const digit=code-48;valid&&value<=Math.floor((Number.MAX_SAFE_INTEGER-digit)/10)?value=value*10+digit:valid=!1;continue}if(code!==59){hasTokenContent=!0,valid=!1;continue}if(params.length>=MAX_SGR_PARAMETERS)return null;params.push(hasTokenContent?valid?value:Number.NaN:0),value=0,hasTokenContent=!1,valid=!0}return params}function createAnsiParser(){let styles={...RESET_STYLES},carry="",discarding=null;function applySgr(params){const list=params.length===0?[0]:params;let i=0;for(;i<list.length;){const p=list[i];if(p===0)styles={...RESET_STYLES};else if(p===1)styles={...styles,bold:!0};else if(p===2)styles={...styles,dim:!0};else if(p===3)styles={...styles,italic:!0};else if(p===4)styles={...styles,underline:!0};else if(p===7)styles={...styles,inverse:!0};else if(p===22)styles={...styles,bold:!1,dim:!1};else if(p===23)styles={...styles,italic:!1};else if(p===24)styles={...styles,underline:!1};else if(p===27)styles={...styles,inverse:!1};else if(p===39)styles={...styles,fg:void 0};else if(p===49)styles={...styles,bg:void 0};else if(FG_VARS[p]!==void 0)styles={...styles,fg:FG_VARS[p]};else if(BG_VARS[p]!==void 0)styles={...styles,bg:BG_VARS[p]};else if(p===38||p===48){const isFg=p===38,mode=list[i+1],idx=list[i+2];if(mode===5&&idx!==void 0){const color=ansi256ToColor(idx,isFg?"fg":"bg");styles=isFg?{...styles,fg:color}:{...styles,bg:color},i+=2}else if(mode===2){const r=list[i+2],g=list[i+3],b=list[i+4];if(r!==void 0&&g!==void 0&&b!==void 0){const color=`rgb(${clampByte(r)}, ${clampByte(g)}, ${clampByte(b)})`;styles=isFg?{...styles,fg:color}:{...styles,bg:color},i+=4}}}i++}}function push(chunk){const input=carry+chunk;carry="";const segments=[];let textStart=0,i=0;if(discarding!==null){for(;i<input.length;){const code=input.charCodeAt(i);if(discarding==="csi"&&code>=64&&code<=126){discarding=null,i++;break}if(discarding==="osc"&&code===7){discarding=null,i++;break}if(code===27){if(discarding==="osc"&&input[i+1]==="\\"){discarding=null,i+=2;break}discarding=null;break}i++}if(discarding!==null)return segments;textStart=i}for(;i<input.length;){if(input.charCodeAt(i)!==27){i++;continue}i>textStart&&segments.push({text:input.slice(textStart,i),styles});const next=input[i+1];if(next===void 0)return carry=input.slice(i),segments;if(next==="["){let j=i+2,overlong=!1;for(;j<input.length&&!CSI_FINAL_BYTE.test(input[j]);)j++,j-i+1>MAX_ANSI_SEQUENCE_LENGTH&&(overlong=!0);if(j>=input.length)return overlong||input.length-i>MAX_ANSI_SEQUENCE_LENGTH?discarding="csi":carry=input.slice(i),segments;if(overlong||=j-i+1>MAX_ANSI_SEQUENCE_LENGTH,!overlong&&input[j]==="m"){const params=parseSgrParameters(input,i+2,j);params!==null&&applySgr(params)}i=j+1,textStart=i;continue}if(next==="]"){let j=i+2,terminated=!1,overlong=!1;for(;j<input.length;){if(input.charCodeAt(j)===7){j++,terminated=!0;break}if(input.charCodeAt(j)===27&&input[j+1]==="\\"){j+=2,terminated=!0;break}j++,j-i>MAX_ANSI_SEQUENCE_LENGTH&&(overlong=!0)}if(!terminated)return overlong||input.length-i>MAX_ANSI_SEQUENCE_LENGTH?discarding="osc":carry=input.slice(i),segments;i=j,textStart=i;continue}i+=1,textStart=i}return textStart<input.length&&segments.push({text:input.slice(textStart),styles}),segments}function reset(){styles={...RESET_STYLES},carry="",discarding=null}return{push,reset}}export{
|
|
1
|
+
const RESET_STYLES={bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},ANSI_16_VAR_NAMES=["black","red","green","yellow","blue","magenta","cyan","white","bright-black","bright-red","bright-green","bright-yellow","bright-blue","bright-magenta","bright-cyan","bright-white"];function ansiVar(index){return`var(--lr-terminal-color-${ANSI_16_VAR_NAMES[index]})`}function ansiBgVar(index){return`var(--lr-terminal-bg-${ANSI_16_VAR_NAMES[index]})`}const FG_VARS={},BG_VARS={};for(let i=0;i<8;i++)FG_VARS[30+i]=ansiVar(i),FG_VARS[90+i]=ansiVar(8+i),BG_VARS[40+i]=ansiBgVar(i),BG_VARS[100+i]=ansiBgVar(8+i);const CUBE_LEVELS=[0,95,135,175,215,255];function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):0}function ansi256ToColor(n,role="fg"){const named=role==="bg"?ansiBgVar:ansiVar;if(!Number.isInteger(n)||n<0)return named(0);if(n<16)return named(n);if(n<=231){const i=n-16,r=CUBE_LEVELS[Math.floor(i/36)%6],g=CUBE_LEVELS[Math.floor(i/6)%6],b=CUBE_LEVELS[i%6];return`rgb(${r}, ${g}, ${b})`}if(n<=255){const v=8+(n-232)*10;return`rgb(${v}, ${v}, ${v})`}return named(0)}const CSI_FINAL_BYTE=/[\x40-\x7e]/,MAX_ANSI_SEQUENCE_LENGTH=4096,MAX_SGR_PARAMETERS=64;function parseSgrParameters(input,start,end){if(start===end)return[0];const params=[];let value=0,hasTokenContent=!1,valid=!0;for(let index=start;index<=end;index++){const code=index===end?59:input.charCodeAt(index);if(code>=48&&code<=57){hasTokenContent=!0;const digit=code-48;valid&&value<=Math.floor((Number.MAX_SAFE_INTEGER-digit)/10)?value=value*10+digit:valid=!1;continue}if(code!==59){hasTokenContent=!0,valid=!1;continue}if(params.length>=MAX_SGR_PARAMETERS)return null;params.push(hasTokenContent?valid?value:Number.NaN:0),value=0,hasTokenContent=!1,valid=!0}return params}function createAnsiParser(){let styles={...RESET_STYLES},carry="",discarding=null;function applySgr(params){const list=params.length===0?[0]:params;let i=0;for(;i<list.length;){const p=list[i];if(p===0)styles={...RESET_STYLES};else if(p===1)styles={...styles,bold:!0};else if(p===2)styles={...styles,dim:!0};else if(p===3)styles={...styles,italic:!0};else if(p===4)styles={...styles,underline:!0};else if(p===7)styles={...styles,inverse:!0};else if(p===22)styles={...styles,bold:!1,dim:!1};else if(p===23)styles={...styles,italic:!1};else if(p===24)styles={...styles,underline:!1};else if(p===27)styles={...styles,inverse:!1};else if(p===39)styles={...styles,fg:void 0};else if(p===49)styles={...styles,bg:void 0};else if(FG_VARS[p]!==void 0)styles={...styles,fg:FG_VARS[p]};else if(BG_VARS[p]!==void 0)styles={...styles,bg:BG_VARS[p]};else if(p===38||p===48){const isFg=p===38,mode=list[i+1],idx=list[i+2];if(mode===5&&idx!==void 0){const color=ansi256ToColor(idx,isFg?"fg":"bg");styles=isFg?{...styles,fg:color}:{...styles,bg:color},i+=2}else if(mode===2){const r=list[i+2],g=list[i+3],b=list[i+4];if(r!==void 0&&g!==void 0&&b!==void 0){const color=`rgb(${clampByte(r)}, ${clampByte(g)}, ${clampByte(b)})`;styles=isFg?{...styles,fg:color}:{...styles,bg:color},i+=4}}}i++}}function push(chunk){const input=carry+chunk;carry="";const segments=[];let textStart=0,i=0;if(discarding!==null){for(;i<input.length;){const code=input.charCodeAt(i);if(discarding==="csi"&&code>=64&&code<=126){discarding=null,i++;break}if(discarding==="osc"&&code===7){discarding=null,i++;break}if(code===27){if(discarding==="osc"&&input[i+1]==="\\"){discarding=null,i+=2;break}discarding=null;break}i++}if(discarding!==null)return segments;textStart=i}for(;i<input.length;){if(input.charCodeAt(i)!==27){i++;continue}i>textStart&&segments.push({text:input.slice(textStart,i),styles});const next=input[i+1];if(next===void 0)return carry=input.slice(i),segments;if(next==="["){let j=i+2,overlong=!1;for(;j<input.length&&!CSI_FINAL_BYTE.test(input[j]);)j++,j-i+1>MAX_ANSI_SEQUENCE_LENGTH&&(overlong=!0);if(j>=input.length)return overlong||input.length-i>MAX_ANSI_SEQUENCE_LENGTH?discarding="csi":carry=input.slice(i),segments;if(overlong||=j-i+1>MAX_ANSI_SEQUENCE_LENGTH,!overlong&&input[j]==="m"){const params=parseSgrParameters(input,i+2,j);params!==null&&applySgr(params)}i=j+1,textStart=i;continue}if(next==="]"){let j=i+2,terminated=!1,overlong=!1;for(;j<input.length;){if(input.charCodeAt(j)===7){j++,terminated=!0;break}if(input.charCodeAt(j)===27&&input[j+1]==="\\"){j+=2,terminated=!0;break}j++,j-i>MAX_ANSI_SEQUENCE_LENGTH&&(overlong=!0)}if(!terminated)return overlong||input.length-i>MAX_ANSI_SEQUENCE_LENGTH?discarding="osc":carry=input.slice(i),segments;i=j,textStart=i;continue}i+=1,textStart=i}return textStart<input.length&&segments.push({text:input.slice(textStart),styles}),segments}function reset(){styles={...RESET_STYLES},carry="",discarding=null}return{push,reset}}export{createAnsiParser};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
type OwnedAriaAttributes = Readonly<Record<string, string | null | undefined>>;
|
|
2
2
|
export interface AriaOwnershipContribution {
|
|
3
3
|
/** Whole-value ARIA attributes. A later owner wins; release reveals the previous owner/baseline. */
|
|
4
4
|
attributes?: OwnedAriaAttributes;
|
|
@@ -20,3 +20,4 @@ export interface AriaOwnershipLease {
|
|
|
20
20
|
* last-owner-wins stack, while treating any late external write as the baseline to restore.
|
|
21
21
|
*/
|
|
22
22
|
export declare function acquireAriaOwnership(initialTarget: HTMLElement | null, initialContribution: AriaOwnershipContribution): AriaOwnershipLease;
|
|
23
|
+
export {};
|
|
@@ -1168,6 +1168,7 @@ export declare const LYRA_DEFAULT_timeInputRangeMessage: LyraMessage;
|
|
|
1168
1168
|
export declare const LYRA_DEFAULT_timeInputSecond: LyraMessage;
|
|
1169
1169
|
export declare const LYRA_DEFAULT_timeInputStepMessage: LyraMessage;
|
|
1170
1170
|
export declare const LYRA_DEFAULT_timeline: LyraMessage;
|
|
1171
|
+
export declare const LYRA_DEFAULT_timelineClusterCount: LyraMessage;
|
|
1171
1172
|
export declare const LYRA_DEFAULT_toastContentIncomplete: LyraMessage;
|
|
1172
1173
|
export declare const LYRA_DEFAULT_toastOverflow: LyraMessage;
|
|
1173
1174
|
export declare const LYRA_DEFAULT_tokenInputEditWithContext: LyraMessage;
|