@aceshooting/lyra-ui 31.0.0 → 31.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/dist/autoloader-cdn.js +1 -1
  3. package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
  4. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
  5. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  6. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +18 -8
  7. package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
  8. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  9. package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
  10. package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
  11. package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
  12. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +6 -3
  13. package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
  14. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  15. package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
  16. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  17. package/dist/components/data/document-library/document-library-cursor.js +1 -0
  18. package/dist/components/data/document-library/document-library-types.d.ts +20 -0
  19. package/dist/components/data/document-library/document-library.class.d.ts +37 -26
  20. package/dist/components/data/document-library/document-library.class.js +20 -11
  21. package/dist/components/data/document-library/document-library.styles.js +1 -1
  22. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
  23. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  24. package/dist/components/data/timeline/timeline.class.js +1 -1
  25. package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
  26. package/dist/components/forms/combobox/combobox.class.js +2 -2
  27. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
  28. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  29. package/dist/components/layout/page/page.class.d.ts +3 -3
  30. package/dist/components/layout/page/page.class.js +1 -1
  31. package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
  32. package/dist/components/layout/segmented/segmented.class.js +34 -24
  33. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  34. package/dist/components/layout/stepper/stepper.styles.js +1 -1
  35. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  36. package/dist/components/media/map/map-anchor-controller.js +1 -1
  37. package/dist/components/media/map/map-canvas-target.js +1 -0
  38. package/dist/components/media/map/map.class.d.ts +10 -1
  39. package/dist/components/media/map/map.class.js +4 -4
  40. package/dist/components/media/map/map.styles.js +1 -1
  41. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
  42. package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
  43. package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
  44. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  45. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  46. package/dist/components/retrieval/graph/graph.class.js +1 -1
  47. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
  48. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
  49. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
  50. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
  51. package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
  52. package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
  53. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  54. package/dist/components/utility/icon/icon.class.js +1 -1
  55. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  56. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  57. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  58. package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
  59. package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
  60. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  61. package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
  62. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  63. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  64. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  65. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +1 -1
  66. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  67. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  68. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  69. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
  70. package/dist/data-sources.d.ts +10 -0
  71. package/dist/events.d.ts +9 -4
  72. package/dist/framework-types.d.ts +1 -1
  73. package/dist/internal/default-strings/conversation.generated.js +1 -1
  74. package/dist/internal/default-strings/data.generated.js +1 -1
  75. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  76. package/dist/internal/localization-types.d.ts +1 -1
  77. package/dist/internal/localization.js +1 -1
  78. package/dist/internal/lyra-element.js +2 -2
  79. package/dist/internal/native-modal-context.js +1 -1
  80. package/dist/internal/overlay-manager.js +1 -1
  81. package/dist/internal/overlay-order.js +1 -1
  82. package/dist/internal/overlay-stack.js +1 -1
  83. package/dist/internal/package-metadata.js +1 -1
  84. package/dist/internal/runtime-diagnostics.js +1 -0
  85. package/dist/internal/source-cursor-controller.js +1 -0
  86. package/dist/internal/source-cursor-projection.js +1 -0
  87. package/dist/internal/source-page-scope.js +1 -1
  88. package/dist/lyra.d.ts +1 -1
  89. package/dist/theme/theme-bootstrap.js +1 -1
  90. package/dist/theme/theme.js +1 -1
  91. package/dist/utilities/overlay-manager.d.ts +2 -0
  92. package/llms/components/lr-budget-meter.md +31 -0
  93. package/llms/components/lr-chat-composer.md +13 -2
  94. package/llms/components/lr-combobox.md +27 -1
  95. package/llms/components/lr-diff-view.md +6 -0
  96. package/llms/components/lr-document-library.md +90 -6
  97. package/llms/components/lr-graph.md +5 -0
  98. package/llms/components/lr-ingestion-queue.md +76 -8
  99. package/llms/components/lr-json-viewer.md +34 -0
  100. package/llms/components/lr-lite-chart.md +2 -1
  101. package/llms/components/lr-map.md +33 -0
  102. package/llms/components/lr-message-feedback.md +38 -3
  103. package/llms/components/lr-page.md +4 -2
  104. package/llms/components/lr-prompt-input.md +5 -2
  105. package/llms/components/lr-segmented.md +30 -10
  106. package/llms/components/lr-sequence-playback.md +47 -12
  107. package/llms/components/lr-virtual-list.md +3 -1
  108. package/llms/peers.md +2 -2
  109. package/llms/shared/events-and-types.md +61 -2
  110. package/llms/shared/forms-and-accessibility.md +25 -0
  111. package/llms/shared/imports-and-registration.md +154 -110
  112. package/llms/shared/testing-and-utilities.md +5 -1
  113. package/llms/shared.md +245 -113
  114. package/locales.json +1 -1
  115. package/package.json +8 -8
  116. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,isNonBlankIdentity,isRecord}from"../retrieval-identity.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,AnnouncementSinkController}from"../../../internal/announcer.js";import{SourcePageController}from"../../../internal/source-page-controller.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{closeIcon}from"../../../internal/icons.js";import{styles}from"./ingestion-queue.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_ingestionAttemptCount,LYRA_DEFAULT_ingestionCancelWithContext,LYRA_DEFAULT_ingestionChunkCount,LYRA_DEFAULT_ingestionEmbeddedOfTotal,LYRA_DEFAULT_ingestionItemProgressLabel,LYRA_DEFAULT_ingestionQueueEmpty,LYRA_DEFAULT_ingestionQueueInputLimit,LYRA_DEFAULT_ingestionQueueLabel,LYRA_DEFAULT_ingestionRetryWithContext,LYRA_DEFAULT_ingestionStageCancelled,LYRA_DEFAULT_ingestionStageChunking,LYRA_DEFAULT_ingestionStageDone,LYRA_DEFAULT_ingestionStageEmbedding,LYRA_DEFAULT_ingestionStageExtracting,LYRA_DEFAULT_ingestionStageFailed,LYRA_DEFAULT_ingestionStageIndexing,LYRA_DEFAULT_ingestionStageQueued,LYRA_DEFAULT_ingestionStageUnknown,LYRA_DEFAULT_ingestionStageUploading,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const INGESTION_STAGES=new Set(["queued","uploading","extracting","chunking","embedding","indexing","done","failed","cancelled"]);function normalizedStage(stage){return INGESTION_STAGES.has(stage)?stage:"unknown"}const ACTIVE_STAGES=["uploading","extracting","chunking","embedding","indexing"],CANCELABLE_STAGES=["queued",...ACTIVE_STAGES];function badgeVariantForStage(stage){switch(stage){case"done":return"success";case"failed":return"danger";case"queued":case"cancelled":case"unknown":return"neutral";default:return"brand"}}const SOURCE_QUERY=Object.freeze({}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
