@aceshooting/lyra-ui 30.9.0 → 31.0.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.
Files changed (201) hide show
  1. package/CHANGELOG.md +236 -339
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  4. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  5. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  6. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  7. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  8. package/dist/components/charts/chart/box-plot.class.js +2 -2
  9. package/dist/components/charts/chart/chart-sync.js +1 -1
  10. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  11. package/dist/components/charts/chart/chart.class.js +4 -4
  12. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  13. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  14. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  15. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  16. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  17. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  18. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  19. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  20. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  21. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  22. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  23. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  24. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  25. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  26. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  27. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  28. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  29. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  30. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  31. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  32. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  33. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  34. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  35. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  36. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  37. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  38. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  39. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  40. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  41. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  42. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  43. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  44. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  45. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  46. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  47. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  48. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  49. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  50. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  51. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  52. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  53. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  54. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  55. package/dist/components/data/pagination/pagination.class.js +1 -1
  56. package/dist/components/data/table/table.class.d.ts +31 -2
  57. package/dist/components/data/table/table.class.js +3 -3
  58. package/dist/components/data/table/table.styles.js +1 -1
  59. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  60. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  61. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  62. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  63. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  64. package/dist/components/data/timeline/timeline.class.js +9 -5
  65. package/dist/components/data/tree/tree-item.class.js +1 -1
  66. package/dist/components/data/tree/tree.class.d.ts +2 -0
  67. package/dist/components/data/tree/tree.class.js +1 -1
  68. package/dist/components/forms/button/button.class.d.ts +8 -6
  69. package/dist/components/forms/button/button.class.js +2 -2
  70. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  71. package/dist/components/forms/color-picker/color-core.js +1 -1
  72. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  73. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  74. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  75. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  76. package/dist/components/forms/input/input-shared.js +2 -2
  77. package/dist/components/forms/input/number-input-locale.js +1 -0
  78. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  79. package/dist/components/forms/input/number-input.class.js +2 -2
  80. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  81. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  82. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  83. package/dist/components/layout/details/accordion-item.class.js +1 -1
  84. package/dist/components/layout/menu/menu.class.js +1 -1
  85. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  86. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  87. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  88. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  89. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  90. package/dist/components/layout/tab-group/tab.class.js +1 -1
  91. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  92. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  93. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  94. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  95. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  96. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  97. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  98. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  99. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  100. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  101. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  102. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  103. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  104. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  105. package/dist/components/media/map/map-owned-features.js +1 -1
  106. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  107. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  108. package/dist/components/media/map/map.class.d.ts +5 -5
  109. package/dist/components/media/map/map.class.js +3 -3
  110. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  111. package/dist/components/media/video/video.class.d.ts +3 -3
  112. package/dist/components/media/video/video.class.js +3 -1
  113. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  114. package/dist/components/overlays/chip/chip.class.js +1 -1
  115. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  116. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  117. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  118. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  119. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  120. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  121. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  122. package/dist/components/retrieval/graph/graph.class.js +1 -1
  123. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  124. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  125. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  126. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  127. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  128. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  129. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  130. package/dist/components/utility/known-date/known-date.class.js +1 -1
  131. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  132. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  133. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  134. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  135. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  136. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  137. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  138. package/dist/components/viewers/include/include.class.js +1 -1
  139. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  140. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  141. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  142. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  143. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  144. package/dist/components/viewers/table-viewer-shared.js +4 -4
  145. package/dist/framework-types.d.ts +1 -1
  146. package/dist/internal/anchored-overlay-runtime.js +1 -1
  147. package/dist/internal/catalog-picker.js +1 -1
  148. package/dist/internal/document-tokens.js +2 -2
  149. package/dist/internal/drop-session-controller.js +1 -1
  150. package/dist/internal/engine-3d.js +1 -1
  151. package/dist/internal/icon-only-content.js +1 -1
  152. package/dist/internal/layered-layout.js +1 -1
  153. package/dist/internal/map-custom-layer-controller.js +1 -1
  154. package/dist/internal/media-panorama.js +1 -1
  155. package/dist/internal/package-metadata.js +1 -1
  156. package/dist/internal/safe-url.js +1 -1
  157. package/dist/internal/scoped-definitions.generated.js +1 -1
  158. package/dist/internal/scroll-overflow.js +1 -1
  159. package/dist/internal/source-window-controller.js +1 -1
  160. package/dist/internal/text-quote.js +1 -1
  161. package/dist/internal/viewer-search.js +1 -1
  162. package/dist/lyra.d.ts +1 -1
  163. package/dist/sequence-time-binding.js +1 -1
  164. package/dist/simulation-clock.js +1 -1
  165. package/dist/styles/reservations.css +1 -1
  166. package/dist/styles/reservations.styles.js +1 -1
  167. package/dist/testing/happy-dom-shims.js +1 -1
  168. package/dist/theme/theme.js +1 -1
  169. package/llms/components/lr-attachment-chip.md +27 -12
  170. package/llms/components/lr-attachment-trigger.md +27 -7
  171. package/llms/components/lr-button.md +6 -4
  172. package/llms/components/lr-chat-composer.md +13 -7
  173. package/llms/components/lr-chat-message.md +44 -3
  174. package/llms/components/lr-chat-viewport.md +39 -2
  175. package/llms/components/lr-data-grid.md +2 -0
  176. package/llms/components/lr-dialog.md +10 -0
  177. package/llms/components/lr-drop-zone.md +26 -2
  178. package/llms/components/lr-icon-button.md +2 -1
  179. package/llms/components/lr-json-viewer.md +17 -0
  180. package/llms/components/lr-locale-picker.md +5 -0
  181. package/llms/components/lr-markdown-core.md +2 -1
  182. package/llms/components/lr-markdown.md +20 -4
  183. package/llms/components/lr-menu.md +3 -1
  184. package/llms/components/lr-number-input.md +28 -1
  185. package/llms/components/lr-prompt-input.md +1 -1
  186. package/llms/components/lr-streaming-text-core.md +3 -2
  187. package/llms/components/lr-streaming-text.md +4 -1
  188. package/llms/components/lr-suggestion-chips.md +28 -5
  189. package/llms/components/lr-tab-group.md +13 -1
  190. package/llms/components/lr-tab.md +5 -0
  191. package/llms/components/lr-table.md +25 -4
  192. package/llms/components/lr-timeline-item.md +1 -1
  193. package/llms/components/lr-timeline.md +38 -4
  194. package/llms/components/lr-tooltip.md +3 -1
  195. package/llms/components/lr-tree.md +4 -0
  196. package/llms/components/lr-virtual-list.md +1 -0
  197. package/llms/peers.md +2 -2
  198. package/llms/shared/forms-and-accessibility.md +21 -4
  199. package/llms/shared.md +21 -4
  200. package/package.json +21 -20
  201. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{createAnsiParser}from"../../../internal/ansi.js";import{loadNotebookSanitizer}from"./dompurify-loader.js";import{styles}from"./notebook-viewer.styles.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_notebookViewerCodeCell,LYRA_DEFAULT_notebookViewerCollapseOutput,LYRA_DEFAULT_notebookViewerErrorOutput,LYRA_DEFAULT_notebookViewerInPrompt,LYRA_DEFAULT_notebookViewerInPromptEmpty,LYRA_DEFAULT_notebookViewerInvalid,LYRA_DEFAULT_notebookViewerLabel,LYRA_DEFAULT_notebookViewerMarkdownCell,LYRA_DEFAULT_notebookViewerRawCell,LYRA_DEFAULT_notebookViewerShowAllOutput,LYRA_DEFAULT_notebookViewerTooManyCells,LYRA_DEFAULT_notebookViewerUnrenderedOutput,LYRA_DEFAULT_notebookViewerUnsupportedVersion}from"../../../internal/default-strings/viewers.generated.js";const MAX_CELLS=2e3,MAX_OUTPUTS=2e4,MAX_JSON_NODES=1e5,SUPPORTED_MAJOR=4,SUPPORTED_MINORS=[0,1,2,3,4,5],MAX_NOTEBOOK_PAINTED_HIGHLIGHTS=100,OMIT_NOTEBOOK_SNAPSHOT=Symbol("omit-notebook-snapshot");function invalidNotebookSnapshot(){return Object.freeze({})}function isNotebookRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isNotebookDataRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const parent=Object.getPrototypeOf(prototype),constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(parent===null)return!constructor||"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object";if(constructor)return!1;const parentConstructor=Object.getOwnPropertyDescriptor(parent,"constructor");return!!(Object.getPrototypeOf(parent)===null&&parentConstructor&&"value"in parentConstructor&&typeof parentConstructor.value=="function"&&parentConstructor.value.name==="Object")}catch{return!1}}function snapshotNotebookDocument(value){if(!isNotebookRecord(value))return OMIT_NOTEBOOK_SNAPSHOT;let remaining=MAX_JSON_NODES;const seen=new WeakSet,created=[],pending=[],createContainer=source=>{let array=!1;try{array=Array.isArray(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}let keys,target;if(array){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(source,"length")}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0||lengthDescriptor.value>remaining)return OMIT_NOTEBOOK_SNAPSHOT;keys=Array.from({length:lengthDescriptor.value},(_,index)=>String(index)),target=new Array(lengthDescriptor.value)}else{if(!isNotebookDataRecord(source))return OMIT_NOTEBOOK_SNAPSHOT;try{keys=Object.keys(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(keys.length>remaining)return OMIT_NOTEBOOK_SNAPSHOT;target={}}return seen.add(source),created.push(target),pending.push({source,target,keys,array}),target};remaining-=1;const root=createContainer(value);if(root===OMIT_NOTEBOOK_SNAPSHOT)return root;for(;pending.length;){const task=pending.pop();for(const key of task.keys){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(task.source,key)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor){if(task.array)continue;return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor.enumerable||!("value"in descriptor)||remaining<=0)return OMIT_NOTEBOOK_SNAPSHOT;remaining-=1;const entry=descriptor.value;let snapshot=entry;if(entry!==null&&(typeof entry=="object"||typeof entry=="function")){if(typeof entry=="function"||seen.has(entry))return OMIT_NOTEBOOK_SNAPSHOT;if(snapshot=createContainer(entry),snapshot===OMIT_NOTEBOOK_SNAPSHOT)return snapshot}Object.defineProperty(task.target,key,{value:snapshot,enumerable:!0,configurable:!1,writable:!1})}}for(let index=created.length-1;index>=0;index-=1)Object.freeze(created[index]);return root}function joinSource(source){return typeof source=="string"?source:source?.join("")??""}function isDenseArray(value){for(let index=0;index<value.length;index++)if(!Object.prototype.hasOwnProperty.call(value,index))return!1;return!0}function joinText(text){return typeof text=="string"?text:Array.isArray(text)&&isDenseArray(text)&&text.every(item=>typeof item=="string")?text.join(""):""}function*notebookSearchTextParts(text){if(typeof text=="string"){yield text;return}if(!(!Array.isArray(text)||!isDenseArray(text)))for(const part of text)typeof part=="string"&&(yield part)}const MARKUP_ENTITIES={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"};function visibleMarkupText(markup){const lower=markup.toLowerCase();let text="",index=0;for(;index<markup.length;){const open=markup.indexOf("<",index);if(open<0){text+=markup.slice(index);break}if(text+=markup.slice(index,open)+" ",lower.startsWith("<!--",open)){const end=markup.indexOf("-->",open+4);index=end<0?markup.length:end+3;continue}const close=markup.indexOf(">",open+1);if(close<0)break;const rawText=lower.startsWith("<script",open)?"<\/script":lower.startsWith("<style",open)?"</style":"";if(rawText){const end=lower.indexOf(rawText,close+1),endClose=end<0?-1:markup.indexOf(">",end);index=endClose<0?markup.length:endClose+1;continue}index=close+1}return text.replace(/&(lt|gt|quot|apos|amp);/g,(_entity,name)=>MARKUP_ENTITIES[name])}function*notebookOutputSearchParts(outputs){for(const output of outputs){yield*notebookSearchTextParts(output.text);const data=output.data;data&&Object.prototype.hasOwnProperty.call(data,"text/plain")&&(yield*notebookSearchTextParts(data["text/plain"]),yield" "),data&&!data["image/png"]&&!data["image/jpeg"]&&(data["image/svg+xml"]?yield visibleMarkupText(joinText(data["image/svg+xml"])):data["text/html"]?yield visibleMarkupText(joinText(data["text/html"])):data["application/json"]&&(yield*notebookSearchTextParts(data["application/json"]))),yield" "}}function isTextValue(value){return typeof value=="string"||Array.isArray(value)&&isDenseArray(value)&&value.every(item=>typeof item=="string")}function isJsonValue(value){const pending=[value];let nodes=0;for(;pending.length;){const current=pending.pop();if(++nodes>MAX_JSON_NODES)return!1;if(!(current===null||typeof current=="string"||typeof current=="boolean")){if(typeof current=="number"){if(!Number.isFinite(current))return!1;continue}if(Array.isArray(current)){if(current.length>MAX_JSON_NODES-nodes-pending.length)return!1;for(let index=current.length-1;index>=0;index--)pending.push(current[index]);continue}if(typeof current!="object")return!1;for(const key in current)if(Object.prototype.hasOwnProperty.call(current,key)){if(pending.length>=MAX_JSON_NODES-nodes)return!1;pending.push(current[key])}}}return!0}function isNotebookOutput(value){if(typeof value!="object"||value===null)return!1;const output=value;if(!["stream","error","display_data","execute_result"].includes(output.output_type)||output.text!==void 0&&!isTextValue(output.text)||output.traceback!==void 0&&!isTextValue(output.traceback)||output.ename!==void 0&&typeof output.ename!="string"||output.evalue!==void 0&&typeof output.evalue!="string"||output.name!==void 0&&output.name!=="stdout"&&output.name!=="stderr")return!1;const data=output.data;if(data===void 0)return!0;if(!isNotebookRecord(data))return!1;const mimeData=data;for(const[mime,payload]of Object.entries(mimeData))if(mime==="application/json"){if(typeof payload=="string")try{if(!isJsonValue(JSON.parse(payload)))return!1}catch{return!1}else if(!isJsonValue(payload))return!1}else if(!isTextValue(payload)&&!isJsonValue(payload))return!1;return!0}function isNotebookShape(value){if(typeof value!="object"||value===null)return!1;const v=value;if(!Number.isInteger(v.nbformat)||!Number.isInteger(v.nbformat_minor)||!Array.isArray(v.cells))return!1;const metadata=v.metadata;if(metadata!==void 0){if(!isNotebookRecord(metadata))return!1;for(const[section,field]of[["language_info","name"],["kernelspec","language"]]){const entry=metadata[section];if(entry===void 0)continue;if(!isNotebookRecord(entry))return!1;const language=entry[field];if(language!==void 0&&typeof language!="string")return!1}}const cells=v.cells;let outputCount=0;for(let index=0;index<cells.length;index++){if(!Object.prototype.hasOwnProperty.call(cells,index))return!1;const value2=cells[index];if(typeof value2!="object"||value2===null)return!1;const cell=value2;if(!["markdown","code","raw"].includes(cell.cell_type)||!isTextValue(cell.source)||cell.id!==void 0&&typeof cell.id!="string"||cell.execution_count!==void 0&&cell.execution_count!==null&&(!Number.isInteger(cell.execution_count)||cell.execution_count<0))return!1;if(cell.outputs!==void 0&&(!Array.isArray(cell.outputs)||!isDenseArray(cell.outputs)||(outputCount+=cell.outputs.length,outputCount>MAX_OUTPUTS||!cell.outputs.every(isNotebookOutput))))return!1}return!0}class LyraNotebookViewerBase extends LyraElement{}class LyraNotebookViewer extends DocumentAnchorTarget(LyraNotebookViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.outputCollapseLines=40,this.maxHeight="",this.anchorKinds=["node-path","fragment"],this.loadState={kind:"idle"},this.expandedOutputs=new Set,this.activeCellIndex=null,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1,this.cellKey=(item,index)=>item.id??index,this.highlightedCells=new Map,this.generation=0,this.lastSearchLocale="",this.sanitizerGeneration=0,this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedNotebook()),this.sanitizedOutputCache=new Map,this.sanitizationTasks=new Map,this.renderCell=(cell,index)=>{const c=cell,numberFormat=getNumberFormat(this.effectiveLocale),inCount=c.execution_count==null?this.localize("notebookViewerInPromptEmpty"):this.localize("notebookViewerInPrompt",void 0,{count:numberFormat.format(c.execution_count)}),rowLabel=c.cell_type==="code"?this.localize("notebookViewerCodeCell",void 0,{index:numberFormat.format(index+1)}):c.cell_type==="markdown"?this.localize("notebookViewerMarkdownCell",void 0,{index:numberFormat.format(index+1)}):this.localize("notebookViewerRawCell",void 0,{index:numberFormat.format(index+1)}),active=this.activeCellIndex===index,highlight=this.highlightedCells.get(index),highlighted=highlight!==void 0,parts=["cell"];return active&&parts.push("cell-active"),highlighted&&(parts.push("cell-highlighted",`cell-highlighted-${highlight.tone??"accent"}`),highlight.id===this.activeHighlightId&&parts.push("cell-highlight-active")),html`<div part=${parts.join(" ")} role="group" aria-label=${rowLabel} data-cell-type=${c.cell_type} ?data-active=${active} ?data-highlighted=${highlighted}>
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{unsafeSVG}from"lit/directives/unsafe-svg.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{createAnsiParser}from"../../../internal/ansi.js";import{loadNotebookSanitizer}from"./dompurify-loader.js";import{styles}from"./notebook-viewer.styles.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{resolveViewerSource}from"../viewer-source.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_notebookViewerCodeCell,LYRA_DEFAULT_notebookViewerCollapseOutput,LYRA_DEFAULT_notebookViewerErrorOutput,LYRA_DEFAULT_notebookViewerInPrompt,LYRA_DEFAULT_notebookViewerInPromptEmpty,LYRA_DEFAULT_notebookViewerInvalid,LYRA_DEFAULT_notebookViewerLabel,LYRA_DEFAULT_notebookViewerMarkdownCell,LYRA_DEFAULT_notebookViewerRawCell,LYRA_DEFAULT_notebookViewerShowAllOutput,LYRA_DEFAULT_notebookViewerTooManyCells,LYRA_DEFAULT_notebookViewerUnrenderedOutput,LYRA_DEFAULT_notebookViewerUnsupportedVersion}from"../../../internal/default-strings/viewers.generated.js";const MAX_CELLS=2e3,MAX_OUTPUTS=2e4,MAX_JSON_NODES=1e5,SUPPORTED_MAJOR=4,SUPPORTED_MINORS=[0,1,2,3,4,5],MAX_NOTEBOOK_PAINTED_HIGHLIGHTS=100,OMIT_NOTEBOOK_SNAPSHOT=Symbol("omit-notebook-snapshot");function invalidNotebookSnapshot(){return Object.freeze({})}function isNotebookRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isNotebookDataRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const parent=Object.getPrototypeOf(prototype),constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");if(parent===null)return!constructor||"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object";if(constructor)return!1;const parentConstructor=Object.getOwnPropertyDescriptor(parent,"constructor");return!!(Object.getPrototypeOf(parent)===null&&parentConstructor&&"value"in parentConstructor&&typeof parentConstructor.value=="function"&&parentConstructor.value.name==="Object")}catch{return!1}}function snapshotNotebookDocument(value){if(!isNotebookRecord(value))return OMIT_NOTEBOOK_SNAPSHOT;let remaining=MAX_JSON_NODES;const seen=new WeakSet,created=[],pending=[],createContainer=source=>{let array=!1;try{array=Array.isArray(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}let keys,target;if(array){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(source,"length")}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0||lengthDescriptor.value>remaining)return OMIT_NOTEBOOK_SNAPSHOT;keys=Array.from({length:lengthDescriptor.value},(_,index)=>String(index)),target=new Array(lengthDescriptor.value)}else{if(!isNotebookDataRecord(source))return OMIT_NOTEBOOK_SNAPSHOT;try{keys=Object.keys(source)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(keys.length>remaining)return OMIT_NOTEBOOK_SNAPSHOT;target={}}return seen.add(source),created.push(target),pending.push({source,target,keys,array}),target};remaining-=1;const root=createContainer(value);if(root===OMIT_NOTEBOOK_SNAPSHOT)return root;for(;pending.length;){const task=pending.pop();for(const key of task.keys){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(task.source,key)}catch{return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor){if(task.array)continue;return OMIT_NOTEBOOK_SNAPSHOT}if(!descriptor.enumerable||!("value"in descriptor)||remaining<=0)return OMIT_NOTEBOOK_SNAPSHOT;remaining-=1;const entry=descriptor.value;let snapshot=entry;if(entry!==null&&(typeof entry=="object"||typeof entry=="function")){if(typeof entry=="function"||seen.has(entry))return OMIT_NOTEBOOK_SNAPSHOT;if(snapshot=createContainer(entry),snapshot===OMIT_NOTEBOOK_SNAPSHOT)return snapshot}Object.defineProperty(task.target,key,{value:snapshot,enumerable:!0,configurable:!1,writable:!1})}}for(let index=created.length-1;index>=0;index-=1)Object.freeze(created[index]);return root}function joinSource(source){return typeof source=="string"?source:source?.join("")??""}function isDenseArray(value){for(let index=0;index<value.length;index++)if(!Object.prototype.hasOwnProperty.call(value,index))return!1;return!0}function joinText(text){return typeof text=="string"?text:Array.isArray(text)&&isDenseArray(text)&&text.every(item=>typeof item=="string")?text.join(""):""}function*notebookSearchTextParts(text){if(typeof text=="string"){yield text;return}if(!(!Array.isArray(text)||!isDenseArray(text)))for(const part of text)typeof part=="string"&&(yield part)}const MARKUP_ENTITIES={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"};function isMarkupTagBoundary(markup,index){return/[\t\n\f\r />]/.test(markup[index]??"")}function markupTagEnd(markup,start){let quote="",inName=!0,beforeValue=!1,unquotedValue=!1;for(let index=start;index<markup.length;index++){const character=markup[index];if(quote){character===quote&&(quote="");continue}if(character===">")return index;const whitespace=/[\t\n\f\r ]/.test(character);if(inName){(whitespace||character==="/"&&index>start)&&(inName=!1);continue}if(beforeValue){if(whitespace)continue;beforeValue=!1,character==='"'||character==="'"?quote=character:unquotedValue=!0}else unquotedValue?whitespace&&(unquotedValue=!1):character==="="&&(beforeValue=!0)}return-1}function visibleMarkupText(markup){const lower=markup.toLowerCase();let text="",index=0;for(;index<markup.length;){const open=markup.indexOf("<",index);if(open<0){text+=markup.slice(index);break}if(text+=markup.slice(index,open)+" ",lower.startsWith("<!--",open)){const end=markup.indexOf("-->",open+4);index=end<0?markup.length:end+3;continue}const close=markupTagEnd(markup,open+1);if(close<0)break;const rawText=lower.startsWith("<script",open)&&isMarkupTagBoundary(lower,open+7)?"<\/script":lower.startsWith("<style",open)&&isMarkupTagBoundary(lower,open+6)?"</style":"";if(rawText){let end=lower.indexOf(rawText,close+1);for(;end>=0&&!isMarkupTagBoundary(lower,end+rawText.length);)end=lower.indexOf(rawText,end+rawText.length);const endClose=end<0?-1:markupTagEnd(markup,end+2);index=endClose<0?markup.length:endClose+1;continue}index=close+1}return text.replace(/&(lt|gt|quot|apos|amp);/g,(_entity,name)=>MARKUP_ENTITIES[name])}function*notebookOutputSearchParts(outputs){for(const output of outputs){yield*notebookSearchTextParts(output.text);const data=output.data;data&&Object.prototype.hasOwnProperty.call(data,"text/plain")&&(yield*notebookSearchTextParts(data["text/plain"]),yield" "),data&&!data["image/png"]&&!data["image/jpeg"]&&(data["image/svg+xml"]?yield visibleMarkupText(joinText(data["image/svg+xml"])):data["text/html"]?yield visibleMarkupText(joinText(data["text/html"])):data["application/json"]&&(yield*notebookSearchTextParts(data["application/json"]))),yield" "}}function isTextValue(value){return typeof value=="string"||Array.isArray(value)&&isDenseArray(value)&&value.every(item=>typeof item=="string")}function isJsonValue(value){const pending=[value];let nodes=0;for(;pending.length;){const current=pending.pop();if(++nodes>MAX_JSON_NODES)return!1;if(!(current===null||typeof current=="string"||typeof current=="boolean")){if(typeof current=="number"){if(!Number.isFinite(current))return!1;continue}if(Array.isArray(current)){if(current.length>MAX_JSON_NODES-nodes-pending.length)return!1;for(let index=current.length-1;index>=0;index--)pending.push(current[index]);continue}if(typeof current!="object")return!1;for(const key in current)if(Object.prototype.hasOwnProperty.call(current,key)){if(pending.length>=MAX_JSON_NODES-nodes)return!1;pending.push(current[key])}}}return!0}function isNotebookOutput(value){if(typeof value!="object"||value===null)return!1;const output=value;if(!["stream","error","display_data","execute_result"].includes(output.output_type)||output.text!==void 0&&!isTextValue(output.text)||output.traceback!==void 0&&!isTextValue(output.traceback)||output.ename!==void 0&&typeof output.ename!="string"||output.evalue!==void 0&&typeof output.evalue!="string"||output.name!==void 0&&output.name!=="stdout"&&output.name!=="stderr")return!1;const data=output.data;if(data===void 0)return!0;if(!isNotebookRecord(data))return!1;const mimeData=data;for(const[mime,payload]of Object.entries(mimeData))if(mime==="application/json"){if(typeof payload=="string")try{if(!isJsonValue(JSON.parse(payload)))return!1}catch{return!1}else if(!isJsonValue(payload))return!1}else if(!isTextValue(payload)&&!isJsonValue(payload))return!1;return!0}function isNotebookShape(value){if(typeof value!="object"||value===null)return!1;const v=value;if(!Number.isInteger(v.nbformat)||!Number.isInteger(v.nbformat_minor)||!Array.isArray(v.cells))return!1;const metadata=v.metadata;if(metadata!==void 0){if(!isNotebookRecord(metadata))return!1;for(const[section,field]of[["language_info","name"],["kernelspec","language"]]){const entry=metadata[section];if(entry===void 0)continue;if(!isNotebookRecord(entry))return!1;const language=entry[field];if(language!==void 0&&typeof language!="string")return!1}}const cells=v.cells;let outputCount=0;for(let index=0;index<cells.length;index++){if(!Object.prototype.hasOwnProperty.call(cells,index))return!1;const value2=cells[index];if(typeof value2!="object"||value2===null)return!1;const cell=value2;if(!["markdown","code","raw"].includes(cell.cell_type)||!isTextValue(cell.source)||cell.id!==void 0&&typeof cell.id!="string"||cell.execution_count!==void 0&&cell.execution_count!==null&&(!Number.isInteger(cell.execution_count)||cell.execution_count<0))return!1;if(cell.outputs!==void 0&&(!Array.isArray(cell.outputs)||!isDenseArray(cell.outputs)||(outputCount+=cell.outputs.length,outputCount>MAX_OUTPUTS||!cell.outputs.every(isNotebookOutput))))return!1}return!0}class LyraNotebookViewerBase extends LyraElement{}class LyraNotebookViewer extends DocumentAnchorTarget(LyraNotebookViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.outputCollapseLines=40,this.maxHeight="",this.anchorKinds=["node-path","fragment"],this.loadState={kind:"idle"},this.expandedOutputs=new Set,this.activeCellIndex=null,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1,this.cellKey=(item,index)=>item.id??index,this.highlightedCells=new Map,this.generation=0,this.lastSearchLocale="",this.sanitizerGeneration=0,this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedNotebook()),this.sanitizedOutputCache=new Map,this.sanitizationTasks=new Map,this.renderCell=(cell,index)=>{const c=cell,numberFormat=getNumberFormat(this.effectiveLocale),inCount=c.execution_count==null?this.localize("notebookViewerInPromptEmpty"):this.localize("notebookViewerInPrompt",void 0,{count:numberFormat.format(c.execution_count)}),rowLabel=c.cell_type==="code"?this.localize("notebookViewerCodeCell",void 0,{index:numberFormat.format(index+1)}):c.cell_type==="markdown"?this.localize("notebookViewerMarkdownCell",void 0,{index:numberFormat.format(index+1)}):this.localize("notebookViewerRawCell",void 0,{index:numberFormat.format(index+1)}),active=this.activeCellIndex===index,highlight=this.highlightedCells.get(index),highlighted=highlight!==void 0,parts=["cell"];return active&&parts.push("cell-active"),highlighted&&(parts.push("cell-highlighted",`cell-highlighted-${highlight.tone??"accent"}`),highlight.id===this.activeHighlightId&&parts.push("cell-highlight-active")),html`<div part=${parts.join(" ")} role="group" aria-label=${rowLabel} data-cell-type=${c.cell_type} ?data-active=${active} ?data-highlighted=${highlighted}>
2
2
  <div part="cell-gutter">${c.cell_type==="code"?inCount:""}</div>
3
3
  <div part="cell-source">
4
4
  ${c.cell_type==="markdown"?html`<lr-markdown
@@ -130,7 +130,7 @@ workerSrc:string;
130
130
  /** Anchor kinds this viewer resolves. `page` and page-addressed `region` anchors require an
131
131
  * integer within the loaded document's range; unlike the public `page` property, anchors are
132
132
  * rejected rather than clamped. */
133
- readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private loadLibrary;private generation;private pendingDocument?;private readonly pageCanvases;private readonly pageRenderTasks;private readonly pageRenderVersions;private pageRenderGeneration;private readonly pageCanvasRefs;private readonly textLayerContainers;private readonly textLayerContainerRefs;private readonly textLayers;private readonly textLayerReadyPromises;private readonly pageTextCache;private readonly pageTextTruncated;private readonly pageSearchIndexes;private readonly mountedPageTextIndexes;private pdfTextScopeBuilds;private readonly thumbnailRenderTasks;private readonly thumbnailRenderVersions;private thumbnailRenderGeneration;private readonly pageHighlightItems;private readonly pageHighlightLayerElements;private readonly highlightLayerRefs;private textSelectionCleanup?;private readonly pendingPageMountWaitCancels;private pdfPageSourceCount;private pdfPageSource;private readonly searchState;private get searchMatches();private set searchMatches(value);private get searchActiveIndex();private set searchActiveIndex(value);private searchGeneration;private textIndexLocale?;private pendingSearchResetEvent;private anchorOperationGeneration;private readonly announcements;
133
+ readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private firstVisiblePage;private loadLibrary;private generation;private pendingDocument?;private readonly pageCanvases;private readonly pageRenderTasks;private readonly pageRenderVersions;private pageRenderGeneration;private readonly pageCanvasRefs;private readonly textLayerContainers;private readonly textLayerContainerRefs;private readonly textLayers;private readonly textLayerReadyPromises;private readonly pageTextCache;private readonly pageTextTruncated;private readonly pageSearchIndexes;private readonly mountedPageTextIndexes;private pdfTextScopeBuilds;private readonly thumbnailRenderTasks;private readonly thumbnailRenderVersions;private thumbnailRenderGeneration;private readonly pageHighlightItems;private readonly pageHighlightLayerElements;private readonly highlightLayerRefs;private textSelectionCleanup?;private readonly pendingPageMountWaitCancels;private pdfPageSourceCount;private pdfPageSource;private readonly searchState;private get searchMatches();private set searchMatches(value);private get searchActiveIndex();private set searchActiveIndex(value);private searchGeneration;private textIndexLocale?;private pendingSearchResetEvent;private anchorOperationGeneration;private readonly announcements;
134
134
  /**
135
135
  * Atomic readonly state for page-rail and other page-addressed integrations. Unlike the legacy
136
136
  * `lr-load`/`lr-page-change` pair, a late subscriber can read this immediately, and `identity`
@@ -142,7 +142,7 @@ get pageViewerSnapshot():LyraPageViewerSnapshot;
142
142
  * every consumer runs) the moment anything assigns to it, including a stray
143
143
  * `.pageViewerSnapshot=${x}` template binding; this no-op keeps that assignment harmless
144
144
  * instead of throwing from inside framework internals. */
145
- set pageViewerSnapshot(_value:LyraPageViewerSnapshot);private focusedToolbarPart;private keepToolbarFocus;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;firstUpdated(changed:PropertyValues):void;private readonly detached;connectedCallback():void;disconnectedCallback():void;private teardownDetachedDocument;adoptedCallback():void;private cancelPendingPageMountWaits;private destroyLoadedDoc;private retirePendingDocument;private clampPage;private publishPageViewerSnapshot;private createPageSource;private indexedPages;private load;nextPage():void;previousPage():void;zoomIn():void;zoomOut():void;
145
+ set pageViewerSnapshot(_value:LyraPageViewerSnapshot);private focusedToolbarPart;private keepToolbarFocus;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;firstUpdated(changed:PropertyValues):void;private readonly detached;connectedCallback():void;disconnectedCallback():void;private teardownDetachedDocument;adoptedCallback():void;private cancelPendingPageMountWaits;private destroyLoadedDoc;private retirePendingDocument;private destroyDocumentResource;private clampPage;private publishPageViewerSnapshot;private createPageSource;private indexedPages;private load;nextPage():void;previousPage():void;zoomIn():void;zoomOut():void;
146
146
  /** Sets `page` and resolves once the target page's canvas has actually mounted inside the
147
147
  * virtualized list (bounded by a timeout, so a page that somehow never mounts can't hang this
148
148
  * promise forever). Resolves `false` without changing `page` for an out-of-range value. */
@@ -1,5 +1,5 @@
1
1
  import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{PageViewerSnapshotController}from"../page-rail/page-viewer-snapshot.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings/viewers.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,MAX_PDF_CANVAS_PIXELS=16777216,MAX_PDF_CANVAS_DIMENSION=16384,TOOLBAR_FOCUS_TWINS=new Map([["previous-button","next-button"],["next-button","previous-button"],["zoom-out-button","zoom-in-button"],["zoom-in-button","zoom-out-button"]]),PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
2
- `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length,retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function boundedPdfCanvas(canvas,viewport){return resolveBoundedCanvasAllocation({cssWidth:viewport.width,cssHeight:viewport.height,desiredScale:canvas.ownerDocument.defaultView?.devicePixelRatio||1,maxDimension:MAX_PDF_CANVAS_DIMENSION,maxPixels:MAX_PDF_CANVAS_PIXELS})}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerState=new PageViewerSnapshotController,this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchState=new ViewerSearchState(()=>[],detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.focusedToolbarPart=null,this.detached=new DeferredTeardown(()=>this.teardownDetachedDocument()),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
2
+ `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length,retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function boundedPdfCanvas(canvas,viewport){return resolveBoundedCanvasAllocation({cssWidth:viewport.width,cssHeight:viewport.height,desiredScale:canvas.ownerDocument.defaultView?.devicePixelRatio||1,maxDimension:MAX_PDF_CANVAS_DIMENSION,maxPixels:MAX_PDF_CANVAS_PIXELS})}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerState=new PageViewerSnapshotController,this.scrollDrivenPage=!1,this.firstVisiblePage=1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchState=new ViewerSearchState(()=>[],detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.focusedToolbarPart=null,this.detached=new DeferredTeardown(()=>this.teardownDetachedDocument()),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
3
3
  <canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
4
4
  <div part="page-error" hidden></div>
5
5
  <lr-highlight-layer
@@ -8,7 +8,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
8
8
  @lr-highlight-activate=${this.onHighlightLayerActivate}
9
9
  ></lr-highlight-layer>
10
10
  <div part="text-layer" ${ref(this.textLayerContainerRef(number))}></div>
11
- </div>`},this.onVisibleRangeChanged=event=>{if(event.stopPropagation(),this.loadState.kind!=="ready")return;const next=this.clampPage(event.detail.start+1);next!==this.page&&(this.scrollDrivenPage=!0,this.page=next)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,pdfViewerLabel:LYRA_DEFAULT_pdfViewerLabel,pdfViewerMissingLibrary:LYRA_DEFAULT_pdfViewerMissingLibrary,pdfViewerNextPage:LYRA_DEFAULT_pdfViewerNextPage,pdfViewerPageOf:LYRA_DEFAULT_pdfViewerPageOf,pdfViewerPreviousPage:LYRA_DEFAULT_pdfViewerPreviousPage,pdfViewerZoomIn:LYRA_DEFAULT_pdfViewerZoomIn,pdfViewerZoomOut:LYRA_DEFAULT_pdfViewerZoomOut,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}get searchMatches(){return this.searchState.matches}set searchMatches(matches){this.searchState.matches=matches}get searchActiveIndex(){return this.searchState.activeIndex}set searchActiveIndex(index){this.searchState.activeIndex=index}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}keepToolbarFocus(){const part=this.focusedToolbarPart;this.focusedToolbarPart=null;const twin=part===null?void 0:TOOLBAR_FOCUS_TWINS.get(part),root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedToolbarPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("page")&&(this.page=this.clampPage(this.page)),changed.has("page")&&!changed.has("scrollDrivenPage")&&(this.scrollDrivenPage=!1),changed.has("zoom")){this.zoom=clampZoom(this.zoom);for(const[pageNumber,canvas]of this.pageCanvases)this.renderPage(pageNumber,canvas)}changed.has("src")&&(this.pendingSearchResetEvent||=this.searchState.dirty,this.resetSearchState())}updated(changed){super.updated(changed),this.keepToolbarFocus();const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear()),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&(this.scheduleAfterUpdate(()=>{this.load()},"pdf-load"),this.pageHighlightItems.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.searchState.emit())),changed.has("page")&&this.loadState.kind==="ready"&&(changed.get("page")!==this.page&&this.emit("lr-page-change",{page:this.page,pageCount:this.loadState.pageCount}),this.publishPageViewerSnapshot("ready",this.loadState.pageCount)),changed.has("zoom")&&changed.get("zoom")!==void 0&&changed.get("zoom")!==this.zoom&&this.emit("lr-zoom-change",{zoom:this.zoom}),(changed.has("highlights")||changed.has("activeHighlightId")||localeChanged)&&this.resolveMountedPageHighlights(),changed.has("activeHighlightId"))for(const layer of this.pageHighlightLayerElements.values())layer.activeHighlightId=this.activeHighlightId;localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();if(this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}teardownDetachedDocument(){this.generation++,this.retirePendingDocument(),this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits();for(const task of this.pageRenderTasks.values())task.cancel();for(const layer of this.textLayers.values())layer.cancel();for(const task of this.thumbnailRenderTasks.values())task.cancel();this.pageRenderTasks.clear(),this.pageRenderVersions.clear(),this.textLayers.clear(),this.pageCanvases.clear(),this.textLayerContainers.clear(),this.textLayerReadyPromises.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.thumbnailRenderTasks.clear(),this.thumbnailRenderVersions.clear(),this.destroyLoadedDoc(),this.loadState={kind:"idle"},this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.loadState.doc.destroy?.()}retirePendingDocument(){const pending=this.pendingDocument;if(this.pendingDocument=void 0,!(!pending||pending.retired)){pending.retired=!0;try{Promise.resolve(pending.task.destroy?.()).catch(()=>{})}catch{}}}clampPage(value){const pageCount=this.loadState.kind==="ready"?this.loadState.pageCount:1,rounded=Math.round(finiteNumber(value,1));return finiteRange(rounded,1,1,pageCount)}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,this.clampPage(this.page),finiteCount(pageCount,0,MAX_PAGE_COUNT));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pdfPageSourceCount&&(this.pdfPageSourceCount=count,this.pdfPageSource=this.createPageSource(count)),this.pdfPageSource}async load(){const generation=++this.generation;this.retirePendingDocument(),this.pageViewerState.advance();const signal=this.beginAbortableLoad();if(this.destroyLoadedDoc(),!this.src){this.loadState={kind:"idle"},this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"},this.publishPageViewerSnapshot("loading",0);try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const data=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const pdfjsLib=await this.loadLibrary(this.workerSrc||null);if(!this.isConnected||generation!==this.generation)return;if(!pdfjsLib){const error=new LyraUserFacingError(this.localize("pdfViewerMissingLibrary"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}const pending={task:pdfjsLib.getDocument({data}),retired:!1};this.pendingDocument=pending;let doc;try{doc=await pending.task.promise}catch(error){throw this.pendingDocument===pending&&this.retirePendingDocument(),error}if(this.pendingDocument===pending&&(this.pendingDocument=void 0),!this.isConnected||generation!==this.generation){(!pending.retired||!pending.task.destroy)&&await doc.destroy?.();return}const pageCount=finiteCount(doc.numPages,0,MAX_PAGE_COUNT);if(pageCount<1||pageCount!==doc.numPages)throw await doc.destroy?.(),new LyraUserFacingError(this.localize("documentPreviewResourceTooLarge"));this.page=1,this.loadState={kind:"ready",doc,pageCount},this.publishPageViewerSnapshot("ready",pageCount),this.emit("lr-load",{pageCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}nextPage(){this.scrollDrivenPage=!1,this.setPage(this.page+1)}previousPage(){this.scrollDrivenPage=!1,this.setPage(this.page-1)}zoomIn(){this.setZoom(this.zoom+ZOOM_STEP)}zoomOut(){this.setZoom(this.zoom-ZOOM_STEP)}async goToPage(page){return this.loadState.kind!=="ready"||!Number.isInteger(page)||page<1||page>this.loadState.pageCount?!1:page===this.page&&this.pageCanvases.has(page)?!0:(this.scrollDrivenPage=!1,this.page=page,await this.updateComplete,this.waitForPageMount(page))}waitForPageMount(page){if(this.pageCanvases.has(page))return Promise.resolve(!0);const list=this.shadowRoot?.querySelector(tag("virtual-list")),view=this.ownerDocument.defaultView;return!list||!view?Promise.resolve(!1):new Promise(resolve=>{let settled=!1,timeoutId,cancel;const finish=mounted=>{settled||(settled=!0,list.removeEventListener("lr-visible-range-change",onRange),timeoutId!==void 0&&view.clearTimeout(timeoutId),this.pendingPageMountWaitCancels.delete(cancel),resolve(mounted))},onRange=()=>{this.pageCanvases.has(page)&&finish(!0)};cancel=()=>finish(!1),this.pendingPageMountWaitCancels.add(cancel),list.addEventListener("lr-visible-range-change",onRange),timeoutId=view.setTimeout(()=>finish(!1),500)})}setPage(value){const next=this.clampPage(value);next!==this.page&&(this.page=next)}setZoom(value){const next=clampZoom(value);next!==this.zoom&&(this.zoom=next)}async scrollToAnchor(target){return this.anchorOperationGeneration++,super.scrollToAnchor(target)}async applyAnchor(anchor){if(this.loadState.kind!=="ready")return!1;const doc=this.loadState.doc,operation=this.anchorOperationGeneration;switch(anchor.kind){case"page":return!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,this.isCurrentAnchorOperation(operation,doc)&&this.pageCanvases.has(anchor.page));case"text-quote":return this.applyTextQuoteAnchor(anchor,operation,doc);case"region":return this.applyRegionAnchor(anchor,operation,doc);default:return!1}}isCurrentAnchorOperation(operation,doc){return operation===this.anchorOperationGeneration&&this.loadState.kind==="ready"&&this.loadState.doc===doc}*pageSearchOrder(hint,pageCount){if(hint==null){for(let page=1;page<=pageCount;page++)yield page;return}const clampedHint=Math.min(pageCount,Math.max(1,Math.round(hint)));yield clampedHint;for(let delta=1;delta<pageCount;delta++)clampedHint-delta>=1&&(yield clampedHint-delta),clampedHint+delta<=pageCount&&(yield clampedHint+delta)}async applyTextQuoteAnchor(anchor,operation,doc){if(!this.isCurrentAnchorOperation(operation,doc)||this.loadState.kind!=="ready"||anchor.quote.length>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.prefix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.suffix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||!normalizeQuoteText(anchor.quote))return!1;const order=this.pageSearchOrder(anchor.page,this.loadState.pageCount);let matchedPage,inspectedPages=0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(const pageNumber of order){if(inspectedPages++>=MAX_SEARCH_PAGES||remainingCorpus<=0||remainingNormalizationWork<=0||workBudget.remainingCodeUnits<=0)break;let pageIndex=this.mountedPageTextIndex(pageNumber);if(!pageIndex){let text;try{text=await this.getPageText(pageNumber)}catch{continue}if(!this.isCurrentAnchorOperation(operation,doc))return!1;pageIndex=this.rawPageTextIndex(pageNumber,text,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits)),remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits}if(!this.isCurrentAnchorOperation(operation,doc))return!1;if(pageIndex.index.resolve(anchor,workBudget)){matchedPage=pageNumber;break}if(pageIndex.scope.truncated)break}if(matchedPage==null||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==matchedPage&&(this.scrollDrivenPage=!1,this.page=matchedPage),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)||!this.pageCanvases.has(matchedPage))||(await this.textLayerReadyPromises.get(matchedPage),!this.isCurrentAnchorOperation(operation,doc)))return!1;const range=this.resolveQuoteRangeOnPage(matchedPage,anchor);return!range||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollRangeIntoView(range),!0)}resolveQuoteRangeOnPage(pageNumber,anchor){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const match=mounted.index.resolve(anchor);return match?rangeFromTextQuoteMatch(mounted.scope,match):null}async applyRegionAnchor(anchor,operation,doc){const rect=sanitizePercentRect(anchor.rect);if(!rect||this.loadState.kind!=="ready"||anchor.page==null||!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)))return!1;const canvas=this.pageCanvases.get(anchor.page);return!canvas||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollPercentRectIntoView(canvas,rect),!0)}virtualListScrollContainer(){return this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot?.querySelector('[part="base"]')??null}scrollRangeIntoView(range){const rect=range.getClientRects()[0],scrollContainer=this.virtualListScrollContainer();if(!rect||!scrollContainer)return;const containerRect=scrollContainer.getBoundingClientRect(),offset=rect.top-containerRect.top-containerRect.height/2+rect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}scrollPercentRectIntoView(pageEl,rect){const scrollContainer=this.virtualListScrollContainer();if(!scrollContainer)return;const pageRect=pageEl.getBoundingClientRect(),containerRect=scrollContainer.getBoundingClientRect(),offset=pageRect.top+rect.y/100*pageRect.height-containerRect.top-containerRect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}computeSelectionAnchor(range){const pageNumber=this.pageForNode(range.startContainer);if(pageNumber==null)return null;const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const anchor=buildQuoteAnchor(range,mounted.scope);return anchor.kind==="text-quote"?{...anchor,page:pageNumber}:anchor}pageForNode(node){for(const[pageNumber,container]of this.textLayerContainers)if(container.contains(node))return pageNumber;return null}selectionShadowRoots(contentRoot){const roots=super.selectionShadowRoots(contentRoot),nested=this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot;return nested&&!roots.includes(nested)&&roots.push(nested),roots}bindTextSelection(contentRoot){super.bindTextSelection(contentRoot),this.textSelectionCleanup=()=>this.unbindTextSelection()}async getPageText(page){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)throw new Error(`Page ${page} is out of range (1-${pageCount}).`);const cached=this.pageTextCache.get(page);if(cached)return this.pageTextCache.delete(page),this.pageTextCache.set(page,cached),(await cached.promise).text;const entry={cancelled:!1,promise:Promise.resolve({text:"",truncated:!1})};if(this.pageTextCache.set(page,entry),this.pageTextCache.size>PAGE_TEXT_CACHE_LIMIT){const oldestKey=this.pageTextCache.keys().next().value;oldestKey!==void 0&&this.evictPageTextCacheEntry(oldestKey)}return entry.promise=this.loadPageText(page,entry),entry.promise.then(result=>{this.pageTextCache.get(page)===entry&&(result.truncated?this.pageTextTruncated.add(page):this.pageTextTruncated.delete(page))},()=>{this.pageTextCache.get(page)===entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page))}),(await entry.promise).text}evictPageTextCacheEntry(page){const entry=this.pageTextCache.get(page);entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page),entry.cancelled=!0,entry.reader?.cancel().catch(()=>{}))}clearPageTextCache(){for(const entry of this.pageTextCache.values())entry.cancelled=!0,entry.reader?.cancel().catch(()=>{});this.pageTextCache.clear(),this.pageTextTruncated.clear()}async loadPageText(page,entry){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const doc=this.loadState.doc,pdfPage=await doc.getPage(page),DOMExceptionCtor=this.ownerDocument.defaultView?.DOMException??DOMException;if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");const accumulator={chunks:[],length:0,inspectedItems:0,truncated:!1},source=pdfPage.streamTextContent?.();if(!isReadablePdfTextStream(source))throw new Error("PDF text streaming is unavailable.");const reader=source.getReader();entry.reader=reader;let inspectedChunks=0;try{for(;inspectedChunks++<MAX_PDF_TEXT_CHUNKS;){const result=await reader.read();if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw reader.cancel().catch(()=>{}),new DOMExceptionCtor("Superseded","AbortError");if(result.done)break;const value=result.value;if(appendPdfTextItems(value&&typeof value=="object"&&"items"in value?value.items:void 0,accumulator),accumulator.truncated){reader.cancel().catch(()=>{});break}}inspectedChunks>MAX_PDF_TEXT_CHUNKS&&(accumulator.truncated=!0,reader.cancel().catch(()=>{}))}finally{entry.reader===reader&&(entry.reader=void 0),reader.releaseLock()}if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");return{text:accumulator.chunks.join(""),truncated:accumulator.truncated}}async renderPageThumbnail(page,canvas,options){if(this.loadState.kind!=="ready")return!1;const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)return!1;const width=options?.width??DEFAULT_THUMBNAIL_WIDTH;if(!Number.isFinite(width)||width<=0||width>MAX_THUMBNAIL_WIDTH)return!1;this.thumbnailRenderTasks.get(canvas)?.cancel(),this.thumbnailRenderTasks.delete(canvas);const version=++this.thumbnailRenderGeneration;this.thumbnailRenderVersions.set(canvas,version);const doc=this.loadState.doc;let renderTask;try{const pdfPage=await doc.getPage(page);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc||this.thumbnailRenderVersions.get(canvas)!==version)return!1;const unscaledViewport=pdfPage.getViewport({scale:1});if(!Number.isFinite(unscaledViewport.width)||unscaledViewport.width<=0)return!1;const scale=width/unscaledViewport.width,viewport=pdfPage.getViewport({scale}),allocation=boundedPdfCanvas(canvas,viewport);canvas.width=allocation.pixelWidth,canvas.height=allocation.pixelHeight,canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(allocation.scaleX,0,0,allocation.scaleY,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(!ref2)return;const pageIndex=await doc.getPageIndex(ref2);return typeof pageIndex=="number"?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;const textNode=node,element=textNode.parentElement??container;items.push({text:textNode.data,element,node:textNode,joinBefore:items.length===0||run!==previousRun}),previousRun=run}const scope=scopeFromItems(items);return traversalTruncated&&(scope.truncated=!0),this.pdfTextScopeBuilds++,scope}mountedPageTextIndex(pageNumber,forceMappingRefresh=!1){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;const cached=this.mountedPageTextIndexes.get(pageNumber);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&!cached.mappingDirty&&!forceMappingRefresh)return cached;const scope=this.buildMountedPageScope(container);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&cached.index.rebindScope(scope))return cached.scope=scope,cached.mappingDirty=!1,cached;const created={scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceWorkCodeUnits:scope.text.length,container,mappingDirty:!1};return this.mountedPageTextIndexes.set(pageNumber,created),created}pdfTextScopeBuildCount(){return this.pdfTextScopeBuilds}pdfTextQuoteScanCount(pageNumber){return this.mountedPageTextIndexes.get(pageNumber)?.index.scanCount??0}async search(query){invalidateLyraLocaleCache(this);const generation=++this.searchGeneration;if(this.searchState.query=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchState.publish(void 0,!1),0;const trimmedQuery=query.trim();if(this.loadState.kind!=="ready"||!trimmedQuery)return this.searchState.publish(),0;const{pageCount}=this.loadState,matches=[];let matchCountExact=!0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const searchBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},inspectedPages=Math.min(pageCount,MAX_SEARCH_PAGES);pageCount>inspectedPages&&(matchCountExact=!1);for(let page=1;page<=inspectedPages;page++){if(generation!==this.searchGeneration)return this.searchMatches.length;if(remainingCorpus<=0||remainingNormalizationWork<=0||searchBudget.remainingCodeUnits<=0){matchCountExact=!1;break}let raw;try{raw=await this.getPageText(page)}catch{matchCountExact=!1;continue}if(generation!==this.searchGeneration)return this.searchMatches.length;const fullPageFits=raw.length<=remainingNormalizationWork,pageIndex=this.rawPageTextIndex(page,raw,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits));remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits;const pageMatches=pageIndex.index.search(trimmedQuery,searchBudget);pageMatches.matchCountExact||(matchCountExact=!1);const retainedBeforePage=matches.length;for(const match of pageMatches){if(matches.length>=MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({page,start:match.start,length:match.end-match.start})}if(matches.length>=MAX_SEARCH_MATCHES&&pageMatches.length>0){const retainedOnPage=matches.length-retainedBeforePage;if(pageMatches.length>retainedOnPage){matchCountExact=!1;break}}if(!fullPageFits||pageIndex.scope.truncated||!pageMatches.scanComplete){matchCountExact=!1;break}}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchState.publish(matches,matchCountExact),this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length)}async searchNext(){return this.searchState.step(1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}async searchPrevious(){return this.searchState.step(-1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.searchState.emit()}resetSearchState(){this.searchGeneration++,this.searchState.reset()}async focusSearchMatch(index){const match=this.searchMatches[index];match&&(await this.goToPage(match.page),await this.textLayerReadyPromises.get(match.page),this.paintSearchMatches(match.page))}clearSearchPaint(container){const containers=container?[container]:this.textLayerContainers.values();for(const target of containers){target.querySelectorAll('mark[part~="search-match"]').forEach(mark=>{unwrapTextMark(mark)});for(const cached of this.mountedPageTextIndexes.values())cached.container===target&&(cached.mappingDirty=!0)}}paintSearchMatches(page){const container=this.textLayerContainers.get(page);if(!container)return;this.clearSearchPaint(container);const count=Math.min(this.searchMatches.length,MAX_PAINTED_SEARCH_MATCHES),half=MAX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchActiveIndex<0?0:this.searchActiveIndex,start=Math.max(0,Math.min(centre-half,this.searchMatches.length-count)),pageMatches=[];for(let matchIndex=start;matchIndex<start+count;matchIndex++){const match=this.searchMatches[matchIndex];match?.page===page&&pageMatches.push({match,matchIndex})}if(pageMatches.length===0)return;const active=pageMatches.find(({matchIndex})=>matchIndex===this.searchActiveIndex),nonOverlapping=[];for(const candidate of active?[active,...pageMatches.filter(entry=>entry!==active)]:pageMatches){const candidateEnd=candidate.match.start+candidate.match.length;nonOverlapping.some(({match})=>candidate.match.start<match.start+match.length&&match.start<candidateEnd)||nonOverlapping.push(candidate)}const mounted=this.mountedPageTextIndex(page);if(!mounted)return;const materialized=rangesFromTextQuoteMatches(mounted.scope,nonOverlapping.map(({match})=>({start:match.start,end:match.start+match.length}))),ranges=[];for(let position=0;position<nonOverlapping.length;position++){const{match,matchIndex}=nonOverlapping[position],range=materialized[position]??null;range&&ranges.push({matchIndex,match,range})}ranges.sort((a,b)=>b.match.start-a.match.start);const budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:this.remainingSearchMarkBudget(container)};let painted=!1;for(const{matchIndex,range}of ranges){const part=matchIndex===this.searchActiveIndex?"search-match search-match-active":"search-match";wrapPdfSearchRange(range,part,budget).length>0&&(painted=!0)}painted&&(mounted.mappingDirty=!0)}remainingSearchMarkBudget(except){let remaining=MAX_PAINTED_SEARCH_MARKS;for(const container of this.textLayerContainers.values()){if(container===except)continue;const count=container.querySelectorAll('mark[part~="search-match"]').length;if(remaining-=Math.min(remaining,count),remaining<=0)return 0}return remaining}resolveMountedPageHighlights(){const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),pages=[...this.pageCanvases.keys()].filter(pageNumber=>this.textLayerContainers.has(pageNumber)).sort((left,right)=>left-right),active=this.activeHighlightId?candidates.find(highlight=>highlight.id===this.activeHighlightId):void 0,activePage=active?.anchor.kind==="page"?active.anchor.page:active?.anchor.kind==="region"?active.anchor.page??this.page:active?.anchor.kind==="text-quote"?active.anchor.page:void 0;activePage!==void 0&&pages.sort((left,right)=>+(right===activePage)-+(left===activePage));for(const layer of this.pageHighlightLayerElements.values())layer.items=[];this.pageHighlightItems.clear();const results=new Map;for(const pageNumber of pages)results.set(pageNumber,[]);const textIndexes=new Map,searchPaintPages=new Set,budget={work:{remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},remainingResolutionAttempts:MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS,remainingItems:MAX_PAINTED_HIGHLIGHTS,remainingRects:MAX_HIGHLIGHT_RECTS},plans=[],textOptionsByPage=new Map,pageRects=new Map;for(const highlight of candidates){const options=[];for(const pageNumber of this.mountedPagesForHighlight(highlight.anchor,pages)){const container=this.textLayerContainers.get(pageNumber),canvas=this.pageCanvases.get(pageNumber);if(!container||!canvas||this.loadState.kind!=="ready")continue;let pageRect=pageRects.get(pageNumber);pageRect||(pageRect=canvas.getBoundingClientRect(),pageRects.set(pageNumber,pageRect));let textIndex;if(highlight.anchor.kind==="text-quote"){if(budget.remainingResolutionAttempts<=0)break;if(textIndexes.has(pageNumber)||(container.querySelector('mark[part~="search-match"]')&&(searchPaintPages.add(pageNumber),this.clearSearchPaint(container)),textIndexes.set(pageNumber,this.mountedPageTextIndex(pageNumber))),textIndex=textIndexes.get(pageNumber)??void 0,!textIndex)continue;budget.remainingResolutionAttempts--;const match=textIndex.index.resolve(highlight.anchor,budget.work);if(!match)continue;const option={pageNumber,pageRect,textIndex,match};options.push(option);const pageOptions=textOptionsByPage.get(pageNumber)??[];pageOptions.push(option),textOptionsByPage.set(pageNumber,pageOptions);continue}options.push({pageNumber,pageRect})}plans.push({highlight,options})}for(const[pageNumber,options]of textOptionsByPage){const textIndex=textIndexes.get(pageNumber);if(!textIndex)continue;const ranges=rangesFromTextQuoteMatches(textIndex.scope,options.map(({match})=>match));for(let position=0;position<options.length;position++)options[position].range=ranges[position]??null}candidateLoop:for(const{highlight,options}of plans){if(budget.remainingItems<=0||budget.remainingRects<=0)break;for(const{pageNumber,pageRect,range}of options){const rects=this.resolveHighlightRectsForPage(highlight.anchor,pageNumber,pageRect,budget,range);if(rects.length!==0){results.get(pageNumber).push({id:highlight.id,rects,label:highlight.label,tone:highlight.tone}),budget.remainingItems--;continue candidateLoop}}}for(const[pageNumber,pageItems]of results){this.pageHighlightItems.set(pageNumber,pageItems);const layer=this.pageHighlightLayerElements.get(pageNumber);layer&&(layer.items=pageItems)}for(const pageNumber of searchPaintPages)this.paintSearchMatches(pageNumber)}*mountedPagesForHighlight(anchor,mountedPages){const addressedPage=anchor.kind==="page"?anchor.page:anchor.kind==="region"?anchor.page??this.page:anchor.kind==="text-quote"?anchor.page:void 0;if(addressedPage!==void 0){mountedPages.includes(addressedPage)&&(yield addressedPage);return}if(anchor.kind==="text-quote")for(const pageNumber of mountedPages)yield pageNumber}resolveHighlightRectsForPage(anchor,pageNumber,pageRect,budget,range){if(anchor.kind==="page"&&anchor.page===pageNumber)return budget.remainingRects<=0?[]:(budget.remainingRects--,[{x:0,y:0,width:100,height:100}]);if(anchor.kind==="region"&&(anchor.page??pageNumber)===pageNumber){const rect=sanitizePercentRect(anchor.rect);return!rect||budget.remainingRects<=0?[]:(budget.remainingRects--,[rect])}if(anchor.kind==="text-quote"&&range&&(anchor.page==null||anchor.page===pageNumber)){if(!(pageRect.width>0)||!(pageRect.height>0))return[];const rects=[];for(const rect of range.getClientRects()){if(rects.length>=budget.remainingRects)return[];rects.push({x:(rect.left-pageRect.left)/pageRect.width*100,y:(rect.top-pageRect.top)/pageRect.height*100,width:rect.width/pageRect.width*100,height:rect.height/pageRect.height*100})}return budget.remainingRects-=rects.length,rects}return[]}highlightLayerRef(pageNumber){let callback=this.highlightLayerRefs.get(pageNumber);return callback||(callback=element=>{if(!element){this.pageHighlightLayerElements.delete(pageNumber),this.pageHighlightItems.delete(pageNumber),this.highlightLayerRefs.delete(pageNumber);return}const layer=element;this.pageHighlightLayerElements.set(pageNumber,layer),layer.items=this.pageHighlightItems.get(pageNumber)??[],layer.activeHighlightId=this.activeHighlightId;const canvas=this.pageCanvases.get(pageNumber);canvas?.style.width&&(layer.style.width=canvas.style.width,layer.style.height=canvas.style.height)},this.highlightLayerRefs.set(pageNumber,callback)),callback}onPageClick(pageNumber,e){const canvas=this.pageCanvases.get(pageNumber),selection=canvas?.ownerDocument.defaultView?.getSelection();if(selection&&!selection.isCollapsed)return;const items=this.pageHighlightItems.get(pageNumber);if(!canvas||!items||items.length===0)return;const pageRect=canvas.getBoundingClientRect(),xPct=(e.clientX-pageRect.left)/pageRect.width*100,yPct=(e.clientY-pageRect.top)/pageRect.height*100;for(let i=items.length-1;i>=0;i--){const item=items[i];if(!item)continue;if(item.rects.some(rect=>xPct>=rect.x&&xPct<=rect.x+rect.width&&yPct>=rect.y&&yPct<=rect.y+rect.height)){this.emit("lr-highlight-activate",{highlightId:item.id});return}}}renderToolbar(){if(this.loadState.kind!=="ready")return html``;const{pageCount}=this.loadState,numberFormat=getNumberFormat(this.effectiveLocale),formattedZoom=numberFormat.format(Math.round(this.zoom*100));return html`<div part="toolbar">
11
+ </div>`},this.onVisibleRangeChanged=event=>{if(event.stopPropagation(),this.loadState.kind!=="ready")return;const next=this.clampPage(event.detail.start+1);next!==this.firstVisiblePage&&(this.firstVisiblePage=next,next!==this.page&&(this.scrollDrivenPage=!0,this.page=next))},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument,pdfViewerCurrentZoom:LYRA_DEFAULT_pdfViewerCurrentZoom,pdfViewerLabel:LYRA_DEFAULT_pdfViewerLabel,pdfViewerMissingLibrary:LYRA_DEFAULT_pdfViewerMissingLibrary,pdfViewerNextPage:LYRA_DEFAULT_pdfViewerNextPage,pdfViewerPageOf:LYRA_DEFAULT_pdfViewerPageOf,pdfViewerPreviousPage:LYRA_DEFAULT_pdfViewerPreviousPage,pdfViewerZoomIn:LYRA_DEFAULT_pdfViewerZoomIn,pdfViewerZoomOut:LYRA_DEFAULT_pdfViewerZoomOut,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}get searchMatches(){return this.searchState.matches}set searchMatches(matches){this.searchState.matches=matches}get searchActiveIndex(){return this.searchState.activeIndex}set searchActiveIndex(index){this.searchState.activeIndex=index}get pageViewerSnapshot(){return this.pageViewerState.value}set pageViewerSnapshot(_value){}keepToolbarFocus(){const part=this.focusedToolbarPart;this.focusedToolbarPart=null;const twin=part===null?void 0:TOOLBAR_FOCUS_TWINS.get(part),root=this.shadowRoot;!twin||!root||root.querySelector(`[part="${part}"]`)?.disabled&&root.querySelector(`[part="${twin}"]:not(:disabled)`)?.focus()}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedToolbarPart=active?.localName==="button"&&!active.disabled?active.getAttribute("part"):null,changed.has("page")&&(this.page=this.clampPage(this.page)),changed.has("page")&&!changed.has("scrollDrivenPage")&&(this.scrollDrivenPage=!1),changed.has("zoom")){this.zoom=clampZoom(this.zoom);for(const[pageNumber,canvas]of this.pageCanvases)this.renderPage(pageNumber,canvas)}changed.has("src")&&(this.pendingSearchResetEvent||=this.searchState.dirty,this.resetSearchState())}updated(changed){super.updated(changed),this.keepToolbarFocus();const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear()),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&(this.scheduleAfterUpdate(()=>{this.load()},"pdf-load"),this.pageHighlightItems.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.searchState.emit())),changed.has("page")&&this.loadState.kind==="ready"&&(changed.get("page")!==this.page&&this.emit("lr-page-change",{page:this.page,pageCount:this.loadState.pageCount}),this.publishPageViewerSnapshot("ready",this.loadState.pageCount)),changed.has("zoom")&&changed.get("zoom")!==void 0&&changed.get("zoom")!==this.zoom&&this.emit("lr-zoom-change",{zoom:this.zoom}),(changed.has("highlights")||changed.has("activeHighlightId")||localeChanged)&&this.resolveMountedPageHighlights(),changed.has("activeHighlightId"))for(const layer of this.pageHighlightLayerElements.values())layer.activeHighlightId=this.activeHighlightId;localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)},"pdf-search")}firstUpdated(changed){super.firstUpdated(changed);const base=this.shadowRoot?.querySelector('[part="base"]');base&&this.bindTextSelection(base)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();if(this.hasUpdated){const base=this.shadowRoot?.querySelector('[part="base"]');base&&!this.textSelectionCleanup&&this.bindTextSelection(base),this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.load()},"pdf-load")}}disconnectedCallback(){this.textSelectionCleanup?.(),this.textSelectionCleanup=void 0,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}teardownDetachedDocument(){this.generation++,this.retirePendingDocument(),this.resetSearchState(),this.pendingSearchResetEvent=!1,this.anchorOperationGeneration++,this.beginAbortableLoad(),this.cancelPendingPageMountWaits();for(const task of this.pageRenderTasks.values())task.cancel();for(const layer of this.textLayers.values())layer.cancel();for(const task of this.thumbnailRenderTasks.values())task.cancel();this.pageRenderTasks.clear(),this.pageRenderVersions.clear(),this.textLayers.clear(),this.pageCanvases.clear(),this.textLayerContainers.clear(),this.textLayerReadyPromises.clear(),this.clearPageTextCache(),this.pageSearchIndexes.clear(),this.mountedPageTextIndexes.clear(),this.thumbnailRenderTasks.clear(),this.thumbnailRenderVersions.clear(),this.destroyLoadedDoc(),this.loadState={kind:"idle"},this.pageViewerState.reset()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.cancelPendingPageMountWaits(),this.announcements.adopted()}cancelPendingPageMountWaits(){for(const cancel of[...this.pendingPageMountWaitCancels])cancel()}destroyLoadedDoc(){this.loadState.kind==="ready"&&this.destroyDocumentResource(this.loadState.doc)}retirePendingDocument(){const pending=this.pendingDocument;this.pendingDocument=void 0,!(!pending||pending.retired)&&(pending.retired=!0,this.destroyDocumentResource(pending.task))}destroyDocumentResource(resource){try{Promise.resolve(resource.destroy?.()).catch(()=>{})}catch{}}clampPage(value){const pageCount=this.loadState.kind==="ready"?this.loadState.pageCount:1,rounded=Math.round(finiteNumber(value,1));return finiteRange(rounded,1,1,pageCount)}publishPageViewerSnapshot(status,pageCount){const snapshot=this.pageViewerState.publish(status,this.clampPage(this.page),finiteCount(pageCount,0,MAX_PAGE_COUNT));snapshot&&this.isConnected&&this.emit("lr-page-viewer-state-change",{snapshot})}createPageSource(count){return Object.freeze({count,itemAt:index=>index+1,keyAt:index=>index+1,indexOfKey:key=>typeof key=="number"?key-1:-1})}indexedPages(count){return count!==this.pdfPageSourceCount&&(this.pdfPageSourceCount=count,this.pdfPageSource=this.createPageSource(count)),this.pdfPageSource}async load(){const generation=++this.generation;this.firstVisiblePage=1,this.retirePendingDocument(),this.pageViewerState.advance();const signal=this.beginAbortableLoad();if(this.destroyLoadedDoc(),!this.src){this.loadState={kind:"idle"},this.publishPageViewerSnapshot("idle",0);return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"},this.publishPageViewerSnapshot("loading",0);try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const data=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const pdfjsLib=await this.loadLibrary(this.workerSrc||null);if(!this.isConnected||generation!==this.generation)return;if(!pdfjsLib){const error=new LyraUserFacingError(this.localize("pdfViewerMissingLibrary"));this.loadState={kind:"error",message:error.message},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error});return}const pending={task:pdfjsLib.getDocument({data}),retired:!1};this.pendingDocument=pending;let doc;try{doc=await pending.task.promise}catch(error){throw this.pendingDocument===pending&&this.retirePendingDocument(),error}if(this.pendingDocument===pending&&(this.pendingDocument=void 0),!this.isConnected||generation!==this.generation){(!pending.retired||!pending.task.destroy)&&await doc.destroy?.();return}const pageCount=finiteCount(doc.numPages,0,MAX_PAGE_COUNT);if(pageCount<1||pageCount!==doc.numPages)throw await doc.destroy?.(),new LyraUserFacingError(this.localize("documentPreviewResourceTooLarge"));this.page=1,this.loadState={kind:"ready",doc,pageCount},this.publishPageViewerSnapshot("ready",pageCount),this.emit("lr-load",{pageCount})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.publishPageViewerSnapshot("error",0),this.emit("lr-render-error",{error})}}nextPage(){this.scrollDrivenPage=!1,this.setPage(this.page+1)}previousPage(){this.scrollDrivenPage=!1,this.setPage(this.page-1)}zoomIn(){this.setZoom(this.zoom+ZOOM_STEP)}zoomOut(){this.setZoom(this.zoom-ZOOM_STEP)}async goToPage(page){return this.loadState.kind!=="ready"||!Number.isInteger(page)||page<1||page>this.loadState.pageCount?!1:page===this.page&&this.pageCanvases.has(page)?!0:(this.scrollDrivenPage=!1,this.page=page,await this.updateComplete,this.waitForPageMount(page))}waitForPageMount(page){if(this.pageCanvases.has(page))return Promise.resolve(!0);const list=this.shadowRoot?.querySelector(tag("virtual-list")),view=this.ownerDocument.defaultView;return!list||!view?Promise.resolve(!1):new Promise(resolve=>{let settled=!1,timeoutId,cancel;const finish=mounted=>{settled||(settled=!0,list.removeEventListener("lr-visible-range-change",onRange),timeoutId!==void 0&&view.clearTimeout(timeoutId),this.pendingPageMountWaitCancels.delete(cancel),resolve(mounted))},onRange=()=>{this.pageCanvases.has(page)&&finish(!0)};cancel=()=>finish(!1),this.pendingPageMountWaitCancels.add(cancel),list.addEventListener("lr-visible-range-change",onRange),timeoutId=view.setTimeout(()=>finish(!1),500)})}setPage(value){const next=this.clampPage(value);next!==this.page&&(this.page=next)}setZoom(value){const next=clampZoom(value);next!==this.zoom&&(this.zoom=next)}async scrollToAnchor(target){return this.anchorOperationGeneration++,super.scrollToAnchor(target)}async applyAnchor(anchor){if(this.loadState.kind!=="ready")return!1;const doc=this.loadState.doc,operation=this.anchorOperationGeneration;switch(anchor.kind){case"page":return!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,this.isCurrentAnchorOperation(operation,doc)&&this.pageCanvases.has(anchor.page));case"text-quote":return this.applyTextQuoteAnchor(anchor,operation,doc);case"region":return this.applyRegionAnchor(anchor,operation,doc);default:return!1}}isCurrentAnchorOperation(operation,doc){return operation===this.anchorOperationGeneration&&this.loadState.kind==="ready"&&this.loadState.doc===doc}*pageSearchOrder(hint,pageCount){if(hint==null){for(let page=1;page<=pageCount;page++)yield page;return}const clampedHint=Math.min(pageCount,Math.max(1,Math.round(hint)));yield clampedHint;for(let delta=1;delta<pageCount;delta++)clampedHint-delta>=1&&(yield clampedHint-delta),clampedHint+delta<=pageCount&&(yield clampedHint+delta)}async applyTextQuoteAnchor(anchor,operation,doc){if(!this.isCurrentAnchorOperation(operation,doc)||this.loadState.kind!=="ready"||anchor.quote.length>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.prefix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||(anchor.suffix?.length??0)>TEXT_QUOTE_LIMITS.maxQueryCodeUnits||!normalizeQuoteText(anchor.quote))return!1;const order=this.pageSearchOrder(anchor.page,this.loadState.pageCount);let matchedPage,inspectedPages=0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(const pageNumber of order){if(inspectedPages++>=MAX_SEARCH_PAGES||remainingCorpus<=0||remainingNormalizationWork<=0||workBudget.remainingCodeUnits<=0)break;let pageIndex=this.mountedPageTextIndex(pageNumber);if(!pageIndex){let text;try{text=await this.getPageText(pageNumber)}catch{continue}if(!this.isCurrentAnchorOperation(operation,doc))return!1;pageIndex=this.rawPageTextIndex(pageNumber,text,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits)),remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits}if(!this.isCurrentAnchorOperation(operation,doc))return!1;if(pageIndex.index.resolve(anchor,workBudget)){matchedPage=pageNumber;break}if(pageIndex.scope.truncated)break}if(matchedPage==null||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==matchedPage&&(this.scrollDrivenPage=!1,this.page=matchedPage),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)||!this.pageCanvases.has(matchedPage))||(await this.textLayerReadyPromises.get(matchedPage),!this.isCurrentAnchorOperation(operation,doc)))return!1;const range=this.resolveQuoteRangeOnPage(matchedPage,anchor);return!range||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollRangeIntoView(range),!0)}resolveQuoteRangeOnPage(pageNumber,anchor){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const match=mounted.index.resolve(anchor);return match?rangeFromTextQuoteMatch(mounted.scope,match):null}async applyRegionAnchor(anchor,operation,doc){const rect=sanitizePercentRect(anchor.rect);if(!rect||this.loadState.kind!=="ready"||anchor.page==null||!Number.isInteger(anchor.page)||anchor.page<1||anchor.page>this.loadState.pageCount||!this.isCurrentAnchorOperation(operation,doc)||(this.page!==anchor.page&&(this.scrollDrivenPage=!1,this.page=anchor.page),await this.updateComplete,!this.isCurrentAnchorOperation(operation,doc)))return!1;const canvas=this.pageCanvases.get(anchor.page);return!canvas||!this.isCurrentAnchorOperation(operation,doc)?!1:(this.scrollPercentRectIntoView(canvas,rect),!0)}virtualListScrollContainer(){return this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot?.querySelector('[part="base"]')??null}scrollRangeIntoView(range){const rect=range.getClientRects()[0],scrollContainer=this.virtualListScrollContainer();if(!rect||!scrollContainer)return;const containerRect=scrollContainer.getBoundingClientRect(),offset=rect.top-containerRect.top-containerRect.height/2+rect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}scrollPercentRectIntoView(pageEl,rect){const scrollContainer=this.virtualListScrollContainer();if(!scrollContainer)return;const pageRect=pageEl.getBoundingClientRect(),containerRect=scrollContainer.getBoundingClientRect(),offset=pageRect.top+rect.y/100*pageRect.height-containerRect.top-containerRect.height/2;scrollContainer.scrollBy({top:offset,behavior:prefersReducedMotion(this)?"auto":"smooth"})}computeSelectionAnchor(range){const pageNumber=this.pageForNode(range.startContainer);if(pageNumber==null)return null;const container=this.textLayerContainers.get(pageNumber);if(!container)return null;container.querySelector('mark[part~="search-match"]')&&this.clearSearchPaint(container);const mounted=this.mountedPageTextIndex(pageNumber);if(!mounted)return null;const anchor=buildQuoteAnchor(range,mounted.scope);return anchor.kind==="text-quote"?{...anchor,page:pageNumber}:anchor}pageForNode(node){for(const[pageNumber,container]of this.textLayerContainers)if(container.contains(node))return pageNumber;return null}selectionShadowRoots(contentRoot){const roots=super.selectionShadowRoots(contentRoot),nested=this.shadowRoot?.querySelector(tag("virtual-list"))?.shadowRoot;return nested&&!roots.includes(nested)&&roots.push(nested),roots}bindTextSelection(contentRoot){super.bindTextSelection(contentRoot),this.textSelectionCleanup=()=>this.unbindTextSelection()}async getPageText(page){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)throw new Error(`Page ${page} is out of range (1-${pageCount}).`);const cached=this.pageTextCache.get(page);if(cached)return this.pageTextCache.delete(page),this.pageTextCache.set(page,cached),(await cached.promise).text;const entry={cancelled:!1,promise:Promise.resolve({text:"",truncated:!1})};if(this.pageTextCache.set(page,entry),this.pageTextCache.size>PAGE_TEXT_CACHE_LIMIT){const oldestKey=this.pageTextCache.keys().next().value;oldestKey!==void 0&&this.evictPageTextCacheEntry(oldestKey)}return entry.promise=this.loadPageText(page,entry),entry.promise.then(result=>{this.pageTextCache.get(page)===entry&&(result.truncated?this.pageTextTruncated.add(page):this.pageTextTruncated.delete(page))},()=>{this.pageTextCache.get(page)===entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page))}),(await entry.promise).text}evictPageTextCacheEntry(page){const entry=this.pageTextCache.get(page);entry&&(this.pageTextCache.delete(page),this.pageTextTruncated.delete(page),entry.cancelled=!0,entry.reader?.cancel().catch(()=>{}))}clearPageTextCache(){for(const entry of this.pageTextCache.values())entry.cancelled=!0,entry.reader?.cancel().catch(()=>{});this.pageTextCache.clear(),this.pageTextTruncated.clear()}async loadPageText(page,entry){if(this.loadState.kind!=="ready")throw new Error("No PDF document is loaded.");const doc=this.loadState.doc,pdfPage=await doc.getPage(page),DOMExceptionCtor=this.ownerDocument.defaultView?.DOMException??DOMException;if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");const accumulator={chunks:[],length:0,inspectedItems:0,truncated:!1},source=pdfPage.streamTextContent?.();if(!isReadablePdfTextStream(source))throw new Error("PDF text streaming is unavailable.");const reader=source.getReader();entry.reader=reader;let inspectedChunks=0;try{for(;inspectedChunks++<MAX_PDF_TEXT_CHUNKS;){const result=await reader.read();if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw reader.cancel().catch(()=>{}),new DOMExceptionCtor("Superseded","AbortError");if(result.done)break;const value=result.value;if(appendPdfTextItems(value&&typeof value=="object"&&"items"in value?value.items:void 0,accumulator),accumulator.truncated){reader.cancel().catch(()=>{});break}}inspectedChunks>MAX_PDF_TEXT_CHUNKS&&(accumulator.truncated=!0,reader.cancel().catch(()=>{}))}finally{entry.reader===reader&&(entry.reader=void 0),reader.releaseLock()}if(entry.cancelled||this.loadState.kind!=="ready"||this.loadState.doc!==doc)throw new DOMExceptionCtor("Superseded","AbortError");return{text:accumulator.chunks.join(""),truncated:accumulator.truncated}}async renderPageThumbnail(page,canvas,options){if(this.loadState.kind!=="ready")return!1;const{pageCount}=this.loadState;if(!Number.isInteger(page)||page<1||page>pageCount)return!1;const width=options?.width??DEFAULT_THUMBNAIL_WIDTH;if(!Number.isFinite(width)||width<=0||width>MAX_THUMBNAIL_WIDTH)return!1;this.thumbnailRenderTasks.get(canvas)?.cancel(),this.thumbnailRenderTasks.delete(canvas);const version=++this.thumbnailRenderGeneration;this.thumbnailRenderVersions.set(canvas,version);const doc=this.loadState.doc;let renderTask;try{const pdfPage=await doc.getPage(page);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc||this.thumbnailRenderVersions.get(canvas)!==version)return!1;const unscaledViewport=pdfPage.getViewport({scale:1});if(!Number.isFinite(unscaledViewport.width)||unscaledViewport.width<=0)return!1;const scale=width/unscaledViewport.width,viewport=pdfPage.getViewport({scale}),allocation=boundedPdfCanvas(canvas,viewport);canvas.width=allocation.pixelWidth,canvas.height=allocation.pixelHeight,canvas.style.width=`${viewport.width}px`,canvas.style.height=`${viewport.height}px`;const context=canvas.getContext("2d");return context?(context.setTransform(allocation.scaleX,0,0,allocation.scaleY,0,0),renderTask=pdfPage.render({canvasContext:context,viewport}),this.thumbnailRenderTasks.set(canvas,renderTask),await renderTask.promise,this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderVersions.get(canvas)===version):!1}catch(error){if(isAbortError(error))return!1;throw error}finally{renderTask&&this.thumbnailRenderTasks.get(canvas)===renderTask&&this.thumbnailRenderTasks.delete(canvas),this.thumbnailRenderVersions.get(canvas)===version&&this.thumbnailRenderVersions.delete(canvas)}}async getOutline(){if(this.loadState.kind!=="ready")return[];const doc=this.loadState.doc;if(!doc.getOutline)return[];const raw=await doc.getOutline();if(!Array.isArray(raw)||this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const result=await this.mapOutlineItems(doc,raw,1,new WeakSet,{count:0});return this.loadState.kind==="ready"&&this.loadState.doc===doc?result:[]}async mapOutlineItems(doc,rawItems,depth,seen,budget){if(depth>MAX_OUTLINE_DEPTH||budget.count>=MAX_OUTLINE_ITEMS)return[];const mapped=[];for(const rawItem of rawItems){if(budget.count>=MAX_OUTLINE_ITEMS)break;if(!rawItem||typeof rawItem!="object"||seen.has(rawItem))continue;seen.add(rawItem),budget.count++;const page=await this.resolveOutlineDestPage(doc,rawItem.dest);if(this.loadState.kind!=="ready"||this.loadState.doc!==doc)return[];const rawChildren=Array.isArray(rawItem.items)?rawItem.items:[],children=depth<MAX_OUTLINE_DEPTH?await this.mapOutlineItems(doc,rawChildren,depth+1,seen,budget):[];mapped.push({title:String(rawItem.title??""),...page!==void 0?{page}:{},...children.length>0?{children}:{}})}return mapped}async resolveOutlineDestPage(doc,dest){if(dest)try{const explicitDest=typeof dest=="string"?await doc.getDestination(dest):dest,ref2=Array.isArray(explicitDest)?explicitDest[0]:void 0;if(ref2==null)return;const pageIndex=typeof ref2=="number"?ref2:await doc.getPageIndex(ref2);return Number.isInteger(pageIndex)&&pageIndex>=0&&pageIndex<doc.numPages?pageIndex+1:void 0}catch{return}}createRawPageTextIndex(raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const inspectedRaw=raw.slice(0,Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)),element=this.ownerDocument.createElement("span");element.textContent=inspectedRaw;const scope=scopeFromItems([{text:inspectedRaw,element}],{maxCorpusCodeUnits,maxNormalizationWorkCodeUnits});return inspectedRaw.length!==raw.length&&(scope.truncated=!0),this.pdfTextScopeBuilds++,{scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceText:raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits?raw:void 0,sourceWorkCodeUnits:Math.min(raw.length,TEXT_QUOTE_LIMITS.maxNodeCodeUnits,maxNormalizationWorkCodeUnits)}}rawPageTextIndex(pageNumber,raw,maxCorpusCodeUnits=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,maxNormalizationWorkCodeUnits=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits){const cacheable=maxCorpusCodeUnits===TEXT_QUOTE_LIMITS.maxCorpusCodeUnits&&maxNormalizationWorkCodeUnits===TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits&&raw.length<=TEXT_QUOTE_LIMITS.maxNodeCodeUnits,cached=this.pageSearchIndexes.get(pageNumber);if(cacheable&&cached&&cached.locale===this.effectiveLocale&&cached.sourceText===raw)return this.pageSearchIndexes.delete(pageNumber),this.pageSearchIndexes.set(pageNumber,cached),cached;const created=this.createRawPageTextIndex(raw,maxCorpusCodeUnits,maxNormalizationWorkCodeUnits);if(this.pageTextTruncated.has(pageNumber)&&(created.scope.truncated=!0),cacheable&&(this.pageSearchIndexes.set(pageNumber,created),this.pageSearchIndexes.size>PAGE_SEARCH_INDEX_CACHE_LIMIT)){const oldest=this.pageSearchIndexes.keys().next().value;oldest!==void 0&&this.pageSearchIndexes.delete(oldest)}return created}buildMountedPageScope(container){const items=[],doc=container.ownerDocument,showAll=doc.defaultView?.NodeFilter.SHOW_ALL??4294967295,textNodeType=doc.defaultView?.Node.TEXT_NODE??3,walker=doc.createTreeWalker(container,showAll),textRunOwners=new WeakMap;textRunOwners.set(container,null);let traversed=0,traversalTruncated=!1,previousRun=null,node;for(;node=walker.nextNode();){if(traversed++,traversed>TEXT_QUOTE_LIMITS.maxTraversalNodes){traversalTruncated=!0;break}const parentRun=node.parentNode?textRunOwners.get(node.parentNode)??null:null,run=node.nodeType===1&&node.localName==="span"?parentRun??node:parentRun;if(textRunOwners.set(node,run),node.nodeType!==textNodeType)continue;const textNode=node,element=textNode.parentElement??container;items.push({text:textNode.data,element,node:textNode,joinBefore:items.length===0||run!==previousRun}),previousRun=run}const scope=scopeFromItems(items);return traversalTruncated&&(scope.truncated=!0),this.pdfTextScopeBuilds++,scope}mountedPageTextIndex(pageNumber,forceMappingRefresh=!1){const container=this.textLayerContainers.get(pageNumber);if(!container)return null;const cached=this.mountedPageTextIndexes.get(pageNumber);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&!cached.mappingDirty&&!forceMappingRefresh)return cached;const scope=this.buildMountedPageScope(container);if(cached&&cached.container===container&&cached.locale===this.effectiveLocale&&cached.index.rebindScope(scope))return cached.scope=scope,cached.mappingDirty=!1,cached;const created={scope,index:createTextQuoteIndex(scope,this.effectiveLocale,{maxMatches:MAX_SEARCH_MATCHES}),locale:this.effectiveLocale,sourceWorkCodeUnits:scope.text.length,container,mappingDirty:!1};return this.mountedPageTextIndexes.set(pageNumber,created),created}pdfTextScopeBuildCount(){return this.pdfTextScopeBuilds}pdfTextQuoteScanCount(pageNumber){return this.mountedPageTextIndexes.get(pageNumber)?.index.scanCount??0}async search(query){invalidateLyraLocaleCache(this);const generation=++this.searchGeneration;if(this.searchState.query=query,this.clearSearchPaint(),!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.searchState.publish(void 0,!1),0;const trimmedQuery=query.trim();if(this.loadState.kind!=="ready"||!trimmedQuery)return this.searchState.publish(),0;const{pageCount}=this.loadState,matches=[];let matchCountExact=!0,remainingCorpus=TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,remainingNormalizationWork=TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits;const searchBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},inspectedPages=Math.min(pageCount,MAX_SEARCH_PAGES);pageCount>inspectedPages&&(matchCountExact=!1);for(let page=1;page<=inspectedPages;page++){if(generation!==this.searchGeneration)return this.searchMatches.length;if(remainingCorpus<=0||remainingNormalizationWork<=0||searchBudget.remainingCodeUnits<=0){matchCountExact=!1;break}let raw;try{raw=await this.getPageText(page)}catch{matchCountExact=!1;continue}if(generation!==this.searchGeneration)return this.searchMatches.length;const fullPageFits=raw.length<=remainingNormalizationWork,pageIndex=this.rawPageTextIndex(page,raw,Math.min(remainingCorpus,TEXT_QUOTE_LIMITS.maxCorpusCodeUnits),Math.min(remainingNormalizationWork,TEXT_QUOTE_LIMITS.maxNormalizationWorkCodeUnits));remainingCorpus-=pageIndex.scope.text.length,remainingNormalizationWork-=pageIndex.sourceWorkCodeUnits;const pageMatches=pageIndex.index.search(trimmedQuery,searchBudget);pageMatches.matchCountExact||(matchCountExact=!1);const retainedBeforePage=matches.length;for(const match of pageMatches){if(matches.length>=MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({page,start:match.start,length:match.end-match.start})}if(matches.length>=MAX_SEARCH_MATCHES&&pageMatches.length>0){const retainedOnPage=matches.length-retainedBeforePage;if(pageMatches.length>retainedOnPage){matchCountExact=!1;break}}if(!fullPageFits||pageIndex.scope.truncated||!pageMatches.scanComplete){matchCountExact=!1;break}}return generation!==this.searchGeneration?this.searchMatches.length:this.searchState.publish(matches,matchCountExact)?(this.searchActiveIndex>=0&&await this.focusSearchMatch(this.searchActiveIndex),matches.length):0}async searchNext(){return this.searchState.step(1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}async searchPrevious(){return this.searchState.step(-1)?(await this.focusSearchMatch(this.searchActiveIndex),!0):!1}clearSearch(){this.resetSearchState(),this.clearSearchPaint(),this.searchState.emit()}resetSearchState(){this.searchGeneration++,this.searchState.reset()}async focusSearchMatch(index){const match=this.searchMatches[index];match&&(await this.goToPage(match.page),await this.textLayerReadyPromises.get(match.page),this.paintSearchMatches(match.page))}clearSearchPaint(container){const containers=container?[container]:this.textLayerContainers.values();for(const target of containers){target.querySelectorAll('mark[part~="search-match"]').forEach(mark=>{unwrapTextMark(mark)});for(const cached of this.mountedPageTextIndexes.values())cached.container===target&&(cached.mappingDirty=!0)}}paintSearchMatches(page){const container=this.textLayerContainers.get(page);if(!container)return;this.clearSearchPaint(container);const count=Math.min(this.searchMatches.length,MAX_PAINTED_SEARCH_MATCHES),half=MAX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchActiveIndex<0?0:this.searchActiveIndex,start=Math.max(0,Math.min(centre-half,this.searchMatches.length-count)),pageMatches=[];for(let matchIndex=start;matchIndex<start+count;matchIndex++){const match=this.searchMatches[matchIndex];match?.page===page&&pageMatches.push({match,matchIndex})}if(pageMatches.length===0)return;const active=pageMatches.find(({matchIndex})=>matchIndex===this.searchActiveIndex),nonOverlapping=[];for(const candidate of active?[active,...pageMatches.filter(entry=>entry!==active)]:pageMatches){const candidateEnd=candidate.match.start+candidate.match.length;nonOverlapping.some(({match})=>candidate.match.start<match.start+match.length&&match.start<candidateEnd)||nonOverlapping.push(candidate)}const mounted=this.mountedPageTextIndex(page);if(!mounted)return;const materialized=rangesFromTextQuoteMatches(mounted.scope,nonOverlapping.map(({match})=>({start:match.start,end:match.start+match.length}))),ranges=[];for(let position=0;position<nonOverlapping.length;position++){const{match,matchIndex}=nonOverlapping[position],range=materialized[position]??null;range&&ranges.push({matchIndex,match,range})}ranges.sort((a,b)=>b.match.start-a.match.start);const budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:this.remainingSearchMarkBudget(container)};let painted=!1;for(const{matchIndex,range}of ranges){const part=matchIndex===this.searchActiveIndex?"search-match search-match-active":"search-match";wrapPdfSearchRange(range,part,budget).length>0&&(painted=!0)}painted&&(mounted.mappingDirty=!0)}remainingSearchMarkBudget(except){let remaining=MAX_PAINTED_SEARCH_MARKS;for(const container of this.textLayerContainers.values()){if(container===except)continue;const count=container.querySelectorAll('mark[part~="search-match"]').length;if(remaining-=Math.min(remaining,count),remaining<=0)return 0}return remaining}resolveMountedPageHighlights(){const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),pages=[...this.pageCanvases.keys()].filter(pageNumber=>this.textLayerContainers.has(pageNumber)).sort((left,right)=>left-right),active=this.activeHighlightId?candidates.find(highlight=>highlight.id===this.activeHighlightId):void 0,activePage=active?.anchor.kind==="page"?active.anchor.page:active?.anchor.kind==="region"?active.anchor.page??this.page:active?.anchor.kind==="text-quote"?active.anchor.page:void 0;activePage!==void 0&&pages.sort((left,right)=>+(right===activePage)-+(left===activePage));for(const layer of this.pageHighlightLayerElements.values())layer.items=[];this.pageHighlightItems.clear();const results=new Map;for(const pageNumber of pages)results.set(pageNumber,[]);const textIndexes=new Map,searchPaintPages=new Set,budget={work:{remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},remainingResolutionAttempts:MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS,remainingItems:MAX_PAINTED_HIGHLIGHTS,remainingRects:MAX_HIGHLIGHT_RECTS},plans=[],textOptionsByPage=new Map,pageRects=new Map;for(const highlight of candidates){const options=[];for(const pageNumber of this.mountedPagesForHighlight(highlight.anchor,pages)){const container=this.textLayerContainers.get(pageNumber),canvas=this.pageCanvases.get(pageNumber);if(!container||!canvas||this.loadState.kind!=="ready")continue;let pageRect=pageRects.get(pageNumber);pageRect||(pageRect=canvas.getBoundingClientRect(),pageRects.set(pageNumber,pageRect));let textIndex;if(highlight.anchor.kind==="text-quote"){if(budget.remainingResolutionAttempts<=0)break;if(textIndexes.has(pageNumber)||(container.querySelector('mark[part~="search-match"]')&&(searchPaintPages.add(pageNumber),this.clearSearchPaint(container)),textIndexes.set(pageNumber,this.mountedPageTextIndex(pageNumber))),textIndex=textIndexes.get(pageNumber)??void 0,!textIndex)continue;budget.remainingResolutionAttempts--;const match=textIndex.index.resolve(highlight.anchor,budget.work);if(!match)continue;const option={pageNumber,pageRect,textIndex,match};options.push(option);const pageOptions=textOptionsByPage.get(pageNumber)??[];pageOptions.push(option),textOptionsByPage.set(pageNumber,pageOptions);continue}options.push({pageNumber,pageRect})}plans.push({highlight,options})}for(const[pageNumber,options]of textOptionsByPage){const textIndex=textIndexes.get(pageNumber);if(!textIndex)continue;const ranges=rangesFromTextQuoteMatches(textIndex.scope,options.map(({match})=>match));for(let position=0;position<options.length;position++)options[position].range=ranges[position]??null}candidateLoop:for(const{highlight,options}of plans){if(budget.remainingItems<=0||budget.remainingRects<=0)break;for(const{pageNumber,pageRect,range}of options){const rects=this.resolveHighlightRectsForPage(highlight.anchor,pageNumber,pageRect,budget,range);if(rects.length!==0){results.get(pageNumber).push({id:highlight.id,rects,label:highlight.label,tone:highlight.tone}),budget.remainingItems--;continue candidateLoop}}}for(const[pageNumber,pageItems]of results){this.pageHighlightItems.set(pageNumber,pageItems);const layer=this.pageHighlightLayerElements.get(pageNumber);layer&&(layer.items=pageItems)}for(const pageNumber of searchPaintPages)this.paintSearchMatches(pageNumber)}*mountedPagesForHighlight(anchor,mountedPages){const addressedPage=anchor.kind==="page"?anchor.page:anchor.kind==="region"?anchor.page??this.page:anchor.kind==="text-quote"?anchor.page:void 0;if(addressedPage!==void 0){mountedPages.includes(addressedPage)&&(yield addressedPage);return}if(anchor.kind==="text-quote")for(const pageNumber of mountedPages)yield pageNumber}resolveHighlightRectsForPage(anchor,pageNumber,pageRect,budget,range){if(anchor.kind==="page"&&anchor.page===pageNumber)return budget.remainingRects<=0?[]:(budget.remainingRects--,[{x:0,y:0,width:100,height:100}]);if(anchor.kind==="region"&&(anchor.page??pageNumber)===pageNumber){const rect=sanitizePercentRect(anchor.rect);return!rect||budget.remainingRects<=0?[]:(budget.remainingRects--,[rect])}if(anchor.kind==="text-quote"&&range&&(anchor.page==null||anchor.page===pageNumber)){if(!(pageRect.width>0)||!(pageRect.height>0))return[];const rects=[];for(const rect of range.getClientRects()){if(rects.length>=budget.remainingRects)return[];rects.push({x:(rect.left-pageRect.left)/pageRect.width*100,y:(rect.top-pageRect.top)/pageRect.height*100,width:rect.width/pageRect.width*100,height:rect.height/pageRect.height*100})}return budget.remainingRects-=rects.length,rects}return[]}highlightLayerRef(pageNumber){let callback=this.highlightLayerRefs.get(pageNumber);return callback||(callback=element=>{if(!element){this.pageHighlightLayerElements.delete(pageNumber),this.pageHighlightItems.delete(pageNumber),this.highlightLayerRefs.delete(pageNumber);return}const layer=element;this.pageHighlightLayerElements.set(pageNumber,layer),layer.items=this.pageHighlightItems.get(pageNumber)??[],layer.activeHighlightId=this.activeHighlightId;const canvas=this.pageCanvases.get(pageNumber);canvas?.style.width&&(layer.style.width=canvas.style.width,layer.style.height=canvas.style.height)},this.highlightLayerRefs.set(pageNumber,callback)),callback}onPageClick(pageNumber,e){const canvas=this.pageCanvases.get(pageNumber),selection=canvas?.ownerDocument.defaultView?.getSelection();if(selection&&!selection.isCollapsed)return;const items=this.pageHighlightItems.get(pageNumber);if(!canvas||!items||items.length===0)return;const pageRect=canvas.getBoundingClientRect(),xPct=(e.clientX-pageRect.left)/pageRect.width*100,yPct=(e.clientY-pageRect.top)/pageRect.height*100;for(let i=items.length-1;i>=0;i--){const item=items[i];if(!item)continue;if(item.rects.some(rect=>xPct>=rect.x&&xPct<=rect.x+rect.width&&yPct>=rect.y&&yPct<=rect.y+rect.height)){this.emit("lr-highlight-activate",{highlightId:item.id});return}}}renderToolbar(){if(this.loadState.kind!=="ready")return html``;const{pageCount}=this.loadState,numberFormat=getNumberFormat(this.effectiveLocale),formattedZoom=numberFormat.format(Math.round(this.zoom*100));return html`<div part="toolbar">
12
12
  <button type="button" part="previous-button" data-action="previous" ?disabled=${this.page<=1} @click=${this.previousPage}>${this.localize("pdfViewerPreviousPage")}</button>
13
13
  <span part="page-indicator">${this.localize("pdfViewerPageOf",void 0,{page:numberFormat.format(this.page),total:numberFormat.format(pageCount)})}</span>
14
14
  <button type="button" part="next-button" data-action="next" ?disabled=${this.page>=pageCount} @click=${this.nextPage}>${this.localize("pdfViewerNextPage")}</button>
@@ -21,7 +21,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
21
21
  .items=${guard([sheet.body],()=>sheet.body.length<=1e4?sheet.body:nothing)}
22
22
  .source=${this.table.indexedSource(sheet.body)}
23
23
  .renderItem=${this.table.rowRenderer(sheet,[this.table.columnWindow(sheet.name,count).columns,this.activeHighlightId,this.strings],(row,bodyIndex)=>this.renderRow(row,count,"data-row",bodyIndex+2,sheet.name))}
24
- .keyFunction=${this.virtualListKeyFunction}
24
+ .keyFunction=${sheet.body.length<=1e4?this.virtualListKeyFunction:void 0}
25
25
  .activeItemId=${index===this.activeRowSheet?this.table.activeRowKey:""}
26
26
  item-role="row"
27
27
  row-index-offset="1"
@@ -13,10 +13,10 @@ import{SourceRequestController,sourceCount,sourceRevision}from"../../internal/so
13
13
  >
14
14
  ${text}
15
15
  </button>
16
- </div>`}columnWindow(key,count,limit=count){if(this.geometryWidth===void 0){const view=this.host.ownerDocument.defaultView,token=view?.getComputedStyle(this.host).getPropertyValue("--lr-size-8rem").trim()||"8rem";if(this.geometryWidth=Math.max(1,resolveCssTokenLength(token,{host:this.host})??1),this.hooks.pageScroll?.()&&view){const rect=this.host.getBoundingClientRect(),leading=view.getComputedStyle(this.host).direction==="rtl"?view.innerWidth-rect.right:rect.left;this.geometryAllocation=Math.max(0,view.innerWidth-Math.max(0,leading)),this.pageOffset=Math.max(0,-leading)}else this.geometryAllocation=this.host.clientWidth}const width=this.geometryWidth,allocation=this.geometryAllocation??0;let window=this.windows.get(key);const offset=this.hooks.pageScroll?.()?this.forcedPageOffset??this.pageOffset:window?.offset??0,start=Math.min(Math.max(0,count-1),Math.max(0,Math.floor(offset/width)-2)),end=Math.min(count,start+Math.max(1,limit),Math.max(start+1,Math.ceil((offset+allocation)/width)+4));return(!window||window.count!==count||window.width!==width||window.start!==start||window.end!==end)&&(window={start,end,count,width,offset,columns:Array.from({length:end-start},(_,index)=>start+index),style:`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr));min-inline-size:calc(${count} * var(--lr-size-8rem))`},this.windows.set(key,window)),window}scrollColumns(key,target){this.setColumnOffset(key,Math.abs(target.scrollLeft))}setColumnOffset(key,offset){const window=this.windows.get(key);if(!window||window.offset===offset)return;window.offset=offset;const previous=window.columns;this.columnWindow(key,window.count).columns!==previous&&this.hooks.repaint()}async showColumn(key,col,scroller){const window=this.windows.get(key);if(!(!window||!scroller)&&(col<window.start||col>=window.end)){const rtl=this.host.ownerDocument.defaultView?.getComputedStyle(this.host).direction==="rtl";scroller.scrollLeft=(rtl?-1:1)*col*window.width,this.hooks.pageScroll?.()?(this.forcedPageOffset=col*window.width,this.setColumnOffset(key,this.forcedPageOffset)):this.scrollColumns(key,scroller),await this.host.updateComplete}}rowRenderer(key,inputs,render){const dependencies=[...inputs,this.highlights,this.hooks.locale(),this.hooks.localize("highlightWithLabel"),this.hooks.localize("cellHighlightWithLabel")],existing=this.renderers.get(key);if(existing&&dependencies.length===existing.inputs.length&&dependencies.every((value,index)=>value===existing.inputs[index]))return existing.render;const rows=new Map,memo=(row,index)=>{const existing2=rows.get(index);if(existing2&&existing2.row===row)return existing2.result;const result=render(row,index);return rows.set(index,{row,result}),rows.size>256&&rows.delete(rows.keys().next().value),result};return this.renderers.set(key,{inputs:dependencies,render:memo}),memo}revealCell(target){return this.scroll.reveal(target),!!target}scrollColumnIntoView(root,selector,col){return this.scroll.scrollColumnIntoView(root.querySelector(selector),col)}async runSearch(query,loaded,scan,source=scan){this.search.query=query;const locale=this.hooks.locale();this.lastLocale=locale;const bounded=boundedViewerSearchQuery(query,locale),matches=[];let exact=bounded.accepted;if(loaded&&bounded.accepted&&bounded.needle){let corpus=this.searchCorpus;if(!corpus||corpus.source!==source||corpus.locale!==locale){const budget=new ViewerSearchWorkBudget,fields=[];scan((text,match)=>(fields.push({text:budget.prepare(text,locale),match}),budget.complete)),corpus={source,locale,fields,exact:budget.complete},this.searchCorpus=corpus}exact=corpus.exact;for(const field of corpus.fields)if(field.text?.includes(bounded.needle)){if(matches.length===MAX_TABLE_SEARCH_MATCHES){exact=!1;break}matches.push(field.match)}}return this.search.publish(matches,exact),matches.length>0&&await this.hooks.jump(matches[0]),matches.length}async step(direction){return this.search.step(direction)?await this.hooks.jump(this.search.matches[this.search.activeIndex])!==!1:!1}clearSearch(){this.activeRowKey="",this.search.clear()}}const TABLE_VIEWER_SOURCE_MESSAGE_KEYS={documentPreviewResourceTooLarge:"documentPreviewResourceTooLarge",documentPreviewFailedToLoad:"documentPreviewFailedToLoad",noData:"noData",loadingDocument:"loadingDocument",sourceSearchUnavailable:"sourceSearchUnavailable"};class TableViewerSourceController{constructor(host,chrome,hooks){this.host=host,this.chrome=chrome,this.hooks=hooks,this.locale="",this.limit=0,this.dirty=!0,this.bindingIntent=0,this.sheets=[],this.sheetIndex=0,this.rows=0,this.columns=0,this.slots=[],this.physicalReads=0,this.epoch=0,this.paint=0,this.firstRow=0,this.visibleRows=0,this.windowIntent=0,this.activeRow="",this.windowColumns=[],this.labels=[],this.columnStart=0,this.labelUnits=0,this.loaded=!1,this.pendingPaint=!1,this.sourceRows=this.makeRows(),this.searchRunning=!1,this.onRange=event=>{if(event.stopPropagation(),!this.loaded||event.currentTarget.source!==this.sourceRows)return;const start=Math.min(this.rows,event.detail.start),row=Math.max(0,start-6),visible=Math.max(0,Math.min(this.rows,event.detail.end)-start);row===this.firstRow&&visible===this.visibleRows||(this.visibleRows=visible,this.firstRow=row,this.requestWindow(),this.notify())},this.searchState=new ViewerSearchState(()=>[],detail=>hooks.emitSearch(detail),()=>hooks.repaint()),this.authority=new SourceRequestController(host,{channels:["cells0","cells1","search","reveal"],onReset:()=>this.reset()}),host.addController(this)}get enabled(){return this.hooks.source()!==void 0}get busy(){return this.enabled&&!this.failure&&this.slots.some(slot=>slot.state!=="ready")}makeRows(){return{count:this.rows,itemAt:index=>index,keyAt:index=>index,indexOfKey:key=>typeof key=="number"&&Number.isSafeInteger(key)&&key>=0&&key<this.rows?key:-1}}notify(){if(this.pendingPaint)return;this.pendingPaint=!0;const document=this.host.ownerDocument;queueMicrotask(()=>{this.pendingPaint=!1,this.host.isConnected&&this.host.ownerDocument===document&&this.hooks.repaint()})}reset(){this.epoch++,this.dirty=!0;for(const slot of this.slots)slot.settle(!1);this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.failure=void 0,this.loaded=!1,this.firstRow=0,this.visibleRows=0,this.paint++,this.queuedSearch=void 0,this.notify()}refresh(){this.bindingIntent++,this.hooks.cancelAnchor(),this.authority.refresh()}hostConnected(){this.dirty=!0,this.notify()}hostDisconnected(){this.dirty=!0}adopted(){this.hooks.cancelAnchor(),this.authority.adopted()}update(){const source=this.hooks.source(),intent=this.bindingIntent,locale=this.hooks.locale(),limit=this.hooks.columnLimit();if(!(source===this.bound&&this.failure&&!this.dirty&&locale===this.locale&&limit===this.limit))try{const revision=source===void 0?void 0:sourceRevision(source.revision);if(source===this.bound&&revision===this.revision&&locale===this.locale&&limit===this.limit&&!this.dirty||source!==this.hooks.source()||intent!==this.bindingIntent||(source===this.bound&&(revision!==this.revision||locale!==this.locale||limit!==this.limit)&&this.hooks.cancelAnchor(),this.authority.setSource(source,revision),source!==this.hooks.source()||intent!==this.bindingIntent))return;source===this.bound&&revision===this.revision&&(locale!==this.locale||limit!==this.limit)&&this.authority.refresh();const epoch=this.epoch;if(this.bound=source,this.revision=revision,this.locale=locale,this.limit=limit,this.dirty=!1,this.failure=void 0,this.sheetIndex=0,this.firstRow=0,this.activeRow="",this.searchState.dirty&&this.searchState.clear(),source===void 0){this.theme&&(this.theme.hostDisconnected(),this.host.removeController(this.theme),this.theme=void 0),this.sheets=[],this.sheet=void 0;return}this.theme??=new ThemeWatcher(this.host,()=>this.notify());let sheets;if(this.hooks.workbook){const raw=source.sheets;if(!Array.isArray(raw)||raw.length>256)throw new LyraResourceLimitError;const keys=new Set,names=new Set;sheets=raw.map(entry=>{if(!entry||typeof entry.key!="string"||!entry.key||typeof entry.name!="string"||!entry.name||keys.has(entry.key)||names.has(entry.name))throw new TypeError("Invalid source sheet");if(entry.key.length>65536||entry.name.length>65536)throw new LyraResourceLimitError;return keys.add(entry.key),names.add(entry.name),Object.freeze({key:entry.key,name:entry.name,data:entry.data})})}else sheets=[{key:"",name:"",data:source}];if(!this.current(epoch))return;this.sheets=Object.freeze(sheets),this.selectSheet(0)}catch(error){if(this.hooks.source()!==source)return;this.bound=source,this.locale=locale,this.limit=limit,this.dirty=!1,this.fail(error)}}current(epoch){return epoch===this.epoch&&this.hooks.source()===this.bound&&this.host.isConnected}fail(error){this.failure!==error&&(this.failure=error,this.hooks.error(error),this.notify())}selectSheet(index){this.authority.invalidate("cells0"),this.authority.invalidate("cells1"),this.authority.invalidate("reveal");for(const slot of this.slots)slot.settle(!1);if(this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.firstRow=0,this.visibleRows=0,this.activeRow="",this.sheetIndex=index,this.sheet=this.sheets[index],this.paint++,!this.sheet){this.rows=this.columns=0,this.sourceRows=this.makeRows();return}const data=this.sheet.data,epoch=this.epoch,revision=sourceRevision(data.revision),rows=sourceCount(data.rowCount),columns=sourceCount(data.columnCount);if(rows>=Number.MAX_SAFE_INTEGER||columns>this.limit)throw new LyraResourceLimitError;if(typeof data.columnAt!="function"||typeof data.cellAt=="function"==(typeof data.readCells=="function"))throw new TypeError("Invalid cell source");this.current(epoch)&&(this.sheetRevision=revision,this.rows=rows,this.columns=columns,this.sourceRows=this.makeRows(),this.loaded=!0,this.host.shadowRoot?.querySelector(tag("virtual-list"))?.scrollToIndex(0,{align:"start",behavior:"auto"}))}scalar(value){if(value!=null&&typeof value!="string"&&typeof value!="boolean"&&(typeof value!="number"||!Number.isFinite(value)))throw new TypeError("Invalid source cell");const text=this.hooks.format(value);if(text.length>65536)throw new LyraResourceLimitError;return text}prepareColumns(columns){if(this.windowColumns===columns||!this.sheet)return;const epoch=this.epoch,sheet=this.sheet,labels=[];let units=0;for(const index of columns){const column=sheet.data.columnAt(index);if(!this.current(epoch)||this.sheet!==sheet)return;if(!column||typeof column.key!="string"||!column.key||typeof column.label!="string")throw new TypeError("Invalid source column");if(column.key.length>65536||column.label.length>65536)throw new LyraResourceLimitError;if(units+=column.key.length+column.label.length,units>2e6)throw new LyraResourceLimitError;labels.push(Object.freeze({key:column.key,label:column.label}))}this.labels=labels,this.labelUnits=units,this.windowColumns=columns,this.columnStart=columns[0]??0,this.paint++,this.requestWindow()}requestWindow(){if(!this.sheet||!this.loaded||!this.windowColumns.length||!this.rows||this.failure)return;const epoch=this.epoch,intent=++this.windowIntent,maximum=Math.min(500,Math.floor(1e4/this.windowColumns.length)),first=Math.min(this.firstRow,this.rows-1),demand=Math.min(this.rows-first,this.visibleRows+12),block=Math.min(maximum,Math.max(64,demand));if(demand>maximum*2){this.fail(new LyraResourceLimitError);return}const aligned=Math.floor(first/block)*block,row=first-aligned+demand<=block*2?aligned:first,starts=row+block<this.rows?[row,row+block]:[row],keys=starts.map(start=>`${this.sheetIndex}:${start}:${block}:${this.columnStart}:${this.windowColumns.length}`),previous=this.slots;this.slots=previous.filter(slot=>keys.includes(slot.key));for(const slot of previous)if(!this.slots.includes(slot)&&(slot.settle(!1),this.authority.invalidate(slot.channel),!this.current(epoch)||intent!==this.windowIntent))return;for(let index=0;index<starts.length;index++){if(this.slots.some(slot2=>slot2.key===keys[index]))continue;const channel=this.slots.some(slot2=>slot2.channel==="cells0")?"cells1":"cells0",lease=this.authority.begin(channel,this.locale);if(!lease||!this.current(epoch)||intent!==this.windowIntent)return;let settle;const promise=new Promise(resolve=>{settle=resolve}),slot={key:keys[index],channel,row:starts[index],rows:Math.min(block,this.rows-starts[index]),column:this.columnStart,columns:this.windowColumns.length,lease,source:this.sheet.data,promise,settle,state:"queued",units:0};lease.context.signal.addEventListener("abort",()=>slot.settle(!1),{once:!0}),this.slots.push(slot)}this.paint++,queueMicrotask(()=>this.pump())}pump(){for(;this.physicalReads<2;){const slot=this.slots.find(value=>value.state==="queued"&&value.lease.isCurrent());if(!slot)return;slot.state="loading",this.physicalReads++,this.read(slot)}}async read(slot){try{const source=slot.source,result=source.readCells?await source.readCells(Object.freeze({...slot.lease.context,revision:this.sheetRevision,row:slot.row,rowCount:slot.rows,column:slot.column,columnCount:slot.columns})):void 0;if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;if(result!==void 0&&(!Array.isArray(result)||result.length!==slot.rows))throw new TypeError("Invalid source rectangle");const values=[];let units=this.labelUnits+this.slots.reduce((sum,other)=>sum+(other===slot?0:other.units),0);const initialUnits=units;for(let row=0;row<slot.rows;row++){const input=result?.[row];if(result!==void 0&&(!Array.isArray(input)||input.length!==slot.columns))throw new TypeError("Invalid source rectangle row");const cells=[];for(let col=0;col<slot.columns;col++){const value=result!==void 0?input[col]:source.cellAt(slot.row+row,slot.column+col);if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;const text=this.scalar(value);if(units+=text.length,units>2e6)throw new LyraResourceLimitError;cells.push(text)}values.push(cells)}slot.values=values,slot.units=units-initialUnits,slot.state="ready",slot.settle(!0),this.paint++,this.notify()}catch(error){slot.lease.isCurrent()&&this.slots.includes(slot)&&this.fail(error),slot.settle(!1)}finally{this.physicalReads--,this.pump()}}scrollColumns(target){this.chrome.scrollColumns(this,target)}row(index,style,height){const slot=this.slots.find(value=>index>=value.row&&index<value.row+value.rows&&value.state==="ready"),rawRow=index+1+Number(this.hooks.header()),highlights=this.chrome.highlightsForRow(rawRow,this.hooks.workbook?this.sheet?.name:void 0);return html`<div part="data-row" role="presentation" aria-busy=${slot?"false":"true"} style=${`${style};height:${height}px;overflow:hidden`}>
16
+ </div>`}columnWindow(key,count,limit=count){if(this.geometryWidth===void 0){const view=this.host.ownerDocument.defaultView,token=view?.getComputedStyle(this.host).getPropertyValue("--lr-size-8rem").trim()||"8rem";if(this.geometryWidth=Math.max(1,resolveCssTokenLength(token,{host:this.host})??1),this.hooks.pageScroll?.()&&view){const rect=this.host.getBoundingClientRect(),leading=view.getComputedStyle(this.host).direction==="rtl"?view.innerWidth-rect.right:rect.left;this.geometryAllocation=Math.max(0,view.innerWidth-Math.max(0,leading)),this.pageOffset=Math.max(0,-leading)}else this.geometryAllocation=this.host.clientWidth}const width=this.geometryWidth,allocation=this.geometryAllocation??0;let window=this.windows.get(key);const offset=this.hooks.pageScroll?.()?this.forcedPageOffset??this.pageOffset:window?.offset??0,start=Math.min(Math.max(0,count-1),Math.max(0,Math.floor(offset/width)-2)),end=Math.min(count,start+Math.max(1,limit),Math.max(start+1,Math.ceil((offset+allocation)/width)+4));return(!window||window.count!==count||window.width!==width||window.start!==start||window.end!==end)&&(window={start,end,count,width,offset,columns:Array.from({length:end-start},(_,index)=>start+index),style:`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr));min-inline-size:calc(${count} * var(--lr-size-8rem))`},this.windows.set(key,window)),window}scrollColumns(key,target){this.setColumnOffset(key,Math.abs(target.scrollLeft))}setColumnOffset(key,offset){const window=this.windows.get(key);if(!window||window.offset===offset)return;window.offset=offset;const previous=window.columns;this.columnWindow(key,window.count).columns!==previous&&this.hooks.repaint()}async showColumn(key,col,scroller){const window=this.windows.get(key);if(!(!window||!scroller)&&(col<window.start||col>=window.end)){const rtl=this.host.ownerDocument.defaultView?.getComputedStyle(this.host).direction==="rtl";scroller.scrollLeft=(rtl?-1:1)*col*window.width,this.hooks.pageScroll?.()?(this.forcedPageOffset=col*window.width,this.setColumnOffset(key,this.forcedPageOffset)):this.scrollColumns(key,scroller),await this.host.updateComplete}}rowRenderer(key,inputs,render){const dependencies=[...inputs,this.highlights,this.hooks.locale(),this.hooks.localize("highlightWithLabel"),this.hooks.localize("cellHighlightWithLabel")],existing=this.renderers.get(key);if(existing&&dependencies.length===existing.inputs.length&&dependencies.every((value,index)=>value===existing.inputs[index]))return existing.render;const rows=new Map,memo=(row,index)=>{const existing2=rows.get(index);if(existing2&&existing2.row===row)return existing2.result;const result=render(row,index);return rows.set(index,{row,result}),rows.size>256&&rows.delete(rows.keys().next().value),result};return this.renderers.set(key,{inputs:dependencies,render:memo}),memo}revealCell(target){return this.scroll.reveal(target),!!target}scrollColumnIntoView(root,selector,col){return this.scroll.scrollColumnIntoView(root.querySelector(selector),col)}async runSearch(query,loaded,scan,source=scan){this.search.query=query;const locale=this.hooks.locale();this.lastLocale=locale;const bounded=boundedViewerSearchQuery(query,locale),matches=[];let exact=bounded.accepted;if(loaded&&bounded.accepted&&bounded.needle){let corpus=this.searchCorpus;if(!corpus||corpus.source!==source||corpus.locale!==locale){const budget=new ViewerSearchWorkBudget,fields=[];scan((text,match)=>(fields.push({text:budget.prepare(text,locale),match}),budget.complete)),corpus={source,locale,fields,exact:budget.complete},this.searchCorpus=corpus}exact=corpus.exact;for(const field of corpus.fields)if(field.text?.includes(bounded.needle)){if(matches.length===MAX_TABLE_SEARCH_MATCHES){exact=!1;break}matches.push(field.match)}}return this.search.publish(matches,exact)?(matches.length>0&&await this.hooks.jump(matches[0]),matches.length):0}async step(direction){return this.search.step(direction)?await this.hooks.jump(this.search.matches[this.search.activeIndex])!==!1:!1}clearSearch(){this.activeRowKey="",this.search.clear()}}const TABLE_VIEWER_SOURCE_MESSAGE_KEYS={documentPreviewResourceTooLarge:"documentPreviewResourceTooLarge",documentPreviewFailedToLoad:"documentPreviewFailedToLoad",noData:"noData",loadingDocument:"loadingDocument",sourceSearchUnavailable:"sourceSearchUnavailable"};class TableViewerSourceController{constructor(host,chrome,hooks){this.host=host,this.chrome=chrome,this.hooks=hooks,this.locale="",this.limit=0,this.dirty=!0,this.bindingIntent=0,this.sheetIntent=0,this.sheets=[],this.sheetIndex=0,this.rows=0,this.columns=0,this.slots=[],this.physicalReads=0,this.epoch=0,this.paint=0,this.firstRow=0,this.visibleRows=0,this.windowIntent=0,this.activeRow="",this.windowColumns=[],this.labels=[],this.columnStart=0,this.labelUnits=0,this.loaded=!1,this.pendingPaint=!1,this.sourceRows=this.makeRows(),this.searchRunning=!1,this.searchIntent=0,this.onRange=event=>{if(event.stopPropagation(),!this.loaded||event.currentTarget.source!==this.sourceRows)return;const start=Math.min(this.rows,event.detail.start),row=Math.max(0,start-6),visible=Math.max(0,Math.min(this.rows,event.detail.end)-start);row===this.firstRow&&visible===this.visibleRows||(this.visibleRows=visible,this.firstRow=row,this.requestWindow(),this.notify())},this.searchState=new ViewerSearchState(()=>[],detail=>hooks.emitSearch(detail),()=>hooks.repaint()),this.authority=new SourceRequestController(host,{channels:["cells0","cells1","search","reveal"],onReset:()=>this.reset()}),host.addController(this)}get enabled(){return this.hooks.source()!==void 0}get busy(){return this.enabled&&!this.failure&&this.slots.some(slot=>slot.state!=="ready")}makeRows(){return{count:this.rows,itemAt:index=>index,keyAt:index=>index,indexOfKey:key=>typeof key=="number"&&Number.isSafeInteger(key)&&key>=0&&key<this.rows?key:-1}}notify(){if(this.pendingPaint)return;this.pendingPaint=!0;const document=this.host.ownerDocument;queueMicrotask(()=>{this.pendingPaint=!1,this.host.isConnected&&this.host.ownerDocument===document&&this.hooks.repaint()})}reset(){this.epoch++,this.searchIntent++,this.dirty=!0;for(const slot of this.slots)slot.settle(!1);this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.failure=void 0,this.loaded=!1,this.firstRow=0,this.visibleRows=0,this.paint++,this.queuedSearch=void 0,this.notify()}refresh(){this.bindingIntent++,this.hooks.cancelAnchor(),this.authority.refresh()}hostConnected(){this.dirty=!0,this.notify()}hostDisconnected(){this.dirty=!0}adopted(){this.hooks.cancelAnchor(),this.authority.adopted()}update(){const source=this.hooks.source(),intent=this.bindingIntent,locale=this.hooks.locale(),limit=this.hooks.columnLimit();if(!(source===this.bound&&this.failure&&!this.dirty&&locale===this.locale&&limit===this.limit))try{const revision=source===void 0?void 0:sourceRevision(source.revision);if(source===this.bound&&revision===this.revision&&locale===this.locale&&limit===this.limit&&!this.dirty||source!==this.hooks.source()||intent!==this.bindingIntent||(source===this.bound&&(revision!==this.revision||locale!==this.locale||limit!==this.limit)&&this.hooks.cancelAnchor(),this.authority.setSource(source,revision),source!==this.hooks.source()||intent!==this.bindingIntent))return;source===this.bound&&revision===this.revision&&(locale!==this.locale||limit!==this.limit)&&this.authority.refresh();const epoch=this.epoch;if(this.bound=source,this.revision=revision,this.locale=locale,this.limit=limit,this.dirty=!1,this.failure=void 0,this.sheetIndex=0,this.firstRow=0,this.activeRow="",this.searchState.dirty&&this.searchState.clear(),source===void 0){this.theme&&(this.theme.hostDisconnected(),this.host.removeController(this.theme),this.theme=void 0),this.sheets=[],this.sheet=void 0;return}this.theme??=new ThemeWatcher(this.host,()=>this.notify());let sheets;if(this.hooks.workbook){const raw=source.sheets;if(!Array.isArray(raw)||raw.length>256)throw new LyraResourceLimitError;const keys=new Set,names=new Set;sheets=raw.map(entry=>{if(!entry||typeof entry.key!="string"||!entry.key||typeof entry.name!="string"||!entry.name||keys.has(entry.key)||names.has(entry.name))throw new TypeError("Invalid source sheet");if(entry.key.length>65536||entry.name.length>65536)throw new LyraResourceLimitError;return keys.add(entry.key),names.add(entry.name),Object.freeze({key:entry.key,name:entry.name,data:entry.data})})}else sheets=[{key:"",name:"",data:source}];if(!this.current(epoch))return;this.sheets=Object.freeze(sheets),this.selectSheet(0)}catch(error){if(this.hooks.source()!==source)return;this.bound=source,this.locale=locale,this.limit=limit,this.dirty=!1,this.fail(error)}}current(epoch){return epoch===this.epoch&&this.hooks.source()===this.bound&&this.host.isConnected}fail(error){this.failure!==error&&(this.failure=error,this.hooks.error(error),this.notify())}selectSheet(index){const intent=++this.sheetIntent,epoch=this.epoch,current=()=>intent===this.sheetIntent&&this.current(epoch);for(const channel of["cells0","cells1","reveal"])if(this.authority.invalidate(channel),!current())return!1;for(const slot of this.slots)slot.settle(!1);if(this.slots=[],this.windowColumns=[],this.labels=[],this.labelUnits=0,this.firstRow=0,this.visibleRows=0,this.activeRow="",this.sheetIndex=index,this.sheet=this.sheets[index],this.paint++,!this.sheet)return this.rows=this.columns=0,this.sourceRows=this.makeRows(),!0;const data=this.sheet.data;try{const revision=sourceRevision(data.revision);if(!current())return!1;const rows=sourceCount(data.rowCount);if(!current())return!1;const columns=sourceCount(data.columnCount);if(!current())return!1;if(rows>=Number.MAX_SAFE_INTEGER||columns>this.limit)throw new LyraResourceLimitError;const columnAt=data.columnAt;if(!current())return!1;const cellAt=data.cellAt;if(!current())return!1;const readCells=data.readCells;if(!current())return!1;if(typeof columnAt!="function"||typeof cellAt=="function"==(typeof readCells=="function"))throw new TypeError("Invalid cell source");return this.sheetRevision=revision,this.rows=rows,this.columns=columns,this.sourceRows=this.makeRows(),this.loaded=!0,this.host.shadowRoot?.querySelector(tag("virtual-list"))?.scrollToIndex(0,{align:"start",behavior:"auto"}),current()}catch(error){if(current())throw error;return!1}}scalar(value){if(value!=null&&typeof value!="string"&&typeof value!="boolean"&&(typeof value!="number"||!Number.isFinite(value)))throw new TypeError("Invalid source cell");const text=this.hooks.format(value);if(text.length>65536)throw new LyraResourceLimitError;return text}prepareColumns(columns){if(this.windowColumns===columns||!this.sheet)return;const epoch=this.epoch,sheet=this.sheet,intent=this.sheetIntent,current=()=>this.current(epoch)&&this.sheet===sheet&&this.sheetIntent===intent,labels=[];let units=0;for(const index of columns){const column=sheet.data.columnAt(index);if(!current())return;if(!column)throw new TypeError("Invalid source column");const key=column.key;if(!current())return;const label=column.label;if(!current())return;if(typeof key!="string"||!key||typeof label!="string")throw new TypeError("Invalid source column");if(key.length>65536||label.length>65536)throw new LyraResourceLimitError;if(units+=key.length+label.length,units>2e6)throw new LyraResourceLimitError;labels.push(Object.freeze({key,label}))}this.labels=labels,this.labelUnits=units,this.windowColumns=columns,this.columnStart=columns[0]??0,this.paint++,this.requestWindow()}requestWindow(){if(!this.sheet||!this.loaded||!this.windowColumns.length||!this.rows||this.failure)return;const epoch=this.epoch,intent=++this.windowIntent,maximum=Math.min(500,Math.floor(1e4/this.windowColumns.length)),first=Math.min(this.firstRow,this.rows-1),demand=Math.min(this.rows-first,this.visibleRows+12),block=Math.min(maximum,Math.max(64,demand));if(demand>maximum*2){this.fail(new LyraResourceLimitError);return}const aligned=Math.floor(first/block)*block,row=first-aligned+demand<=block*2?aligned:first,starts=row+block<this.rows?[row,row+block]:[row],keys=starts.map(start=>`${this.sheetIndex}:${start}:${block}:${this.columnStart}:${this.windowColumns.length}`),previous=this.slots;this.slots=previous.filter(slot=>keys.includes(slot.key));for(const slot of previous)if(!this.slots.includes(slot)&&(slot.settle(!1),this.authority.invalidate(slot.channel),!this.current(epoch)||intent!==this.windowIntent))return;for(let index=0;index<starts.length;index++){if(this.slots.some(slot2=>slot2.key===keys[index]))continue;const channel=this.slots.some(slot2=>slot2.channel==="cells0")?"cells1":"cells0",lease=this.authority.begin(channel,this.locale);if(!lease||!this.current(epoch)||intent!==this.windowIntent)return;let settle;const promise=new Promise(resolve=>{settle=resolve}),slot={key:keys[index],channel,row:starts[index],rows:Math.min(block,this.rows-starts[index]),column:this.columnStart,columns:this.windowColumns.length,lease,source:this.sheet.data,promise,settle,state:"queued",units:0};lease.context.signal.addEventListener("abort",()=>slot.settle(!1),{once:!0}),this.slots.push(slot)}this.paint++,queueMicrotask(()=>this.pump())}pump(){for(;this.physicalReads<2;){const slot=this.slots.find(value=>value.state==="queued"&&value.lease.isCurrent());if(!slot)return;slot.state="loading",this.physicalReads++,this.read(slot)}}async read(slot){try{const source=slot.source,result=source.readCells?await source.readCells(Object.freeze({...slot.lease.context,revision:this.sheetRevision,row:slot.row,rowCount:slot.rows,column:slot.column,columnCount:slot.columns})):void 0;if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;if(result!==void 0&&(!Array.isArray(result)||result.length!==slot.rows))throw new TypeError("Invalid source rectangle");const values=[];let units=this.labelUnits+this.slots.reduce((sum,other)=>sum+(other===slot?0:other.units),0);const initialUnits=units;for(let row=0;row<slot.rows;row++){const input=result?.[row];if(result!==void 0&&(!Array.isArray(input)||input.length!==slot.columns))throw new TypeError("Invalid source rectangle row");const cells=[];for(let col=0;col<slot.columns;col++){const value=result!==void 0?input[col]:source.cellAt(slot.row+row,slot.column+col);if(!slot.lease.isCurrent()||!this.slots.includes(slot))return;const text=this.scalar(value);if(units+=text.length,units>2e6)throw new LyraResourceLimitError;cells.push(text)}values.push(cells)}slot.values=values,slot.units=units-initialUnits,slot.state="ready",slot.settle(!0),this.paint++,this.notify()}catch(error){slot.lease.isCurrent()&&this.slots.includes(slot)&&this.fail(error),slot.settle(!1)}finally{this.physicalReads--,this.pump()}}scrollColumns(target){this.chrome.scrollColumns(this,target)}row(index,style,height){const slot=this.slots.find(value=>index>=value.row&&index<value.row+value.rows&&value.state==="ready"),rawRow=index+1+Number(this.hooks.header()),highlights=this.chrome.highlightsForRow(rawRow,this.hooks.workbook?this.sheet?.name:void 0);return html`<div part="data-row" role="presentation" aria-busy=${slot?"false":"true"} style=${`${style};height:${height}px;overflow:hidden`}>
17
17
  ${this.windowColumns.map((column,position)=>this.chrome.renderCell(slot?.values?.[index-slot.row]?.[position]??"",column,highlights,"cell","cell",this.hooks.colorVar,this.hooks.activeHighlight()))}
