@aceshooting/lyra-ui 31.0.0 → 31.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/dist/autoloader-cdn.js +1 -1
  3. package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
  4. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
  5. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  6. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +18 -8
  7. package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
  8. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  9. package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
  10. package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
  11. package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
  12. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +6 -3
  13. package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
  14. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  15. package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
  16. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  17. package/dist/components/data/document-library/document-library-cursor.js +1 -0
  18. package/dist/components/data/document-library/document-library-types.d.ts +20 -0
  19. package/dist/components/data/document-library/document-library.class.d.ts +37 -26
  20. package/dist/components/data/document-library/document-library.class.js +20 -11
  21. package/dist/components/data/document-library/document-library.styles.js +1 -1
  22. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
  23. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  24. package/dist/components/data/timeline/timeline.class.js +1 -1
  25. package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
  26. package/dist/components/forms/combobox/combobox.class.js +2 -2
  27. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
  28. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  29. package/dist/components/layout/page/page.class.d.ts +3 -3
  30. package/dist/components/layout/page/page.class.js +1 -1
  31. package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
  32. package/dist/components/layout/segmented/segmented.class.js +34 -24
  33. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  34. package/dist/components/layout/stepper/stepper.styles.js +1 -1
  35. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  36. package/dist/components/media/map/map-anchor-controller.js +1 -1
  37. package/dist/components/media/map/map-canvas-target.js +1 -0
  38. package/dist/components/media/map/map.class.d.ts +10 -1
  39. package/dist/components/media/map/map.class.js +4 -4
  40. package/dist/components/media/map/map.styles.js +1 -1
  41. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
  42. package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
  43. package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
  44. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  45. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  46. package/dist/components/retrieval/graph/graph.class.js +1 -1
  47. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
  48. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
  49. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
  50. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
  51. package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
  52. package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
  53. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  54. package/dist/components/utility/icon/icon.class.js +1 -1
  55. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  56. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  57. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  58. package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
  59. package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
  60. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  61. package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
  62. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  63. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  64. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  65. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +1 -1
  66. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  67. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  68. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  69. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
  70. package/dist/data-sources.d.ts +10 -0
  71. package/dist/events.d.ts +9 -4
  72. package/dist/framework-types.d.ts +1 -1
  73. package/dist/internal/default-strings/conversation.generated.js +1 -1
  74. package/dist/internal/default-strings/data.generated.js +1 -1
  75. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  76. package/dist/internal/localization-types.d.ts +1 -1
  77. package/dist/internal/localization.js +1 -1
  78. package/dist/internal/lyra-element.js +2 -2
  79. package/dist/internal/native-modal-context.js +1 -1
  80. package/dist/internal/overlay-manager.js +1 -1
  81. package/dist/internal/overlay-order.js +1 -1
  82. package/dist/internal/overlay-stack.js +1 -1
  83. package/dist/internal/package-metadata.js +1 -1
  84. package/dist/internal/runtime-diagnostics.js +1 -0
  85. package/dist/internal/source-cursor-controller.js +1 -0
  86. package/dist/internal/source-cursor-projection.js +1 -0
  87. package/dist/internal/source-page-scope.js +1 -1
  88. package/dist/lyra.d.ts +1 -1
  89. package/dist/theme/theme-bootstrap.js +1 -1
  90. package/dist/theme/theme.js +1 -1
  91. package/dist/utilities/overlay-manager.d.ts +2 -0
  92. package/llms/components/lr-budget-meter.md +31 -0
  93. package/llms/components/lr-chat-composer.md +13 -2
  94. package/llms/components/lr-combobox.md +27 -1
  95. package/llms/components/lr-diff-view.md +6 -0
  96. package/llms/components/lr-document-library.md +90 -6
  97. package/llms/components/lr-graph.md +5 -0
  98. package/llms/components/lr-ingestion-queue.md +76 -8
  99. package/llms/components/lr-json-viewer.md +34 -0
  100. package/llms/components/lr-lite-chart.md +2 -1
  101. package/llms/components/lr-map.md +33 -0
  102. package/llms/components/lr-message-feedback.md +38 -3
  103. package/llms/components/lr-page.md +4 -2
  104. package/llms/components/lr-prompt-input.md +5 -2
  105. package/llms/components/lr-segmented.md +30 -10
  106. package/llms/components/lr-sequence-playback.md +47 -12
  107. package/llms/components/lr-virtual-list.md +3 -1
  108. package/llms/peers.md +2 -2
  109. package/llms/shared/events-and-types.md +61 -2
  110. package/llms/shared/forms-and-accessibility.md +25 -0
  111. package/llms/shared/imports-and-registration.md +154 -110
  112. package/llms/shared/testing-and-utilities.md +5 -1
  113. package/llms/shared.md +245 -113
  114. package/locales.json +1 -1
  115. package/package.json +8 -8
  116. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./document-preview.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{snapshotLyraHighlightAnchorKind,snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_convertingDocument,LYRA_DEFAULT_documentPreviewAlt,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewNotAvailable,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const IDLE_TEXT_FETCH={kind:"idle"};function classifyFormat(mimeType){const mt=(mimeType??"").split(";",1)[0].trim().toLowerCase();return mt.startsWith("text/")||mt==="application/json"?"text":mt.startsWith("image/")?"image":"generic"}const EMPTY_REGION_HIGHLIGHTS=Object.freeze([]);function projectRegionAnchor(value,knownRegionKind=!1){try{if(value===null||typeof value!="object"||Array.isArray(value))return;if(!knownRegionKind){const kind=getOwnDataDescriptor(value,"kind");if(kind===MISSING_OWN_DATA_DESCRIPTOR||kind===UNSAFE_OWN_DATA_DESCRIPTOR||kind.value!=="region")return}const rectDescriptor=getOwnDataDescriptor(value,"rect");if(rectDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rectDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const rect=sanitizePercentRect(rectDescriptor.value);if(!rect)return;const pageDescriptor=getOwnDataDescriptor(value,"page"),page=pageDescriptor===MISSING_OWN_DATA_DESCRIPTOR||pageDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:pageDescriptor.value;return Object.freeze({rect,...typeof page=="number"&&Number.isFinite(page)?{page}:{}})}catch{return}}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function downloadIcon(){return icon(svg`
1
+ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./document-preview.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{snapshotLyraHighlightAnchorKind,snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_convertingDocument,LYRA_DEFAULT_documentPreviewAlt,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewNotAvailable,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const IDLE_TEXT_FETCH={kind:"idle"};function classifyFormat(mimeType){const mt=(mimeType??"").split(";",1)[0].trim().toLowerCase();return mt.startsWith("text/")||mt==="application/json"?"text":mt.startsWith("image/")?"image":"generic"}const EMPTY_REGION_HIGHLIGHTS=Object.freeze([]);function projectRegionAnchor(value,knownRegionKind=!1){try{if(value===null||typeof value!="object"||Array.isArray(value))return;if(!knownRegionKind){const kind=getOwnDataDescriptor(value,"kind");if(kind===MISSING_OWN_DATA_DESCRIPTOR||kind===UNSAFE_OWN_DATA_DESCRIPTOR||kind.value!=="region")return}const rectDescriptor=getOwnDataDescriptor(value,"rect");if(rectDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rectDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const rect=sanitizePercentRect(rectDescriptor.value);if(!rect)return;const pageDescriptor=getOwnDataDescriptor(value,"page"),page=pageDescriptor===MISSING_OWN_DATA_DESCRIPTOR||pageDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:pageDescriptor.value;return Object.freeze({rect,...typeof page=="number"&&Number.isFinite(page)?{page}:{}})}catch{return}}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function downloadIcon(){return icon(svg`
2
2
  <path d="M12 3v12"></path>
3
3
  <polyline points="7 11 12 16 17 11"></polyline>
4
4
  <path d="M4 18v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"></path>
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
15
15
  aria-hidden="true"
16
16
  focusable="false"
17
17
  >${paths}</svg>
18
- `}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedPreview()),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,convertingDocument:LYRA_DEFAULT_convertingDocument,details:LYRA_DEFAULT_details,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly]}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;this.highlightsSource=value;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"&&!moved&&(this.textFetch=IDLE_TEXT_FETCH,this.scheduleAfterUpdate(()=>{const url=safeFetchUrl(this.src);url&&this.status!=="converting"&&this.status!=="error"&&this.fetchText(url)}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPreview(){this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")),this.textFetch.kind!=="idle"&&(classifyFormat(this.mimeType)!=="text"||safeFetchUrl(this.src)===null||this.status==="converting"||this.status==="error")&&(this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH)}updated(changed){super.updated(changed),this.syncAnnouncementState();const safeTextSrc=safeFetchUrl(this.src);classifyFormat(this.mimeType)==="text"&&safeTextSrc!==null&&this.status!=="converting"&&this.status!=="error"&&(changed.has("src")||changed.has("mimeType")||changed.has("status")&&this.textFetch.kind==="idle")&&this.scheduleAfterUpdate(()=>{this.fetchText(safeTextSrc)})}syncAnnouncementState(){if(this.status==="converting"){if(this.progress!=null&&Number.isFinite(this.progress)){this.announcements.transition("preview","progress");return}this.announcements.transition("preview","loading",this.localize("convertingDocument"));return}if(this.status==="error"){this.announcements.transition("preview","error",this.errorText||this.localize("documentPreviewGenericError"));return}if(classifyFormat(this.mimeType)!=="text"||this.src===""){this.announcements.transition("preview","idle");return}if(safeFetchUrl(this.src)===null){this.announcements.transition("preview","error",this.localize("documentPreviewUrlNotAllowed"));return}if(this.textFetch.kind==="error"){this.announcements.transition("preview","error",this.textFetch.message);return}if(this.textFetch.kind==="loaded"){this.announcements.transition("preview","loaded");return}this.announcements.transition("preview","loading",this.localize("loadingDocument"))}async fetchText(url){const generation=++this.generation,signal=this.beginAbortableLoad(),fetchTarget=resolveOwnerFetchTarget(this,url);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.textFetch={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.textFetch={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;this.textFetch={kind:"loaded",text}}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;const message=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.textFetch={kind:"error",message},this.emit("lr-render-error",{error})}}renderSpinner(label,progressValue){if(progressValue!=null&&Number.isFinite(progressValue)){const clamped=finiteRange(progressValue,0,0,100),rounded=Math.round(clamped),formatted=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:0}).format(clamped/100);return html`
18
+ `}class LyraDocumentPreview extends LyraElement{constructor(){super(...arguments),this.src="",this.mimeType="",this.filename="",this.status="idle",this.errorText="",this.maxHeight="",this.zoomable=!1,this.suppressDownload=!1,this._highlights=snapshotLyraHighlights([]),this._regionHighlights=EMPTY_REGION_HIGHLIGHTS,this.activeHighlightId=null,this.anchorKinds=["region"],this.hasUnsupportedSlot=!1,this.textFetch=IDLE_TEXT_FETCH,this.generation=0,this.invalidUrlReportedFor=null,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>this.releaseDetachedPreview()),this.onUnsupportedSlotChange=()=>{this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")},this.onDownloadClick=()=>{this.emit("lr-download",{src:this.src,filename:this.filename})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,convertingDocument:LYRA_DEFAULT_convertingDocument,details:LYRA_DEFAULT_details,documentPreviewAlt:LYRA_DEFAULT_documentPreviewAlt,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewNotAvailable:LYRA_DEFAULT_documentPreviewNotAvailable,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly]}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;this.highlightsSource=value;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this._regionHighlights=this.projectRegionHighlights(this._highlights),this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect();const moved=this.detached.cancel();this.hasUpdated&&this.src&&classifyFormat(this.mimeType)==="text"&&(!moved||this.textFetch.kind==="loading")&&(this.textFetch=IDLE_TEXT_FETCH,this.scheduleAfterUpdate(()=>{const url=safeFetchUrl(this.src);url&&this.status!=="converting"&&this.status!=="error"&&this.fetchText(url)}))}disconnectedCallback(){this.textFetch.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedPreview(){this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasUnsupportedSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="unsupported")),this.textFetch.kind!=="idle"&&(classifyFormat(this.mimeType)!=="text"||safeFetchUrl(this.src)===null||this.status==="converting"||this.status==="error")&&(this.generation++,this.beginAbortableLoad(),this.textFetch=IDLE_TEXT_FETCH)}updated(changed){super.updated(changed),this.syncAnnouncementState();const safeTextSrc=safeFetchUrl(this.src);classifyFormat(this.mimeType)==="text"&&safeTextSrc!==null&&this.status!=="converting"&&this.status!=="error"&&(changed.has("src")||changed.has("mimeType")||changed.has("status")&&this.textFetch.kind==="idle")&&this.scheduleAfterUpdate(()=>{this.fetchText(safeTextSrc)})}syncAnnouncementState(){if(this.status==="converting"){if(this.progress!=null&&Number.isFinite(this.progress)){this.announcements.transition("preview","progress");return}this.announcements.transition("preview","loading",this.localize("convertingDocument"));return}if(this.status==="error"){this.announcements.transition("preview","error",this.errorText||this.localize("documentPreviewGenericError"));return}if(classifyFormat(this.mimeType)!=="text"||this.src===""){this.announcements.transition("preview","idle");return}if(safeFetchUrl(this.src)===null){this.announcements.transition("preview","error",this.localize("documentPreviewUrlNotAllowed"));return}if(this.textFetch.kind==="error"){this.announcements.transition("preview","error",this.textFetch.message);return}if(this.textFetch.kind==="loaded"){this.announcements.transition("preview","loaded");return}this.announcements.transition("preview","loading",this.localize("loadingDocument"))}async fetchText(url){const generation=++this.generation,signal=this.beginAbortableLoad(),fetchTarget=resolveOwnerFetchTarget(this,url);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.textFetch={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.textFetch={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.textFetch={kind:"loaded",text}}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const message=this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad");this.textFetch={kind:"error",message},this.emit("lr-render-error",{error})}}renderSpinner(label,progressValue){if(progressValue!=null&&Number.isFinite(progressValue)){const clamped=finiteRange(progressValue,0,0,100),rounded=Math.round(clamped),formatted=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:0}).format(clamped/100);return html`
19
19
  <div
20
20
  part="spinner"
21
21
  role="progressbar"
@@ -88,7 +88,7 @@ name:string;
88
88
  /** A CSS `max-height` that caps the scrollable document body; invalid values are ignored.*/
89
89
  maxHeight:string;
90
90
  /** Anchor kinds this viewer resolves via `scrollToAnchor()`. Readonly.*/
91
- readonly anchorKinds:readonly['fragment','text-quote'];private fetchState;private readonly searchState;private resolvedHighlightActions;private generation;private lastLoadSrc;private loadLibrary;private readonly announcements;private headingTree;private highlightHandle?;private resolvedHighlightRanges;private pendingResolvedHighlightActions;private resolvedHighlightActionSyncPending;private paintedSearchMarks;private textIndexCache;private textIndexMappingDirty;private textIndexLocale?;private readonly detached;connectedCallback():void;disconnectedCallback():void;private releaseDetachedDocument;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private contentRoot;private resetSearchForContentChange;private load;private failWithLocalizedMessage;private stampHeadings;
91
+ readonly anchorKinds:readonly['fragment','text-quote'];private fetchState;private readonly searchState;private resolvedHighlightActions;private generation;private pendingTransportGeneration?;private lastLoadSrc;private loadLibrary;private readonly announcements;private headingTree;private highlightHandle?;private resolvedHighlightRanges;private pendingResolvedHighlightActions;private resolvedHighlightActionSyncPending;private paintedSearchMarks;private textIndexCache;private textIndexMappingDirty;private textIndexLocale?;private readonly detached;connectedCallback():void;disconnectedCallback():void;private releaseDetachedDocument;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private contentRoot;private resetSearchForContentChange;private load;private failWithLocalizedMessage;private stampHeadings;
92
92
  /** A document-ordered, flattened heading outline -- empty until a document has finished loading.*/
93
93
  getHeadingTree():DocxHeadingItem[];protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private applyFragmentAnchor;private applyTextQuoteAnchor;
94
94
  /** Overrides `DocumentAnchorTarget`'s default (whole render-root) selection scope -- only
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();root&&this.bindTextSelection(root);return}this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"},this.headingTree=[];return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();if(root&&this.bindTextSelection(root),this.pendingTransportGeneration===void 0)return}this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.pendingTransportGeneration!==void 0&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}async load(){const generation=++this.generation;this.pendingTransportGeneration=void 0;const signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"},this.headingTree=[];return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.pendingTransportGeneration=generation,this.fetchState={kind:"loading"};let acquiringDocument=!0;try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}acquiringDocument=!1,this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0);const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(acquiringDocument&&signal?.aborted||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}finally{this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0)}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
2
2
  <div part="highlight-actions">
3
3
  ${highlights.map(highlight=>{const label=this.highlightActionLabel(highlight);return html`
4
4
  <button
@@ -81,4 +81,4 @@ foldQuotes:boolean;
81
81
  /** Shared text search and anchor-target API for message body text. Searching for text
82
82
  * inside a folded quote reveals matching quotes before navigating the active match, using the
83
83
  * same bounded Unicode/whitespace normalization and locale matching as the shared text index. */
84
- search(query:string):Promise<number>;searchNext():Promise<boolean>;searchPrevious():Promise<boolean>;clearSearch():void;private searchDocument?;private fetchState;private textQuoteExpanded;private expandedHtmlQuoteIndices;private generation;private lastLoadSrc;private readonly announcements;private foldedHtmlCache;protected textContentRoot():Element|null;protected buildTextScope(root:Element):ReturnType<typeof scopeFromElement>;connectedCallback():void;private readonly detached;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private load;private failWithLocalizedMessage;private isCurrentLoad;private parse;private formatAddress;private formatAddresses;private formatDate;private renderHeaders;private renderAttachments;private renderTextBody;private onBodyClick;private getFoldedHtml;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-email-viewer':LyraEmailViewer;}}export{};
84
+ search(query:string):Promise<number>;searchNext():Promise<boolean>;searchPrevious():Promise<boolean>;clearSearch():void;private searchDocument?;private fetchState;private textQuoteExpanded;private expandedHtmlQuoteIndices;private generation;private pendingTransportGeneration;private lastLoadSrc;private readonly announcements;private foldedHtmlCache;protected textContentRoot():Element|null;protected buildTextScope(root:Element):ReturnType<typeof scopeFromElement>;connectedCallback():void;private readonly detached;disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private load;private failWithLocalizedMessage;private isCurrentLoad;private parse;private formatAddress;private formatAddresses;private formatDate;private renderHeaders;private renderAttachments;private renderTextBody;private onBodyClick;private getFoldedHtml;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-email-viewer':LyraEmailViewer;}}export{};
@@ -1,6 +1,6 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/file-size.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_emailViewerUnnamedAttachment,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_EMAIL_RECIPIENT_POSITIONS=1e4,MAX_EMAIL_RECIPIENT_DEPTH=100,MAX_EMAIL_ATTACHMENT_POSITIONS=1e4;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isSafeRecord(value){if(value===null||typeof value!="object"||isArrayValue(value))return!1;try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function optionalOwnString(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="string"?descriptor.value:void 0}function optionalOwnValue(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectAddressList(value,budget,depth){if(!isArrayValue(value)||budget.positions>=MAX_EMAIL_RECIPIENT_POSITIONS)return[];const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return[];const addresses=[],count=Math.min(length.value,MAX_EMAIL_RECIPIENT_POSITIONS-budget.positions);for(let index=0;index<count;index+=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const address=projectAddress(descriptor.value,budget,depth);address&&addresses.push(address)}return addresses}function projectAddress(value,budget,depth){if(depth>MAX_EMAIL_RECIPIENT_DEPTH||budget.nodes>=MAX_EMAIL_RECIPIENT_POSITIONS||!isSafeRecord(value)||budget.seen.has(value))return;budget.seen.add(value),budget.nodes+=1;const name=optionalOwnString(value,"name"),address=optionalOwnString(value,"address"),groupValue=optionalOwnValue(value,"group"),group=groupValue===void 0?[]:projectAddressList(groupValue,budget,depth+1);if(!(name===void 0&&address===void 0&&group.length===0))return Object.freeze({...name===void 0?{}:{name},...address===void 0?{}:{address},...group.length===0?{}:{group:Object.freeze(group)}})}function normalizeAttachmentContent(content){try{if(typeof content=="string")return new TextEncoder().encode(content);if(content instanceof Uint8Array)return new Uint8Array(content);if(content instanceof ArrayBuffer)return new Uint8Array(content.slice(0))}catch{return}}function projectAttachments(value){if(!isArrayValue(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const attachments=[],count=Math.min(length.value,MAX_EMAIL_ATTACHMENT_POSITIONS);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||!isSafeRecord(entry.value))continue;const content=normalizeAttachmentContent(optionalOwnValue(entry.value,"content"));if(!content)continue;const filename=optionalOwnString(entry.value,"filename")??"",mimeType=optionalOwnString(entry.value,"mimeType")??"";attachments.push(Object.freeze({filename,mimeType,size:content.byteLength,content}))}return Object.freeze(attachments)}function normalizeParsedEmail(value){if(!isSafeRecord(value))return null;const budget={positions:0,nodes:0,seen:new WeakSet},htmlValue=optionalOwnValue(value,"html"),textValue=optionalOwnValue(value,"text"),subjectValue=optionalOwnValue(value,"subject"),dateValue=optionalOwnValue(value,"date"),html2=typeof htmlValue=="string"?htmlValue:void 0,text=typeof textValue=="string"?textValue:void 0,subject=typeof subjectValue=="string"?subjectValue:void 0,date=typeof dateValue=="string"?dateValue:void 0,from=projectAddress(optionalOwnValue(value,"from"),budget,0),to=projectAddressList(optionalOwnValue(value,"to"),budget,0);return Object.freeze({...html2===void 0?{}:{html:html2},...text===void 0?{}:{text},...from===void 0?{}:{from},to:Object.freeze(to),...subject===void 0?{}:{subject},...date===void 0?{}:{date},attachments:projectAttachments(optionalOwnValue(value,"attachments"))})}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/file-size.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_emailViewerUnnamedAttachment,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_EMAIL_RECIPIENT_POSITIONS=1e4,MAX_EMAIL_RECIPIENT_DEPTH=100,MAX_EMAIL_ATTACHMENT_POSITIONS=1e4;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isSafeRecord(value){if(value===null||typeof value!="object"||isArrayValue(value))return!1;try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function optionalOwnString(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="string"?descriptor.value:void 0}function optionalOwnValue(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectAddressList(value,budget,depth){if(!isArrayValue(value)||budget.positions>=MAX_EMAIL_RECIPIENT_POSITIONS)return[];const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return[];const addresses=[],count=Math.min(length.value,MAX_EMAIL_RECIPIENT_POSITIONS-budget.positions);for(let index=0;index<count;index+=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const address=projectAddress(descriptor.value,budget,depth);address&&addresses.push(address)}return addresses}function projectAddress(value,budget,depth){if(depth>MAX_EMAIL_RECIPIENT_DEPTH||budget.nodes>=MAX_EMAIL_RECIPIENT_POSITIONS||!isSafeRecord(value)||budget.seen.has(value))return;budget.seen.add(value),budget.nodes+=1;const name=optionalOwnString(value,"name"),address=optionalOwnString(value,"address"),groupValue=optionalOwnValue(value,"group"),group=groupValue===void 0?[]:projectAddressList(groupValue,budget,depth+1);if(!(name===void 0&&address===void 0&&group.length===0))return Object.freeze({...name===void 0?{}:{name},...address===void 0?{}:{address},...group.length===0?{}:{group:Object.freeze(group)}})}function normalizeAttachmentContent(content){try{if(typeof content=="string")return new TextEncoder().encode(content);if(content instanceof Uint8Array)return new Uint8Array(content);if(content instanceof ArrayBuffer)return new Uint8Array(content.slice(0))}catch{return}}function projectAttachments(value){if(!isArrayValue(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const attachments=[],count=Math.min(length.value,MAX_EMAIL_ATTACHMENT_POSITIONS);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||!isSafeRecord(entry.value))continue;const content=normalizeAttachmentContent(optionalOwnValue(entry.value,"content"));if(!content)continue;const filename=optionalOwnString(entry.value,"filename")??"",mimeType=optionalOwnString(entry.value,"mimeType")??"";attachments.push(Object.freeze({filename,mimeType,size:content.byteLength,content}))}return Object.freeze(attachments)}function normalizeParsedEmail(value){if(!isSafeRecord(value))return null;const budget={positions:0,nodes:0,seen:new WeakSet},htmlValue=optionalOwnValue(value,"html"),textValue=optionalOwnValue(value,"text"),subjectValue=optionalOwnValue(value,"subject"),dateValue=optionalOwnValue(value,"date"),html2=typeof htmlValue=="string"?htmlValue:void 0,text=typeof textValue=="string"?textValue:void 0,subject=typeof subjectValue=="string"?subjectValue:void 0,date=typeof dateValue=="string"?dateValue:void 0,from=projectAddress(optionalOwnValue(value,"from"),budget,0),to=projectAddressList(optionalOwnValue(value,"to"),budget,0);return Object.freeze({...html2===void 0?{}:{html:html2},...text===void 0?{}:{text},...from===void 0?{}:{from},to:Object.freeze(to),...subject===void 0?{}:{subject},...date===void 0?{}:{date},attachments:projectAttachments(optionalOwnValue(value,"attachments"))})}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
2
2
  `),quoted:lines.slice(start).join(`
3
- `)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);if(!doc)return html2;for(const forged of doc.body.querySelectorAll("[data-quote-toggle], [data-quote-index], [data-email-chrome]"))forged.removeAttribute("data-quote-toggle"),forged.removeAttribute("data-quote-index"),forged.removeAttribute("data-email-chrome");const blocks=doc.body.querySelectorAll(QUOTE_SELECTOR),expandedQuotes=new Set(expandedIndices);return blocks.forEach((block,index)=>{const expanded=expandedQuotes.has(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("data-email-chrome","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&candidate.localName==="button"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.detached=new DeferredTeardown(()=>{this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null}),this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=shadowFocusTarget(this)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,emailViewerUnnamedAttachment:LYRA_DEFAULT_emailViewerUnnamedAttachment,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()&&query.length<=TEXT_QUOTE_LIMITS.maxQueryCodeUnits){const budget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},matchesQuote=block=>createTextQuoteIndex(scopeFromElement(block),this.effectiveLocale).search(query,budget).length>0,{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){this.searchDocument?.html!==bodyHtml&&(this.searchDocument={html:bodyHtml,doc:parseHtmlDocument(bodyHtml,this.ownerDocument)});const next=new Set(this.expandedHtmlQuoteIndices);this.searchDocument.doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{!next.has(index)&&matchesQuote(block)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText),quote=this.ownerDocument.createElement("pre");quote.textContent=split?.quoted??"",split&&!this.textQuoteExpanded&&matchesQuote(quote)&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector('[part="body"]')}buildTextScope(root){return scopeFromElement(root,void 0,element=>this.foldQuotes&&element.localName==="button"&&element.getAttribute("data-email-chrome")==="quote-toggle")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isCurrentLoad(generation,fetchTarget.view))return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isCurrentLoad(generation,fetchTarget.view))return;const result=await this.parse(buffer,generation,fetchTarget.view);result&&this.isCurrentLoad(generation,fetchTarget.view)&&(this.fetchState={kind:"loaded",...result})}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}async parse(buffer,generation,ownerView){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isCurrentLoad(generation,ownerView))return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const rawParsed=await PostalMime.parse(buffer);if(!this.isCurrentLoad(generation,ownerView))return null;const parsed=normalizeParsedEmail(rawParsed);if(!parsed)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const sanitized=parsed.html!==void 0&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):"",bodyHtml=sanitized.trim()?sanitized:null;if(!this.isCurrentLoad(generation,ownerView))return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));return{...parsed.from===void 0?{}:{fromAddress:parsed.from},toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:[...parsed.attachments]}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
3
+ `)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);if(!doc)return html2;for(const forged of doc.body.querySelectorAll("[data-quote-toggle], [data-quote-index], [data-email-chrome]"))forged.removeAttribute("data-quote-toggle"),forged.removeAttribute("data-quote-index"),forged.removeAttribute("data-email-chrome");const blocks=doc.body.querySelectorAll(QUOTE_SELECTOR),expandedQuotes=new Set(expandedIndices);return blocks.forEach((block,index)=>{const expanded=expandedQuotes.has(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("data-email-chrome","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&candidate.localName==="button"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.detached=new DeferredTeardown(()=>{this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null}),this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=shadowFocusTarget(this)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,emailViewerUnnamedAttachment:LYRA_DEFAULT_emailViewerUnnamedAttachment,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()&&query.length<=TEXT_QUOTE_LIMITS.maxQueryCodeUnits){const budget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},matchesQuote=block=>createTextQuoteIndex(scopeFromElement(block),this.effectiveLocale).search(query,budget).length>0,{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){this.searchDocument?.html!==bodyHtml&&(this.searchDocument={html:bodyHtml,doc:parseHtmlDocument(bodyHtml,this.ownerDocument)});const next=new Set(this.expandedHtmlQuoteIndices);this.searchDocument.doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{!next.has(index)&&matchesQuote(block)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText),quote=this.ownerDocument.createElement("pre");quote.textContent=split?.quoted??"",split&&!this.textQuoteExpanded&&matchesQuote(quote)&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector('[part="body"]')}buildTextScope(root){return scopeFromElement(root,void 0,element=>this.foldQuotes&&element.localName==="button"&&element.getAttribute("data-email-chrome")==="quote-toggle")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.pendingTransportGeneration===void 0)&&this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.pendingTransportGeneration!==void 0&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation;this.pendingTransportGeneration=void 0;const signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"},this.pendingTransportGeneration=generation;let acquiringMessage=!0;try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0),acquiringMessage=!1;const result=await this.parse(buffer,generation,fetchTarget.view);result&&this.isCurrentLoad(generation,fetchTarget.view)&&(this.fetchState={kind:"loaded",...result})}catch(error){if(acquiringMessage&&signal?.aborted||!this.isCurrentLoad(generation,fetchTarget.view))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}finally{this.pendingTransportGeneration===generation&&(this.pendingTransportGeneration=void 0)}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}async parse(buffer,generation,ownerView){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isCurrentLoad(generation,ownerView))return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const rawParsed=await PostalMime.parse(buffer);if(!this.isCurrentLoad(generation,ownerView))return null;const parsed=normalizeParsedEmail(rawParsed);if(!parsed)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const sanitized=parsed.html!==void 0&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):"",bodyHtml=sanitized.trim()?sanitized:null;if(!this.isCurrentLoad(generation,ownerView))return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));return{...parsed.from===void 0?{}:{fromAddress:parsed.from},toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:[...parsed.attachments]}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
4
4
  <span part="from-label">${this.localize("emailViewerFrom")}</span><span part="from">${fromAddress?this.formatAddress(fromAddress):email.from}</span>
5
5
  <span part="to-label">${this.localize("emailViewerTo")}</span><span part="to">${toAddresses?this.formatAddresses(toAddresses):email.to}</span>
6
6
  <span part="subject-label">${this.localize("emailViewerSubject")}</span><span part="subject">${email.subject||this.localize("emailViewerNoSubject")}</span>
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadHtmlSanitizer}from"./dompurify-loader.js";import{styles}from"./html-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_htmlViewerLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";class LyraHtmlViewerBase extends LyraElement{}class LyraHtmlViewer extends TextViewerTarget(LyraHtmlViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++,this.beginAbortableLoad(),this.fetchState={kind:"idle"}})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,htmlViewerLabel:LYRA_DEFAULT_htmlViewerLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const sanitizer=await loadHtmlSanitizer();if(!this.isConnected||generation!==this.generation)return;if(!sanitizer)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const raw=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const markup=sanitizePassiveMarkup(sanitizer,raw,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation)return;this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",markup})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}renderBody(){switch(this.fetchState.kind){case"loaded":return html`<div part="html" role=${viewerSemanticRole(this,"document")??nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("htmlViewerLabel"))??nothing}>${unsafeHTML(this.fetchState.markup)}</div>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-html-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraHtmlViewer.prototype,"src",void 0),__decorate([property()],LyraHtmlViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraHtmlViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraHtmlViewer.prototype,"fetchState",void 0);export{LyraHtmlViewer};
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadHtmlSanitizer}from"./dompurify-loader.js";import{styles}from"./html-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_htmlViewerLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";class LyraHtmlViewerBase extends LyraElement{}class LyraHtmlViewer extends TextViewerTarget(LyraHtmlViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++,this.beginAbortableLoad(),this.fetchState={kind:"idle"}})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,htmlViewerLabel:LYRA_DEFAULT_htmlViewerLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const sanitizer=await loadHtmlSanitizer();if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!sanitizer)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const raw=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const markup=sanitizePassiveMarkup(sanitizer,raw,this.ownerDocument,"passive-document");if(signal?.aborted||!this.isConnected||generation!==this.generation)return;!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",markup})}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}renderBody(){switch(this.fetchState.kind){case"loaded":return html`<div part="html" role=${viewerSemanticRole(this,"document")??nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("htmlViewerLabel"))??nothing}>${unsafeHTML(this.fetchState.markup)}</div>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-html-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraHtmlViewer.prototype,"src",void 0),__decorate([property()],LyraHtmlViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraHtmlViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraHtmlViewer.prototype,"fetchState",void 0);export{LyraHtmlViewer};
@@ -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 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}>
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{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
@@ -23,7 +23,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
23
23
  ></lr-code-block>`:html`<pre part="raw-source" tabindex="0">${joinSource(c.source)}</pre>`}
24
24
  ${c.cell_type==="code"&&c.outputs?.length?html`<div part="outputs">${c.outputs.map((o,i)=>this.renderOutput(index,o,i))}</div>`:nothing}
25
25
  </div>
26
- </div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,loadingDocument:LYRA_DEFAULT_loadingDocument,notebookViewerCodeCell:LYRA_DEFAULT_notebookViewerCodeCell,notebookViewerCollapseOutput:LYRA_DEFAULT_notebookViewerCollapseOutput,notebookViewerErrorOutput:LYRA_DEFAULT_notebookViewerErrorOutput,notebookViewerInPrompt:LYRA_DEFAULT_notebookViewerInPrompt,notebookViewerInPromptEmpty:LYRA_DEFAULT_notebookViewerInPromptEmpty,notebookViewerInvalid:LYRA_DEFAULT_notebookViewerInvalid,notebookViewerLabel:LYRA_DEFAULT_notebookViewerLabel,notebookViewerMarkdownCell:LYRA_DEFAULT_notebookViewerMarkdownCell,notebookViewerRawCell:LYRA_DEFAULT_notebookViewerRawCell,notebookViewerShowAllOutput:LYRA_DEFAULT_notebookViewerShowAllOutput,notebookViewerTooManyCells:LYRA_DEFAULT_notebookViewerTooManyCells,notebookViewerUnrenderedOutput:LYRA_DEFAULT_notebookViewerUnrenderedOutput,notebookViewerUnsupportedVersion:LYRA_DEFAULT_notebookViewerUnsupportedVersion}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["notebook"])}static{this.identityCollectionObjectProperties=Object.freeze(["notebook"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,viewerLoadingStyles]}get notebook(){return this._notebook}set notebook(value){if(value!==void 0&&(value===this.notebookSource||value===this._notebook))return;this.notebookSource=value;const old=this._notebook,next=typeof value=="string"||value===void 0?value:(()=>{const snapshot=snapshotNotebookDocument(value);return snapshot===OMIT_NOTEBOOK_SNAPSHOT?invalidNotebookSnapshot():snapshot})();Object.is(old,next)||(this._notebook=next,this.requestUpdate("notebook",old),next===void 0?(this.beginSourceTransition(this.src?"loading":"idle"),this.isConnected&&this.scheduleSourceLoad()):this.parseInline())}get source(){return resolveViewerSource(this.src,this._notebook)}set source(_value){}get effectiveOutputCollapseLines(){return finiteCount(this.outputCollapseLines,40)}updated(changed){super.updated(changed),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&this._notebook===void 0&&this.scheduleSourceLoad();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&this._notebook===void 0&&this.beginSourceTransition(this.src?"loading":"idle"),(changed.has("highlights")||changed.has("activeHighlightId")||changed.has("loadState"))&&this.repaintHighlights()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&(this.hasUpdated&&this.src&&this._notebook===void 0&&this.scheduleSourceLoad(),this.hasUpdated&&this._notebook!==void 0&&this.loadState.kind==="loaded"&&this.requestUpdate())}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedNotebook(){this.generation++,this.sanitizerGeneration++,this.beginAbortableLoad(),this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this._notebook===void 0&&(this.loadState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}parseInline(){if(this._notebook===void 0)return;const generation=++this.generation;this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind:"idle"};try{const raw=typeof this._notebook=="string"?JSON.parse(this._notebook):this._notebook;this.setDoc(raw,generation)}catch(error){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error})}}resetParsedState(){const shouldEmitSearchReset=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.activeSearchIndex!==-1;this.sanitizerGeneration++,this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.expandedOutputs=new Set,this.clearSearchState(),this.activeCellIndex=null,shouldEmitSearchReset&&this.emitSearchChange()}beginSourceTransition(kind){this.generation++,this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind}}scheduleSourceLoad(){this.sourceLoadScheduled||(this.sourceLoadScheduled=!0,this.scheduleAfterUpdate(()=>{this.sourceLoadScheduled=!1,this.isConnected&&this._notebook===void 0&&this.loadFromSrc()}))}async loadFromSrc(){if(!this.isConnected||this._notebook!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;this.setDoc(JSON.parse(text),generation)}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.emit("lr-render-error",{error})}}setDoc(raw,generation){if(generation!==this.generation)return;if(!isNotebookShape(raw)){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error:new Error("invalid notebook shape")});return}if(raw.nbformat!==SUPPORTED_MAJOR||!SUPPORTED_MINORS.includes(raw.nbformat_minor)){this.loadState={kind:"error",message:this.localize("notebookViewerUnsupportedVersion",void 0,{version:`${raw.nbformat}.${raw.nbformat_minor}`})},this.emit("lr-render-error",{error:new Error("unsupported nbformat version")});return}if(raw.cells.length>MAX_CELLS){this.loadState={kind:"error",message:this.localize("notebookViewerTooManyCells")},this.emit("lr-render-error",{error:new Error("too many cells")});return}this.resetParsedState(),this.loadState={kind:"loaded",doc:raw};const language=raw.metadata?.language_info?.name??raw.metadata?.kernelspec?.language??"";this.emit("lr-load",{cellCount:raw.cells.length,language})}async applyAnchor(anchor){const index=this.resolveAnchorCellIndex(anchor);return index<0?!1:this.activateCell(index,"start")}async activateCell(index,align){const generation=this.generation,ownerDocument=this.ownerDocument;if(this.activeCellIndex=index,!this.isConnected||(await this.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index))return!1;const list=this.virtualListEl;return!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index)?!1:(list.scrollToIndex(index,{align,behavior:"auto"}),await list.updateComplete,this.isConnected&&this.ownerDocument===ownerDocument&&generation===this.generation&&this.activeCellIndex===index)}resolveAnchorCellIndex(anchor){if(this.loadState.kind!=="loaded")return-1;const cells=this.loadState.doc.cells;let index=-1;if(anchor.kind==="node-path"&&Number.isInteger(anchor.path[0]))index=anchor.path[0];else if(anchor.kind==="fragment")index=cells.findIndex(c=>c.id===anchor.id);else return-1;return index<0||index>=cells.length?-1:index}repaintHighlights(){if(this.loadState.kind!=="loaded"){this.highlightedCells.size>0&&(this.highlightedCells=new Map);return}const next=new Map;let considered=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(considered>=MAX_NOTEBOOK_PAINTED_HIGHLIGHTS)break;considered++;const index=this.resolveAnchorCellIndex(highlight.anchor);index<0||next.has(index)||next.set(index,highlight)}this.highlightedCells=next}async search(query2){const boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale),q=boundedQuery.needle;if(this.searchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.searchMatchCountExact=boundedQuery.accepted,this.loadState.kind!=="loaded"||!q||!boundedQuery.accepted)this.searchMatches=[];else{const budget=new ViewerSearchWorkBudget,matches=[];for(let index=0;index<this.loadState.doc.cells.length;index++){const cell=this.loadState.doc.cells[index],sourceParts=typeof cell.source=="string"?[cell.source]:cell.source,sourceMatch=budget.includesJoined(sourceParts,q,this.effectiveLocale),outputMatch=sourceMatch?!1:budget.includesJoined(notebookOutputSearchParts(cell.outputs??[]),q,this.effectiveLocale);if((sourceMatch||outputMatch)&&matches.push(index),!budget.complete){this.searchMatchCountExact=!1;break}}this.searchMatches=matches}return this.activeSearchIndex=this.searchMatches.length?0:-1,await this.activateSearchMatch(),this.emitSearchChange(),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchMatches.length)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}clearSearch(){this.clearSearchState(),this.emitSearchChange()}clearSearchState(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1}async activateSearchMatch(){const index=this.searchMatches[this.activeSearchIndex];index!==void 0&&await this.activateCell(index,"auto")}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.activeSearchIndex})}toggleOutput(index){const next=new Set(this.expandedOutputs);next.has(index)?next.delete(index):next.add(index),this.expandedOutputs=next}renderAnsiText(text){const segments=createAnsiParser().push(text);return html`${segments.map(seg=>html`<span style=${styleMap(this.segmentStyle(seg.styles))}>${seg.text}</span>`)}`}segmentStyle(s){const fg=sanitizeCssColor(s.fg)??"var(--lr-color-text)",bg=sanitizeCssColor(s.bg)??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}renderTextOutput(index,text,tone){const lines=text.split(`
26
+ </div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,loadingDocument:LYRA_DEFAULT_loadingDocument,notebookViewerCodeCell:LYRA_DEFAULT_notebookViewerCodeCell,notebookViewerCollapseOutput:LYRA_DEFAULT_notebookViewerCollapseOutput,notebookViewerErrorOutput:LYRA_DEFAULT_notebookViewerErrorOutput,notebookViewerInPrompt:LYRA_DEFAULT_notebookViewerInPrompt,notebookViewerInPromptEmpty:LYRA_DEFAULT_notebookViewerInPromptEmpty,notebookViewerInvalid:LYRA_DEFAULT_notebookViewerInvalid,notebookViewerLabel:LYRA_DEFAULT_notebookViewerLabel,notebookViewerMarkdownCell:LYRA_DEFAULT_notebookViewerMarkdownCell,notebookViewerRawCell:LYRA_DEFAULT_notebookViewerRawCell,notebookViewerShowAllOutput:LYRA_DEFAULT_notebookViewerShowAllOutput,notebookViewerTooManyCells:LYRA_DEFAULT_notebookViewerTooManyCells,notebookViewerUnrenderedOutput:LYRA_DEFAULT_notebookViewerUnrenderedOutput,notebookViewerUnsupportedVersion:LYRA_DEFAULT_notebookViewerUnsupportedVersion}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["notebook"])}static{this.identityCollectionObjectProperties=Object.freeze(["notebook"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,viewerLoadingStyles]}get notebook(){return this._notebook}set notebook(value){if(value!==void 0&&(value===this.notebookSource||value===this._notebook))return;this.notebookSource=value;const old=this._notebook,next=typeof value=="string"||value===void 0?value:(()=>{const snapshot=snapshotNotebookDocument(value);return snapshot===OMIT_NOTEBOOK_SNAPSHOT?invalidNotebookSnapshot():snapshot})();Object.is(old,next)||(this._notebook=next,this.requestUpdate("notebook",old),next===void 0?(this.beginSourceTransition(this.src?"loading":"idle"),this.isConnected&&this.scheduleSourceLoad()):this.parseInline())}get source(){return resolveViewerSource(this.src,this._notebook)}set source(_value){}get effectiveOutputCollapseLines(){return finiteCount(this.outputCollapseLines,40)}updated(changed){super.updated(changed),this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument")),changed.has("src")&&this._notebook===void 0&&this.scheduleSourceLoad();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&this._notebook===void 0&&this.beginSourceTransition(this.src?"loading":"idle"),(changed.has("highlights")||changed.has("activeHighlightId")||changed.has("loadState"))&&this.repaintHighlights()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.loadState.kind!=="loading")&&(this.hasUpdated&&this.src&&this._notebook===void 0&&this.scheduleSourceLoad(),this.hasUpdated&&this._notebook!==void 0&&this.loadState.kind==="loaded"&&this.requestUpdate())}disconnectedCallback(){this._notebook===void 0&&this.loadState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedNotebook(){this.generation++,this.sanitizerGeneration++,this.beginAbortableLoad(),this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.sourceLoadScheduled=!1,this._notebook===void 0&&(this.loadState={kind:"idle"})}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}parseInline(){if(this._notebook===void 0)return;const generation=++this.generation;this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind:"idle"};try{const raw=typeof this._notebook=="string"?JSON.parse(this._notebook):this._notebook;this.setDoc(raw,generation)}catch(error){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error})}}resetParsedState(){const shouldEmitSearchReset=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.activeSearchIndex!==-1;this.sanitizerGeneration++,this.sanitizedOutputCache.clear(),this.sanitizationTasks.clear(),this.sanitizerFailureReported=!1,this.expandedOutputs=new Set,this.clearSearchState(),this.activeCellIndex=null,shouldEmitSearchReset&&this.emitSearchChange()}beginSourceTransition(kind){this.generation++,this.beginAbortableLoad(),this.resetParsedState(),this.loadState={kind}}scheduleSourceLoad(){this.sourceLoadScheduled||(this.sourceLoadScheduled=!0,this.scheduleAfterUpdate(()=>{this.sourceLoadScheduled=!1,this.isConnected&&this._notebook===void 0&&this.loadFromSrc()}))}async loadFromSrc(){if(!this.isConnected||this._notebook!==void 0)return;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.loadState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.setDoc(JSON.parse(text),generation)}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}setDoc(raw,generation){if(generation!==this.generation)return;if(!isNotebookShape(raw)){this.loadState={kind:"error",message:this.localize("notebookViewerInvalid")},this.emit("lr-render-error",{error:new Error("invalid notebook shape")});return}if(raw.nbformat!==SUPPORTED_MAJOR||!SUPPORTED_MINORS.includes(raw.nbformat_minor)){this.loadState={kind:"error",message:this.localize("notebookViewerUnsupportedVersion",void 0,{version:`${raw.nbformat}.${raw.nbformat_minor}`})},this.emit("lr-render-error",{error:new Error("unsupported nbformat version")});return}if(raw.cells.length>MAX_CELLS){this.loadState={kind:"error",message:this.localize("notebookViewerTooManyCells")},this.emit("lr-render-error",{error:new Error("too many cells")});return}this.resetParsedState(),this.loadState={kind:"loaded",doc:raw};const language=raw.metadata?.language_info?.name??raw.metadata?.kernelspec?.language??"";this.emit("lr-load",{cellCount:raw.cells.length,language})}async applyAnchor(anchor){const index=this.resolveAnchorCellIndex(anchor);return index<0?!1:this.activateCell(index,"start")}async activateCell(index,align){const generation=this.generation,ownerDocument=this.ownerDocument;if(this.activeCellIndex=index,!this.isConnected||(await this.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index))return!1;const list=this.virtualListEl;return!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==ownerDocument||generation!==this.generation||this.activeCellIndex!==index)?!1:(list.scrollToIndex(index,{align,behavior:"auto"}),await list.updateComplete,this.isConnected&&this.ownerDocument===ownerDocument&&generation===this.generation&&this.activeCellIndex===index)}resolveAnchorCellIndex(anchor){if(this.loadState.kind!=="loaded")return-1;const cells=this.loadState.doc.cells;let index=-1;if(anchor.kind==="node-path"&&Number.isInteger(anchor.path[0]))index=anchor.path[0];else if(anchor.kind==="fragment")index=cells.findIndex(c=>c.id===anchor.id);else return-1;return index<0||index>=cells.length?-1:index}repaintHighlights(){if(this.loadState.kind!=="loaded"){this.highlightedCells.size>0&&(this.highlightedCells=new Map);return}const next=new Map;let considered=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(considered>=MAX_NOTEBOOK_PAINTED_HIGHLIGHTS)break;considered++;const index=this.resolveAnchorCellIndex(highlight.anchor);index<0||next.has(index)||next.set(index,highlight)}this.highlightedCells=next}async search(query2){const boundedQuery=boundedViewerSearchQuery(query2,this.effectiveLocale),q=boundedQuery.needle;if(this.searchQuery=query2,this.lastSearchLocale=this.effectiveLocale,this.searchMatchCountExact=boundedQuery.accepted,this.loadState.kind!=="loaded"||!q||!boundedQuery.accepted)this.searchMatches=[];else{const budget=new ViewerSearchWorkBudget,matches=[];for(let index=0;index<this.loadState.doc.cells.length;index++){const cell=this.loadState.doc.cells[index],sourceParts=typeof cell.source=="string"?[cell.source]:cell.source,sourceMatch=budget.includesJoined(sourceParts,q,this.effectiveLocale),outputMatch=sourceMatch?!1:budget.includesJoined(notebookOutputSearchParts(cell.outputs??[]),q,this.effectiveLocale);if((sourceMatch||outputMatch)&&matches.push(index),!budget.complete){this.searchMatchCountExact=!1;break}}this.searchMatches=matches}return this.activeSearchIndex=this.searchMatches.length?0:-1,await this.activateSearchMatch(),this.emitSearchChange(),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchMatches.length)%this.searchMatches.length,await this.activateSearchMatch(),this.emitSearchChange(),!0):!1}clearSearch(){this.clearSearchState(),this.emitSearchChange()}clearSearchState(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.activeSearchIndex=-1}async activateSearchMatch(){const index=this.searchMatches[this.activeSearchIndex];index!==void 0&&await this.activateCell(index,"auto")}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.activeSearchIndex})}toggleOutput(index){const next=new Set(this.expandedOutputs);next.has(index)?next.delete(index):next.add(index),this.expandedOutputs=next}renderAnsiText(text){const segments=createAnsiParser().push(text);return html`${segments.map(seg=>html`<span style=${styleMap(this.segmentStyle(seg.styles))}>${seg.text}</span>`)}`}segmentStyle(s){const fg=sanitizeCssColor(s.fg)??"var(--lr-color-text)",bg=sanitizeCssColor(s.bg)??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}renderTextOutput(index,text,tone){const lines=text.split(`
27
27
  `),outputCollapseLines=this.effectiveOutputCollapseLines,collapsible=outputCollapseLines>0&&lines.length>outputCollapseLines,expanded=this.expandedOutputs.has(index)||!collapsible,shown=expanded?text:lines.slice(0,outputCollapseLines).join(`
28
28
  `);return html`<div part=${tone==="danger"?"output output-error":"output"} data-output-type="stream" data-stream=${tone==="danger"?"stderr":"stdout"}
29
29
  >${this.renderAnsiText(shown)}${collapsible?html`<button
@@ -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 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;
133
+ readonly anchorKinds:readonly['page','text-quote','region'];private loadState;private readonly pageViewerState;private scrollDrivenPage;private firstVisiblePage;private loadLibrary;private generation;private pendingTransportGeneration?;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`