1
+ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{tag}from"../../../internal/prefix.js";import{devWarnOnce}from"../../../internal/dev-warning.js";import{projectIngestionPresentation,ingestionActionKey}from"./ingestion-queue-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity,isNonBlankIdentity,isRecord}from"../retrieval-identity.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,AnnouncementSinkController}from"../../../internal/announcer.js";import{SourcePageController}from"../../../internal/source-page-controller.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{closeIcon}from"../../../internal/icons.js";import{styles}from"./ingestion-queue.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_ingestionActionWithContext,LYRA_DEFAULT_ingestionAttemptCount,LYRA_DEFAULT_ingestionCancelWithContext,LYRA_DEFAULT_ingestionChunkCount,LYRA_DEFAULT_ingestionEmbeddedOfTotal,LYRA_DEFAULT_ingestionItemProgressLabel,LYRA_DEFAULT_ingestionQueueActionLimit,LYRA_DEFAULT_ingestionQueueEmpty,LYRA_DEFAULT_ingestionQueueInputLimit,LYRA_DEFAULT_ingestionQueueLabel,LYRA_DEFAULT_ingestionRetryWithContext,LYRA_DEFAULT_ingestionStageCancelled,LYRA_DEFAULT_ingestionStageChunking,LYRA_DEFAULT_ingestionStageDone,LYRA_DEFAULT_ingestionStageEmbedding,LYRA_DEFAULT_ingestionStageExtracting,LYRA_DEFAULT_ingestionStageFailed,LYRA_DEFAULT_ingestionStageIndexing,LYRA_DEFAULT_ingestionStageQueued,LYRA_DEFAULT_ingestionStageUnknown,LYRA_DEFAULT_ingestionStageUploading,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const INGESTION_STAGES=new Set(["queued","uploading","extracting","chunking","embedding","indexing","done","failed","cancelled","custom"]);function normalizedStage(stage){return INGESTION_STAGES.has(stage)?stage:"unknown"}const ACTIVE_STAGES=["uploading","extracting","chunking","embedding","indexing"],CANCELABLE_STAGES=["queued",...ACTIVE_STAGES],DEFAULT_RETRY_ACTIONS=Object.freeze([Object.freeze({type:"retry"})]),DEFAULT_CANCEL_ACTIONS=Object.freeze([Object.freeze({type:"cancel"})]),NO_ACTIONS=Object.freeze([]);function badgeVariantForStage(stage){switch(stage){case"done":return"success";case"failed":return"danger";case"queued":case"cancelled":case"unknown":case"custom":return"neutral";default:return"brand"}}const SOURCE_QUERY=Object.freeze({}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
11
11
  aria-hidden="true"
12
12
  focusable="false"
13
13
  ><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
14
- `}const DEFAULT_VIRTUALIZE_AT=100;class LyraIngestionQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.sourceItemIdentities=new WeakSet,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceItem(record,isCurrent),validateMetadata:()=>{},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceBlocked||(this.sourcePage=event.detail.page-1)},this.virtualizeAt=DEFAULT_VIRTUALIZE_AT,this.announce=!1,this.failureLiveText="",this.isMounting=!0,this.initialFailuresAnnounced=!1,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitInitialized=!1,this.previouslyInputTruncated=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.fallbackFailureItems=new WeakSet,this.ingestionItemKey=item=>item.id,this.stopOwnedEvent=event=>{event.stopPropagation()},this.itemTemplate=(item,ownRole)=>{const stage=normalizedStage(item.stage),stageLabel=this.stageLabel(stage),name=item.document.name.trim()?item.document.name:this.localize("untitledSource"),showProgress=stage!=="unknown"&&ACTIVE_STAGES.includes(stage),canRetry=stage==="failed",canCancel=stage!=="unknown"&&CANCELABLE_STAGES.includes(stage),attempts=this.normalizedAttempts(item),hasMeta=item.chunkCount!==void 0||item.embeddedChunkCount!==void 0||attempts>0,indeterminate=item.progress===void 0||!Number.isFinite(item.progress);return html`
14
+ `}const DEFAULT_VIRTUALIZE_AT=100;class LyraIngestionQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.sourceEpoch=0,this.sourceSyncing=!1,this.sourceRows=[],this.presentations=new WeakMap,this.focusRepairGeneration=0,this.sourceStateVersion=0,this.sourcePages=new SourcePageController(this,{normalizeRecord:(record,isCurrent)=>this.projectSourceItem(record,isCurrent),validateMetadata:()=>{},onChange:()=>{this.sourceStateVersion++}}),this.sourcePage=0,this.sourcePageSize=100,this.onSourcePage=event=>{event.stopPropagation(),this.sourceBlocked||(this.sourcePage=event.detail.page-1)},this.virtualizeAt=DEFAULT_VIRTUALIZE_AT,this.announce=!1,this.failureLiveText="",this.isMounting=!0,this.initialFailuresAnnounced=!1,this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitInitialized=!1,this.previouslyInputTruncated=!1,this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.fallbackFailureItems=new WeakSet,this.ingestionItemKey=item=>item.id,this.stopOwnedEvent=event=>{event.stopPropagation()},this.itemTemplate=(item,ownRole)=>{const stage=this.itemStage(item),stageLabel=stage==="custom"?item.customStage.label:this.stageLabel(stage),name=item.document.name.trim()?item.document.name:this.localize("untitledSource"),showProgress=stage==="custom"?item.customStage.showProgress===!0:ACTIVE_STAGES.includes(stage),actions=this.rowActions(item),attempts=this.normalizedAttempts(item),hasMeta=item.chunkCount!==void 0||item.embeddedChunkCount!==void 0||attempts>0,indeterminate=item.progress===void 0||!Number.isFinite(item.progress);return html`
15
15
  <div
16
16
  part="item"
17
17
  role=${ownRole?"listitem":nothing}
@@ -19,7 +19,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
19
19
  >
20
20
  <div part="item-header">
21
21
  <span part="item-name" title=${name}>${name}</span>
22
- <lr-badge part="item-stage" variant=${badgeVariantForStage(stage)}
22
+ <lr-badge part="item-stage" variant=${stage==="custom"?item.customStage.variant??"neutral":badgeVariantForStage(stage)}
23
23
  >${stageLabel}</lr-badge
24
24
  >
25
25
  </div>
@@ -41,39 +41,26 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
41
41
  >`:nothing}
42
42
  </div>`:nothing}
43
43
  ${stage==="failed"&&item.error?html`<p part="item-error">${this.fallbackFailureItems.has(item)?this.localize("ingestionStageFailed"):item.error}</p>`:nothing}
44
- ${canRetry||canCancel?html`<div part="item-actions">
45
- ${canRetry?html`<button
46
- part="retry-button"
47
- type="button"
48
- aria-label=${this.localize("ingestionRetryWithContext",void 0,{label:name})}
49
- @click=${()=>this.onRetryClick(item)}
50
- >
51
- ${retryIcon()}<span>${this.localize("retry")}</span>
52
- </button>`:nothing}
53
- ${canCancel?html`<button
54
- part="cancel-button"
55
- type="button"
56
- aria-label=${this.localize("ingestionCancelWithContext",void 0,{label:name})}
57
- @click=${()=>this.onCancelClick(item)}
58
- >
59
- ${closeIcon()}<span>${this.localize("cancel")}</span>
60
- </button>`:nothing}
61
- </div>`:nothing}
44
+ ${actions.length?html`<div part="item-actions">${repeat(actions,ingestionActionKey,action=>this.renderRowAction(item,action,name))}</div>`:nothing}
45
+ ${this.renderActionLimit(item,name)}
62
46
  </div>