18
- </div>`}render(){if(this.failure)return html`<div part="error">${this.hooks.localize(isResourceLimitError(this.failure)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`;if(!this.loaded||!this.sheet||!this.columns)return html`<p class="empty-note">${this.hooks.localize("noData")}</p>`;try{const epoch=this.epoch,window=this.chrome.columnWindow(this,this.columns,100);if(this.prepareColumns(window.columns),!this.current(epoch))return html``;if(this.failure)return html`<div part="error">${this.hooks.localize("documentPreviewFailedToLoad")}</div>`;const view=this.host.ownerDocument.defaultView,height=Math.max(1,resolveCssTokenLength(view?.getComputedStyle(this.host).getPropertyValue("--lr-size-3rem").trim()||"3rem",{host:this.host})??48),header=this.hooks.header(),search=this.hooks.workbook?this.bound.search:this.sheet.data.search;return html`
19
- ${this.hooks.workbook&&this.sheets.length>1?this.hooks.renderSheetTabs?.(this.sheets.map(sheet=>sheet.name),this.sheetIndex,index=>{if(Number.isInteger(index)&&index>=0&&index<this.sheets.length&&index!==this.sheetIndex)try{this.selectSheet(index),this.notify()}catch(error){this.fail(error)}})??nothing:nothing}
18
+ </div>`}render(){if(this.failure)return html`<div part="error">${this.hooks.localize(isResourceLimitError(this.failure)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`;if(!this.loaded||!this.sheet||!this.columns)return html`<p class="empty-note">${this.hooks.localize("noData")}</p>`;const epoch=this.epoch,intent=this.sheetIntent,current=()=>this.current(epoch)&&this.sheetIntent===intent;try{const window=this.chrome.columnWindow(this,this.columns,100);if(this.prepareColumns(window.columns),!current())return html``;if(this.failure)return html`<div part="error">${this.hooks.localize("documentPreviewFailedToLoad")}</div>`;const view=this.host.ownerDocument.defaultView,height=Math.max(1,resolveCssTokenLength(view?.getComputedStyle(this.host).getPropertyValue("--lr-size-3rem").trim()||"3rem",{host:this.host})??48),header=this.hooks.header(),search=this.hooks.workbook?this.bound.search:this.sheet.data.search;return html`
19
+ ${this.hooks.workbook&&this.sheets.length>1?this.hooks.renderSheetTabs?.(this.sheets.map(sheet=>sheet.name),this.sheetIndex,index=>{if(Number.isInteger(index)&&index>=0&&index<this.sheets.length&&index!==this.sheetIndex){this.hooks.cancelAnchor();try{this.selectSheet(index)&&this.notify()}catch(error){this.fail(error)}}})??nothing:nothing}
20
20
  ${this.busy?html`<p part="spinner" class="empty-note">${this.hooks.localize("loadingDocument")}</p>`:nothing}
21
21
  ${typeof search!="function"?html`<p part="search-status" class="empty-note">${this.hooks.localize("sourceSearchUnavailable")}</p>`:nothing}
22
22
  <div part=${this.hooks.headerPart==="header-cell"?"table":"sheet"} role="table" aria-label=${this.hooks.workbook?this.sheet.name:this.hooks.label(this.rows)} aria-rowcount=${this.rows+Number(header)} aria-colcount=${this.columns}
@@ -28,4 +28,4 @@ import{SourceRequestController,sourceCount,sourceRevision}from"../../internal/so
28
28
  .scrollElement=${this.hooks.pageScroll?.()?view??void 0:void 0}
29
29
  @lr-visible-range-change=${this.onRange} @lr-virtual-scroll=${event=>event.stopPropagation()} @lr-load-more=${event=>event.stopPropagation()}
30
30
  ></lr-virtual-list>
31
- </div>`}catch(error){return this.fail(error),html`<div part="error">${this.hooks.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`}}async revealAnchor(anchor){if(anchor.kind!=="cell-range")return!1;const range=parseCellRange(anchor.range);if(!range)return!1;const name=anchor.sheet??range.sheet;if(!this.hooks.workbook&&name)return!1;const index=name?this.sheets.findIndex(sheet=>sheet.name===name):this.sheetIndex;return this.reveal(index,range.startRow-Number(this.hooks.header()),range.startCol)}async reveal(sheetIndex,row,column){if(this.failure||sheetIndex<0||sheetIndex>=this.sheets.length)return!1;if(sheetIndex!==this.sheetIndex)try{this.selectSheet(sheetIndex),this.notify()}catch(error){return this.fail(error),!1}if(!Number.isSafeInteger(row)||row<(this.hooks.header()?-1:0)||row>=this.rows||!Number.isSafeInteger(column)||column<0||column>=this.columns)return!1;const lease=this.authority.begin("reveal",this.locale);if(!lease||(await this.host.updateComplete,!lease.isCurrent())||(await this.chrome.showColumn(this,column,this.hooks.scrollContainer?.()??this.host.shadowRoot?.querySelector('[part="sheet"]')??null),!lease.isCurrent()))return!1;if(row<0)return this.chrome.revealCell(this.host.shadowRoot?.querySelector(`[part="header-row"] [aria-colindex="${column+1}"]`));if(this.firstRow=row,this.activeRow=row,this.requestWindow(),this.notify(),await this.host.updateComplete,!lease.isCurrent())return!1;const list=this.host.shadowRoot?.querySelector(tag("virtual-list"));if(!list||(list.scrollToIndex(row,{align:"start",behavior:"auto"}),await list.updateComplete,!lease.isCurrent()))return!1;const slot=this.slots.find(value=>row>=value.row&&row<value.row+value.rows&&column>=value.column&&column<value.column+value.columns);if(!slot||!await slot.promise||!lease.isCurrent()||(await this.host.updateComplete,await list.updateComplete,!lease.isCurrent()))return!1;const target=list.shadowRoot?.querySelector(`[data-row-index="${row}"] [aria-colindex="${column+1}"]`);return this.chrome.revealCell(target)&&lease.isCurrent()}async search(query){this.hooks.cancelAnchor(),this.authority.invalidate("search"),this.authority.invalidate("reveal"),this.searchState.query=query;const bounded=boundedViewerSearchQuery(query,this.locale);if(!bounded.needle||!bounded.accepted)return this.searchState.publish([],bounded.accepted),0;const source=this.bound,search=this.hooks.workbook?source?.search:this.sheet?.data.search;if(!source||!search||this.failure)return this.searchState.publish([],!1),0;const lease=this.authority.begin("search",this.locale);return lease?new Promise(resolve=>{lease.context.signal.addEventListener("abort",()=>resolve(0),{once:!0});const run=async()=>{if(!lease.isCurrent()){resolve(0);return}this.searchRunning=!0;try{const result=await search.call(source,Object.freeze({...lease.context,query,limit:MAX_TABLE_SEARCH_MATCHES}));if(!lease.isCurrent())return;if(!result||!Array.isArray(result.hits)||result.hits.length>MAX_TABLE_SEARCH_MATCHES||typeof result.exhaustive!="boolean"||result.total!==null&&sourceCount(result.total)<result.hits.length)throw new TypeError("Invalid source search result");if(result.exhaustive&&result.total!==null&&result.total!==result.hits.length)throw new TypeError("Inconsistent source search total");let exact=result.exhaustive;const hits=[];for(const hit of result.hits){const index=this.hooks.workbook?this.sheets.findIndex(sheet=>sheet.key===hit.sheetKey):0;if(index<0||!Number.isSafeInteger(hit.row)||hit.row<-1||!Number.isSafeInteger(hit.column)||hit.column<0)throw new TypeError("Invalid source search hit");const data=this.sheets[index].data;if(hit.row>=sourceCount(data.rowCount)||hit.column>=sourceCount(data.columnCount)||hit.column>=this.limit)throw new TypeError("Source search hit is out of bounds");if(!lease.isCurrent())return;if(hit.row===-1&&!this.hooks.header()){exact=!1;continue}hits.push({sheetIndex:index,row:hit.row,col:hit.column})}if(!lease.isCurrent())return;this.searchState.publish(hits,exact),hits.length&&await this.reveal(hits[0].sheetIndex,hits[0].row,hits[0].col),lease.isCurrent()&&resolve(hits.length)}catch(error){lease.isCurrent()&&(this.fail(error),this.searchState.publish([],!1),resolve(0))}finally{this.searchRunning=!1;const next=this.queuedSearch;this.queuedSearch=void 0,next&&next()}};this.searchRunning?this.queuedSearch=run:run()}):0}async step(direction){if(!this.searchState.step(direction))return!1;const hit=this.searchState.matches[this.searchState.activeIndex];return this.reveal(hit.sheetIndex,hit.row,hit.col)}clearSearch(){this.hooks.cancelAnchor(),this.authority.invalidate("search"),this.authority.invalidate("reveal"),this.activeRow="",this.searchState.clear(),this.notify()}}export{TABLE_VIEWER_SOURCE_MESSAGE_KEYS,TableViewerController,TableViewerScrollController,TableViewerSourceController,collectTableSearchMatches,tableHighlightsForColumn,tableHighlightsForRow};
31
+ </div>`}catch(error){return current()?(this.fail(error),html`<div part="error">${this.hooks.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")}</div>`):html``}}async revealAnchor(anchor){if(anchor.kind!=="cell-range")return!1;const range=parseCellRange(anchor.range);if(!range)return!1;const name=anchor.sheet??range.sheet;if(!this.hooks.workbook&&name)return!1;const index=name?this.sheets.findIndex(sheet=>sheet.name===name):this.sheetIndex;return this.reveal(index,range.startRow-Number(this.hooks.header()),range.startCol)}async reveal(sheetIndex,row,column){if(this.failure||sheetIndex<0||sheetIndex>=this.sheets.length)return!1;if(sheetIndex!==this.sheetIndex)try{if(!this.selectSheet(sheetIndex))return!1;this.notify()}catch(error){return this.fail(error),!1}if(!Number.isSafeInteger(row)||row<(this.hooks.header()?-1:0)||row>=this.rows||!Number.isSafeInteger(column)||column<0||column>=this.columns)return!1;const lease=this.authority.begin("reveal",this.locale);if(!lease||(await this.host.updateComplete,!lease.isCurrent())||(await this.chrome.showColumn(this,column,this.hooks.scrollContainer?.()??this.host.shadowRoot?.querySelector('[part="sheet"]')??null),!lease.isCurrent()))return!1;if(row<0)return this.chrome.revealCell(this.host.shadowRoot?.querySelector(`[part="header-row"] [aria-colindex="${column+1}"]`));const previousRow=this.firstRow,sheet=this.sheet,epoch=this.epoch;this.firstRow=row,this.activeRow=row,this.requestWindow(),this.notify();const abandon=()=>(this.firstRow===row&&this.sheet===sheet&&this.current(epoch)&&(this.firstRow=previousRow,this.requestWindow(),this.notify()),!1);if(await this.host.updateComplete,!lease.isCurrent())return abandon();const list=this.host.shadowRoot?.querySelector(tag("virtual-list"));if(!list)return abandon();if(list.scrollToIndex(row,{align:"start",behavior:"auto"}),await list.updateComplete,!lease.isCurrent())return!1;const slot=this.slots.find(value=>row>=value.row&&row<value.row+value.rows&&column>=value.column&&column<value.column+value.columns);if(!slot||!await slot.promise||!lease.isCurrent()||(await this.host.updateComplete,await list.updateComplete,!lease.isCurrent()))return!1;const target=list.shadowRoot?.querySelector(`[data-row-index="${row}"] [aria-colindex="${column+1}"]`);return this.chrome.revealCell(target)&&lease.isCurrent()}beginSearchChange(){const intent=++this.searchIntent;this.hooks.cancelAnchor();for(const channel of["search","reveal"]){if(intent!==this.searchIntent)return;this.authority.invalidate(channel)}return intent===this.searchIntent?intent:void 0}async search(query){const intent=this.beginSearchChange();if(intent===void 0)return 0;this.searchState.query=query;const bounded=boundedViewerSearchQuery(query,this.locale);if(!bounded.needle||!bounded.accepted)return this.searchState.publish([],bounded.accepted),0;const source=this.bound,search=this.hooks.workbook?source?.search:this.sheet?.data.search;if(intent!==this.searchIntent)return 0;if(!source||!search||this.failure)return this.searchState.publish([],!1),0;const lease=this.authority.begin("search",this.locale);return lease?new Promise(resolve=>{lease.context.signal.addEventListener("abort",()=>resolve(0),{once:!0});const run=async()=>{if(!lease.isCurrent()){resolve(0);return}this.searchRunning=!0;try{const result=await search.call(source,Object.freeze({...lease.context,query,limit:MAX_TABLE_SEARCH_MATCHES}));if(!lease.isCurrent())return;if(!result||!Array.isArray(result.hits)||result.hits.length>MAX_TABLE_SEARCH_MATCHES||typeof result.exhaustive!="boolean"||result.total!==null&&sourceCount(result.total)<result.hits.length)throw new TypeError("Invalid source search result");if(result.exhaustive&&result.total!==null&&result.total!==result.hits.length)throw new TypeError("Inconsistent source search total");let exact=result.exhaustive;const hits=[];for(const hit of result.hits){const index=this.hooks.workbook?this.sheets.findIndex(sheet=>sheet.key===hit.sheetKey):0;if(index<0||!Number.isSafeInteger(hit.row)||hit.row<-1||!Number.isSafeInteger(hit.column)||hit.column<0)throw new TypeError("Invalid source search hit");const data=this.sheets[index].data;if(hit.row>=sourceCount(data.rowCount)||hit.column>=sourceCount(data.columnCount)||hit.column>=this.limit)throw new TypeError("Source search hit is out of bounds");if(!lease.isCurrent())return;if(hit.row===-1&&!this.hooks.header()){exact=!1;continue}hits.push({sheetIndex:index,row:hit.row,col:hit.column})}if(!lease.isCurrent())return;if(!this.searchState.publish(hits,exact)||!lease.isCurrent()){resolve(0);return}hits.length&&await this.reveal(hits[0].sheetIndex,hits[0].row,hits[0].col),lease.isCurrent()&&resolve(hits.length)}catch(error){lease.isCurrent()&&(this.fail(error),this.searchState.publish([],!1),resolve(0))}finally{this.searchRunning=!1;const next=this.queuedSearch;this.queuedSearch=void 0,next&&next()}};this.searchRunning?this.queuedSearch=run:run()}):0}async step(direction){const intent=this.searchIntent;if(!this.searchState.step(direction)||intent!==this.searchIntent)return!1;const hit=this.searchState.matches[this.searchState.activeIndex];return this.reveal(hit.sheetIndex,hit.row,hit.col)}clearSearch(){this.beginSearchChange()!==void 0&&(this.activeRow="",this.searchState.clear(),this.notify())}}export{TABLE_VIEWER_SOURCE_MESSAGE_KEYS,TableViewerController,TableViewerScrollController,TableViewerSourceController,collectTableSearchMatches,tableHighlightsForColumn,tableHighlightsForRow};