@aceshooting/lyra-ui 11.0.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +8 -0
  3. package/custom-elements.json +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  5. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  6. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  7. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  8. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  9. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  10. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  11. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  12. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  13. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  14. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  15. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  16. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  17. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  18. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  19. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  20. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  21. package/dist/components/charts/chart/chart.class.js +1 -1
  22. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  23. package/dist/components/charts/chart/histogram.class.js +1 -1
  24. package/dist/components/charts/chart/line-chart.class.js +1 -1
  25. package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
  26. package/dist/components/charts/chart/lite-chart.class.js +17 -4
  27. package/dist/components/charts/chart/lite-chart.styles.js +29 -0
  28. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  29. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  30. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  31. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  32. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  33. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  34. package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
  35. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  36. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  37. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
  38. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  39. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  40. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  41. package/dist/components/data/heatmap/heatmap.class.d.ts +36 -1
  42. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  43. package/dist/components/data/table/table.class.d.ts +19 -0
  44. package/dist/components/data/table/table.class.js +3 -3
  45. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  46. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  47. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  48. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  49. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  50. package/dist/components/forms/combobox/combobox.class.js +1 -1
  51. package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
  52. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  53. package/dist/components/forms/date-picker/date-picker.class.d.ts +30 -4
  54. package/dist/components/forms/date-picker/date-picker.class.js +4 -4
  55. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  56. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  57. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  58. package/dist/components/forms/radio/radio-group.class.js +1 -1
  59. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  60. package/dist/components/forms/radio/radio.class.js +1 -1
  61. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  62. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  63. package/dist/components/forms/select/select.class.d.ts +1 -0
  64. package/dist/components/forms/select/select.class.js +1 -1
  65. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  66. package/dist/components/forms/slider/slider.class.js +1 -1
  67. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  68. package/dist/components/forms/switch/switch.class.js +1 -1
  69. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  70. package/dist/components/forms/time-range/time-range.class.js +1 -1
  71. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  72. package/dist/components/forms/token-input/token-input.class.js +1 -1
  73. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  74. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  75. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  76. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  77. package/dist/components/media/file-input/file-input.class.js +1 -1
  78. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  79. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  80. package/dist/components/media/flag/flag.class.d.ts +28 -0
  81. package/dist/components/media/flag/flag.class.js +2 -2
  82. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  83. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  84. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  85. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  86. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  87. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  88. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  89. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  90. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  91. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  92. package/dist/custom-elements-jsx.d.ts +5 -3
  93. package/dist/events.d.ts +7 -0
  94. package/dist/internal/canvas.js +1 -1
  95. package/dist/internal/form-associated.d.ts +1 -0
  96. package/dist/internal/form-associated.js +1 -1
  97. package/dist/internal/form-control-labels.js +1 -1
  98. package/dist/internal/lyra-element.js +1 -1
  99. package/dist/internal/package-metadata.d.ts +1 -1
  100. package/dist/internal/package-metadata.js +1 -1
  101. package/dist/lyra.d.ts +1 -1
  102. package/dist/svelte.d.ts +5 -3
  103. package/dist/theme.css +32 -0
  104. package/dist/vue.d.ts +5 -3
  105. package/llms/components/lr-agent-eval-dashboard.md +1 -1
  106. package/llms/components/lr-agent-workspace.md +1 -1
  107. package/llms/components/lr-box-plot.md +2 -2
  108. package/llms/components/lr-chart.md +1 -1
  109. package/llms/components/lr-chunk-inspector.md +1 -1
  110. package/llms/components/lr-combobox.md +3 -3
  111. package/llms/components/lr-date-input.md +22 -6
  112. package/llms/components/lr-date-picker.md +21 -5
  113. package/llms/components/lr-entity-dossier.md +1 -1
  114. package/llms/components/lr-eval-run.md +1 -1
  115. package/llms/components/lr-flag.md +24 -1
  116. package/llms/components/lr-grounding-summary.md +1 -1
  117. package/llms/components/lr-heatmap.md +18 -6
  118. package/llms/components/lr-lite-chart.md +19 -3
  119. package/llms/components/lr-map.md +2 -2
  120. package/llms/components/lr-memory-panel.md +1 -1
  121. package/llms/components/lr-option.md +3 -3
  122. package/llms/components/lr-popover.md +1 -1
  123. package/llms/components/lr-provenance-panel.md +1 -1
  124. package/llms/components/lr-rag-answer.md +1 -1
  125. package/llms/components/lr-rag-eval-dashboard.md +1 -1
  126. package/llms/components/lr-retrieval-results.md +1 -1
  127. package/llms/components/lr-retrieval-trace.md +1 -1
  128. package/llms/peers.md +10 -10
  129. package/llms/shared.md +19 -0
  130. package/llms/tokens.md +12 -0
  131. package/llms-full.txt +109 -21
  132. package/package.json +6 -6
  133. package/vscode-css-data.json +14 -0
  134. package/vscode-html-data.json +17 -3
  135. package/web-types.json +30 -4
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.slotPresence=new SlotPresenceController(this),this.hovering=!1,this.focused=!1,this.onPointerEnter=()=>{this.hovering=!0,this.showPreview()},this.onPointerLeave=()=>{this.hovering=!1,this.scheduleHidePreview()},this.onFocusIn=()=>{this.focused=!0,this.showPreview()},this.onFocusOut=()=>{this.focused=!1,!this.hovering&&this.hidePreviewNow()},this.onKeyDown=e=>{if(e.key==="Escape"&&this.popoverOpen){e.stopPropagation(),this.hidePreviewNow();return}e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed),this.popoverOpen&&!this.hasPreviewSlot&&this.hidePreviewNow()}updated(changed){super.updated(changed),changed.has("popoverOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.popoverOpen&&this.buttonEl&&this.popoverEl&&(this.cleanupPositioner=place(this.buttonEl,this.popoverEl,{placement:"top-start"})))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen=!1,this.hovering=!1,this.focused=!1}get accessibleLabel(){const index=getNumberFormat(this.effectiveLocale).format(this.index);if(this.label)return this.localize("citationWithCustomLabel",void 0,{index,label:this.label});const key=STATUS_MESSAGE_KEY[this.status],statusText=key?this.localize(key):"",citationLabel=this.localize("citation",void 0,{index});return statusText?this.localize("citationWithStatus",void 0,{index,status:statusText}):citationLabel}showPreview(){this.hasPreviewSlot&&(clearTimeout(this.hideTimer),this.hideTimer=void 0,!this.popoverOpen&&(this.popoverOpen=!0))}scheduleHidePreview(){!this.popoverOpen||this.hovering||this.focused||(clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{this.hideTimer=void 0,this.popoverOpen=!1},HIDE_DELAY_MS))}hidePreviewNow(){clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen&&(this.popoverOpen=!1)}emitOpen(){this.emit("lr-citation-open",{sourceId:this.sourceId,index:this.index,href:this.href||void 0})}render(){const formattedIndex=getNumberFormat(this.effectiveLocale).format(this.index);return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.slotPresence=new SlotPresenceController(this),this.hovering=!1,this.focused=!1,this.onPointerEnter=()=>{this.hovering=!0,this.showPreview()},this.onPointerLeave=()=>{this.hovering=!1,this.scheduleHidePreview()},this.onFocusIn=()=>{this.focused=!0,this.showPreview()},this.onFocusOut=()=>{this.focused=!1,!this.hovering&&this.hidePreviewNow()},this.onKeyDown=e=>{if(e.key==="Escape"&&this.popoverOpen){e.stopPropagation(),this.hidePreviewNow();return}e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,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]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}get hasPreviewSlot(){return this.slotPresence.has()}willUpdate(changed){super.willUpdate(changed),this.popoverOpen&&!this.hasPreviewSlot&&this.hidePreviewNow()}updated(changed){super.updated(changed),changed.has("popoverOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.popoverOpen&&this.buttonEl&&this.popoverEl&&(this.cleanupPositioner=place(this.buttonEl,this.popoverEl,{placement:"top-start"})))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen=!1,this.hovering=!1,this.focused=!1}get accessibleLabel(){const index=getNumberFormat(this.effectiveLocale).format(this.index);if(this.label)return this.localize("citationWithCustomLabel",void 0,{index,label:this.label});const key=STATUS_MESSAGE_KEY[this.status],statusText=key?this.localize(key):"",citationLabel=this.localize("citation",void 0,{index});return statusText?this.localize("citationWithStatus",void 0,{index,status:statusText}):citationLabel}showPreview(){this.hasPreviewSlot&&(clearTimeout(this.hideTimer),this.hideTimer=void 0,!this.popoverOpen&&(this.popoverOpen=!0))}scheduleHidePreview(){!this.popoverOpen||this.hovering||this.focused||(clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{this.hideTimer=void 0,this.popoverOpen=!1},HIDE_DELAY_MS))}hidePreviewNow(){clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen&&(this.popoverOpen=!1)}emitOpen(){this.emit("lr-citation-open",{sourceId:this.sourceId,index:this.index,href:this.href||void 0})}render(){const formattedIndex=getNumberFormat(this.effectiveLocale).format(this.index);return html`
2
2
  <span
3
3
  class="wrapper"
4
4
  @pointerenter=${this.onPointerEnter}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteRange}from"../../../internal/numbers.js";import"../../overlays/badge/badge.class.js";import"../../overlays/empty/empty.class.js";import"../citation-badge/citation-badge.class.js";import{styles}from"./claim-evidence.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_claimEvidenceConfidence,LYRA_DEFAULT_claimEvidenceContradicted,LYRA_DEFAULT_claimEvidenceEmpty,LYRA_DEFAULT_claimEvidenceLabel,LYRA_DEFAULT_claimEvidencePartiallySupported,LYRA_DEFAULT_claimEvidenceSupported,LYRA_DEFAULT_claimEvidenceUnsupported,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_VARIANT={supported:"success","partially-supported":"warning",unsupported:"danger",contradicted:"danger"};class LyraClaimEvidence extends LyraElement{constructor(){super(...arguments),this.claims=[],this.citations=[],this.selectedClaimId="",this.label="",this.compact=!1,this.frame="card"}static{this.defaultStrings={...super.defaultStrings,claimEvidenceConfidence:LYRA_DEFAULT_claimEvidenceConfidence,claimEvidenceContradicted:LYRA_DEFAULT_claimEvidenceContradicted,claimEvidenceEmpty:LYRA_DEFAULT_claimEvidenceEmpty,claimEvidenceLabel:LYRA_DEFAULT_claimEvidenceLabel,claimEvidencePartiallySupported:LYRA_DEFAULT_claimEvidencePartiallySupported,claimEvidenceSupported:LYRA_DEFAULT_claimEvidenceSupported,claimEvidenceUnsupported:LYRA_DEFAULT_claimEvidenceUnsupported,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["claims","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-claim-select","lr-citation-select"])}get normalizedClaims(){return firstByRetrievalIdentity(Array.isArray(this.claims)?this.claims:[],claim=>claim.id)}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}statusLabel(status){switch(status){case"supported":return this.localize("claimEvidenceSupported");case"partially-supported":return this.localize("claimEvidencePartiallySupported");case"unsupported":return this.localize("claimEvidenceUnsupported");case"contradicted":return this.localize("claimEvidenceContradicted")}}confidenceLabel(value){const percent=getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1));return this.localize("claimEvidenceConfidence",void 0,{percent})}resolvedCitations(claim,citations){const ids=new Set(claim.citationIds);return citations.filter(citation=>ids.has(citation.id))}renderClaim(claim,allCitations){const selected=claim.id===this.selectedClaimId,citations=this.resolvedCitations(claim,allCitations);return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteRange}from"../../../internal/numbers.js";import"../../overlays/badge/badge.class.js";import"../../overlays/empty/empty.class.js";import"../citation-badge/citation-badge.class.js";import{styles}from"./claim-evidence.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_claimEvidenceConfidence,LYRA_DEFAULT_claimEvidenceContradicted,LYRA_DEFAULT_claimEvidenceEmpty,LYRA_DEFAULT_claimEvidenceLabel,LYRA_DEFAULT_claimEvidencePartiallySupported,LYRA_DEFAULT_claimEvidenceSupported,LYRA_DEFAULT_claimEvidenceUnsupported,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_VARIANT={supported:"success","partially-supported":"warning",unsupported:"danger",contradicted:"danger"};class LyraClaimEvidence extends LyraElement{constructor(){super(...arguments),this.claims=[],this.citations=[],this.selectedClaimId="",this.label="",this.compact=!1,this.frame="card"}static{this.defaultStrings={...super.defaultStrings,claimEvidenceConfidence:LYRA_DEFAULT_claimEvidenceConfidence,claimEvidenceContradicted:LYRA_DEFAULT_claimEvidenceContradicted,claimEvidenceEmpty:LYRA_DEFAULT_claimEvidenceEmpty,claimEvidenceLabel:LYRA_DEFAULT_claimEvidenceLabel,claimEvidencePartiallySupported:LYRA_DEFAULT_claimEvidencePartiallySupported,claimEvidenceSupported:LYRA_DEFAULT_claimEvidenceSupported,claimEvidenceUnsupported:LYRA_DEFAULT_claimEvidenceUnsupported,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,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.ownedCollectionProperties=Object.freeze(["claims","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-claim-select","lr-citation-select"])}get normalizedClaims(){return firstByRetrievalIdentity(Array.isArray(this.claims)?this.claims:[],claim=>claim.id)}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}statusLabel(status){switch(status){case"supported":return this.localize("claimEvidenceSupported");case"partially-supported":return this.localize("claimEvidencePartiallySupported");case"unsupported":return this.localize("claimEvidenceUnsupported");case"contradicted":return this.localize("claimEvidenceContradicted")}}confidenceLabel(value){const percent=getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1));return this.localize("claimEvidenceConfidence",void 0,{percent})}resolvedCitations(claim,citations){const ids=new Set(claim.citationIds);return citations.filter(citation=>ids.has(citation.id))}renderClaim(claim,allCitations){const selected=claim.id===this.selectedClaimId,citations=this.resolvedCitations(claim,allCitations);return html`
2
2
  <li part=${selected?"claim claim-selected":"claim"} aria-current=${selected?"true":"false"}>
3
3
  <button
4
4
  part="claim-trigger"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import"../../data/stat/stat.class.js";import"../citation-badge/citation-badge.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./grounding-summary.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import"../claim-evidence/claim-evidence.class.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_groundingSummaryConfidenceLabel,LYRA_DEFAULT_groundingSummaryCoverageLabel,LYRA_DEFAULT_groundingSummaryEmpty,LYRA_DEFAULT_groundingSummaryEvidenceHeading,LYRA_DEFAULT_groundingSummaryEvidenceSpan,LYRA_DEFAULT_groundingSummaryLabel,LYRA_DEFAULT_groundingSummarySupportedLabel,LYRA_DEFAULT_groundingSummaryUnsupportedLabel,LYRA_DEFAULT_groundingSummaryWarningsHeading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraGroundingSummary extends LyraElement{constructor(){super(...arguments),this.assessment=null,this.citations=[],this.thresholds={high:.8,medium:.5},this.showClaims=!0,this.headingLevel="3",this.renderEvidenceItem=(citation,index)=>{const numberFormat=getNumberFormat(this.effectiveLocale),spanText=citation.span?this.localize("groundingSummaryEvidenceSpan",void 0,{start:numberFormat.format(finiteCount(citation.span.start)),end:numberFormat.format(finiteCount(citation.span.end))}):"";return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import"../../data/stat/stat.class.js";import"../citation-badge/citation-badge.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./grounding-summary.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import"../claim-evidence/claim-evidence.class.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_groundingSummaryConfidenceLabel,LYRA_DEFAULT_groundingSummaryCoverageLabel,LYRA_DEFAULT_groundingSummaryEmpty,LYRA_DEFAULT_groundingSummaryEvidenceHeading,LYRA_DEFAULT_groundingSummaryEvidenceSpan,LYRA_DEFAULT_groundingSummaryLabel,LYRA_DEFAULT_groundingSummarySupportedLabel,LYRA_DEFAULT_groundingSummaryUnsupportedLabel,LYRA_DEFAULT_groundingSummaryWarningsHeading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraGroundingSummary extends LyraElement{constructor(){super(...arguments),this.assessment=null,this.citations=[],this.thresholds={high:.8,medium:.5},this.showClaims=!0,this.headingLevel="3",this.renderEvidenceItem=(citation,index)=>{const numberFormat=getNumberFormat(this.effectiveLocale),spanText=citation.span?this.localize("groundingSummaryEvidenceSpan",void 0,{start:numberFormat.format(finiteCount(citation.span.start)),end:numberFormat.format(finiteCount(citation.span.end))}):"";return html`
2
2
  <li part="evidence-item">
3
3
  <lr-citation-badge
4
4
  index=${index+1}
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  ${citation.label?html`<span part="evidence-label">${citation.label}</span>`:nothing}
12
12
  ${spanText?html`<span part="evidence-span">${spanText}</span>`:nothing}
13
13
  </li>
14
- `}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,groundingSummaryConfidenceLabel:LYRA_DEFAULT_groundingSummaryConfidenceLabel,groundingSummaryCoverageLabel:LYRA_DEFAULT_groundingSummaryCoverageLabel,groundingSummaryEmpty:LYRA_DEFAULT_groundingSummaryEmpty,groundingSummaryEvidenceHeading:LYRA_DEFAULT_groundingSummaryEvidenceHeading,groundingSummaryEvidenceSpan:LYRA_DEFAULT_groundingSummaryEvidenceSpan,groundingSummaryLabel:LYRA_DEFAULT_groundingSummaryLabel,groundingSummarySupportedLabel:LYRA_DEFAULT_groundingSummarySupportedLabel,groundingSummaryUnsupportedLabel:LYRA_DEFAULT_groundingSummaryUnsupportedLabel,groundingSummaryWarningsHeading:LYRA_DEFAULT_groundingSummaryWarningsHeading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["assessment","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-claim-select"])}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}normalizedClaims(assessment){return firstByRetrievalIdentity(Array.isArray(assessment.claims)?assessment.claims:[],claim=>claim.id)}sectionHeading(part,text){switch(resolveHeadingLevel(this.headingLevel)){case"1":return html`<h1 part=${part}>${text}</h1>`;case"2":return html`<h2 part=${part}>${text}</h2>`;case"4":return html`<h4 part=${part}>${text}</h4>`;case"5":return html`<h5 part=${part}>${text}</h5>`;case"6":return html`<h6 part=${part}>${text}</h6>`;case"3":return html`<h3 part=${part}>${text}</h3>`;default:return html`<span part=${part}>${text}</span>`}}tone(value){return value>=this.thresholds.high?"success":value>=this.thresholds.medium?"warning":"danger"}formatPercent(value){return getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1))}onCitationSelect(citation,event){event.stopPropagation(),this.emit("lr-citation-select",{citation})}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("groundingSummaryLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),a=this.assessment;if(!a)return html`<div
14
+ `}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,groundingSummaryConfidenceLabel:LYRA_DEFAULT_groundingSummaryConfidenceLabel,groundingSummaryCoverageLabel:LYRA_DEFAULT_groundingSummaryCoverageLabel,groundingSummaryEmpty:LYRA_DEFAULT_groundingSummaryEmpty,groundingSummaryEvidenceHeading:LYRA_DEFAULT_groundingSummaryEvidenceHeading,groundingSummaryEvidenceSpan:LYRA_DEFAULT_groundingSummaryEvidenceSpan,groundingSummaryLabel:LYRA_DEFAULT_groundingSummaryLabel,groundingSummarySupportedLabel:LYRA_DEFAULT_groundingSummarySupportedLabel,groundingSummaryUnsupportedLabel:LYRA_DEFAULT_groundingSummaryUnsupportedLabel,groundingSummaryWarningsHeading:LYRA_DEFAULT_groundingSummaryWarningsHeading,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.ownedCollectionProperties=Object.freeze(["assessment","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-claim-select"])}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}normalizedClaims(assessment){return firstByRetrievalIdentity(Array.isArray(assessment.claims)?assessment.claims:[],claim=>claim.id)}sectionHeading(part,text){switch(resolveHeadingLevel(this.headingLevel)){case"1":return html`<h1 part=${part}>${text}</h1>`;case"2":return html`<h2 part=${part}>${text}</h2>`;case"4":return html`<h4 part=${part}>${text}</h4>`;case"5":return html`<h5 part=${part}>${text}</h5>`;case"6":return html`<h6 part=${part}>${text}</h6>`;case"3":return html`<h3 part=${part}>${text}</h3>`;default:return html`<span part=${part}>${text}</span>`}}tone(value){return value>=this.thresholds.high?"success":value>=this.thresholds.medium?"warning":"danger"}formatPercent(value){return getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1))}onCitationSelect(citation,event){event.stopPropagation(),this.emit("lr-citation-select",{citation})}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("groundingSummaryLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),a=this.assessment;if(!a)return html`<div
15
15
  part="base"
16
16
  role=${groupRole??nothing}
17
17
  aria-label=${groupLabel??nothing}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import"../../agent-tools/span-waterfall/span-waterfall.class.js";import"../chunk-inspector/chunk-inspector.class.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{styles}from"./retrieval-trace.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_retrievalStageEmbed,LYRA_DEFAULT_retrievalStageFilter,LYRA_DEFAULT_retrievalStageQueryRewrite,LYRA_DEFAULT_retrievalStageRerank,LYRA_DEFAULT_retrievalStageRetrieve,LYRA_DEFAULT_retrievalTraceEvidenceToggle,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STAGE_SPAN_KIND={"query-rewrite":"llm",embed:"embedding",retrieve:"retriever",rerank:"tool",filter:"tool"},STAGE_LABEL={"query-rewrite":{key:"retrievalStageQueryRewrite"},embed:{key:"retrievalStageEmbed"},retrieve:{key:"retrievalStageRetrieve"},rerank:{key:"retrievalStageRerank"},filter:{key:"retrievalStageFilter"}};function hasEvidence(evidence){return evidence?!!evidence.text||!!(evidence.chunks&&evidence.chunks.length>0)||!!(evidence.metadata&&Object.keys(evidence.metadata).length>0):!1}function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,...chunk.locator?{anchor:chunk.locator}:{},...chunk.locator?.kind==="page"?{page:chunk.locator.page}:{}}}class LyraRetrievalTrace extends LyraElement{constructor(){super(...arguments),this.stages=[],this.activeStageId=null,this.label="",this.expandedStageIds=new Set,this.evidenceDomIdPrefix=nextId("retrieval-trace-evidence"),this.onStageSelect=e=>{e.stopPropagation();const{spanId:stageId}=e.detail;this.emit("lr-stage-select",{stageId});const stage=this.normalizedStages.find(s=>s.id===stageId);if(stage&&hasEvidence(stage.evidence)&&!this.expandedStageIds.has(stageId)){const next=new Set(this.expandedStageIds);next.add(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded:!0})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,retrievalStageEmbed:LYRA_DEFAULT_retrievalStageEmbed,retrievalStageFilter:LYRA_DEFAULT_retrievalStageFilter,retrievalStageQueryRewrite:LYRA_DEFAULT_retrievalStageQueryRewrite,retrievalStageRerank:LYRA_DEFAULT_retrievalStageRerank,retrievalStageRetrieve:LYRA_DEFAULT_retrievalStageRetrieve,retrievalTraceEvidenceToggle:LYRA_DEFAULT_retrievalTraceEvidenceToggle,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["stages"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-stage-chunk-action"])}get normalizedStages(){return firstByRetrievalIdentity(Array.isArray(this.stages)?this.stages:[],stage=>stage.id)}stageLabel(stage){return stage.label?stage.label:this.localize(STAGE_LABEL[stage.kind].key)}toSpans(){return this.normalizedStages.map(stage=>({id:stage.id,name:this.stageLabel(stage),kind:STAGE_SPAN_KIND[stage.kind],startMs:stage.startMs,endMs:stage.endMs,status:stage.status,detail:stage.detail}))}toggleEvidence(stageId){const expanded=!this.expandedStageIds.has(stageId),next=new Set(this.expandedStageIds);expanded?next.add(stageId):next.delete(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded})}willUpdate(changed){if(super.willUpdate(changed),changed.has("stages")){const ids=new Set(this.normalizedStages.map(s=>s.id));let pruned=null;for(const id of this.expandedStageIds)ids.has(id)||(pruned??=new Set(this.expandedStageIds),pruned.delete(id));pruned&&(this.expandedStageIds=pruned)}}renderEvidenceBody(stage){const evidence=stage.evidence,chunks=evidence.chunks&&evidence.chunks.length>0?evidence.chunks.map(toLyraChunk):[],metaEntries=evidence.metadata?Object.entries(evidence.metadata):[];return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import"../../agent-tools/span-waterfall/span-waterfall.class.js";import"../chunk-inspector/chunk-inspector.class.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{styles}from"./retrieval-trace.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_retrievalStageEmbed,LYRA_DEFAULT_retrievalStageFilter,LYRA_DEFAULT_retrievalStageQueryRewrite,LYRA_DEFAULT_retrievalStageRerank,LYRA_DEFAULT_retrievalStageRetrieve,LYRA_DEFAULT_retrievalTraceEvidenceToggle,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STAGE_SPAN_KIND={"query-rewrite":"llm",embed:"embedding",retrieve:"retriever",rerank:"tool",filter:"tool"},STAGE_LABEL={"query-rewrite":{key:"retrievalStageQueryRewrite"},embed:{key:"retrievalStageEmbed"},retrieve:{key:"retrievalStageRetrieve"},rerank:{key:"retrievalStageRerank"},filter:{key:"retrievalStageFilter"}};function hasEvidence(evidence){return evidence?!!evidence.text||!!(evidence.chunks&&evidence.chunks.length>0)||!!(evidence.metadata&&Object.keys(evidence.metadata).length>0):!1}function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,...chunk.locator?{anchor:chunk.locator}:{},...chunk.locator?.kind==="page"?{page:chunk.locator.page}:{}}}class LyraRetrievalTrace extends LyraElement{constructor(){super(...arguments),this.stages=[],this.activeStageId=null,this.label="",this.expandedStageIds=new Set,this.evidenceDomIdPrefix=nextId("retrieval-trace-evidence"),this.onStageSelect=e=>{e.stopPropagation();const{spanId:stageId}=e.detail;this.emit("lr-stage-select",{stageId});const stage=this.normalizedStages.find(s=>s.id===stageId);if(stage&&hasEvidence(stage.evidence)&&!this.expandedStageIds.has(stageId)){const next=new Set(this.expandedStageIds);next.add(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded:!0})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,retrievalStageEmbed:LYRA_DEFAULT_retrievalStageEmbed,retrievalStageFilter:LYRA_DEFAULT_retrievalStageFilter,retrievalStageQueryRewrite:LYRA_DEFAULT_retrievalStageQueryRewrite,retrievalStageRerank:LYRA_DEFAULT_retrievalStageRerank,retrievalStageRetrieve:LYRA_DEFAULT_retrievalStageRetrieve,retrievalTraceEvidenceToggle:LYRA_DEFAULT_retrievalTraceEvidenceToggle,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["stages"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-stage-chunk-action"])}get normalizedStages(){return firstByRetrievalIdentity(Array.isArray(this.stages)?this.stages:[],stage=>stage.id)}stageLabel(stage){return stage.label?stage.label:this.localize(STAGE_LABEL[stage.kind].key)}toSpans(){return this.normalizedStages.map(stage=>({id:stage.id,name:this.stageLabel(stage),kind:STAGE_SPAN_KIND[stage.kind],startMs:stage.startMs,endMs:stage.endMs,status:stage.status,detail:stage.detail}))}toggleEvidence(stageId){const expanded=!this.expandedStageIds.has(stageId),next=new Set(this.expandedStageIds);expanded?next.add(stageId):next.delete(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded})}willUpdate(changed){if(super.willUpdate(changed),changed.has("stages")){const ids=new Set(this.normalizedStages.map(s=>s.id));let pruned=null;for(const id of this.expandedStageIds)ids.has(id)||(pruned??=new Set(this.expandedStageIds),pruned.delete(id));pruned&&(this.expandedStageIds=pruned)}}renderEvidenceBody(stage){const evidence=stage.evidence,chunks=evidence.chunks&&evidence.chunks.length>0?evidence.chunks.map(toLyraChunk):[],metaEntries=evidence.metadata?Object.entries(evidence.metadata):[];return html`
2
2
  ${evidence.text?html`<p part="evidence-text">${evidence.text}</p>`:nothing}
3
3
  ${chunks.length>0?html`<lr-chunk-inspector
4
4
  part="chunk-inspector"
@@ -1 +1 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=item=>item.name,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;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>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=item=>item.name,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;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>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.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{getListFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{parseVCards}from"./vcard.js";import{styles}from"./contact-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_contactViewerAddressFormat,LYRA_DEFAULT_contactViewerAddressLabel,LYRA_DEFAULT_contactViewerEmailLabel,LYRA_DEFAULT_contactViewerLabel,LYRA_DEFAULT_contactViewerNoContacts,LYRA_DEFAULT_contactViewerOrganization,LYRA_DEFAULT_contactViewerPhoneLabel,LYRA_DEFAULT_contactViewerTypeCell,LYRA_DEFAULT_contactViewerTypeFax,LYRA_DEFAULT_contactViewerTypeHome,LYRA_DEFAULT_contactViewerTypeInternet,LYRA_DEFAULT_contactViewerTypePreferred,LYRA_DEFAULT_contactViewerTypeVoice,LYRA_DEFAULT_contactViewerTypeWork,LYRA_DEFAULT_contactViewerTypedValue,LYRA_DEFAULT_contactViewerUnnamedContact,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraContactViewerBase extends LyraElement{}class LyraContactViewer extends TextViewerTarget(LyraContactViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.headingLevel="3",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this)}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,contactViewerAddressFormat:LYRA_DEFAULT_contactViewerAddressFormat,contactViewerAddressLabel:LYRA_DEFAULT_contactViewerAddressLabel,contactViewerEmailLabel:LYRA_DEFAULT_contactViewerEmailLabel,contactViewerLabel:LYRA_DEFAULT_contactViewerLabel,contactViewerNoContacts:LYRA_DEFAULT_contactViewerNoContacts,contactViewerOrganization:LYRA_DEFAULT_contactViewerOrganization,contactViewerPhoneLabel:LYRA_DEFAULT_contactViewerPhoneLabel,contactViewerTypeCell:LYRA_DEFAULT_contactViewerTypeCell,contactViewerTypeFax:LYRA_DEFAULT_contactViewerTypeFax,contactViewerTypeHome:LYRA_DEFAULT_contactViewerTypeHome,contactViewerTypeInternet:LYRA_DEFAULT_contactViewerTypeInternet,contactViewerTypePreferred:LYRA_DEFAULT_contactViewerTypePreferred,contactViewerTypeVoice:LYRA_DEFAULT_contactViewerTypeVoice,contactViewerTypeWork:LYRA_DEFAULT_contactViewerTypeWork,contactViewerTypedValue:LYRA_DEFAULT_contactViewerTypedValue,contactViewerUnnamedContact:LYRA_DEFAULT_contactViewerUnnamedContact,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeContact:LYRA_DEFAULT_documentPreviewTypeContact,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){this.lastLoadSrc=this.src;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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}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})}}formatList(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(values)}formatAddress(address){return this.localize("contactViewerAddressFormat",void 0,{poBox:address.poBox,extendedAddress:address.extendedAddress,streetAddress:address.streetAddress,locality:address.locality,region:address.region,postalCode:address.postalCode,country:address.country}).split(/\r\n|\r|\n/).map(line=>line.replace(/\s+/g," ").trim()).filter(Boolean).join(`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.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{getListFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{parseVCards}from"./vcard.js";import{styles}from"./contact-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_contactViewerAddressFormat,LYRA_DEFAULT_contactViewerAddressLabel,LYRA_DEFAULT_contactViewerEmailLabel,LYRA_DEFAULT_contactViewerLabel,LYRA_DEFAULT_contactViewerNoContacts,LYRA_DEFAULT_contactViewerOrganization,LYRA_DEFAULT_contactViewerPhoneLabel,LYRA_DEFAULT_contactViewerTypeCell,LYRA_DEFAULT_contactViewerTypeFax,LYRA_DEFAULT_contactViewerTypeHome,LYRA_DEFAULT_contactViewerTypeInternet,LYRA_DEFAULT_contactViewerTypePreferred,LYRA_DEFAULT_contactViewerTypeVoice,LYRA_DEFAULT_contactViewerTypeWork,LYRA_DEFAULT_contactViewerTypedValue,LYRA_DEFAULT_contactViewerUnnamedContact,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraContactViewerBase extends LyraElement{}class LyraContactViewer extends TextViewerTarget(LyraContactViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.headingLevel="3",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this)}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,contactViewerAddressFormat:LYRA_DEFAULT_contactViewerAddressFormat,contactViewerAddressLabel:LYRA_DEFAULT_contactViewerAddressLabel,contactViewerEmailLabel:LYRA_DEFAULT_contactViewerEmailLabel,contactViewerLabel:LYRA_DEFAULT_contactViewerLabel,contactViewerNoContacts:LYRA_DEFAULT_contactViewerNoContacts,contactViewerOrganization:LYRA_DEFAULT_contactViewerOrganization,contactViewerPhoneLabel:LYRA_DEFAULT_contactViewerPhoneLabel,contactViewerTypeCell:LYRA_DEFAULT_contactViewerTypeCell,contactViewerTypeFax:LYRA_DEFAULT_contactViewerTypeFax,contactViewerTypeHome:LYRA_DEFAULT_contactViewerTypeHome,contactViewerTypeInternet:LYRA_DEFAULT_contactViewerTypeInternet,contactViewerTypePreferred:LYRA_DEFAULT_contactViewerTypePreferred,contactViewerTypeVoice:LYRA_DEFAULT_contactViewerTypeVoice,contactViewerTypeWork:LYRA_DEFAULT_contactViewerTypeWork,contactViewerTypedValue:LYRA_DEFAULT_contactViewerTypedValue,contactViewerUnnamedContact:LYRA_DEFAULT_contactViewerUnnamedContact,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeContact:LYRA_DEFAULT_documentPreviewTypeContact,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,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,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){this.lastLoadSrc=this.src;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(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}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})}}formatList(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(values)}formatAddress(address){return this.localize("contactViewerAddressFormat",void 0,{poBox:address.poBox,extendedAddress:address.extendedAddress,streetAddress:address.streetAddress,locality:address.locality,region:address.region,postalCode:address.postalCode,country:address.country}).split(/\r\n|\r|\n/).map(line=>line.replace(/\s+/g," ").trim()).filter(Boolean).join(`
2
2
  `)}formatType(type){const key={home:"contactViewerTypeHome",work:"contactViewerTypeWork",cell:"contactViewerTypeCell",voice:"contactViewerTypeVoice",fax:"contactViewerTypeFax",internet:"contactViewerTypeInternet",pref:"contactViewerTypePreferred",preferred:"contactViewerTypePreferred"}[type.toLowerCase()];return key?this.localize(key):type}formatTypedValue(value,types){return types.length?this.localize("contactViewerTypedValue",void 0,{value,types:this.formatList(types.map(type=>this.formatType(type)))}):value}renderContact(contact){const headingLevel=resolveHeadingLevel(this.headingLevel);return html`<article part="contact">
3
3
  <div
4
4
  part="contact-name"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified");function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this.language="",this.syncScroll=!0,this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified");function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this.language="",this.syncScroll=!0,this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,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]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
2
2
  <lr-diff-view
3
3
  part="diff"
4
4
  .oldText=${this.oldVersion?.text??""}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{Announcer}from"../../../internal/announcer.js";import{announceSearchResult}from"../../../internal/viewer-search.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_previous,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_PAINTED_HIGHLIGHTS=100,TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:"#0969da"};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,previous:LYRA_DEFAULT_previous,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.src="",this.name="",this.accessibleLabel=null,this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.announcer=new Announcer({onFlush:text=>this.announcements.announcePolite(text)}),this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();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.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcer.cancel(),this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.book?.destroy(),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isConnected||generation!==this.generation||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isConnected||generation!==this.generation))return}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError")},this.emit("lr-render-error",{error});return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=factory(data);candidateBook=book;const rendition=book.renderTo(mount,{width:"100%",height:"100%"});if(await book.ready,!this.isConnected||generation!==this.generation){book.destroy();return}if(await rendition.display(this.location||void 0),!this.isConnected||generation!==this.generation){book.destroy();return}rendition.on("relocated",loc=>{const cfi=loc?.start?.cfi??"",href=loc?.start?.href??"";!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href}))}),rendition.on("selected",(cfiRange,contents)=>{const selection=contents?.window?.getSelection?.(),range=selection&&selection.rangeCount>0?selection.getRangeAt(0):null;if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contents.window);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(candidateBook?.destroy(),isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.ebookState={kind:"error",message},this.emit("lr-render-error",{error})}reportRenditionFailure(error,rendition,generation){!this.isConnected||generation!==this.generation||rendition!==this.rendition||(this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error}))}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&&current!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}async getToc(){const book=this.book;if(!book)return[];if(await book.ready,this.book!==book)return[];const items=[],seen=new WeakSet,stack=(book.navigation?.toc??[]).map(entry=>({entry,level:1})).reverse();for(;stack.length>0&&items.length<MAX_TOC_ITEMS;){const current=stack.pop(),{entry,level}=current;if(!(!entry||typeof entry!="object"||seen.has(entry))&&(seen.add(entry),items.push({id:entry.id||entry.href,label:String(entry.label??"").trim(),href:entry.href,level}),!(level>=MAX_TOC_DEPTH||!Array.isArray(entry.subitems))))for(let index=entry.subitems.length-1;index>=0;index--)stack.push({entry:entry.subitems[index],level:level+1})}return items}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){if(operation!==this.anchorOperationGeneration)return!1;const rendition=this.rendition;return rendition&&this.reportRenditionFailure(error,rendition,this.generation),this.emit("lr-anchor-result",{found:!1}),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration;if(!rendition)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor.quote);return!cfi||operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition)}return!1}async findTextQuoteCfi(quote){const book=this.book,generation=this.generation,boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!boundedQuery.accepted||!boundedQuery.needle)return null;const work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(!work.consume(""))return null;let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,!this.isConnected||generation!==this.generation||this.book!==book)return null;const results=await item.find(quote)??[];if(!this.isConnected||generation!==this.generation||this.book!==book)return null;for(const result of results){if(!work.consume(""))return null;if(!(!result||typeof result.cfi!="string"))return work.consume(result.cfi)?result.cfi:null}}catch{continue}finally{loaded&&item.unload()}}return null}repaintHighlights(){if(!this.rendition)return;const work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;this.rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2=this.resolveHighlightFill(TONE_FILL_TOKEN[tone]);if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":this.resolveHighlightFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN).fill,styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}this.rendition.annotations.highlight(cfi,{id:highlight.id},()=>this.emit("lr-highlight-activate",{highlightId:highlight.id}),active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);spineItems.length>itemCount&&(matchCountExact=!1);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(generation!==this.searchGeneration)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;const results=await item.find(query.trim())??[];if(generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;for(const r of results){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(!r||typeof r.cfi!="string")continue;const excerpt=typeof r.excerpt=="string"?r.excerpt:"";if(!work.consume(r.cfi)||!work.consume(excerpt)){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push({cfi:r.cfi,excerpt})}}catch{matchCountExact=!1;continue}finally{loaded&&item.unload()}if(matchCeilingExceeded)break}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){this.searchAnnotationCfi&&this.rendition?.annotations.remove(this.searchAnnotationCfi,"highlight"),this.searchAnnotationCfi=void 0}async showSearchMatch(index,generation=this.searchGeneration){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.reportRenditionFailure(error,rendition,this.generation),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex});const numberFormat=getNumberFormat(this.effectiveLocale);announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values?Object.fromEntries(Object.entries(values).map(([name,value])=>[name,typeof value=="number"?numberFormat.format(value):value])):void 0),this.announcer,this.searchMatches.length,this.searchActiveIndex)}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?html`<p class="status-note">${this.localize("loadingDocument")}</p>`:this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const disabled=this.ebookState.kind!=="ready";return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{Announcer}from"../../../internal/announcer.js";import{announceSearchResult}from"../../../internal/viewer-search.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_previous,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_PAINTED_HIGHLIGHTS=100,TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:"#0969da"};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.src="",this.name="",this.accessibleLabel=null,this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.announcer=new Announcer({onFlush:text=>this.announcements.announcePolite(text)}),this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();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.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcer.cancel(),this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.book?.destroy(),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isConnected||generation!==this.generation||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isConnected||generation!==this.generation))return}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError")},this.emit("lr-render-error",{error});return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=factory(data);candidateBook=book;const rendition=book.renderTo(mount,{width:"100%",height:"100%"});if(await book.ready,!this.isConnected||generation!==this.generation){book.destroy();return}if(await rendition.display(this.location||void 0),!this.isConnected||generation!==this.generation){book.destroy();return}rendition.on("relocated",loc=>{const cfi=loc?.start?.cfi??"",href=loc?.start?.href??"";!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href}))}),rendition.on("selected",(cfiRange,contents)=>{const selection=contents?.window?.getSelection?.(),range=selection&&selection.rangeCount>0?selection.getRangeAt(0):null;if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contents.window);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(candidateBook?.destroy(),isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.ebookState={kind:"error",message},this.emit("lr-render-error",{error})}reportRenditionFailure(error,rendition,generation){!this.isConnected||generation!==this.generation||rendition!==this.rendition||(this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error}))}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&&current!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}async getToc(){const book=this.book;if(!book)return[];if(await book.ready,this.book!==book)return[];const items=[],seen=new WeakSet,stack=(book.navigation?.toc??[]).map(entry=>({entry,level:1})).reverse();for(;stack.length>0&&items.length<MAX_TOC_ITEMS;){const current=stack.pop(),{entry,level}=current;if(!(!entry||typeof entry!="object"||seen.has(entry))&&(seen.add(entry),items.push({id:entry.id||entry.href,label:String(entry.label??"").trim(),href:entry.href,level}),!(level>=MAX_TOC_DEPTH||!Array.isArray(entry.subitems))))for(let index=entry.subitems.length-1;index>=0;index--)stack.push({entry:entry.subitems[index],level:level+1})}return items}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){if(operation!==this.anchorOperationGeneration)return!1;const rendition=this.rendition;return rendition&&this.reportRenditionFailure(error,rendition,this.generation),this.emit("lr-anchor-result",{found:!1}),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration;if(!rendition)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor.quote);return!cfi||operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition)}return!1}async findTextQuoteCfi(quote){const book=this.book,generation=this.generation,boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!boundedQuery.accepted||!boundedQuery.needle)return null;const work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(!work.consume(""))return null;let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,!this.isConnected||generation!==this.generation||this.book!==book)return null;const results=await item.find(quote)??[];if(!this.isConnected||generation!==this.generation||this.book!==book)return null;for(const result of results){if(!work.consume(""))return null;if(!(!result||typeof result.cfi!="string"))return work.consume(result.cfi)?result.cfi:null}}catch{continue}finally{loaded&&item.unload()}}return null}repaintHighlights(){if(!this.rendition)return;const work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;this.rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2=this.resolveHighlightFill(TONE_FILL_TOKEN[tone]);if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":this.resolveHighlightFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN).fill,styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}this.rendition.annotations.highlight(cfi,{id:highlight.id},()=>this.emit("lr-highlight-activate",{highlightId:highlight.id}),active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);spineItems.length>itemCount&&(matchCountExact=!1);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(generation!==this.searchGeneration)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;const results=await item.find(query.trim())??[];if(generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;for(const r of results){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(!r||typeof r.cfi!="string")continue;const excerpt=typeof r.excerpt=="string"?r.excerpt:"";if(!work.consume(r.cfi)||!work.consume(excerpt)){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push({cfi:r.cfi,excerpt})}}catch{matchCountExact=!1;continue}finally{loaded&&item.unload()}if(matchCeilingExceeded)break}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){this.searchAnnotationCfi&&this.rendition?.annotations.remove(this.searchAnnotationCfi,"highlight"),this.searchAnnotationCfi=void 0}async showSearchMatch(index,generation=this.searchGeneration){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.reportRenditionFailure(error,rendition,this.generation),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex});const numberFormat=getNumberFormat(this.effectiveLocale);announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values?Object.fromEntries(Object.entries(values).map(([name,value])=>[name,typeof value=="number"?numberFormat.format(value):value])):void 0),this.announcer,this.searchMatches.length,this.searchActiveIndex)}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?html`<p class="status-note">${this.localize("loadingDocument")}</p>`:this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const disabled=this.ebookState.kind!=="ready";return html`
2
2
  <div
3
3
  part="base"
4
4
  aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
@@ -1,6 +1,6 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{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{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/attachment-chip.class.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.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{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_download,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_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizeAttachmentContent(content){return content instanceof Uint8Array?content:content instanceof ArrayBuffer?new Uint8Array(content):new TextEncoder().encode(content)}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.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
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{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{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/attachment-chip.class.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.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{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_download,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_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizeAttachmentContent(content){return content instanceof Uint8Array?content:content instanceof ArrayBuffer?new Uint8Array(content):new TextEncoder().encode(content)}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.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);return doc?(doc.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{const expanded=expandedIndices.includes(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("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML):html2}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&typeof candidate.hasAttribute=="function"&&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.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=activeElementIn(this.shadowRoot)===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,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,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,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,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()){const normalizedQuery=query.toLocaleLowerCase(this.effectiveLocale),{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){const doc=parseHtmlDocument(bodyHtml,this.ownerDocument),next=new Set(this.expandedHtmlQuoteIndices);doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{(block.textContent??"").toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&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);split&&split.quoted.toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&!this.textQuoteExpanded&&(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("[data-email-text-content]")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),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.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const result=await this.parse(buffer,generation);result&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",...result})}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})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}async parse(buffer,generation){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isConnected||generation!==this.generation)return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const parsed=await PostalMime.parse(buffer);if(!this.isConnected||generation!==this.generation)return null;const bodyHtml=parsed.html&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):null;if(!this.isConnected||generation!==this.generation)return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const content=parsed.attachments??[];return{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:content.map(attachment=>{const normalized=normalizeAttachmentContent(attachment.content);return{filename:attachment.filename||this.localize("documentPreviewGenericFile"),mimeType:attachment.mimeType??"",size:normalized.byteLength,content:normalized}})}}}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);return doc?(doc.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{const expanded=expandedIndices.includes(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("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML):html2}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&typeof candidate.hasAttribute=="function"&&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.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=activeElementIn(this.shadowRoot)===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,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,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,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,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()){const normalizedQuery=query.toLocaleLowerCase(this.effectiveLocale),{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){const doc=parseHtmlDocument(bodyHtml,this.ownerDocument),next=new Set(this.expandedHtmlQuoteIndices);doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{(block.textContent??"").toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&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);split&&split.quoted.toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&!this.textQuoteExpanded&&(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("[data-email-text-content]")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),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.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const result=await this.parse(buffer,generation);result&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",...result})}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})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}async parse(buffer,generation){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isConnected||generation!==this.generation)return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const parsed=await PostalMime.parse(buffer);if(!this.isConnected||generation!==this.generation)return null;const bodyHtml=parsed.html&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):null;if(!this.isConnected||generation!==this.generation)return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const content=parsed.attachments??[];return{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:content.map(attachment=>{const normalized=normalizeAttachmentContent(attachment.content);return{filename:attachment.filename||this.localize("documentPreviewGenericFile"),mimeType:attachment.mimeType??"",size:normalized.byteLength,content:normalized}})}}}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,5 +1,5 @@
1
1
  var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedSelectionRects,boundedSelectionText,normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
2
- `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[],fontNames=new Set;let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),typeof record.fontName=="string"&&fontNames.add(record.fontName),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length),"fontName"in item&&typeof item.fontName=="string"&&fontNames.add(item.fontName)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const fontName of fontNames)Object.prototype.hasOwnProperty.call(sourceStyles,fontName)&&(styles2[fontName]=sourceStyles[fontName])}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
2
+ `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
3
3
  <canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
4
4
  <div part="page-error" hidden></div>
5
5
  <lr-highlight-layer