63
- `}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,ingestionAttemptCount:LYRA_DEFAULT_ingestionAttemptCount,ingestionCancelWithContext:LYRA_DEFAULT_ingestionCancelWithContext,ingestionChunkCount:LYRA_DEFAULT_ingestionChunkCount,ingestionEmbeddedOfTotal:LYRA_DEFAULT_ingestionEmbeddedOfTotal,ingestionItemProgressLabel:LYRA_DEFAULT_ingestionItemProgressLabel,ingestionQueueEmpty:LYRA_DEFAULT_ingestionQueueEmpty,ingestionQueueInputLimit:LYRA_DEFAULT_ingestionQueueInputLimit,ingestionQueueLabel:LYRA_DEFAULT_ingestionQueueLabel,ingestionRetryWithContext:LYRA_DEFAULT_ingestionRetryWithContext,ingestionStageCancelled:LYRA_DEFAULT_ingestionStageCancelled,ingestionStageChunking:LYRA_DEFAULT_ingestionStageChunking,ingestionStageDone:LYRA_DEFAULT_ingestionStageDone,ingestionStageEmbedding:LYRA_DEFAULT_ingestionStageEmbedding,ingestionStageExtracting:LYRA_DEFAULT_ingestionStageExtracting,ingestionStageFailed:LYRA_DEFAULT_ingestionStageFailed,ingestionStageIndexing:LYRA_DEFAULT_ingestionStageIndexing,ingestionStageQueued:LYRA_DEFAULT_ingestionStageQueued,ingestionStageUnknown:LYRA_DEFAULT_ingestionStageUnknown,ingestionStageUploading:LYRA_DEFAULT_ingestionStageUploading,loading:LYRA_DEFAULT_loading,retry:LYRA_DEFAULT_retry,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.sourcePages.state.pending||this.sourceFailed)}projectSourceItem(record,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key);return assertCurrent(),descriptor};assertCurrent();const field=(value2,key)=>{if(!isRecord(value2))throw new TypeError("Invalid source item");const descriptor=descriptorOf(value2,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source field");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value};let units=0;const text=(value2,required=!1)=>{if(!(value2===void 0&&!required)){if(typeof value2!="string"||value2.length>65536||(units+=value2.length)>65536)throw new TypeError("Invalid source text");return value2}},raw=record.value,id=text(field(raw,"id"),!0),rawDocument=field(raw,"document"),documentId=text(field(rawDocument,"id"),!0);if(id!==record.key||!isNonBlankIdentity(documentId))throw new TypeError("Invalid source identity");const document=Object.freeze({id:documentId,name:text(field(rawDocument,"name"),!0),mimeType:text(field(rawDocument,"mimeType")),uri:text(field(rawDocument,"uri")),version:text(field(rawDocument,"version"))}),stage=text(field(raw,"stage")),errorValue=field(raw,"error"),error=errorValue==null?void 0:text(typeof errorValue=="string"?errorValue:this.localize("ingestionStageFailed")),numbers={};for(const key of["progress","chunkCount","embeddedChunkCount","attempts"]){const value2=field(raw,key);if(value2!==void 0){if(typeof value2!="number")throw new TypeError("Invalid source number");numbers[key]=value2}}const value=Object.freeze({id,document,stage,error,...numbers});return assertCurrent(),this.sourceItemIdentities.add(value),errorValue!=null&&typeof errorValue!="string"&&this.fallbackFailureItems.add(value),assertCurrent(),{key:record.key,order:record.order,value}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceSize=void 0,this.sourceResult=void 0,this.sourceRows=[];return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));this.sourceSize!==void 0&&this.sourceSize!==size&&(page=0,this.sourcePage=0),this.sourceSize=size;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,size,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRows=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale}),this.sourcePages.request(SOURCE_QUERY,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;!result||result===this.sourceResult||(this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0))}requestUpdate(...args){args[0]===void 0&&(this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}onSourceRetry(source,state2){!this.isConnected||!this.sourceMode||!this.sourceFailed||this.dataSource!==source||this.sourcePages.state!==state2||(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceStatusInitialized=!1}inputLimitText(){const truncation=publicCollectionTruncation(this,"items"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("ingestionQueueInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourceFailed?this.localize("tableLoadFailed"):this.sourcePages.state.pending?this.localize("loading"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.limitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status;return}this.sourceStatusInitialized=!1,this.previousSourceStatus="";const inputTruncated=publicCollectionTruncation(this,"items")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.limitAnnouncements.announcePolite(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,DEFAULT_VIRTUALIZE_AT)}normalizeItems(value){const rows=[];for(const valueItem of Array.isArray(value)?value:[])try{if(!isRecord(valueItem))continue;const id=readOwnDataValue(valueItem,"id"),source=readOwnDataValue(valueItem,"document");if(!isNonBlankIdentity(id)||!isRecord(source))continue;const documentId=readOwnDataValue(source,"id"),name=readOwnDataValue(source,"name");if(!isNonBlankIdentity(documentId)||typeof name!="string")continue;const document=Object.freeze(Object.fromEntries(["id","name","mimeType","uri","version"].map(key=>[key,readOwnDataValue(source,key)]).filter(([,field])=>field!==void 0))),fields=Object.fromEntries(["stage","progress","chunkCount","embeddedChunkCount","attempts"].map(key=>[key,readOwnDataValue(valueItem,key)]).filter(([,field])=>field!==void 0)),error=readOwnDataValue(valueItem,"error"),row=Object.freeze({...fields,id,document,...error===void 0?{}:{error:error===null||typeof error=="string"?error:this.localize("ingestionStageFailed")}});error!=null&&typeof error!="string"&&this.fallbackFailureItems.add(row),rows.push(row)}catch{continue}return firstByRetrievalIdentity(rows,item=>item.id)}get normalizedItems(){const cached=this.normalizedItemsCache;if(cached&&cached.source===this.items&&cached.locale===this.effectiveLocale&&cached.failureText===this.localize("ingestionStageFailed"))return cached.result;const result=this.normalizeItems(this.items);return this.normalizedItemsCache={source:this.items,locale:this.effectiveLocale,failureText:this.localize("ingestionStageFailed"),result},result}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){super.disconnectedCallback(),this.failureLiveText="",this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.isMounting=!0,this.sink?.release(),this.sink=void 0}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.failureLiveText="",this.isMounting=!0;return}const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting){this.announce&&!this.initialFailuresAnnounced&&(this.initialFailuresAnnounced=!0,this.announceFailures(this.normalizedItems.flatMap(item=>item.stage==="failed"&&item.error?[item.error]:[])));return}if(!changed.has("items"))return;const previousItems=this.normalizedItemsCache?.result??[],previousById=new Map(previousItems.map(item=>[item.id,item]));this.announceFailures(this.normalizedItems.flatMap(item=>{if(item.stage!=="failed"||!item.error)return[];const previous=previousById.get(item.id),previousError=previous&&this.fallbackFailureItems.has(previous)?this.localize("ingestionStageFailed"):previous?.error;return!previous||previous.stage!=="failed"||previousError!==item.error?[item.error]:[]}))}announceFailures(freshErrors){this.failureLiveText=freshErrors.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(freshErrors):"",this.failureLiveText!==""&&this.sink?.announce(this.failureLiveText)}stageLabel(stage){switch(stage){case"queued":return this.localize("ingestionStageQueued");case"uploading":return this.localize("ingestionStageUploading");case"extracting":return this.localize("ingestionStageExtracting");case"chunking":return this.localize("ingestionStageChunking");case"embedding":return this.localize("ingestionStageEmbedding");case"indexing":return this.localize("ingestionStageIndexing");case"done":return this.localize("ingestionStageDone");case"failed":return this.localize("ingestionStageFailed");case"cancelled":return this.localize("ingestionStageCancelled");case"unknown":return this.localize("ingestionStageUnknown")}}chunkCountText(count){const safeCount=finiteCount(count);return this.localize("ingestionChunkCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(safeCount),pluralCount:safeCount})}normalizedAttempts(item){return finiteCount(item.attempts??0,0,Number.MAX_SAFE_INTEGER-1)}onRetryClick(item){(this.sourceMode||this.sourceItemIdentities.has(item))&&(!this.sourceMode||this.sourceBlocked||!this.sourceRows.includes(item))||this.emit("lr-retry",{itemId:item.id,attempt:this.normalizedAttempts(item)+1})}onCancelClick(item){(this.sourceMode||this.sourceItemIdentities.has(item))&&(!this.sourceMode||this.sourceBlocked||!this.sourceRows.includes(item))||this.emit("lr-cancel",{itemId:item.id})}renderRows(items){return items.length>this.effectiveVirtualizeAt?html`<lr-virtual-list
47
+ `}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,ingestionActionWithContext:LYRA_DEFAULT_ingestionActionWithContext,ingestionAttemptCount:LYRA_DEFAULT_ingestionAttemptCount,ingestionCancelWithContext:LYRA_DEFAULT_ingestionCancelWithContext,ingestionChunkCount:LYRA_DEFAULT_ingestionChunkCount,ingestionEmbeddedOfTotal:LYRA_DEFAULT_ingestionEmbeddedOfTotal,ingestionItemProgressLabel:LYRA_DEFAULT_ingestionItemProgressLabel,ingestionQueueActionLimit:LYRA_DEFAULT_ingestionQueueActionLimit,ingestionQueueEmpty:LYRA_DEFAULT_ingestionQueueEmpty,ingestionQueueInputLimit:LYRA_DEFAULT_ingestionQueueInputLimit,ingestionQueueLabel:LYRA_DEFAULT_ingestionQueueLabel,ingestionRetryWithContext:LYRA_DEFAULT_ingestionRetryWithContext,ingestionStageCancelled:LYRA_DEFAULT_ingestionStageCancelled,ingestionStageChunking:LYRA_DEFAULT_ingestionStageChunking,ingestionStageDone:LYRA_DEFAULT_ingestionStageDone,ingestionStageEmbedding:LYRA_DEFAULT_ingestionStageEmbedding,ingestionStageExtracting:LYRA_DEFAULT_ingestionStageExtracting,ingestionStageFailed:LYRA_DEFAULT_ingestionStageFailed,ingestionStageIndexing:LYRA_DEFAULT_ingestionStageIndexing,ingestionStageQueued:LYRA_DEFAULT_ingestionStageQueued,ingestionStageUnknown:LYRA_DEFAULT_ingestionStageUnknown,ingestionStageUploading:LYRA_DEFAULT_ingestionStageUploading,loading:LYRA_DEFAULT_loading,retry:LYRA_DEFAULT_retry,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-item-action"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get dataSource(){return this._dataSource}set dataSource(value){const previous=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",previous)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceFailed(){return this.sourceMode&&!this.sourcePages.state.pending&&!this.sourcePages.state.result}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||this.sourcePages.state.pending||this.sourceFailed)}projectSourceItem(record,isCurrent){const assertCurrent=()=>{if(!isCurrent())throw new TypeError("Obsolete source record")},descriptorOf=(target,key)=>{assertCurrent();const descriptor=getOwnDataDescriptor(target,key);return assertCurrent(),descriptor};assertCurrent();const field=(value2,key)=>{if(!isRecord(value2))throw new TypeError("Invalid source item");const descriptor=descriptorOf(value2,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid source field");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value};let units=0;const text=(value2,required=!1)=>{if(!(value2===void 0&&!required)){if(typeof value2!="string"||value2.length>65536||(units+=value2.length)>65536)throw new TypeError("Invalid source text");return value2}},raw=record.value,id=text(field(raw,"id"),!0),rawDocument=field(raw,"document"),documentId=text(field(rawDocument,"id"),!0);if(id!==record.key||!isNonBlankIdentity(documentId))throw new TypeError("Invalid source identity");const document=Object.freeze({id:documentId,name:text(field(rawDocument,"name"),!0),mimeType:text(field(rawDocument,"mimeType")),uri:text(field(rawDocument,"uri")),version:text(field(rawDocument,"version"))}),stage=text(field(raw,"stage")),errorValue=field(raw,"error"),error=errorValue==null?void 0:text(typeof errorValue=="string"?errorValue:this.localize("ingestionStageFailed")),numbers={};for(const key of["progress","chunkCount","embeddedChunkCount","attempts"]){const value2=field(raw,key);if(value2!==void 0){if(typeof value2!="number")throw new TypeError("Invalid source number");numbers[key]=value2}}const presentation=projectIngestionPresentation(raw,stage,isCurrent,65536-units),value=Object.freeze({id,document,stage,error,...numbers,...presentation.customStage?{customStage:presentation.customStage}:{},...presentation.actions===void 0?{}:{actions:presentation.actions}});return this.presentations.set(value,presentation),assertCurrent(),errorValue!=null&&typeof errorValue!="string"&&this.fallbackFailureItems.add(value),assertCurrent(),{key:record.key,order:record.order,value}}syncSource(){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&this.sourcePages.bind(void 0),this.sourceInputs=void 0,this.sourceSize=void 0,this.sourceResult=void 0,this.sourceRows=[];return}const source=this.dataSource,size=finiteInteger(this.sourcePageSize,100,1,500);let page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size));this.sourceSize!==void 0&&this.sourceSize!==size&&(page=0,this.sourcePage=0),this.sourceSize=size;const revision=source.revision,inputs=[source,revision,this.sourceEpoch,this.effectiveLocale,size,page];if(this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;this.sourceInputs=inputs,this.sourceRows=[],this.sourceResult=void 0,this.sourcePages.bind({source,revision,epoch:this.sourceEpoch,locale:this.effectiveLocale}),this.sourcePages.request(SOURCE_QUERY,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}acceptSourcePage(){const result=this.sourcePages.state.result;!result||result===this.sourceResult||(this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value),this.sourcePage!==this.sourcePages.state.page&&(this.sourceSyncing=!0,this.sourcePage=this.sourcePages.state.page,this.sourceSyncing=!1,this.sourceInputs=this.sourceInputs?[...this.sourceInputs.slice(0,-1),this.sourcePages.state.page]:void 0))}requestUpdate(...args){args[0]===void 0&&(this.sourceEpoch=(this.sourceEpoch??0)+1),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}onSourceRetry(source,state2){!this.isConnected||!this.sourceMode||!this.sourceFailed||this.dataSource!==source||this.sourcePages.state!==state2||(this.sourceInputs=void 0,this.syncSource(),this.sourceStateVersion++)}adoptedCallback(){this.focusRepairGeneration++,this.actionFocusRepair=void 0,super.adoptedCallback(),this.limitAnnouncements.adopted(),this.sourcePages.adopted(),this.sourceStatusInitialized=!1}inputLimitText(){const truncation=publicCollectionTruncation(this,"items"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("ingestionQueueInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}updated(changed){if(super.updated(changed),this.restoreActionFocus(),this.sourceMode){const status=this.sourceFailed?this.localize("tableLoadFailed"):this.sourcePages.state.pending?this.localize("loading"):"";this.sourceStatusInitialized&&status&&status!==this.previousSourceStatus&&this.limitAnnouncements.announcePolite(status),this.sourceStatusInitialized=!0,this.previousSourceStatus=status;return}this.sourceStatusInitialized=!1,this.previousSourceStatus="";const inputTruncated=publicCollectionTruncation(this,"items")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.limitAnnouncements.announcePolite(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,DEFAULT_VIRTUALIZE_AT)}normalizeItems(value){const rows=[];for(const valueItem of Array.isArray(value)?value:[])try{if(!isRecord(valueItem))continue;const id=readOwnDataValue(valueItem,"id"),source=readOwnDataValue(valueItem,"document");if(!isNonBlankIdentity(id)||!isRecord(source))continue;const documentId=readOwnDataValue(source,"id"),name=readOwnDataValue(source,"name");if(!isNonBlankIdentity(documentId)||typeof name!="string")continue;const document=Object.freeze(Object.fromEntries(["id","name","mimeType","uri","version"].map(key=>[key,readOwnDataValue(source,key)]).filter(([,field])=>field!==void 0))),fields=Object.fromEntries(["stage","progress","chunkCount","embeddedChunkCount","attempts"].map(key=>[key,readOwnDataValue(valueItem,key)]).filter(([,field])=>field!==void 0)),error=readOwnDataValue(valueItem,"error"),presentation=projectIngestionPresentation(valueItem,fields.stage,()=>this.items===value&&!this.sourceMode),row=Object.freeze({...fields,id,document,...error===void 0?{}:{error:error===null||typeof error=="string"?error:this.localize("ingestionStageFailed")},...presentation.customStage?{customStage:presentation.customStage}:{},...presentation.actions===void 0?{}:{actions:presentation.actions}});this.presentations.set(row,presentation),error!=null&&typeof error!="string"&&this.fallbackFailureItems.add(row),rows.push(row)}catch{continue}return firstByRetrievalIdentity(rows,item=>item.id)}get normalizedItems(){const cached=this.normalizedItemsCache;if(cached&&cached.source===this.items&&cached.locale===this.effectiveLocale&&cached.failureText===this.localize("ingestionStageFailed"))return cached.result;const result=this.normalizeItems(this.items);return this.normalizedItemsCache={source:this.items,locale:this.effectiveLocale,failureText:this.localize("ingestionStageFailed"),result},result}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.focusRepairGeneration++,this.actionFocusRepair=void 0,super.disconnectedCallback(),this.failureLiveText="",this.sourceStatusInitialized=!1,this.previousSourceStatus="",this.isMounting=!0,this.sink?.release(),this.sink=void 0}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.captureActionFocus(),this.failureLiveText="",this.isMounting=!0;return}this.captureActionFocus();const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting){this.announce&&!this.initialFailuresAnnounced&&(this.initialFailuresAnnounced=!0,this.announceFailures(this.normalizedItems.flatMap(item=>item.stage==="failed"&&item.error?[item.error]:[])));return}if(!changed.has("items"))return;const previousItems=this.normalizedItemsCache?.result??[],previousById=new Map(previousItems.map(item=>[item.id,item]));this.announceFailures(this.normalizedItems.flatMap(item=>{if(item.stage!=="failed"||!item.error)return[];const previous=previousById.get(item.id),previousError=previous&&this.fallbackFailureItems.has(previous)?this.localize("ingestionStageFailed"):previous?.error;return!previous||previous.stage!=="failed"||previousError!==item.error?[item.error]:[]}))}announceFailures(freshErrors){this.failureLiveText=freshErrors.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(freshErrors):"",this.failureLiveText!==""&&this.sink?.announce(this.failureLiveText)}stageLabel(stage){switch(stage){case"queued":return this.localize("ingestionStageQueued");case"uploading":return this.localize("ingestionStageUploading");case"extracting":return this.localize("ingestionStageExtracting");case"chunking":return this.localize("ingestionStageChunking");case"embedding":return this.localize("ingestionStageEmbedding");case"indexing":return this.localize("ingestionStageIndexing");case"done":return this.localize("ingestionStageDone");case"failed":return this.localize("ingestionStageFailed");case"cancelled":return this.localize("ingestionStageCancelled");case"unknown":case"custom":return this.localize("ingestionStageUnknown")}}chunkCountText(count){const safeCount=finiteCount(count);return this.localize("ingestionChunkCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(safeCount),pluralCount:safeCount})}normalizedAttempts(item){return finiteCount(item.attempts??0,0,Number.MAX_SAFE_INTEGER-1)}itemStage(item){const stage=normalizedStage(item.stage);return stage==="custom"&&!item.customStage?"unknown":stage}rowActions(item){const stage=this.itemStage(item);return stage==="unknown"?NO_ACTIONS:(item.actions??(stage==="failed"?DEFAULT_RETRY_ACTIONS:CANCELABLE_STAGES.includes(stage)?DEFAULT_CANCEL_ACTIONS:NO_ACTIONS)).filter(action=>action.type==="custom"||(action.type==="retry"?stage==="failed":CANCELABLE_STAGES.includes(stage)))}currentRows(){return this.sourceMode?this.sourceRows:this.normalizedItems}activateRowAction(item,action){!this.isConnected||this.sourceMode&&this.sourceBlocked||!this.currentRows().includes(item)||!this.rowActions(item).includes(action)||action.disabled||(action.type==="retry"?this.emit("lr-retry",{itemId:item.id,attempt:this.normalizedAttempts(item)+1}):action.type==="cancel"?this.emit("lr-cancel",{itemId:item.id}):action.type==="custom"&&this.emit("lr-item-action",Object.freeze({itemId:item.id,actionId:action.id})))}renderedActionButtons(){const virtual=this.renderRoot.querySelector(tag("virtual-list"));return[...this.renderRoot.querySelectorAll("button[data-ingestion-action]"),...virtual?.shadowRoot?.querySelectorAll("button[data-ingestion-action]")??[]]}captureActionFocus(){const active=deepActiveElementIn(this.ownerDocument);if(!active||!this.renderedActionButtons().includes(active))return;const itemId=active.getAttribute("data-ingestion-item"),key=active.getAttribute("data-ingestion-action"),current=this.currentRows().find(row=>row.id===itemId);if(current&&this.rowActions(current).some(action=>ingestionActionKey(action)===key&&!action.disabled))return;const snapshot=captureComposedFocusRepair(this,active);if(!snapshot)return;const siblings=this.renderedActionButtons().filter(button=>button.getAttribute("data-ingestion-item")===itemId),renderedIds=[...new Set(this.renderedActionButtons().map(button=>button.getAttribute("data-ingestion-item")))];this.focusRepairGeneration++,this.actionFocusRepair={snapshot,itemId,actionIndex:Math.max(0,siblings.indexOf(active)),rowIndex:Math.max(0,renderedIds.indexOf(itemId))}}restoreActionFocus(){const pending=this.actionFocusRepair;if(this.actionFocusRepair=void 0,!pending)return;const generation=this.focusRepairGeneration;this.updateComplete.then(async()=>{const virtual=this.renderRoot.querySelector(tag("virtual-list"));if(virtual&&await virtual.updateComplete,!this.isConnected||generation!==this.focusRepairGeneration)return;const available=this.renderedActionButtons().filter(button=>!button.disabled),sameRow=available.filter(button=>button.getAttribute("data-ingestion-item")===pending.itemId),target=sameRow[Math.min(pending.actionIndex,sameRow.length-1)],ids=[...new Set(available.map(button=>button.getAttribute("data-ingestion-item")))],nearId=ids[Math.min(pending.rowIndex,ids.length-1)],nearby=available.filter(button=>button.getAttribute("data-ingestion-item")===nearId),list=this.renderRoot.querySelector('[part="list"]'),virtualBase=virtual?.shadowRoot?.querySelector('[part="base"]');applyComposedFocusRepair(pending.snapshot,[target,...sameRow,...nearby,virtualBase,list])})}renderRowAction(item,action,name){const custom=action.type==="custom",part=custom?"item-action-button":action.type==="retry"?"retry-button":"cancel-button",label=custom?action.label:this.localize(action.type==="retry"?"retry":"cancel"),accessibleName=custom?this.localize("ingestionActionWithContext",void 0,{action:label,label:name}):this.localize(action.type==="retry"?"ingestionRetryWithContext":"ingestionCancelWithContext",void 0,{label:name});return html`<button part=${part} type="button" ?disabled=${action.disabled===!0}
48
+ data-ingestion-item=${item.id} data-ingestion-action=${ingestionActionKey(action)}
49
+ aria-label=${accessibleName} @click=${()=>this.activateRowAction(item,action)}
50
+ >${custom?nothing:action.type==="retry"?retryIcon():closeIcon()}<span>${label}</span></button>`}renderActionLimit(item,name){const limit=this.presentations.get(item)?.actionLimit;if(!limit)return nothing;devWarnOnce(`lyra-ingestion-action-limit:${this.localName}`,`<${this.localName}>: a row retained ${limit.retained} of ${limit.source} actions; only the first 32 action positions are inspected.`);const number=getNumberFormat(this.effectiveLocale);return html`<p part="item-action-limit" role="note">${this.localize("ingestionQueueActionLimit",void 0,{count:number.format(limit.retained),total:number.format(limit.source),label:name})}</p>`}renderRows(items){return items.length>this.effectiveVirtualizeAt?html`<lr-virtual-list
64
51
  part="list"
65
- exportparts="item:item, item-header:item-header, item-name:item-name, item-stage:item-stage, item-progress:item-progress, item-meta:item-meta, item-chunk-count:item-chunk-count, item-embedding-status:item-embedding-status, item-attempts:item-attempts, item-error:item-error, item-actions:item-actions, retry-button:retry-button, cancel-button:cancel-button"
52
+ exportparts="item:item, item-header:item-header, item-name:item-name, item-stage:item-stage, item-progress:item-progress, item-meta:item-meta, item-chunk-count:item-chunk-count, item-embedding-status:item-embedding-status, item-attempts:item-attempts, item-error:item-error, item-actions:item-actions, retry-button:retry-button, cancel-button:cancel-button, item-action-button:item-action-button, item-action-limit:item-action-limit"
66
53
  .items=${items}
67
54
  .renderItem=${item=>this.itemTemplate(item,!1)}
68
55
  .keyFunction=${this.ingestionItemKey}
69
56
  @lr-virtual-scroll=${this.stopOwnedEvent}
70
57
  @lr-visible-range-change=${this.stopOwnedEvent}
71
- ></lr-virtual-list>`:html`<div part="list" role="list">
58
+ ></lr-virtual-list>`:html`<div part="list" role="list" tabindex="-1">
72
59
  ${repeat(items,item=>item.id,item=>this.itemTemplate(item,!0))}
73
60
  </div>`}renderSource(){const failed=this.sourceFailed,retrySource=this.dataSource,retryState=this.sourcePages.state,pending=this.sourcePages.state.pending,label=retrievalSemanticLabel(this,this.label==null?this.localize("ingestionQueueLabel"):this.label);return html`<div part="base" role=${retrievalSemanticRole(this,"region")??nothing} aria-label=${label??nothing} aria-busy=${pending?"true":"false"}>
74
61
  ${failed||pending?html`<p part="source-status">${this.localize(failed?"tableLoadFailed":"loading")}</p>`:nothing}
75
62
  ${failed?html`<button type="button" part="source-retry" @click=${()=>this.onSourceRetry(retrySource,retryState)}>${this.localize("retry")}</button>`:nothing}
76
- ${failed||pending?nothing:this.sourceRows.length?this.renderRows(this.sourceRows):html`<div part="list"><lr-empty part="empty" heading=${this.localize("ingestionQueueEmpty")}></lr-empty></div>`}
63
+ ${failed||pending?nothing:this.sourceRows.length?this.renderRows(this.sourceRows):html`<div part="list" tabindex="-1"><lr-empty part="empty" heading=${this.localize("ingestionQueueEmpty")}></lr-empty></div>`}
77
64
  <lr-pagination part="source-pagination" format="compact" .page=${finiteInteger(this.sourcePage,0,0,Number.MAX_SAFE_INTEGER-1)+1}
78
65
  .pageSize=${finiteInteger(this.sourcePageSize,100,1,500)} .total=${this.sourceTotal??-1} .disabled=${this.sourceBlocked||this.sourceTotal===null}
79
66
  .strings=${this.strings} @lr-page-change=${this.onSourcePage} @lr-before-page-change=${this.stopOwnedEvent} @lr-activate=${this.stopOwnedEvent}
@@ -87,7 +74,7 @@ import{__decorate}from"tslib";import{collectionSupport,publicCollectionTruncatio
87
74
  <div part="failure-live" class="sr-only" aria-hidden="true">
88
75
  ${this.failureLiveText}
89
76
  </div>
90
- <div part="list">
77
+ <div part="list" tabindex="-1">
91
78
  <lr-empty
92
79
  part="empty"
93
80
  heading=${this.localize("ingestionQueueEmpty")}
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-ingestion-queue-max-height: none; } [part="base"] { display: block; box-sizing: border-box; min-inline-size: 0; } [part="list"] { display: flex; flex-direction: column; box-sizing: border-box; max-block-size: var( --lr-ingestion-queue-max-height, var(--_lr-ingestion-queue-max-height) ); overflow-y: auto; overflow-x: clip; } lr-virtual-list { display: block; --lr-virtual-list-height: var(--lr-size-24rem); } [part="item"], lr-virtual-list::part(item) { display: flex; flex-direction: column; gap: var(--lr-space-xs); box-sizing: border-box; padding: var(--lr-space-s) var(--lr-space-m); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); } [part="item-header"], lr-virtual-list::part(item-header) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--lr-space-s); } [part="item-name"], lr-virtual-list::part(item-name) { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); } [part="item-progress"], lr-virtual-list::part(item-progress) { display: block; } [part="item-meta"], lr-virtual-list::part(item-meta) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part="item-chunk-count"], lr-virtual-list::part(item-chunk-count), [part="item-embedding-status"], lr-virtual-list::part(item-embedding-status), [part="item-attempts"], lr-virtual-list::part(item-attempts) { unicode-bidi: plaintext; } [part="item-error"], lr-virtual-list::part(item-error) { margin: 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part="item-actions"], lr-virtual-list::part(item-actions) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); } [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button) { display: inline-flex; align-items: center; gap: var(--lr-size-0-35em); box-sizing: border-box; ${iconHitTarget} padding: var(--lr-size-0-25rem) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="source-retry"]:hover, [part="retry-button"]:hover, lr-virtual-list::part(retry-button):hover { border-color: var(--lr-color-brand); color: var(--lr-color-brand); } [part="source-retry"]:active, [part="retry-button"]:active, lr-virtual-list::part(retry-button):active { border-color: var(--lr-color-brand); color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="cancel-button"]:hover, lr-virtual-list::part(cancel-button):hover { border-color: var(--lr-color-danger); color: var(--lr-color-danger); } [part="cancel-button"]:active, lr-virtual-list::part(cancel-button):active { border-color: var(--lr-color-danger); color: var(--lr-color-danger); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="source-retry"]:focus-visible, [part="retry-button"]:focus-visible, lr-virtual-list::part(retry-button):focus-visible, [part="cancel-button"]:focus-visible, lr-virtual-list::part(cancel-button):focus-visible { ${focusRing} } @media (prefers-reduced-motion: reduce) { [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button) { transition: none !important; } } [part='source-pagination'] { display: block; margin-block-start: var(--lr-space-s); } [part='source-status'], [part='limit'] { margin: 0; padding: var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-ingestion-queue-max-height: none; } [part="base"] { display: block; box-sizing: border-box; min-inline-size: 0; } [part="list"] { display: flex; flex-direction: column; box-sizing: border-box; max-block-size: var( --lr-ingestion-queue-max-height, var(--_lr-ingestion-queue-max-height) ); overflow-y: auto; overflow-x: clip; } lr-virtual-list { display: block; --lr-virtual-list-height: var(--lr-size-24rem); } [part="item"], lr-virtual-list::part(item) { display: flex; flex-direction: column; gap: var(--lr-space-xs); box-sizing: border-box; padding: var(--lr-space-s) var(--lr-space-m); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); } [part="item-header"], lr-virtual-list::part(item-header) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--lr-space-s); } [part="item-name"], lr-virtual-list::part(item-name) { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); } [part="item-progress"], lr-virtual-list::part(item-progress) { display: block; } [part='item-stage'], lr-virtual-list::part(item-stage) { min-inline-size: 0; max-inline-size: 100%; } [part="item-meta"], lr-virtual-list::part(item-meta) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part="item-chunk-count"], lr-virtual-list::part(item-chunk-count), [part="item-embedding-status"], lr-virtual-list::part(item-embedding-status), [part="item-attempts"], lr-virtual-list::part(item-attempts) { unicode-bidi: plaintext; } [part="item-error"], lr-virtual-list::part(item-error) { margin: 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part="item-actions"], lr-virtual-list::part(item-actions) { display: flex; flex-wrap: wrap; gap: var(--lr-space-s); } [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button), [part='item-action-button'], lr-virtual-list::part(item-action-button) { display: inline-flex; align-items: center; gap: var(--lr-size-0-35em); box-sizing: border-box; ${iconHitTarget} padding: var(--lr-size-0-25rem) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; max-inline-size: 100%; overflow-wrap: anywhere; transition: var(--lr-transition-interactive); } [part="source-retry"]:hover:where(:not(:disabled)), [part="retry-button"]:hover:where(:not(:disabled)), lr-virtual-list::part(retry-button):hover:not(:disabled), [part='item-action-button']:hover:where(:not(:disabled)), lr-virtual-list::part(item-action-button):hover:not(:disabled) { border-color: var(--lr-color-brand); color: var(--lr-color-brand); } [part="source-retry"]:active:where(:not(:disabled)), [part="retry-button"]:active:where(:not(:disabled)), lr-virtual-list::part(retry-button):active:not(:disabled), [part='item-action-button']:active:where(:not(:disabled)), lr-virtual-list::part(item-action-button):active:not(:disabled) { border-color: var(--lr-color-brand); color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="cancel-button"]:hover:where(:not(:disabled)), lr-virtual-list::part(cancel-button):hover:not(:disabled) { border-color: var(--lr-color-danger); color: var(--lr-color-danger); } [part="cancel-button"]:active:where(:not(:disabled)), lr-virtual-list::part(cancel-button):active:not(:disabled) { border-color: var(--lr-color-danger); color: var(--lr-color-danger); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="source-retry"]:focus-visible, [part="retry-button"]:focus-visible, lr-virtual-list::part(retry-button):focus-visible, [part="cancel-button"]:focus-visible, lr-virtual-list::part(cancel-button):focus-visible, [part='item-action-button']:focus-visible, lr-virtual-list::part(item-action-button):focus-visible { ${focusRing} } [part='retry-button']:disabled, [part='cancel-button']:disabled, [part='item-action-button']:disabled, lr-virtual-list::part(retry-button):disabled, lr-virtual-list::part(cancel-button):disabled, lr-virtual-list::part(item-action-button):disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } @media (prefers-reduced-motion: reduce) { [part="source-retry"], [part="retry-button"], lr-virtual-list::part(retry-button), [part="cancel-button"], lr-virtual-list::part(cancel-button), [part='item-action-button'], lr-virtual-list::part(item-action-button) { transition: none !important; } } [part='source-pagination'] { display: block; margin-block-start: var(--lr-space-s); } [part='source-status'], [part='limit'], [part='item-action-limit'], lr-virtual-list::part(item-action-limit) { margin: 0; padding: var(--lr-space-s); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } `;export{styles};
@@ -123,7 +123,7 @@ maxLines:number;
123
123
  /** Anchor kinds this component resolves via `scrollToAnchor()`. Feature-detectable capability
124
124
  * mirror -- the same pattern every other `DocumentAnchorTarget`-adopting viewer uses for this
125
125
  * field. */
126
- readonly anchorKinds:readonly LyraAnchorKind[];private copyStatus;private diffTooLarge;private copyAnnouncementSink?;private searchMatches;private searchMatchCountExact;private searchActiveIndex;private searchQuery;private lastSearchLocale;private pendingSearchResetEvent;private forcedVisibleOps;private readonly searchAnnouncements;private readonly searchAnnouncer;private highlightedOldLines;private highlightedNewLines;private highlightToken;private loadHighlighterCore;private copyTimer?;private copyGeneration;private oldTextSnapshot;private newTextSnapshot;private languageSnapshot;private languagesSnapshot?;private diffOps;private opIndexMap;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hasSearchState;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private cancelCopyTimer;private resetCopyFeedback;private get highlightLimited();private syncHighlight;private tokenizeLines;private computeFolds;private foldMarker;private revealOp;private lineElementForOpIndex;private scrollOpIndexIntoView;
126
+ readonly anchorKinds:readonly LyraAnchorKind[];private copyStatus;private diffTooLarge;private copyAnnouncementSink?;private searchMatches;private searchMatchCountExact;private searchActiveIndex;private searchQuery;private lastSearchLocale;private pendingSearchResetEvent;private forcedVisibleOps;private readonly searchAnnouncements;private readonly searchAnnouncer;private highlightedOldLines;private highlightedNewLines;private highlightToken;private loadHighlighterCore;private copyTimer?;private copyGeneration;private scrollGeneration;private searchGeneration;private oldTextSnapshot;private newTextSnapshot;private languageSnapshot;private languagesSnapshot?;private diffOps;private opIndexMap;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hasSearchState;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private cancelCopyTimer;private resetCopyFeedback;private get highlightLimited();private syncHighlight;private tokenizeLines;private computeFolds;private foldMarker;private revealOp;private lineElementForOpIndex;private scrollAuthority;private scrollOpIndexIntoView;
127
127
  /** Resolves a `line-range` anchor by scrolling the line at its 0-based `start` op index into
128
128
  * view, first expanding any `contextLines` fold currently hiding it. `end` is not consulted
129
129
  * here -- it only widens what a covering `highlights` entry paints; the scroll target is
@@ -133,14 +133,14 @@ protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private resolvedHighli
133
133
  * contains a locale-aware case-insensitive substring of `query`, ordered by that line's
134
134
  * `line-range` op index; an empty/whitespace query behaves like `clearSearch()` and resolves
135
135
  * `0`. Inspect `lr-search-change.matchCountExact` to distinguish an exact total from a lower
136
- * bound once a resource ceiling is reached. */
136
+ * bound once a resource ceiling is reached. A superseded search resolves `0`. */
137
137
  search(query:string):Promise<number>;
138
138
  /** Advances to the next match, wrapping to the first after the last. Resolves `true` once the
139
- * active match moved, `false` when there are no matches -- the shape the shared
140
- * `LyraTextViewerTarget` search contract declares. */
139
+ * active match moved, `false` when there are no matches or navigation is superseded -- the
140
+ * shape the shared `LyraTextViewerTarget` search contract declares. */
141
141
  searchNext():Promise<boolean>;
142
142
  /** Moves to the previous match, wrapping to the last before the first. Resolves `true` once the
143
- * active match moved, `false` when there are no matches. */
143
+ * active match moved, `false` when there are no matches or navigation is superseded. */
144
144
  searchPrevious():Promise<boolean>;
145
145
  /** Clears the query, matches, and active index, and resets `lr-search-change` to a
146
146
  * 0-match/no-active-index state. */
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,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]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++)if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)&&matches.push({opIndex:index}),!budget.complete){matchCountExact=!1;break}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
1
+ import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES,SHIKI_SOURCE_MAX_CODE_UNITS,resolvedShikiLanguages,ensureShikiLanguageLoaded}from"../../conversation/code-block/shiki-types.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewHighlightLimit,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_RENDERED_LINES=1e4,MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.scrollGeneration=0,this.searchGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewHighlightLimit:LYRA_DEFAULT_diffViewHighlightLimit,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,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]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if((changed.has("oldText")||changed.has("newText")||changed.has("maxLines"))&&(this.scrollGeneration++,this.searchGeneration++,this.cancelPendingAnchor()),super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"";const languages=projectLanguages(this.languages);if(this.languageLoaders===void 0)this.languagesSnapshot=languages;else{const loaders=projectLanguages(this.languageLoaders);this.languagesSnapshot=projectLanguages(combineShikiLanguageSources(languages,loaders))}}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.diffOps.length>MAX_DIFF_RENDERED_LINES&&(this.diffTooLarge=!0,this.diffOps=[]),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("languageLoaders")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncHighlight(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){this.highlightToken++,this.scrollGeneration++,this.searchGeneration++,super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){this.highlightToken++,this.scrollGeneration++,this.searchGeneration++,super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get highlightLimited(){return this.oldTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS||this.newTextSnapshot.length>SHIKI_SOURCE_MAX_CODE_UNITS}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge||this.highlightLimited){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=null,this.highlightedNewLines=null;let loading;try{loading=this.loadHighlighterCore(resolvedShikiLanguages(languages))}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(async hl=>{if(token!==this.highlightToken||!this.isConnected)return;if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const loaded=await ensureShikiLanguageLoaded(hl,lang,languages[lang]);if(!(token!==this.highlightToken||!this.isConnected)){if(!loaded){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){if(text.length>SHIKI_SOURCE_MAX_CODE_UNITS)return null;try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}scrollAuthority(){const generation=this.scrollGeneration,document=this.ownerDocument,ops=this.diffOps,oldText=this.oldText,newText=this.newText,maxLines=this.maxLines;return()=>this.isConnected&&this.ownerDocument===document&&this.scrollGeneration===generation&&this.diffOps===ops&&this.oldText===oldText&&this.newText===newText&&Object.is(this.maxLines,maxLines)}async scrollOpIndexIntoView(index,isCurrent=this.scrollAuthority()){const op=this.diffOps[index];if(!op||!isCurrent()||(await this.revealOp(op),!isCurrent()))return!1;const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){const generation=this.searchGeneration,isCurrent=this.scrollAuthority();this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),!(generation!==this.searchGeneration||!isCurrent())&&announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++)if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)&&matches.push({opIndex:index}),!budget.complete){matchCountExact=!1;break}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1;const active=this.searchMatches[this.searchActiveIndex],count=this.searchMatches.length;return this.emitSearchChange(),!isCurrent()||active&&!await this.scrollOpIndexIntoView(active.opIndex,isCurrent)?0:isCurrent()?count:0}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1);const active=this.searchMatches[this.searchActiveIndex];return this.emitSearchChange(),isCurrent()?this.scrollOpIndexIntoView(active.opIndex,isCurrent):!1}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration,ownsSource=this.scrollAuthority(),isCurrent=()=>generation===this.searchGeneration&&ownsSource();this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1);const active=this.searchMatches[this.searchActiveIndex];return this.emitSearchChange(),isCurrent()?this.scrollOpIndexIntoView(active.opIndex,isCurrent):!1}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
2
2
  `)}isCurrentCopy(generation,owner){return this.isConnected&&this.copyable&&!this.diffTooLarge&&generation===this.copyGeneration&&this.ownerDocument.defaultView===owner}showCopyStatus(status,generation){const owner=this.ownerDocument.defaultView;if(!owner||!this.isCurrentCopy(generation,owner))return;this.copyStatus=status,this.copyAnnouncementSink?.announce(status==="success"?this.localize("copied"):this.localize("copyFailed")),this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||!this.isCurrentCopy(generation,owner)||(this.copyTimer=void 0,this.copyStatus="rest")},COPY_CONFIRM_MS),this.copyTimer={owner,handle,generation}}async copy(){if(!this.copyable||this.diffTooLarge)return;const generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyStatus="rest";const text=this.unifiedText,owner=this.isConnected?this.ownerDocument.defaultView:null;if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.showCopyStatus("error",generation),this.emit("lr-error"),this.emit("lr-copy-error",outcome);return}this.showCopyStatus("success",generation),this.emit("lr-copy",outcome)}}lineRenderContext(){const{perOp,owners,order,total}=this.resolvedHighlightOps();return{perOp,owners,order,total,matchedOpIndexes:new Set(this.searchMatches.map(match=>match.opIndex)),activeMatchOpIndex:this.searchMatches[this.searchActiveIndex]?.opIndex??-1}}renderDiffLine(op,marker,content,context){const index=this.opIndexMap.get(op),isMatch=index!==void 0&&context.matchedOpIndexes.has(index),isActiveMatch=index!==void 0&&index===context.activeMatchOpIndex,highlight=context.perOp.get(op),owner=highlight&&context.owners.get(highlight)===op?highlight:void 0,ownerLabel=owner?this.highlightActionLabel(owner,context.order.get(owner)??0,context.total):"",text=html`${marker} ${content}`;return html`<div
3
3
  part="line"
4
4
  data-type=${op.type}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
1
+ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),!this.isConnected||generation!==this.generation||(this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation))return;this.emit("lr-load",{src:safeSource})}catch(error){const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
2
2
  part="svg"
3
3
  viewBox="0 0 24 24"
4
4
  fill="none"
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.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{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/file-size.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.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_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=Number.POSITIVE_INFINITY;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);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.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=(item,index)=>`${item.name}\0${index}`,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++}),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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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();const moved=this.detached.cancel();this.hasUpdated&&this.src&&!moved&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),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(tag("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(),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(tag("virtual-list"));index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}activeArchiveMatchKey(){if(this.fetchState.kind!=="loaded")return"";const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return"";const index=this.fetchState.entries.indexOf(match);return index>=0?this.archiveEntryKey(match,index):""}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.activeArchiveMatchKey()} @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
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.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{isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/file-size.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerFrameStyles}from"../viewer-frame.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_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=Number.POSITIVE_INFINITY;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);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.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=(item,index)=>`${item.name}\0${index}`,this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++}),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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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();const moved=this.detached.cancel();this.hasUpdated&&this.src&&(!moved||this.fetchState.kind==="loading")&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}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(signal?.aborted||!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(signal?.aborted||!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(signal?.aborted||!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(tag("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(),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(tag("virtual-list"));index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}activeArchiveMatchKey(){if(this.fetchState.kind!=="loaded")return"";const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return"";const index=this.fetchState.entries.indexOf(match);return index>=0?this.archiveEntryKey(match,index):""}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.activeArchiveMatchKey()} @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 +1 @@
1
- import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";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{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadIcal}from"./calendar-loader.js";import{styles}from"./calendar-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getDateTimeFormat}from"../../../internal/intl-cache.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_calendarViewerEmpty,LYRA_DEFAULT_calendarViewerLabel,LYRA_DEFAULT_calendarViewerMissingParser,LYRA_DEFAULT_calendarViewerNoSummary,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeCalendar,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_CALENDAR_EVENTS=250,MAX_CALENDAR_RENDERED_CHARS=2*1024*1024;function formatEventTime(event,locale){if(!event.start)return"";if(event.startKind==="date"){const formatter2=getDateTimeFormat(locale,{dateStyle:"medium",timeZone:"UTC"});if(!event.end||event.endKind!=="date")return formatter2.format(event.start);const inclusiveEnd=new Date(event.end.getTime());return inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate()-1),inclusiveEnd.getTime()<=event.start.getTime()?formatter2.format(event.start):formatter2.formatRange(event.start,inclusiveEnd)}const formatter=getDateTimeFormat(locale,{dateStyle:"medium",timeStyle:"short"});return event.end&&event.endKind==="date-time"?formatter.formatRange(event.start,event.end):formatter.format(event.start)}function parseCalendarTime(time){if(!time)return null;let value;if(time.isDate===!0&&Number.isInteger(time.year)&&Number.isInteger(time.month)&&Number.isInteger(time.day)){if(value=utcDate(time.year,time.month-1,time.day),value.getUTCFullYear()!==time.year||value.getUTCMonth()+1!==time.month||value.getUTCDate()!==time.day)throw new Error("Invalid all-day calendar date.")}else value=time.toJSDate();if(!Number.isFinite(value.getTime()))throw new Error("Invalid calendar date.");return{value,kind:time.isDate===!0?"date":"date-time"}}function eventTime(read){try{return parseCalendarTime(read())}catch{return null}}class LyraCalendarViewerBase extends LyraElement{}class LyraCalendarViewer extends TextViewerTarget(LyraCalendarViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,calendarViewerEmpty:LYRA_DEFAULT_calendarViewerEmpty,calendarViewerLabel:LYRA_DEFAULT_calendarViewerLabel,calendarViewerMissingParser:LYRA_DEFAULT_calendarViewerMissingParser,calendarViewerNoSummary:LYRA_DEFAULT_calendarViewerNoSummary,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeCalendar:LYRA_DEFAULT_documentPreviewTypeCalendar,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}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(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const events=await this.parse(source,generation);if(!this.isConnected||generation!==this.generation||!events)return;generation===this.generation&&(this.fetchState={kind:"loaded",events})}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})}}async parse(source,generation){const ical=await loadIcal();if(!this.isConnected||generation!==this.generation)return;if(!ical)throw new LyraUserFacingError(this.localize("calendarViewerMissingParser"));if((source.match(/^BEGIN:VEVENT\r?$/gim)?.length??0)>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");const subcomponents=new ical.Component(ical.parse(source)).getAllSubcomponents("vevent");if(subcomponents.length>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");let renderedChars=0;return subcomponents.map(subcomponent=>{const event=new ical.Event(subcomponent),parsedStart=eventTime(()=>event.startDate),parsedEnd=eventTime(()=>event.endDate),end=parsedStart&&parsedEnd&&(parsedStart.kind!==parsedEnd.kind||parsedEnd.value.getTime()<parsedStart.value.getTime())?null:parsedEnd,uid=event.uid??"",summary=event.summary??"",location=event.location??"",description=event.description??"";if(renderedChars+=uid.length+summary.length+location.length+description.length,renderedChars>MAX_CALENDAR_RENDERED_CHARS)throw new LyraResourceLimitError("The calendar contains too much rendered text.");return{uid,summary,start:parsedStart?.value??null,end:end?.value??null,startKind:parsedStart?.kind??null,endKind:end?.kind??null,location,description}})}renderEvent(event){return html`<li part="event"><span part="event-summary">${event.summary||this.localize("calendarViewerNoSummary")}</span><span part="event-time">${formatEventTime(event,this.effectiveLocale)}</span>${event.location?html`<span part="event-location">${event.location}</span>`:nothing}${event.description?html`<p part="event-description">${event.description}</p>`:nothing}</li>`}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.events.length?html`<ul part="event-list">${this.fetchState.events.map(event=>this.renderEvent(event))}</ul>`:html`<p class="empty-note">${this.localize("calendarViewerEmpty")}</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("documentPreviewTypeCalendar")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"&&this.fetchState.events.length>0?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${viewerSemanticRole(this,"region")??nothing} style=${maxHeight?styleMap({"--lr-calendar-viewer-max-height":maxHeight}):nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("calendarViewerLabel"))??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraCalendarViewer.prototype,"src",void 0),__decorate([property()],LyraCalendarViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraCalendarViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraCalendarViewer.prototype,"fetchState",void 0);export{LyraCalendarViewer};
1
+ import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";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{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadIcal}from"./calendar-loader.js";import{styles}from"./calendar-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getDateTimeFormat}from"../../../internal/intl-cache.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_calendarViewerEmpty,LYRA_DEFAULT_calendarViewerLabel,LYRA_DEFAULT_calendarViewerMissingParser,LYRA_DEFAULT_calendarViewerNoSummary,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeCalendar,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_CALENDAR_EVENTS=250,MAX_CALENDAR_RENDERED_CHARS=2*1024*1024;function formatEventTime(event,locale){if(!event.start)return"";if(event.startKind==="date"){const formatter2=getDateTimeFormat(locale,{dateStyle:"medium",timeZone:"UTC"});if(!event.end||event.endKind!=="date")return formatter2.format(event.start);const inclusiveEnd=new Date(event.end.getTime());return inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate()-1),inclusiveEnd.getTime()<=event.start.getTime()?formatter2.format(event.start):formatter2.formatRange(event.start,inclusiveEnd)}const formatter=getDateTimeFormat(locale,{dateStyle:"medium",timeStyle:"short"});return event.end&&event.endKind==="date-time"?formatter.formatRange(event.start,event.end):formatter.format(event.start)}function parseCalendarTime(time){if(!time)return null;let value;if(time.isDate===!0&&Number.isInteger(time.year)&&Number.isInteger(time.month)&&Number.isInteger(time.day)){if(value=utcDate(time.year,time.month-1,time.day),value.getUTCFullYear()!==time.year||value.getUTCMonth()+1!==time.month||value.getUTCDate()!==time.day)throw new Error("Invalid all-day calendar date.")}else value=time.toJSDate();if(!Number.isFinite(value.getTime()))throw new Error("Invalid calendar date.");return{value,kind:time.isDate===!0?"date":"date-time"}}function eventTime(read){try{return parseCalendarTime(read())}catch{return null}}class LyraCalendarViewerBase extends LyraElement{}class LyraCalendarViewer extends TextViewerTarget(LyraCalendarViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,calendarViewerEmpty:LYRA_DEFAULT_calendarViewerEmpty,calendarViewerLabel:LYRA_DEFAULT_calendarViewerLabel,calendarViewerMissingParser:LYRA_DEFAULT_calendarViewerMissingParser,calendarViewerNoSummary:LYRA_DEFAULT_calendarViewerNoSummary,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeCalendar:LYRA_DEFAULT_documentPreviewTypeCalendar,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){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(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const events=await this.parse(source,generation,signal);if(signal?.aborted||!this.isConnected||generation!==this.generation||!events)return;!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",events})}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}async parse(source,generation,signal){const ical=await loadIcal();if(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!ical)throw new LyraUserFacingError(this.localize("calendarViewerMissingParser"));if((source.match(/^BEGIN:VEVENT\r?$/gim)?.length??0)>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");const subcomponents=new ical.Component(ical.parse(source)).getAllSubcomponents("vevent");if(subcomponents.length>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");let renderedChars=0;return subcomponents.map(subcomponent=>{const event=new ical.Event(subcomponent),parsedStart=eventTime(()=>event.startDate),parsedEnd=eventTime(()=>event.endDate),end=parsedStart&&parsedEnd&&(parsedStart.kind!==parsedEnd.kind||parsedEnd.value.getTime()<parsedStart.value.getTime())?null:parsedEnd,uid=event.uid??"",summary=event.summary??"",location=event.location??"",description=event.description??"";if(renderedChars+=uid.length+summary.length+location.length+description.length,renderedChars>MAX_CALENDAR_RENDERED_CHARS)throw new LyraResourceLimitError("The calendar contains too much rendered text.");return{uid,summary,start:parsedStart?.value??null,end:end?.value??null,startKind:parsedStart?.kind??null,endKind:end?.kind??null,location,description}})}renderEvent(event){return html`<li part="event"><span part="event-summary">${event.summary||this.localize("calendarViewerNoSummary")}</span><span part="event-time">${formatEventTime(event,this.effectiveLocale)}</span>${event.location?html`<span part="event-location">${event.location}</span>`:nothing}${event.description?html`<p part="event-description">${event.description}</p>`:nothing}</li>`}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.events.length?html`<ul part="event-list">${this.fetchState.events.map(event=>this.renderEvent(event))}</ul>`:html`<p class="empty-note">${this.localize("calendarViewerEmpty")}</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("documentPreviewTypeCalendar")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"&&this.fetchState.events.length>0?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${viewerSemanticRole(this,"region")??nothing} style=${maxHeight?styleMap({"--lr-calendar-viewer-max-height":maxHeight}):nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("calendarViewerLabel"))??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraCalendarViewer.prototype,"src",void 0),__decorate([property()],LyraCalendarViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraCalendarViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraCalendarViewer.prototype,"fetchState",void 0);export{LyraCalendarViewer};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{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{viewerFrameStyles}from"../viewer-frame.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{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_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.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),this.detached=new DeferredTeardown(()=>{this.generation++})}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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}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(!this.isConnected||generation!==this.generation)return;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
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{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{viewerFrameStyles}from"../viewer-frame.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{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_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.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),this.detached=new DeferredTeardown(()=>{this.generation++})}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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!(this.detached.cancel()&&this.fetchState.kind!=="loading")&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.fetchState.kind==="loading"&&this.generation++,this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){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(signal?.aborted||!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(signal?.aborted||!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);!signal?.aborted&&this.isConnected&&generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}catch(error){if(signal?.aborted||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}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"