@aceshooting/lyra-ui 30.9.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/CHANGELOG.md +236 -339
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  4. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  5. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  6. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  7. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  8. package/dist/components/charts/chart/box-plot.class.js +2 -2
  9. package/dist/components/charts/chart/chart-sync.js +1 -1
  10. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  11. package/dist/components/charts/chart/chart.class.js +4 -4
  12. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  13. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  14. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  15. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  16. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  17. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  18. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  19. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  20. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  21. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  22. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  23. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  24. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  25. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  26. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  27. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  28. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  29. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  30. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  31. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  32. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  33. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  34. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  35. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  36. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  37. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  38. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  39. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  40. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  41. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  42. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  43. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  44. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  45. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  46. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  47. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  48. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  49. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  50. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  51. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  52. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  53. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  54. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  55. package/dist/components/data/pagination/pagination.class.js +1 -1
  56. package/dist/components/data/table/table.class.d.ts +31 -2
  57. package/dist/components/data/table/table.class.js +3 -3
  58. package/dist/components/data/table/table.styles.js +1 -1
  59. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  60. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  61. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  62. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  63. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  64. package/dist/components/data/timeline/timeline.class.js +9 -5
  65. package/dist/components/data/tree/tree-item.class.js +1 -1
  66. package/dist/components/data/tree/tree.class.d.ts +2 -0
  67. package/dist/components/data/tree/tree.class.js +1 -1
  68. package/dist/components/forms/button/button.class.d.ts +8 -6
  69. package/dist/components/forms/button/button.class.js +2 -2
  70. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  71. package/dist/components/forms/color-picker/color-core.js +1 -1
  72. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  73. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  74. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  75. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  76. package/dist/components/forms/input/input-shared.js +2 -2
  77. package/dist/components/forms/input/number-input-locale.js +1 -0
  78. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  79. package/dist/components/forms/input/number-input.class.js +2 -2
  80. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  81. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  82. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  83. package/dist/components/layout/details/accordion-item.class.js +1 -1
  84. package/dist/components/layout/menu/menu.class.js +1 -1
  85. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  86. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  87. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  88. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  89. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  90. package/dist/components/layout/tab-group/tab.class.js +1 -1
  91. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  92. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  93. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  94. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  95. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  96. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  97. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  98. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  99. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  100. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  101. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  102. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  103. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  104. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  105. package/dist/components/media/map/map-owned-features.js +1 -1
  106. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  107. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  108. package/dist/components/media/map/map.class.d.ts +5 -5
  109. package/dist/components/media/map/map.class.js +3 -3
  110. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  111. package/dist/components/media/video/video.class.d.ts +3 -3
  112. package/dist/components/media/video/video.class.js +3 -1
  113. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  114. package/dist/components/overlays/chip/chip.class.js +1 -1
  115. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  116. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  117. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  118. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  119. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  120. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  121. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  122. package/dist/components/retrieval/graph/graph.class.js +1 -1
  123. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  124. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  125. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  126. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  127. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  128. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  129. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  130. package/dist/components/utility/known-date/known-date.class.js +1 -1
  131. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  132. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  133. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  134. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  135. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  136. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  137. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  138. package/dist/components/viewers/include/include.class.js +1 -1
  139. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  140. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  141. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  142. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  143. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  144. package/dist/components/viewers/table-viewer-shared.js +4 -4
  145. package/dist/framework-types.d.ts +1 -1
  146. package/dist/internal/anchored-overlay-runtime.js +1 -1
  147. package/dist/internal/catalog-picker.js +1 -1
  148. package/dist/internal/document-tokens.js +2 -2
  149. package/dist/internal/drop-session-controller.js +1 -1
  150. package/dist/internal/engine-3d.js +1 -1
  151. package/dist/internal/icon-only-content.js +1 -1
  152. package/dist/internal/layered-layout.js +1 -1
  153. package/dist/internal/map-custom-layer-controller.js +1 -1
  154. package/dist/internal/media-panorama.js +1 -1
  155. package/dist/internal/package-metadata.js +1 -1
  156. package/dist/internal/safe-url.js +1 -1
  157. package/dist/internal/scoped-definitions.generated.js +1 -1
  158. package/dist/internal/scroll-overflow.js +1 -1
  159. package/dist/internal/source-window-controller.js +1 -1
  160. package/dist/internal/text-quote.js +1 -1
  161. package/dist/internal/viewer-search.js +1 -1
  162. package/dist/lyra.d.ts +1 -1
  163. package/dist/sequence-time-binding.js +1 -1
  164. package/dist/simulation-clock.js +1 -1
  165. package/dist/styles/reservations.css +1 -1
  166. package/dist/styles/reservations.styles.js +1 -1
  167. package/dist/testing/happy-dom-shims.js +1 -1
  168. package/dist/theme/theme.js +1 -1
  169. package/llms/components/lr-attachment-chip.md +27 -12
  170. package/llms/components/lr-attachment-trigger.md +27 -7
  171. package/llms/components/lr-button.md +6 -4
  172. package/llms/components/lr-chat-composer.md +13 -7
  173. package/llms/components/lr-chat-message.md +44 -3
  174. package/llms/components/lr-chat-viewport.md +39 -2
  175. package/llms/components/lr-data-grid.md +2 -0
  176. package/llms/components/lr-dialog.md +10 -0
  177. package/llms/components/lr-drop-zone.md +26 -2
  178. package/llms/components/lr-icon-button.md +2 -1
  179. package/llms/components/lr-json-viewer.md +17 -0
  180. package/llms/components/lr-locale-picker.md +5 -0
  181. package/llms/components/lr-markdown-core.md +2 -1
  182. package/llms/components/lr-markdown.md +20 -4
  183. package/llms/components/lr-menu.md +3 -1
  184. package/llms/components/lr-number-input.md +28 -1
  185. package/llms/components/lr-prompt-input.md +1 -1
  186. package/llms/components/lr-streaming-text-core.md +3 -2
  187. package/llms/components/lr-streaming-text.md +4 -1
  188. package/llms/components/lr-suggestion-chips.md +28 -5
  189. package/llms/components/lr-tab-group.md +13 -1
  190. package/llms/components/lr-tab.md +5 -0
  191. package/llms/components/lr-table.md +25 -4
  192. package/llms/components/lr-timeline-item.md +1 -1
  193. package/llms/components/lr-timeline.md +38 -4
  194. package/llms/components/lr-tooltip.md +3 -1
  195. package/llms/components/lr-tree.md +4 -0
  196. package/llms/components/lr-virtual-list.md +1 -0
  197. package/llms/peers.md +2 -2
  198. package/llms/shared/forms-and-accessibility.md +21 -4
  199. package/llms/shared.md +21 -4
  200. package/package.json +21 -20
  201. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import"../../data/pagination/pagination.class.js";function sourceField(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid neighborhood value");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Accessor neighborhood field");return descriptor?.value}function sourceRows(raw,limit){if(!Array.isArray(raw))throw new TypeError("Invalid neighborhood page");const length=sourceCount(sourceField(raw,"length"));if(length>limit)throw new RangeError("Neighborhood page limit");let units=0;const text=(value,required=!1)=>{if(!(value===void 0&&!required)){if(typeof value!="string"||required&&!value.trim()||value.length>65536||(units+=value.length)>2e6)throw new TypeError("Invalid neighborhood text");return value}};return Object.freeze(Array.from({length},(_,index)=>{const entry=sourceField(raw,index),record=sourceField(entry,"value");if(sourceField(record,"kind")!=="node")throw new TypeError("Expected neighborhood node");const node=sourceField(record,"value"),key=text(sourceField(entry,"key"),!0),id=text(sourceField(node,"id"),!0);if(key!==`node:${id}`)throw new TypeError("Invalid neighborhood identity");const label=text(sourceField(node,"label")),accessibleLabel=text(sourceField(node,"accessibleLabel")),type=text(sourceField(node,"type"));return Object.freeze({key,order:sourceCount(sourceField(entry,"order")),value:Object.freeze({id,...label===void 0?{}:{label},...accessibleLabel===void 0?{}:{accessibleLabel},...type===void 0?{}:{type}})})}))}function sourceSummary(raw){return Object.freeze({nodes:sourceCount(sourceField(raw,"nodes")),edges:sourceCount(sourceField(raw,"edges"))})}import{AnnouncementSinkController}from"../../../internal/announcer.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteInteger,finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel,LYRA_DEFAULT_neighborSourceChoose,LYRA_DEFAULT_neighborSourceError,LYRA_DEFAULT_neighborSourceSummary}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_retry}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.centerKey=null,this.sourceDirection="both",this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!1,this.sourceTypesVersion=0,this.sourcePage=0,this.sourcePageSize=100,this.sourceEpoch=0,this.sourceNavigation=0,this.sourcePaint=0,this.sourceError=!1,this.sourceSyncing=!1,this.sourcePromise=Promise.resolve(!1),this.sourcePages=new SourcePageController(this,{normalizeRecord:row=>row,normalizeSummary:sourceSummary,validateMetadata:result=>{if(result.total>result.summary.nodes)throw new RangeError("Invalid neighborhood total")},onChange:()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)}}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.explicitRefresh=0,this.renderRow=item=>this.renderNeighborRow(item),this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,loading:LYRA_DEFAULT_loading,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel,neighborSourceChoose:LYRA_DEFAULT_neighborSourceChoose,neighborSourceError:LYRA_DEFAULT_neighborSourceError,neighborSourceSummary:LYRA_DEFAULT_neighborSourceSummary,retry:LYRA_DEFAULT_retry}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get graphSource(){return this._graphSource}set graphSource(value){const previous=this._graphSource;this._graphSource=value,this.requestUpdate("graphSource",previous),previous===value&&super.requestUpdate()}get sourceNodeTypes(){return this._sourceNodeTypes}set sourceNodeTypes(value){const previous=this._sourceNodeTypes,transaction=++this.sourceTypesVersion;try{if(!Array.isArray(value))throw new TypeError("Invalid neighborhood types");const length=sourceCount(sourceField(value,"length"));if(length>500)throw new RangeError("Neighborhood type limit");const types=new Set;let units=0;for(let i=0;i<length;i++){const item=sourceField(value,i);if(typeof item!="string"||!item.trim()||item.length>65536)throw new TypeError("Invalid neighborhood type");if(!types.has(item)){if(units+=item.length,units>2e6)throw new RangeError("Neighborhood type budget");types.add(item)}}if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([...types].sort()),this.sourceTypesError=!1}catch{if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!0}this.requestUpdate("sourceNodeTypes",previous)}get sourceTotal(){return this.graphSource!==void 0&&this.centerKey!==null&&!this.sourceError&&this.sourceBinding?.[3]===this.sourceEpoch?this.sourcePages.state.result?.total??null:null}sourceCurrent(){const source=this.graphSource,epoch=this.sourceEpoch,owner=this.ownerDocument;let revision;try{revision=source?.revision}catch{return()=>!1}return()=>{try{return source?.revision===revision&&this.isConnected&&this.ownerDocument===owner&&this.graphSource===source&&this.sourceEpoch===epoch}catch{return!1}}}syncSource(){if(!this.sourcePages||this.sourceSyncing)return;this.sourceSyncing=!0;const epoch=this.sourceEpoch;try{if(this.sourceError&&this.sourceFailedEpoch===epoch)return;const source=this.graphSource;if(source===void 0||this.centerKey===null||!this.isConnected){(this.sourceBinding||this.sourcePageBinding)&&this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,this.sourceError=!1;return}if(this.sourceTypesError||typeof this.centerKey!="string"||!this.centerKey.startsWith("node:")||!this.centerKey.slice(5).trim()||this.centerKey.length>65536||!["in","out","both"].includes(this.sourceDirection))throw new TypeError("Invalid neighborhood scope");const revision=sourceRevision(source.revision),records=source.records,locale=this.effectiveLocale,queryRead=records.query,lookupRead=records.lookup,locateRead=records.locate;if(sourceRevision(records.revision)!==revision||typeof queryRead!="function"||typeof lookupRead!="function"||typeof locateRead!="function")throw new TypeError("Invalid neighborhood provider");if(epoch!==this.sourceEpoch||source!==this.graphSource)return;const binding=[source,records,revision,epoch,locale];if(!this.sourceBinding||binding.some((value,index)=>value!==this.sourceBinding[index])){this.sourceBinding=binding,this.sourcePageBinding=void 0,this.sourceError=!1;const current=()=>source.revision===revision&&source.records===records&&records.revision===revision&&this.isConnected&&epoch===this.sourceEpoch&&source===this.graphSource,check=()=>{if(!current())throw new Error("Obsolete neighborhood")};if(this.sourcePages.bind({revision,epoch,locale,source:{revision,query:async request=>{check();const raw=await queryRead.call(records,request);if(check(),sourceField(raw,"groups")!==void 0||sourceField(raw,"tags")!==void 0)throw new TypeError("Unexpected neighborhood metadata");const result={rows:sourceRows(sourceField(raw,"rows"),request.pageSize),total:sourceCount(sourceField(raw,"total")),summary:sourceSummary(sourceField(raw,"summary"))};return check(),result},lookup:async(keys,context)=>{check();const raw=await lookupRead.call(records,keys,context);check();const rows=sourceRows(raw,keys.length);return check(),rows},locate:async(key,query,context)=>{check();const result=await locateRead.call(records,key,query,context);return check(),result}}}),epoch!==this.sourceEpoch||source!==this.graphSource)return}const size=finiteInteger(this.sourcePageSize,100,1,500),page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size)),signature=[page,size,this.centerKey,this.sourceDirection,this.sourceNodeTypes];(!this.sourcePageBinding||signature.some((value,index)=>value!==this.sourcePageBinding[index]))&&(this.sourcePageBinding=signature,this.sourcePromise=this.sourcePages.request(Object.freeze({kind:"nodes",search:"",centerKey:this.centerKey,direction:this.sourceDirection,nodeTypes:this.sourceNodeTypes}),page,size))}catch{epoch===this.sourceEpoch&&(this.sourceError=!0,this.sourceFailedEpoch=epoch,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0)}finally{this.sourceSyncing=!1,epoch!==this.sourceEpoch&&queueMicrotask(()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)})}}async revealSourceKey(key){const navigation=++this.sourceNavigation;if(this.graphSource===void 0||this.centerKey===null||typeof key!="string"||!key.startsWith("node:")||!key.slice(5).trim()||key.length>65536)return!1;this.syncSource();const sourceCurrent=this.sourceCurrent(),current=()=>sourceCurrent()&&this.sourceNavigation===navigation;if(await this.sourcePromise,!current()||this.sourceError)return!1;const index=await this.sourcePages.locate(key);if(!current()||index===null||(this.sourceSyncing=!0,this.sourcePage=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500)),this.sourceSyncing=!1,this.syncSource(),await this.sourcePromise,await this.updateComplete,!current()))return!1;const target=[...this.renderRoot.querySelectorAll("[data-source-key]")].find(node=>node.dataset.sourceKey===key);return!target||!current()||(target.scrollIntoView({block:"nearest"}),!current())?!1:(target.focus(),current()&&this.renderRoot.querySelector("[data-source-key]:focus")===target)}connectedCallback(){super.connectedCallback(),this.sourceEpoch++,this.syncSource()}disconnectedCallback(){this.sourceEpoch++,this.sourceNavigation++,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,super.disconnectedCallback()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}requestUpdate(...args){if(this.sourcePages&&(!this.sourceSyncing||args[0]!=="sourcePage"))if(args[0]===void 0||["graphSource","centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){if(this.sourceEpoch++,this.sourceNavigation++,["centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){const syncing=this.sourceSyncing;this.sourceSyncing=!0,this.sourcePage=0,this.sourceSyncing=syncing}}else args[0]==="sourcePage"&&this.sourceNavigation++;args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.graphSource!==void 0){const state=this.sourcePages.state;state.result&&this.sourcePage!==state.page&&(this.sourceSyncing=!0,this.sourcePage=state.page,this.sourceSyncing=!1,this.sourcePageBinding&&(this.sourcePageBinding=[state.page,...this.sourcePageBinding.slice(1)])),(changed.has("rows")||changed.has("groupByRelation"))&&(this.hasComputedRows=!1);return}if(this.hasUpdated&&changed.has("rows")){const message=this.inputLimitMessage();message&&this.announcements.announcePolite(message)}const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows());const groupDeps=[this.sortedRowsCache,this.effectiveLocale,this.strings,lyraLocaleCatalogVersion(this.effectiveLocale),this.explicitRefresh];(!this.groupDeps||groupDeps.some((value,index)=>value!==this.groupDeps[index]))&&(this.groupDeps=groupDeps,this.groupsCache=this.computeGroups(this.sortedRowsCache));const presentationDeps=[...groupDeps,this.types,this.expandable];(!this.presentationDeps||presentationDeps.some((value,index)=>value!==this.presentationDeps[index]))&&(this.presentationDeps=presentationDeps,this.renderRow=item=>this.renderNeighborRow(item)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);if(!this.groupByRelation)return rows;const compare=getCollator(this.effectiveLocale).compare;return rows.sort((a,b)=>compare(a.relation,b.relation))}groups(sorted){return sorted===this.sortedRowsCache?this.groupsCache:this.computeGroups(sorted)}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
1
+ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal/source-page-controller.js";import{sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import"../../data/pagination/pagination.class.js";function sourceField(value,key){if(!value||typeof value!="object")throw new TypeError("Invalid neighborhood value");const descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Accessor neighborhood field");return descriptor?.value}function sourceRows(raw,limit){if(!Array.isArray(raw))throw new TypeError("Invalid neighborhood page");const length=sourceCount(sourceField(raw,"length"));if(length>limit)throw new RangeError("Neighborhood page limit");let units=0;const text=(value,required=!1)=>{if(!(value===void 0&&!required)){if(typeof value!="string"||required&&!value.trim()||value.length>65536||(units+=value.length)>2e6)throw new TypeError("Invalid neighborhood text");return value}};return Object.freeze(Array.from({length},(_,index)=>{const entry=sourceField(raw,index),record=sourceField(entry,"value");if(sourceField(record,"kind")!=="node")throw new TypeError("Expected neighborhood node");const node=sourceField(record,"value"),key=text(sourceField(entry,"key"),!0),id=text(sourceField(node,"id"),!0);if(key!==`node:${id}`)throw new TypeError("Invalid neighborhood identity");const label=text(sourceField(node,"label")),accessibleLabel=text(sourceField(node,"accessibleLabel")),type=text(sourceField(node,"type"));return Object.freeze({key,order:sourceCount(sourceField(entry,"order")),value:Object.freeze({id,...label===void 0?{}:{label},...accessibleLabel===void 0?{}:{accessibleLabel},...type===void 0?{}:{type}})})}))}function sourceSummary(raw){return Object.freeze({nodes:sourceCount(sourceField(raw,"nodes")),edges:sourceCount(sourceField(raw,"edges"))})}import{AnnouncementSinkController}from"../../../internal/announcer.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{expandIcon}from"../../../internal/icons.js";import{finiteInteger,finiteCount}from"../../../internal/numbers.js";import{getCollator,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import"../../overlays/empty/empty.class.js";import{styles}from"./neighbor-list.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_graphDataListLimit,LYRA_DEFAULT_neighborExpand,LYRA_DEFAULT_neighborGroupHeader,LYRA_DEFAULT_neighborListEmpty,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_neighborRowLabel,LYRA_DEFAULT_neighborSourceChoose,LYRA_DEFAULT_neighborSourceError,LYRA_DEFAULT_neighborSourceSummary}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_loading,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_retry}from"../../../internal/default-strings/shared.generated.js";let virtualListRegistration;class LyraNeighborList extends LyraElement{constructor(){super(...arguments),this.rows=[],this.types=[],this.groupByRelation=!1,this.expandable=!1,this.virtualizeAt=100,this.centerKey=null,this.sourceDirection="both",this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!1,this.sourceTypesVersion=0,this.sourcePage=0,this.sourcePageSize=100,this.sourceEpoch=0,this.sourceNavigation=0,this.sourcePaint=0,this.sourceError=!1,this.sourceSyncing=!1,this.sourcePromise=Promise.resolve(!1),this.sourcePages=new SourcePageController(this,{normalizeRecord:row=>row,normalizeSummary:sourceSummary,validateMetadata:result=>{if(result.total>result.summary.nodes)throw new RangeError("Invalid neighborhood total")},onChange:()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)}}),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sortedRowsCache=[],this.hasComputedRows=!1,this.processedSignature="",this.explicitRefresh=0,this.virtualListKeyFunction=item=>item.node.id}static{this.defaultStrings={...super.defaultStrings,graphDataListLimit:LYRA_DEFAULT_graphDataListLimit,loading:LYRA_DEFAULT_loading,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,neighborExpand:LYRA_DEFAULT_neighborExpand,neighborGroupHeader:LYRA_DEFAULT_neighborGroupHeader,neighborListEmpty:LYRA_DEFAULT_neighborListEmpty,neighborListLabel:LYRA_DEFAULT_neighborListLabel,neighborRowLabel:LYRA_DEFAULT_neighborRowLabel,neighborSourceChoose:LYRA_DEFAULT_neighborSourceChoose,neighborSourceError:LYRA_DEFAULT_neighborSourceError,neighborSourceSummary:LYRA_DEFAULT_neighborSourceSummary,retry:LYRA_DEFAULT_retry}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["rows","types"])}static{this.styles=[LyraElement.styles,styles]}get graphSource(){return this._graphSource}set graphSource(value){const previous=this._graphSource;this._graphSource=value,this.requestUpdate("graphSource",previous),previous===value&&super.requestUpdate()}get sourceNodeTypes(){return this._sourceNodeTypes}set sourceNodeTypes(value){const previous=this._sourceNodeTypes,transaction=++this.sourceTypesVersion;try{if(!Array.isArray(value))throw new TypeError("Invalid neighborhood types");const length=sourceCount(sourceField(value,"length"));if(length>500)throw new RangeError("Neighborhood type limit");const types=new Set;let units=0;for(let i=0;i<length;i++){const item=sourceField(value,i);if(typeof item!="string"||!item.trim()||item.length>65536)throw new TypeError("Invalid neighborhood type");if(!types.has(item)){if(units+=item.length,units>2e6)throw new RangeError("Neighborhood type budget");types.add(item)}}if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([...types].sort()),this.sourceTypesError=!1}catch{if(transaction!==this.sourceTypesVersion)return;this._sourceNodeTypes=Object.freeze([]),this.sourceTypesError=!0}this.requestUpdate("sourceNodeTypes",previous)}get sourceTotal(){return this.graphSource!==void 0&&this.centerKey!==null&&!this.sourceError&&this.sourceBinding?.[3]===this.sourceEpoch?this.sourcePages.state.result?.total??null:null}sourceCurrent(){const source=this.graphSource,epoch=this.sourceEpoch,owner=this.ownerDocument;let revision;try{revision=source?.revision}catch{return()=>!1}return()=>{try{return source?.revision===revision&&this.isConnected&&this.ownerDocument===owner&&this.graphSource===source&&this.sourceEpoch===epoch}catch{return!1}}}syncSource(){if(!this.sourcePages||this.sourceSyncing)return;this.sourceSyncing=!0;const epoch=this.sourceEpoch;try{if(this.sourceError&&this.sourceFailedEpoch===epoch)return;const source=this.graphSource;if(source===void 0||this.centerKey===null||!this.isConnected){(this.sourceBinding||this.sourcePageBinding)&&this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,this.sourceError=!1;return}if(this.sourceTypesError||typeof this.centerKey!="string"||!this.centerKey.startsWith("node:")||!this.centerKey.slice(5).trim()||this.centerKey.length>65536||!["in","out","both"].includes(this.sourceDirection))throw new TypeError("Invalid neighborhood scope");const revision=sourceRevision(source.revision),records=source.records,locale=this.effectiveLocale,queryRead=records.query,lookupRead=records.lookup,locateRead=records.locate;if(sourceRevision(records.revision)!==revision||typeof queryRead!="function"||typeof lookupRead!="function"||typeof locateRead!="function")throw new TypeError("Invalid neighborhood provider");if(epoch!==this.sourceEpoch||source!==this.graphSource)return;const binding=[source,records,revision,epoch,locale];if(!this.sourceBinding||binding.some((value,index)=>value!==this.sourceBinding[index])){this.sourceBinding=binding,this.sourcePageBinding=void 0,this.sourceError=!1;const current=()=>source.revision===revision&&source.records===records&&records.revision===revision&&this.isConnected&&epoch===this.sourceEpoch&&source===this.graphSource,check=()=>{if(!current())throw new Error("Obsolete neighborhood")};if(this.sourcePages.bind({revision,epoch,locale,source:{revision,query:async request=>{check();const raw=await queryRead.call(records,request);if(check(),sourceField(raw,"groups")!==void 0||sourceField(raw,"tags")!==void 0)throw new TypeError("Unexpected neighborhood metadata");const result={rows:sourceRows(sourceField(raw,"rows"),request.pageSize),total:sourceCount(sourceField(raw,"total")),summary:sourceSummary(sourceField(raw,"summary"))};return check(),result},lookup:async(keys,context)=>{check();const raw=await lookupRead.call(records,keys,context);check();const rows=sourceRows(raw,keys.length);return check(),rows},locate:async(key,query,context)=>{check();const result=await locateRead.call(records,key,query,context);return check(),result}}}),epoch!==this.sourceEpoch||source!==this.graphSource)return}const size=finiteInteger(this.sourcePageSize,100,1,500),page=finiteInteger(this.sourcePage,0,0,Math.floor(Number.MAX_SAFE_INTEGER/size)),signature=[page,size,this.centerKey,this.sourceDirection,this.sourceNodeTypes];(!this.sourcePageBinding||signature.some((value,index)=>value!==this.sourcePageBinding[index]))&&(this.sourcePageBinding=signature,this.sourcePromise=this.sourcePages.request(Object.freeze({kind:"nodes",search:"",centerKey:this.centerKey,direction:this.sourceDirection,nodeTypes:this.sourceNodeTypes}),page,size))}catch{epoch===this.sourceEpoch&&(this.sourceError=!0,this.sourceFailedEpoch=epoch,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0)}finally{this.sourceSyncing=!1,epoch!==this.sourceEpoch&&queueMicrotask(()=>{const old=this.sourcePaint++;this.requestUpdate("sourcePaint",old)})}}async revealSourceKey(key){const navigation=++this.sourceNavigation;if(this.graphSource===void 0||this.centerKey===null||typeof key!="string"||!key.startsWith("node:")||!key.slice(5).trim()||key.length>65536)return!1;this.syncSource();const sourceCurrent=this.sourceCurrent(),current=()=>sourceCurrent()&&this.sourceNavigation===navigation;if(await this.sourcePromise,!current()||this.sourceError)return!1;const index=await this.sourcePages.locate(key);if(!current()||index===null||(this.sourceSyncing=!0,this.sourcePage=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500)),this.sourceSyncing=!1,this.syncSource(),await this.sourcePromise,await this.updateComplete,!current()))return!1;const target=[...this.renderRoot.querySelectorAll("[data-source-key]")].find(node=>node.dataset.sourceKey===key);return!target||!current()||(target.scrollIntoView({block:"nearest"}),!current())?!1:(target.focus(),current()&&this.renderRoot.querySelector("[data-source-key]:focus")===target)}connectedCallback(){super.connectedCallback(),this.sourceEpoch++,this.syncSource()}disconnectedCallback(){this.sourceEpoch++,this.sourceNavigation++,this.sourcePages.bind(void 0),this.sourceBinding=void 0,this.sourcePageBinding=void 0,super.disconnectedCallback()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,100)}requestUpdate(...args){if(this.sourcePages&&(!this.sourceSyncing||args[0]!=="sourcePage"))if(args[0]===void 0||["graphSource","centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){if(this.sourceEpoch++,this.sourceNavigation++,["centerKey","sourceDirection","sourceNodeTypes","sourcePageSize"].includes(String(args[0]))){const syncing=this.sourceSyncing;this.sourceSyncing=!0,this.sourcePage=0,this.sourceSyncing=syncing}}else args[0]==="sourcePage"&&this.sourceNavigation++;args[0]===void 0&&(this.explicitRefresh=(this.explicitRefresh??0)+1),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.graphSource!==void 0){const state=this.sourcePages.state;state.result&&this.sourcePage!==state.page&&(this.sourceSyncing=!0,this.sourcePage=state.page,this.sourceSyncing=!1,this.sourcePageBinding&&(this.sourcePageBinding=[state.page,...this.sourcePageBinding.slice(1)])),(changed.has("rows")||changed.has("groupByRelation"))&&(this.hasComputedRows=!1);return}if(this.hasUpdated&&changed.has("rows")){const message=this.inputLimitMessage();message&&this.announcements.announcePolite(message)}const signature=`${this.effectiveLocale} ${this.groupByRelation}`;(!this.hasComputedRows||changed.has("rows")||changed.has("groupByRelation")||signature!==this.processedSignature)&&(this.hasComputedRows=!0,this.processedSignature=signature,this.sortedRowsCache=this.computeSortedRows());const groupDeps=[this.sortedRowsCache,this.effectiveLocale,this.strings,lyraLocaleCatalogVersion(this.effectiveLocale),this.explicitRefresh];(!this.groupDeps||groupDeps.some((value,index)=>value!==this.groupDeps[index]))&&(this.groupDeps=groupDeps,this.groupsCache=this.computeGroups(this.sortedRowsCache));const presentationDeps=[...groupDeps,this.types,this.expandable];(!this.presentationDeps||presentationDeps.some((value,index)=>value!==this.presentationDeps[index]))&&(this.presentationDeps=presentationDeps,this.renderRow=item=>this.renderNeighborRow(item)),this.sortedRowsCache.length>this.effectiveVirtualizeAt&&(virtualListRegistration??=import("../../layout/virtual-list/virtual-list.js").catch(()=>virtualListRegistration=void 0))}sortedRows(){return this.sortedRowsCache}computeSortedRows(){const rows=firstByRetrievalIdentity(this.rows,row=>row?.node?.id);if(!this.groupByRelation)return rows;const compare=getCollator(this.effectiveLocale).compare;return rows.sort((a,b)=>compare(a.relation,b.relation))}computeGroups(sorted){if(!this.groupByRelation)return;const groups=[],counts=new Map;for(const row of sorted)counts.set(row.relation,(counts.get(row.relation)??0)+1);const numberFormat=getNumberFormat(this.effectiveLocale);let lastRelation;return sorted.forEach((row,i)=>{if(row.relation!==lastRelation){const count=numberFormat.format(counts.get(row.relation)??0);groups.push({key:row.relation,label:this.localize("neighborGroupHeader",void 0,{relation:row.relation,count}),startIndex:i}),lastRelation=row.relation}}),groups}directionGlyph(direction){return direction==="both"?"↔":direction==="out"?"→":"←"}directionText(direction){return this.localize(direction==="in"?"neighborDirectionIn":direction==="out"?"neighborDirectionOut":"neighborDirectionBoth")}renderNeighborRow(row){const nodeLabel=row.node.label||row.node.id,directionText=this.directionText(row.direction),accessibleName=this.localize("neighborRowLabel",void 0,{label:nodeLabel,relation:row.relation,direction:directionText}),nodeType=typeof row.node.type=="string"&&row.node.type.trim()!==""?row.node.type:void 0;this.typeLabels?.[0]!==this.types&&(this.typeLabels=[this.types,new Map(firstByRetrievalIdentity(this.types,type=>type?.id).map(type=>[type.id,type.label]))]);const meta=[nodeType&&(this.typeLabels[1].get(nodeType)??nodeType),row.node.degree!=null?getNumberFormat(this.effectiveLocale).format(finiteCount(row.node.degree)):void 0].filter(v=>typeof v=="string"&&v!==""),metaText=getListFormat(this.effectiveLocale,{style:"short",type:"unit"}).format(meta);return html`
2
2
  <button
3
3
  part="node-label"
4
4
  type="button"
@@ -51,10 +51,10 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
51
51
  .items=${guard([sorted],()=>sorted)}
52
52
  .renderItem=${this.renderRow}
53
53
  .keyFunction=${this.virtualListKeyFunction}
54
- .groups=${this.groups(sorted)}
54
+ .groups=${this.groupsCache}
55
55
  ></lr-virtual-list>
56
56
  </div>
57
- `;const groups=this.groups(sorted),groupsByStartIndex=new Map(groups?.map(g=>[g.startIndex,g])??[]);return html`
57
+ `;const groups=this.groupsCache,groupsByStartIndex=new Map(groups?.map(g=>[g.startIndex,g])??[]);return html`
58
58
  <div part="base" role=${role??nothing} aria-label=${label??nothing}>
59
59
  ${this.renderInputLimit()}
60
60
  <div role="list">
@@ -31,7 +31,7 @@ import{__decorate}from"tslib";import{SourcePageController}from"../../../internal
31
31
  ></lr-chunk-inspector>
32
32
  ${this.presentation==="expanded"?this.renderMetadata(chunk.metadata):nothing}
33
33
  </div>
34
- `}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,retrievalResultsInputLimit:LYRA_DEFAULT_retrievalResultsInputLimit,retrievalResultsSelectRowOrdinal:LYRA_DEFAULT_retrievalResultsSelectRowOrdinal,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource,valueInvalid:LYRA_DEFAULT_valueInvalid,valueTruncated:LYRA_DEFAULT_valueTruncated}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["chunks"])}static{this.ownedCollectionProperties=Object.freeze(["chunks","selectedChunkIds","groupOrder"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-chunk-open"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-selection-change":Object.freeze(["chunks"])})}get dataSource(){return this._dataSource}set dataSource(value){const old=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",old)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||!!this.errorText||this.sourcePages.state.pending||!this.sourcePages.state.result)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||this.sourceSelectionFailed)}projectSourceChunk(record,isCurrent){let units=0;const read=(input,key)=>{if(!isCurrent())throw new Error("Obsolete source chunk");const value2=readOwnDataValue(input,key);if(!isCurrent())throw new Error("Obsolete source chunk");return value2},fields=(input,keys)=>{if(!input||typeof input!="object"||Array.isArray(input))throw new TypeError("Invalid source chunk");const copy={};for(const key of keys){const value2=read(input,key);if(typeof value2=="string"&&(units+=value2.length,value2.length>65536||units>65536))throw new RangeError("Source chunk text too large");value2!==void 0&&(copy[key]=value2)}return copy},raw=fields(record.value,["id","text","score","metadata","rank","queryId","stage","traceId","scores"]);raw.source=fields(read(record.value,"source"),["id","name","mimeType","uri","version"]);const locator=read(record.value,"locator");if(locator!==void 0){const projected=fields(locator,["kind","page","quote","prefix","suffix","id","start","end","sheet","range","cfi"]);for(const key of["kind","quote","prefix","suffix","id","sheet","range","cfi"])if(projected[key]!==void 0&&typeof projected[key]!="string")throw new TypeError("Invalid source locator text");for(const key of["page","start","end"])if(projected[key]!==void 0&&(typeof projected[key]!="number"||!Number.isFinite(projected[key])))throw new TypeError("Invalid source locator number");const rect=read(locator,"rect");if(rect!==void 0){const coordinates=fields(rect,["x","y","width","height"]);for(const key of["x","y","width","height"])if(typeof coordinates[key]!="number"||!Number.isFinite(coordinates[key]))throw new TypeError("Invalid source locator rectangle");projected.rect=coordinates}const path=read(locator,"path");if(path!==void 0){if(!Array.isArray(path))throw new TypeError("Invalid source locator path");const length=read(path,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>500)throw new RangeError("Source locator path too large");projected.path=Array.from({length},(_,index)=>{const value2=read(path,String(index));if(typeof value2!="string"&&typeof value2!="number")throw new TypeError("Invalid source locator path");if(typeof value2=="string"&&(units+=value2.length,units>65536))throw new RangeError("Source chunk text too large");return value2})}raw.locator=projected}const scores=raw.scores;scores&&typeof scores=="object"&&!Array.isArray(scores)&&(raw.scores=fields(scores,["dense","sparse","rerank","final"]));const value=projectRetrievalChunk(raw);if(!isCurrent())throw new Error("Obsolete source chunk");if(!value)throw new TypeError("Invalid source chunk");return this.sourceRowKeys.set(value,record.key),{key:record.key,order:record.order,value}}validateSourcePage(result,query){if(!query.withoutDedupe&&result.rows.some(record=>record.key!==record.value.id))throw new TypeError("Invalid canonical source identity");if(query.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=group.startIndex+group.itemCount,covered=Math.min(end,previousEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}canonicalSourceAdapter(source){if(this.sourceAdapter?.original===source)return this.sourceAdapter.adapter;if(!source||typeof source.query!="function"||typeof source.lookup!="function"||typeof source.locate!="function")throw new TypeError("Invalid source");const adapter={revision:source.revision,query:request=>source.query(request),locate:(key,query,context)=>source.locate(key,query,context),lookup:async(keys,context)=>{const records=await source.lookup(keys,context);if(!Array.isArray(records)||records.length>500)throw new TypeError("Invalid canonical lookup");for(let index=0;index<records.length;index++){const record=readOwnDataValue(records,String(index)),key=readOwnDataValue(record,"key"),value=readOwnDataValue(record,"value");if(key!==readOwnDataValue(value,"id"))throw new TypeError("Invalid canonical lookup identity")}return records}};return this.sourceAdapter={original:source,adapter},adapter}syncSource(force=!1){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceVersion++,this.focusRestoreGeneration++,this.sourcePages.bind(void 0),this.processedChunksCache=void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourceGroups=[],this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0;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));const queryInputs=[this.sort,this.withoutDedupe,this.grouping,this.groupBy,this.groupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,page];if(!force&&this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;(!this.sourceInputs||inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index]))&&(this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0),this.sourceInputs=inputs,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0,this.sourceReveal=void 0,this.expandedChunkIds=[],this.sourcePages.bind({source:this.canonicalSourceAdapter(source),revision:source.revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query=Object.freeze({sort:this.sort,withoutDedupe:this.withoutDedupe,grouping:this.grouping,groupBy:this.groupBy,groupLabel:this.groupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||!this.isConnected||!this.sourceAdapter||!this.sourceInputs)return;const ids=this.selectedChunkIds,source=this.dataSource,epoch=this.sourceEpoch,revision=source.revision,inputs=[source,revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs,this.sourceSelectionFailed=!1;const owner=this.ownerDocument,lifecycle=this.sourceLifecycle,canonicalIds=canonicalIdentityList(ids);this.sourcePages.resolveSelection(canonicalIds).then(records=>{if(source.revision!==revision||lifecycle!==this.sourceLifecycle||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.selectedChunkIds!==ids)return;if(!records){this.sourceSelectionFailed=!0,this.sourceStateVersion++;return}const retained=new Set(records.map(record=>record.key)),accepted=canonicalIds.filter(id=>retained.has(id)),report=this.sourceSelectionEvent===ids;this.sourceSelectionEvent=void 0,accepted.length!==ids.length&&(this.selectedChunkIds=accepted);const committed=this.selectedChunkIds;if(report){const chunks=records.map(record=>record.value);this.emit("lr-selection-change",{selectedChunkIds:[...committed],chunks})}this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value);const start=this.sourcePages.state.page*this.sourcePages.state.pageSize;this.sourceGroups=(result.groups??[]).map(group=>({key:group.key,label:group.label,startIndex:Math.max(0,group.startIndex-start)})),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);const reveal=this.sourceReveal;this.sourceReveal=void 0,reveal?.version===this.sourceVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeChunkId){this.sourceActiveInputs=void 0;return}if(this.sourceBlocked)return;const source=this.dataSource,id=this.activeChunkId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.sourceVersion!==version||this.activeChunkId!==id)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceReveal={id,version:this.sourceVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.renderRoot.querySelector(tag("virtual-list"));if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceVersion!==version||this.activeChunkId!==id||list!==this.renderRoot.querySelector(tag("virtual-list"))))return;const index=this.sourceRows.findIndex(chunk=>chunk.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}currentSourceRow(chunk){return!(this.sourceMode||this.sourceRowKeys.has(chunk))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(chunk)}invalidateSourceLifecycle(){this.sourceLifecycle++,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0,this.sourceStatusInitialized=!1,this.sourceStatus=""}adoptedCallback(){this.invalidateSourceLifecycle(),this.sourcePages.adopted(),super.adoptedCallback()}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),args[0]==="selectedChunkIds"&&(this.sourceSelectionEvent=void 0),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","sort","withoutDedupe","grouping","groupBy","groupLabel","groupOrder"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}inputLimitText(){if(this.sourceMode)return"";const truncation=publicCollectionTruncation(this,"chunks"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("retrievalResultsInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.invalidateSourceLifecycle(),this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}deepActiveElement(){return deepActiveElementIn(this.isConnected?this.shadowRoot:null)}chunkAnchor(start){let current=start;for(;current&&current!==this;){if(current.hasAttribute("data-chunk-id"))return current;if(current.parentElement){current=current.parentElement;continue}const root=current.getRootNode();current=root.nodeType===11&&"host"in root?root.host:null}return null}renderedChunkIds(){const roots=[this.renderRoot],virtualList=this.renderRoot.querySelector(tag("virtual-list"));return virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot),roots.flatMap(root=>[...root.querySelectorAll(`${tag("chunk-inspector")}[data-chunk-id]`)].map(element=>element.getAttribute("data-chunk-id")).filter(id=>id!==null))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection(),this.syncSourceActive();return}const refresh=this.explicitRefresh;this.explicitRefresh=!1;const groupingLocaleSignature=this.grouping==="source"?`${this.effectiveLocale}\0${this.localize("untitledSource")}`:"";if((this.processedChunksCache===void 0||refresh||changed.has("chunks")||changed.has("withoutDedupe")||changed.has("sort")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupLabel")||changed.has("groupOrder")||groupingLocaleSignature!==this.processedGroupingLocaleSignature)&&(this.processedGroupingLocaleSignature=groupingLocaleSignature,this.processedChunksCache=this.computeProcessedChunks()),changed.has("chunks")){const present=new Set(this.processedChunks.chunks.map(chunk=>chunk.id)),kept=this.expandedChunkIds.filter(id=>present.has(id));kept.length!==this.expandedChunkIds.length&&(this.expandedChunkIds=kept)}if(changed.has("chunks")||changed.has("selectedChunkIds")){const normalized=this.normalizedSelectedChunkIds();if(normalized.length!==this.selectedChunkIds.length||normalized.some((id,index)=>id!==this.selectedChunkIds[index])){const shouldAnnounce=this.hasUpdated&&changed.has("chunks");writeNormalizedOwnedCollection(this,"selectedChunkIds",()=>{this.selectedChunkIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("chunks")&&!changed.has("withoutDedupe")&&!changed.has("sort")&&!changed.has("grouping")&&!changed.has("groupBy")&&!changed.has("groupLabel")&&!changed.has("groupOrder")&&!changed.has("presentation")&&!changed.has("withoutSelection")&&!changed.has("virtualizeAt")&&!changed.has("loading")&&!changed.has("errorText"))return;const focusedId=this.chunkAnchor(this.deepActiveElement())?.getAttribute("data-chunk-id");if(!focusedId)return;const previousIds=this.previousProcessedChunkIds.length?this.previousProcessedChunkIds:this.renderedChunkIds(),focusedIndex=Math.max(0,previousIds.indexOf(focusedId)),nextChunks=this.errorText?[]:this.processedChunks.chunks;if(nextChunks.length===0){this.pendingFocusTarget="base";return}const survivingIndex=nextChunks.findIndex(chunk=>chunk.id===focusedId),nextIndex=survivingIndex>=0?survivingIndex:Math.min(focusedIndex,nextChunks.length-1);this.pendingFocusTarget=nextChunks[nextIndex].id}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourcePages.state.pending?this.localize("loading"):this.sourcePages.state.result?this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):this.sourceSelectionFailed?this.localize("sourceSelectionFailed"):"":this.localize("tableLoadFailed");this.sourceStatusInitialized&&status&&status!==this.sourceStatus&&this.emptyAnnouncementSink?.announce(status),this.sourceStatusInitialized=!0,this.sourceStatus=status;return}const inputTruncated=publicCollectionTruncation(this,"chunks")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.emptyAnnouncementSink?.announce(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated;const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=!this.loading&&this.errorText===""&&this.processedChunks.chunks.length===0;!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))),this.wasEmptyPresented=emptyPresented,this.previousProcessedChunkIds=this.errorText?[]:this.processedChunks.chunks.map(chunk=>chunk.id);const generation=++this.focusRestoreGeneration,target=this.pendingFocusTarget;target!==void 0&&(this.pendingFocusTarget=void 0,this.restoreControlledFocus(target,generation))}announcePresentedState(){if(!this.sourceMode){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}!this.loading&&this.processedChunks.chunks.length===0&&this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))}}async restoreControlledFocus(target,generation){if(await this.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;if(target==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}const virtualList=this.renderRoot.querySelector(tag("virtual-list"));if(await virtualList?.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;const roots=[this.renderRoot];virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot);const candidates=roots.flatMap(root=>[...root.querySelectorAll("[data-chunk-id]")]),checkbox=candidates.find(element=>element.localName===tag("checkbox")&&element.getAttribute("data-chunk-id")===target);if(checkbox){checkbox.focus();return}const inspector=candidates.find(element=>element.localName===tag("chunk-inspector")&&element.getAttribute("data-chunk-id")===target);await inspector?.updateComplete,!(generation!==this.focusRestoreGeneration||!this.isConnected)&&inspector?.shadowRoot?.querySelector('[part="open-button"]')?.focus()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}canonicalChunks(){return this.canonicalSource!==this.chunks&&(this.canonicalSource=this.chunks,this.canonicalCache=firstByRetrievalIdentity(this.chunks.flatMap(value=>projectRetrievalChunk(value)??[]),chunk=>chunk.id),this.canonicalById=new Map(this.canonicalCache.map(chunk=>[chunk.id,chunk])),this.canonicalOrder=new Map(this.canonicalCache.map((chunk,index)=>[chunk.id,index]))),this.canonicalCache}normalizedSelectedChunkIds(){return this.canonicalSource!==this.chunks&&this.canonicalChunks(),canonicalIdentityList(this.selectedChunkIds).filter(id=>this.canonicalById.has(id))}get processedChunks(){return this.sourceMode?{chunks:this.sourceRows,groups:this.sourceGroups}:this.processedChunksCache??=this.computeProcessedChunks()}computeProcessedChunks(){const canonical=this.canonicalChunks(),sorted=this.sort==="score"?[...canonical].sort((a,b)=>safeScore(b.score)-safeScore(a.score)):canonical;if(this.grouping==="source")return this.bucketed(sorted,chunk=>chunk.source.id,(_id,groupChunks)=>groupChunks[0].source.name||this.localize("untitledSource"));if(this.grouping==="custom"&&this.groupBy){const groupBy=this.groupBy;return this.bucketed(sorted,groupBy,(id,groupChunks)=>this.groupLabel?.(id,groupChunks)??id)}return{chunks:sorted,groups:[]}}orderedGroupKeys(grouped){const firstSeen=[...grouped.keys()];if(this.grouping!=="custom"||!this.groupOrder)return firstSeen;if(typeof this.groupOrder=="function")return firstSeen.sort(this.groupOrder);const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}bucketed(sorted,keyOf,labelOf){const grouped=new Map;for(const chunk of sorted){const key=keyOf(chunk),existing=grouped.get(key);existing?existing.push(chunk):grouped.set(key,[chunk])}const rows=[],groups=[];for(const key of this.orderedGroupKeys(grouped)){const groupChunks=grouped.get(key);!groupChunks||groupChunks.length===0||(groups.push({key,label:labelOf(key,groupChunks),startIndex:rows.length}),rows.push(...groupChunks))}return{chunks:rows,groups}}reportSelection(chunkIds){this.canonicalSource!==this.chunks&&this.canonicalChunks();const chunks=[...new Set(chunkIds)].flatMap(id=>this.canonicalById.get(id)??[]).sort((a,b)=>this.canonicalOrder.get(a.id)-this.canonicalOrder.get(b.id));this.emit("lr-selection-change",snapshotEventDetail({selectedChunkIds:chunkIds,chunks},this.ownerDocument.defaultView))}toggleSelect(chunk){if(!this.currentSourceRow(chunk)||this.sourceSelectionBlocked)return;if(this.sourceMode){const next2=new Set(this.selectedChunkIds);next2.has(chunk.id)?next2.delete(chunk.id):next2.size<1e4&&next2.add(chunk.id),this.selectedChunkIds=[...next2],this.sourceSelectionEvent=this.selectedChunkIds;return}const next=new Set(this.normalizedSelectedChunkIds());next.has(chunk.id)?next.delete(chunk.id):next.add(chunk.id),this.selectedChunkIds=[...next],this.reportSelection(this.selectedChunkIds)}rowChunksFor(chunk){let row=this.rowChunks.get(chunk);return row||this.rowChunks.set(chunk,row=[toLyraChunk(chunk)]),row}renderMetadata(metadata){return renderRetrievalMetadata(metadata,this.effectiveLocale,this.localize("valueInvalid"),this.localize("valueTruncated"))}isChunkSelected(id){const source=this.selectedChunkIds;return source.length===0||this.processedChunks.chunks.length<=1?(this.selectedMembership=void 0,source.includes(id)):(this.selectedMembership?.source!==source&&(this.selectedMembership={source,ids:new Set(source)}),this.selectedMembership.ids.has(id))}legacyLoadMoreHandler(){const chunks=this.chunks,version=this.sourceVersion;return event=>{event.stopPropagation(),!(!this.isConnected||this.sourceMode||this.sourceVersion!==version||this.chunks!==chunks||!this.hasMore||this.loading||this.errorText||event.currentTarget?.getRootNode()!==this.renderRoot)&&this.emit("lr-load-more")}}renderLoadMoreFooter(){return this.hasMore?html`
34
+ `}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorEmpty:LYRA_DEFAULT_chunkInspectorEmpty,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,retrievalResultsInputLimit:LYRA_DEFAULT_retrievalResultsInputLimit,retrievalResultsSelectRowOrdinal:LYRA_DEFAULT_retrievalResultsSelectRowOrdinal,retry:LYRA_DEFAULT_retry,sourceSelectionFailed:LYRA_DEFAULT_sourceSelectionFailed,sourceSelectionLoading:LYRA_DEFAULT_sourceSelectionLoading,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,untitledSource:LYRA_DEFAULT_untitledSource,valueInvalid:LYRA_DEFAULT_valueInvalid,valueTruncated:LYRA_DEFAULT_valueTruncated}}static{this.collectionSupport=collectionSupport}static{this.identityCollectionProperties=Object.freeze(["chunks"])}static{this.ownedCollectionProperties=Object.freeze(["chunks","selectedChunkIds","groupOrder"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-chunk-open"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-selection-change":Object.freeze(["chunks"])})}get dataSource(){return this._dataSource}set dataSource(value){const old=this._dataSource;this._dataSource=value,this.sourceEpoch++,this.requestUpdate("dataSource",old)}get sourceTotal(){return this.sourceMode?this.sourcePages.state.result?.total??null:null}get sourceMode(){return this.dataSource!==void 0}get sourceBlocked(){return this.sourceMode&&(!this.isConnected||!!this.errorText||this.sourcePages.state.pending||!this.sourcePages.state.result)}get sourceSelectionBlocked(){return this.sourceBlocked||this.sourceMode&&(this.sourcePages.state.selectionPending||this.sourceSelectionFailed)}projectSourceChunk(record,isCurrent){let units=0;const read=(input,key)=>{if(!isCurrent())throw new Error("Obsolete source chunk");const value2=readOwnDataValue(input,key);if(!isCurrent())throw new Error("Obsolete source chunk");return value2},fields=(input,keys)=>{if(!input||typeof input!="object"||Array.isArray(input))throw new TypeError("Invalid source chunk");const copy={};for(const key of keys){const value2=read(input,key);if(typeof value2=="string"&&(units+=value2.length,value2.length>65536||units>65536))throw new RangeError("Source chunk text too large");value2!==void 0&&(copy[key]=value2)}return copy},raw=fields(record.value,["id","text","score","metadata","rank","queryId","stage","traceId","scores"]);raw.source=fields(read(record.value,"source"),["id","name","mimeType","uri","version"]);const locator=read(record.value,"locator");if(locator!==void 0){const projected=fields(locator,["kind","page","quote","prefix","suffix","id","start","end","sheet","range","cfi"]);for(const key of["kind","quote","prefix","suffix","id","sheet","range","cfi"])if(projected[key]!==void 0&&typeof projected[key]!="string")throw new TypeError("Invalid source locator text");for(const key of["page","start","end"])if(projected[key]!==void 0&&(typeof projected[key]!="number"||!Number.isFinite(projected[key])))throw new TypeError("Invalid source locator number");const rect=read(locator,"rect");if(rect!==void 0){const coordinates=fields(rect,["x","y","width","height"]);for(const key of["x","y","width","height"])if(typeof coordinates[key]!="number"||!Number.isFinite(coordinates[key]))throw new TypeError("Invalid source locator rectangle");projected.rect=coordinates}const path=read(locator,"path");if(path!==void 0){if(!Array.isArray(path))throw new TypeError("Invalid source locator path");const length=read(path,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>500)throw new RangeError("Source locator path too large");projected.path=Array.from({length},(_,index)=>{const value2=read(path,String(index));if(typeof value2!="string"&&typeof value2!="number")throw new TypeError("Invalid source locator path");if(typeof value2=="string"&&(units+=value2.length,units>65536))throw new RangeError("Source chunk text too large");return value2})}raw.locator=projected}const scores=raw.scores;scores&&typeof scores=="object"&&!Array.isArray(scores)&&(raw.scores=fields(scores,["dense","sparse","rerank","final"]));const value=projectRetrievalChunk(raw);if(!isCurrent())throw new Error("Obsolete source chunk");if(!value)throw new TypeError("Invalid source chunk");return this.sourceRowKeys.set(value,record.key),{key:record.key,order:record.order,value}}validateSourcePage(result,query){if(!query.withoutDedupe&&result.rows.some(record=>record.key!==record.value.id))throw new TypeError("Invalid canonical source identity");if(query.grouping==="none"){if(result.groups?.length)throw new TypeError("Unexpected source groups");return}if(!result.groups)throw new TypeError("Missing source groups");if(!result.rows.length)return;const size=this.sourcePages.state.pageSize,start=Math.min(this.sourcePages.state.page,Math.floor((result.total-1)/size))*size,end=start+result.rows.length;let covered=start,previousEnd=-1;for(const group of result.groups){if(group.startIndex<previousEnd||Math.max(start,group.startIndex)!==covered)throw new TypeError("Invalid source group coverage");previousEnd=group.startIndex+group.itemCount,covered=Math.min(end,previousEnd)}if(covered!==end)throw new TypeError("Incomplete source groups")}canonicalSourceAdapter(source){if(this.sourceAdapter?.original===source)return this.sourceAdapter.adapter;if(!source||typeof source.query!="function"||typeof source.lookup!="function"||typeof source.locate!="function")throw new TypeError("Invalid source");const adapter={revision:source.revision,query:request=>source.query(request),locate:(key,query,context)=>source.locate(key,query,context),lookup:async(keys,context)=>{const records=await source.lookup(keys,context);if(!Array.isArray(records)||records.length>500)throw new TypeError("Invalid canonical lookup");for(let index=0;index<records.length;index++){const record=readOwnDataValue(records,String(index)),key=readOwnDataValue(record,"key"),value=readOwnDataValue(record,"value");if(key!==readOwnDataValue(value,"id"))throw new TypeError("Invalid canonical lookup identity")}return records}};return this.sourceAdapter={original:source,adapter},adapter}syncSource(force=!1){if(!(!this.sourcePages||this.sourceSyncing)){this.sourceSyncing=!0;try{if(!this.sourceMode){this.sourceInputs&&(this.sourceVersion++,this.focusRestoreGeneration++,this.sourcePages.bind(void 0),this.processedChunksCache=void 0),this.sourceInputs=void 0,this.sourceQueryInputs=void 0,this.sourceResult=void 0,this.sourceRows=[],this.sourceGroups=[],this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0;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));const queryInputs=[this.sort,this.withoutDedupe,this.grouping,this.groupBy,this.groupLabel,this.groupOrder,size];this.hasUpdated&&this.sourceQueryInputs&&queryInputs.some((value,index)=>value!==this.sourceQueryInputs[index])&&(page=0,this.sourcePage=0),this.sourceQueryInputs=queryInputs;const inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...queryInputs,page];if(!force&&this.sourceInputs&&inputs.every((value,index)=>value===this.sourceInputs[index]))return;(!this.sourceInputs||inputs.slice(0,3).some((value,index)=>value!==this.sourceInputs[index]))&&(this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0),this.sourceInputs=inputs,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0,this.sourceReveal=void 0,this.expandedChunkIds=[],this.sourcePages.bind({source:this.canonicalSourceAdapter(source),revision:source.revision,epoch:this.sourceEpoch,locale:this.effectiveLocale});const query=Object.freeze({sort:this.sort,withoutDedupe:this.withoutDedupe,grouping:this.grouping,groupBy:this.groupBy,groupLabel:this.groupLabel,groupOrder:this.groupOrder});this.sourcePages.request(query,page,size)}catch{this.sourcePages.bind(void 0),this.sourceRows=[],this.sourceGroups=[],this.sourceResult=void 0}finally{this.sourceSyncing=!1}}}syncSourceSelection(){if(!this.sourceMode||!this.isConnected||!this.sourceAdapter||!this.sourceInputs)return;const ids=this.selectedChunkIds,source=this.dataSource,epoch=this.sourceEpoch,revision=source.revision,inputs=[source,revision,epoch,ids];if(this.sourceSelectionInputs&&inputs.every((value,index)=>value===this.sourceSelectionInputs[index]))return;this.sourceSelectionInputs=inputs,this.sourceSelectionFailed=!1;const owner=this.ownerDocument,lifecycle=this.sourceLifecycle,canonicalIds=canonicalIdentityList(ids);this.sourcePages.resolveSelection(canonicalIds).then(records=>{if(source.revision!==revision||lifecycle!==this.sourceLifecycle||!this.isConnected||this.ownerDocument!==owner||this.dataSource!==source||this.sourceEpoch!==epoch||this.selectedChunkIds!==ids)return;if(!records){this.sourceSelectionFailed=!0,this.sourceStateVersion++;return}const retained=new Set(records.map(record=>record.key)),accepted=canonicalIds.filter(id=>retained.has(id)),report=this.sourceSelectionEvent===ids;this.sourceSelectionEvent=void 0,accepted.length!==ids.length&&(this.selectedChunkIds=accepted);const committed=this.selectedChunkIds;if(report){const chunks=records.map(record=>record.value);this.emit("lr-selection-change",{selectedChunkIds:[...committed],chunks})}this.sourceStateVersion++})}acceptSourcePage(){const result=this.sourcePages.state.result;if(!result||result===this.sourceResult)return;this.sourceResult=result,this.sourceRows=result.rows.map(record=>record.value);const start=this.sourcePages.state.page*this.sourcePages.state.pageSize;this.sourceGroups=(result.groups??[]).map(group=>({key:group.key,label:group.label,startIndex:Math.max(0,group.startIndex-start)})),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);const reveal=this.sourceReveal;this.sourceReveal=void 0,reveal?.version===this.sourceVersion&&this.revealSourceActive(reveal.id,reveal.version)}syncSourceActive(){if(!this.activeChunkId){this.sourceActiveInputs=void 0;return}if(this.sourceBlocked)return;const source=this.dataSource,id=this.activeChunkId,inputs=[source,source.revision,this.sourceEpoch,this.effectiveLocale,...this.sourceQueryInputs??[],id];if(this.sourceActiveInputs&&inputs.every((value,index)=>value===this.sourceActiveInputs[index]))return;this.sourceActiveInputs=inputs;const version=this.sourceVersion,owner=this.ownerDocument;this.sourcePages.locate(id).then(index=>{if(index===null||!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.dataSource!==source||this.sourceVersion!==version||this.activeChunkId!==id)return;const page=Math.floor(index/finiteInteger(this.sourcePageSize,100,1,500));if(page===this.sourcePage){this.revealSourceActive(id,version);return}this.sourcePage=page,this.sourceReveal={id,version:this.sourceVersion}})}revealSourceActive(id,version){const owner=this.ownerDocument;this.updateComplete.then(async()=>{const list=this.renderRoot.querySelector(tag("virtual-list"));if(!list||(await list.updateComplete,!this.isConnected||this.ownerDocument!==owner||!this.sourceMode||this.sourceBlocked||this.sourceVersion!==version||this.activeChunkId!==id||list!==this.renderRoot.querySelector(tag("virtual-list"))))return;const index=this.sourceRows.findIndex(chunk=>chunk.id===id);index>=0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})})}currentSourceRow(chunk){return!(this.sourceMode||this.sourceRowKeys.has(chunk))||this.sourceMode&&!this.sourceBlocked&&this.sourceRows.includes(chunk)}invalidateSourceLifecycle(){this.sourceLifecycle++,this.sourceVersion++,this.focusRestoreGeneration++,this.sourceSelectionInputs=void 0,this.sourceSelectionEvent=void 0,this.sourceActiveInputs=void 0,this.sourceReveal=void 0,this.sourceStatusInitialized=!1,this.sourceStatus=""}adoptedCallback(){this.invalidateSourceLifecycle(),this.sourcePages.adopted(),super.adoptedCallback()}requestUpdate(...args){args[0]===void 0&&(this.explicitRefresh=!0,this.sourceEpoch=(this.sourceEpoch??0)+1),args[0]==="selectedChunkIds"&&(this.sourceSelectionEvent=void 0),(args[0]===void 0||["dataSource","sourcePage","sourcePageSize","sort","withoutDedupe","grouping","groupBy","groupLabel","groupOrder"].includes(String(args[0])))&&this.syncSource(),super.requestUpdate(...args)}inputLimitText(){const truncation=publicCollectionTruncation(this,"chunks"),number=getNumberFormat(this.effectiveLocale);return truncation?this.localize("retrievalResultsInputLimit",void 0,{count:number.format(truncation.retained),total:number.format(truncation.source)}):""}renderInputLimit(){const text=this.inputLimitText();return text?html`<p part="limit" role="note">${text}</p>`:nothing}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.invalidateSourceLifecycle(),this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}deepActiveElement(){return deepActiveElementIn(this.isConnected?this.shadowRoot:null)}chunkAnchor(start){let current=start;for(;current&&current!==this;){if(current.hasAttribute("data-chunk-id"))return current;if(current.parentElement){current=current.parentElement;continue}const root=current.getRootNode();current=root.nodeType===11&&"host"in root?root.host:null}return null}renderedChunkIds(){const roots=[this.renderRoot],virtualList=this.renderRoot.querySelector(tag("virtual-list"));return virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot),roots.flatMap(root=>[...root.querySelectorAll(`${tag("chunk-inspector")}[data-chunk-id]`)].map(element=>element.getAttribute("data-chunk-id")).filter(id=>id!==null))}willUpdate(changed){if(super.willUpdate(changed),this.syncSource(),this.sourceMode){this.acceptSourcePage(),this.syncSourceSelection(),this.syncSourceActive();return}const refresh=this.explicitRefresh;this.explicitRefresh=!1;const groupingLocaleSignature=this.grouping==="source"?`${this.effectiveLocale}\0${this.localize("untitledSource")}`:"";if((this.processedChunksCache===void 0||refresh||changed.has("chunks")||changed.has("withoutDedupe")||changed.has("sort")||changed.has("grouping")||changed.has("groupBy")||changed.has("groupLabel")||changed.has("groupOrder")||groupingLocaleSignature!==this.processedGroupingLocaleSignature)&&(this.processedGroupingLocaleSignature=groupingLocaleSignature,this.processedChunksCache=this.computeProcessedChunks()),changed.has("chunks")){const present=new Set(this.processedChunks.chunks.map(chunk=>chunk.id)),kept=this.expandedChunkIds.filter(id=>present.has(id));kept.length!==this.expandedChunkIds.length&&(this.expandedChunkIds=kept)}if(changed.has("chunks")||changed.has("selectedChunkIds")){const normalized=this.normalizedSelectedChunkIds();if(normalized.length!==this.selectedChunkIds.length||normalized.some((id,index)=>id!==this.selectedChunkIds[index])){const shouldAnnounce=this.hasUpdated&&changed.has("chunks");writeNormalizedOwnedCollection(this,"selectedChunkIds",()=>{this.selectedChunkIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("chunks")&&!changed.has("withoutDedupe")&&!changed.has("sort")&&!changed.has("grouping")&&!changed.has("groupBy")&&!changed.has("groupLabel")&&!changed.has("groupOrder")&&!changed.has("presentation")&&!changed.has("withoutSelection")&&!changed.has("virtualizeAt")&&!changed.has("loading")&&!changed.has("errorText"))return;const focusedId=this.chunkAnchor(this.deepActiveElement())?.getAttribute("data-chunk-id");if(!focusedId)return;const previousIds=this.previousProcessedChunkIds.length?this.previousProcessedChunkIds:this.renderedChunkIds(),focusedIndex=Math.max(0,previousIds.indexOf(focusedId)),nextChunks=this.errorText?[]:this.processedChunks.chunks;if(nextChunks.length===0){this.pendingFocusTarget="base";return}const survivingIndex=nextChunks.findIndex(chunk=>chunk.id===focusedId),nextIndex=survivingIndex>=0?survivingIndex:Math.min(focusedIndex,nextChunks.length-1);this.pendingFocusTarget=nextChunks[nextIndex].id}updated(changed){if(super.updated(changed),this.sourceMode){const status=this.sourcePages.state.pending?this.localize("loading"):this.sourcePages.state.result?this.sourcePages.state.selectionPending?this.localize("sourceSelectionLoading"):this.sourceSelectionFailed?this.localize("sourceSelectionFailed"):"":this.localize("tableLoadFailed");this.sourceStatusInitialized&&status&&status!==this.sourceStatus&&this.emptyAnnouncementSink?.announce(status),this.sourceStatusInitialized=!0,this.sourceStatus=status;return}const inputTruncated=publicCollectionTruncation(this,"chunks")!==void 0;this.limitInitialized&&inputTruncated&&!this.previouslyInputTruncated&&this.emptyAnnouncementSink?.announce(this.inputLimitText()),this.limitInitialized=!0,this.previouslyInputTruncated=inputTruncated;const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=!this.loading&&this.errorText===""&&this.processedChunks.chunks.length===0;!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))),this.wasEmptyPresented=emptyPresented,this.previousProcessedChunkIds=this.errorText?[]:this.processedChunks.chunks.map(chunk=>chunk.id);const generation=++this.focusRestoreGeneration,target=this.pendingFocusTarget;target!==void 0&&(this.pendingFocusTarget=void 0,this.restoreControlledFocus(target,generation))}announcePresentedState(){if(!this.sourceMode){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}!this.loading&&this.processedChunks.chunks.length===0&&this.emptyAnnouncementSink?.announce(this.localize("chunkInspectorEmpty"))}}async restoreControlledFocus(target,generation){if(await this.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;if(target==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}const virtualList=this.renderRoot.querySelector(tag("virtual-list"));if(await virtualList?.updateComplete,generation!==this.focusRestoreGeneration||!this.isConnected)return;const roots=[this.renderRoot];virtualList?.shadowRoot&&roots.push(virtualList.shadowRoot);const candidates=roots.flatMap(root=>[...root.querySelectorAll("[data-chunk-id]")]),checkbox=candidates.find(element=>element.localName===tag("checkbox")&&element.getAttribute("data-chunk-id")===target);if(checkbox){checkbox.focus();return}const inspector=candidates.find(element=>element.localName===tag("chunk-inspector")&&element.getAttribute("data-chunk-id")===target);await inspector?.updateComplete,!(generation!==this.focusRestoreGeneration||!this.isConnected)&&inspector?.shadowRoot?.querySelector('[part="open-button"]')?.focus()}get effectiveVirtualizeAt(){return finiteCount(this.virtualizeAt,50)}canonicalChunks(){return this.canonicalSource!==this.chunks&&(this.canonicalSource=this.chunks,this.canonicalCache=firstByRetrievalIdentity(this.chunks.flatMap(value=>projectRetrievalChunk(value)??[]),chunk=>chunk.id),this.canonicalById=new Map(this.canonicalCache.map(chunk=>[chunk.id,chunk])),this.canonicalOrder=new Map(this.canonicalCache.map((chunk,index)=>[chunk.id,index]))),this.canonicalCache}normalizedSelectedChunkIds(){return this.canonicalSource!==this.chunks&&this.canonicalChunks(),canonicalIdentityList(this.selectedChunkIds).filter(id=>this.canonicalById.has(id))}get processedChunks(){return this.sourceMode?{chunks:this.sourceRows,groups:this.sourceGroups}:this.processedChunksCache??=this.computeProcessedChunks()}computeProcessedChunks(){const canonical=this.canonicalChunks(),sorted=this.sort==="score"?[...canonical].sort((a,b)=>safeScore(b.score)-safeScore(a.score)):canonical;if(this.grouping==="source")return this.bucketed(sorted,chunk=>chunk.source.id,(_id,groupChunks)=>groupChunks[0].source.name||this.localize("untitledSource"));if(this.grouping==="custom"&&this.groupBy){const groupBy=this.groupBy;return this.bucketed(sorted,groupBy,(id,groupChunks)=>this.groupLabel?.(id,groupChunks)??id)}return{chunks:sorted,groups:[]}}orderedGroupKeys(grouped){const firstSeen=[...grouped.keys()];if(this.grouping!=="custom"||!this.groupOrder)return firstSeen;if(typeof this.groupOrder=="function")return firstSeen.sort(this.groupOrder);const ordered=[...new Set(this.groupOrder)].filter(id=>grouped.has(id)),listed=new Set(ordered);return[...ordered,...firstSeen.filter(id=>!listed.has(id))]}bucketed(sorted,keyOf,labelOf){const grouped=new Map;for(const chunk of sorted){const key=keyOf(chunk),existing=grouped.get(key);existing?existing.push(chunk):grouped.set(key,[chunk])}const rows=[],groups=[];for(const key of this.orderedGroupKeys(grouped)){const groupChunks=grouped.get(key);!groupChunks||groupChunks.length===0||(groups.push({key,label:labelOf(key,groupChunks),startIndex:rows.length}),rows.push(...groupChunks))}return{chunks:rows,groups}}reportSelection(chunkIds){this.canonicalSource!==this.chunks&&this.canonicalChunks();const chunks=[...new Set(chunkIds)].flatMap(id=>this.canonicalById.get(id)??[]).sort((a,b)=>this.canonicalOrder.get(a.id)-this.canonicalOrder.get(b.id));this.emit("lr-selection-change",snapshotEventDetail({selectedChunkIds:chunkIds,chunks},this.ownerDocument.defaultView))}toggleSelect(chunk){if(!this.currentSourceRow(chunk)||this.sourceSelectionBlocked)return;if(this.sourceMode){const next2=new Set(this.selectedChunkIds);next2.has(chunk.id)?next2.delete(chunk.id):next2.size<1e4&&next2.add(chunk.id),this.selectedChunkIds=[...next2],this.sourceSelectionEvent=this.selectedChunkIds;return}const next=new Set(this.normalizedSelectedChunkIds());next.has(chunk.id)?next.delete(chunk.id):next.add(chunk.id),this.selectedChunkIds=[...next],this.reportSelection(this.selectedChunkIds)}rowChunksFor(chunk){let row=this.rowChunks.get(chunk);return row||this.rowChunks.set(chunk,row=[toLyraChunk(chunk)]),row}renderMetadata(metadata){return renderRetrievalMetadata(metadata,this.effectiveLocale,this.localize("valueInvalid"),this.localize("valueTruncated"))}isChunkSelected(id){const source=this.selectedChunkIds;return source.length===0||this.processedChunks.chunks.length<=1?(this.selectedMembership=void 0,source.includes(id)):(this.selectedMembership?.source!==source&&(this.selectedMembership={source,ids:new Set(source)}),this.selectedMembership.ids.has(id))}legacyLoadMoreHandler(){const chunks=this.chunks,version=this.sourceVersion;return event=>{event.stopPropagation(),!(!this.isConnected||this.sourceMode||this.sourceVersion!==version||this.chunks!==chunks||!this.hasMore||this.loading||this.errorText||event.currentTarget?.getRootNode()!==this.renderRoot)&&this.emit("lr-load-more")}}renderLoadMoreFooter(){return this.hasMore?html`
35
35
  <div part="load-more-row">
36
36
  ${this.loading?html`<lr-spinner part="spinner"></lr-spinner>`:html`<button
37
37
  type="button"
@@ -1,4 +1,6 @@
1
- import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraSearchChangeDetail}from'../../../internal/text-viewer-target.js';import type{LyraHierarchySource,LyraHierarchyQuery,LyraInspectionNode}from'../../../data-sources.js';export type JsonViewerTreeSource=LyraHierarchySource<LyraInspectionNode,LyraHierarchyQuery>;import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';export interface LyraJsonViewerEventMap{'lr-copy':CustomEvent<LyraClipboardWriteSuccess>;'lr-error':CustomEvent<null>;'lr-copy-error':CustomEvent<LyraClipboardWriteFailure>;'lr-search-change':CustomEvent<LyraSearchChangeDetail>;}
1
+ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraSearchChangeDetail}from'../../../internal/text-viewer-target.js';import type{LyraHierarchySource,LyraHierarchyQuery,LyraInspectionNode}from'../../../data-sources.js';export type JsonViewerTreeSource=LyraHierarchySource<LyraInspectionNode,LyraHierarchyQuery>;import{type LyraClipboardWriteFailure,type LyraClipboardWriteSuccess}from'../../../internal/clipboard.js';
2
+ /** How a scalar row places its key and value; see `LyraJsonViewer.layout`.*/
3
+ export type LyraJsonViewerLayout='auto'|'inline'|'stacked';export interface LyraJsonViewerEventMap{'lr-copy':CustomEvent<LyraClipboardWriteSuccess>;'lr-error':CustomEvent<null>;'lr-copy-error':CustomEvent<LyraClipboardWriteFailure>;'lr-search-change':CustomEvent<LyraSearchChangeDetail>;}
2
4
  /**
3
5
  * `<lr-json-viewer>` — a collapsible, copyable tree view for an arbitrary
4
6
  * JSON-serializable value (object/array/string/number/boolean/null/
@@ -85,6 +87,19 @@ expandDepth?:number;
85
87
  /** A CSS length (e.g. `"20rem"`); once set, the viewer scrolls internally past this height
86
88
  * instead of growing the page. Invalid values are ignored. */
87
89
  maxHeight:string;
90
+ /**
91
+ * How a scalar row places its key and value.
92
+ *
93
+ * `'auto'` (the default) keeps them side by side while the viewer's own inline size is at least
94
+ * 30rem and switches to the stacked layout below that, through a container query on the
95
+ * viewer's allocation, not the viewport. `'stacked'` always puts the value on its own line under
96
+ * its key and tightens rows: leaf rows lose the icon-button-sized floor their hidden toggle
97
+ * spacer otherwise imposes, and lines use the snug line height. Real expand/collapse toggles keep
98
+ * their full hit area. `'inline'` keeps the side-by-side row at every width. Unknown values
99
+ * fall back to `'auto'`. Applies to the `data` tree; `treeSource` rows keep their fixed
100
+ * virtualized layout.
101
+ */
102
+ layout:LyraJsonViewerLayout;
88
103
  /** Shows copy-to-clipboard affordances: one for the whole value, plus one per node.*/
89
104
  copyable:boolean;
90
105
  /** Removing the attribute clears search without changing its null readback. Case-insensitive substring match against keys/values; matches are highlighted and their ancestors auto-expanded. See also `runSearch()`/`searchNext()`/`searchPrevious()`/`clearSearch()` for imperative, cursor-navigable search built on top of this property.*/
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}return projected.length=retainedLength,Object.freeze(projected)}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}return projected.length=retainedLength,Object.freeze(projected)}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}const JSON_VIEWER_LAYOUT=literalSetConverter(["auto","inline","stacked"],"auto"),KEY_BREAK_POINT=/(?<=[_\-./:@])(?=.)|(?<=\p{Ll})(?=\p{Lu})/u;function keyWithBreaks(label){const segments=label.split(KEY_BREAK_POINT);return segments.length<2?label:segments.map((segment,index)=>index===0?segment:html`<wbr>${segment}`)}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.layout="auto",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
2
2
  @keydown=${event=>event.stopPropagation()}
3
3
  @click=${event=>{event.stopPropagation();const button=event.currentTarget;button.isConnected&&button.getRootNode()===this.renderRoot&&!this.hierarchy.loading&&projection===this.hierarchy.projection&&source===this.treeSource&&epoch===this.hierarchy.epoch&&this.copySource(key,node?node.kind==="object"||node.kind==="array"||node.kind==="element"?"subtree":"node":"document")}}>${this.copyLabel(key??"toolbar",this.localize("copy"))}</button>`}renderSourceNode(node){const match=this.sourceHits?.isCurrent()&&this.sourceHitKeys.has(node.path),active=this.sourceHits?.value.hits[this.activeSearchIndex]?.key===node.path;return html`<span part="key" ?data-match=${match} ?data-active=${active}>${node.name}</span><span aria-hidden="true">:</span><span
4
4
  part="value" data-type=${node.kind==="scalar"?"string":node.kind} ?data-match=${match} ?data-active=${active}>${node.value??node.kind}</span>${this.sourceCopyButton(node)}`}renderSource(){const partial=!this.sourceSearchExact&&!!this.query,count=this.sourceHitKeys.size;return html`<div class="source-shell" style=${styleMap({"--lr-json-viewer-max-height":sanitizeCssLength(this.maxHeight)??"var(--lr-size-20rem)"})}>
@@ -34,7 +34,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
34
34
  ?data-match=${search.keyMatches.has(pathKey)}
35
35
  ?data-active=${!!activeMatch&&activeMatch.pathKey===pathKey&&activeMatch.kind==="key"}
36
36
  aria-current=${activeMatch&&activeMatch.pathKey===pathKey&&activeMatch.kind==="key"?"true":"false"}
37
- >${keyLabel}</span
37
+ >${keyWithBreaks(keyLabel)}</span
38
38
  ><span class="colon">:</span>`:nothing}
39
39
  ${isCircular?html`
40
40
  <span part="bracket">${openBracket}</span>
@@ -83,8 +83,8 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
83
83
  ${this.copyLabel("toolbar",this.localize("copy"))}
84
84
  </button>
85
85
  </div>`:nothing}
86
- <div part="tree" role="list" aria-label=${hostAriaLabel(this)??nothing}>${tree}</div>
86
+ <div part="tree" role="list" data-layout=${JSON_VIEWER_LAYOUT.normalize(this.layout)} aria-label=${hostAriaLabel(this)??nothing}>${tree}</div>
87
87
  ${limited?html`<p part="limit">${this.localize("jsonViewerLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(this.effectiveMaxNodes),depth:getNumberFormat(this.effectiveLocale).format(MAX_JSON_DEPTH)})}</p>`:nothing}
88
88
  <span class="sr-only" aria-hidden="true">${this.activeSearchAnnouncement()}</span>
89
89
  </div>
90
- `}}__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"treeSource",null),__decorate([property({type:Number,attribute:"max-nodes"})],LyraJsonViewer.prototype,"maxNodes",void 0),__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"data",void 0),__decorate([property({type:Number,attribute:"expand-depth"})],LyraJsonViewer.prototype,"expandDepth",void 0),__decorate([property({attribute:"max-height"})],LyraJsonViewer.prototype,"maxHeight",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraJsonViewer.prototype,"copyable",void 0),__decorate([property()],LyraJsonViewer.prototype,"query",void 0),__decorate([state()],LyraJsonViewer.prototype,"expandedOverrides",void 0),__decorate([state()],LyraJsonViewer.prototype,"activeSearchIndex",void 0),__decorate([state()],LyraJsonViewer.prototype,"copyFeedback",void 0);export{LyraJsonViewer};
90
+ `}}__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"treeSource",null),__decorate([property({type:Number,attribute:"max-nodes"})],LyraJsonViewer.prototype,"maxNodes",void 0),__decorate([property({attribute:!1})],LyraJsonViewer.prototype,"data",void 0),__decorate([property({type:Number,attribute:"expand-depth"})],LyraJsonViewer.prototype,"expandDepth",void 0),__decorate([property({attribute:"max-height"})],LyraJsonViewer.prototype,"maxHeight",void 0),__decorate([property({converter:JSON_VIEWER_LAYOUT})],LyraJsonViewer.prototype,"layout",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraJsonViewer.prototype,"copyable",void 0),__decorate([property()],LyraJsonViewer.prototype,"query",void 0),__decorate([state()],LyraJsonViewer.prototype,"expandedOverrides",void 0),__decorate([state()],LyraJsonViewer.prototype,"activeSearchIndex",void 0),__decorate([state()],LyraJsonViewer.prototype,"copyFeedback",void 0);export{LyraJsonViewer};
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; --_lr-json-viewer-max-height: none; --_lr-json-viewer-font: var(--lr-font-mono); --_lr-json-viewer-active-outline: var(--lr-focus-ring-color); --_lr-json-viewer-string-color: var(--lr-color-success); --_lr-json-viewer-number-color: var(--lr-color-brand); --_lr-json-viewer-boolean-color: var(--lr-color-warning); --_lr-json-viewer-null-color: var(--lr-color-text-quiet); font-family: var(--lr-json-viewer-font, var(--_lr-json-viewer-font)); font-size: var(--lr-font-size-sm); line-height: var(--lr-line-height-loose); white-space: normal; } .source-shell { min-inline-size: 0; } .source-shell .source-tree { block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); max-block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); } .source-shell [part~='source-list'] { block-size: 100%; } [part='search-status'] { padding: var(--lr-space-xs); color: var(--lr-color-text-quiet); } [part="base"] { display: block; max-block-size: var( --lr-json-viewer-max-height, var(--_lr-json-viewer-max-height) ); overflow: auto; border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface); } [part="toolbar"] { position: sticky; inset-block-start: 0; z-index: var(--lr-layer-content); display: flex; justify-content: flex-end; padding: var(--lr-space-xs) var(--lr-space-s); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); background: var(--lr-color-surface); } [part="tree"] { padding: var(--lr-space-s); direction: ltr; } .row { display: flex; align-items: flex-start; gap: var(--lr-space-xs); min-inline-size: 0; border-radius: var(--lr-radius); } .row:hover { background: var(--lr-json-viewer-row-hover-bg, var(--lr-color-brand-quiet)); } .row:hover [part="copy-button"], .row:focus-within [part="copy-button"] { opacity: 1; } [part="toggle"] { inline-size: var(--lr-size-1-25rem); block-size: var(--lr-size-1-25rem); ${iconHitTarget} margin-block-start: var(--lr-size-0-1875rem); flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; padding: 0; border: none; background: none; color: var(--lr-color-text-quiet); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); font: inherit; } [part="toggle"][hidden] { visibility: hidden; } [part="toggle"] .chevron { display: inline-flex; transform: rotate(0deg); transition: transform var(--lr-transition-fast); } [part="toggle"][aria-expanded="true"] .chevron { transform: rotate(90deg); } :where([part="toggle"]):hover:where(:not([hidden])) { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } :where([part="toggle"]):active:where(:not([hidden])) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } [part="toggle"]:focus-visible, [part="copy-button"]:focus-visible { ${focusRing} } .toggle-space { inline-size: var(--lr-icon-button-size); flex: 0 0 auto; } [part="key"] { flex: 0 1 auto; min-inline-size: 0; overflow-wrap: anywhere; font-weight: var(--lr-font-weight-semibold); color: var(--lr-color-text); } .colon { flex: 0 0 auto; color: var(--lr-color-text-quiet); margin-inline-end: var(--lr-space-xs); } [part="bracket"] { flex: 0 0 auto; color: var(--lr-color-text-quiet); } [part="key"][data-match], [part="value"][data-match] { background: var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); border-radius: var(--lr-size-0-1875rem); box-shadow: 0 0 0 var(--lr-size-0-125rem) var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); } [part="value"] { min-inline-size: 0; overflow-wrap: anywhere; word-break: break-word; white-space: pre-wrap; } [part="value"][data-type="string"] { color: var( --lr-json-viewer-string-color, var(--_lr-json-viewer-string-color) ); } [part="value"][data-type="number"] { color: var( --lr-json-viewer-number-color, var(--_lr-json-viewer-number-color) ); } [part="value"][data-type="boolean"] { color: var( --lr-json-viewer-boolean-color, var(--_lr-json-viewer-boolean-color) ); } [part="value"][data-type="null"], [part="value"][data-type="undefined"], [part="value"][data-type="circular"] { color: var(--lr-json-viewer-null-color, var(--_lr-json-viewer-null-color)); font-style: italic; } [part="key"][data-active], [part="value"][data-active] { outline: var(--lr-focus-ring-width) solid var( --lr-json-viewer-active-outline, var(--_lr-json-viewer-active-outline) ); outline-offset: var(--lr-focus-ring-offset); } .preview { flex: 0 0 auto; color: var(--lr-color-text-quiet); font-style: italic; margin-inline: var(--lr-space-xs); } [part="copy-button"] { flex: 0 0 auto; margin-inline-start: auto; border: none; background: none; color: var(--lr-color-text-quiet); font: inherit; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); ${iconHitTarget} padding: var(--lr-size-0-125rem) var(--lr-space-xs); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); } [part="copy-button"]:hover { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } [part="copy-button"]:active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } .row [part="copy-button"] { opacity: 0; } .row [part="copy-button"]:focus-visible { opacity: 1; } @media (hover: none), (pointer: coarse) { .row [part="copy-button"] { opacity: 1; } } @media (prefers-reduced-motion: reduce) { [part="toggle"], [part="copy-button"], [part="toggle"] .chevron { transition: none !important; } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{mediumContainerQuery}from"../../../internal/container-breakpoints.styles.js";const styles=css` :host { display: block; --_lr-json-viewer-max-height: none; --_lr-json-viewer-font: var(--lr-font-mono); --_lr-json-viewer-active-outline: var(--lr-focus-ring-color); --_lr-json-viewer-string-color: var(--lr-color-success); --_lr-json-viewer-number-color: var(--lr-color-brand); --_lr-json-viewer-boolean-color: var(--lr-color-warning); --_lr-json-viewer-null-color: var(--lr-color-text-quiet); font-family: var(--lr-json-viewer-font, var(--_lr-json-viewer-font)); font-size: var(--lr-font-size-sm); line-height: var(--lr-line-height-loose); white-space: normal; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); } .source-shell { min-inline-size: 0; } .source-shell .source-tree { block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); max-block-size: var(--lr-json-viewer-max-height, var(--lr-size-20rem)); } .source-shell [part~='source-list'] { block-size: 100%; } [part='search-status'] { padding: var(--lr-space-xs); color: var(--lr-color-text-quiet); } [part="base"] { display: block; max-block-size: var( --lr-json-viewer-max-height, var(--_lr-json-viewer-max-height) ); overflow: auto; border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface); } [part="toolbar"] { position: sticky; inset-block-start: 0; z-index: var(--lr-layer-content); display: flex; justify-content: flex-end; padding: var(--lr-space-xs) var(--lr-space-s); border-block-end: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); background: var(--lr-color-surface); } [part="tree"] { padding: var(--lr-space-s); direction: ltr; } .row { display: flex; flex-wrap: var(--_lr-json-viewer-row-wrap, nowrap); align-items: flex-start; gap: var(--lr-space-xs); row-gap: 0; min-inline-size: 0; border-radius: var(--lr-radius); } [part='tree'][data-layout='stacked'] { --_lr-json-viewer-row-wrap: wrap; --_lr-json-viewer-value-basis: 100%; --_lr-json-viewer-value-indent: calc(var(--lr-icon-button-size) + var(--lr-space-xs)); --_lr-json-viewer-value-order: 1; --_lr-json-viewer-spacer-margin-block: calc(var(--lr-icon-button-size) / -2); line-height: var(--lr-line-height-snug); } @container ${mediumContainerQuery} { [part='tree'][data-layout='auto'] { --_lr-json-viewer-row-wrap: wrap; --_lr-json-viewer-value-basis: 100%; --_lr-json-viewer-value-indent: calc(var(--lr-icon-button-size) + var(--lr-space-xs)); --_lr-json-viewer-value-order: 1; --_lr-json-viewer-spacer-margin-block: calc(var(--lr-icon-button-size) / -2); line-height: var(--lr-line-height-snug); } } [part='key'] ~ [part='value'] { flex-basis: var(--_lr-json-viewer-value-basis, auto); order: var(--_lr-json-viewer-value-order, 0); margin-inline-start: var(--_lr-json-viewer-value-indent, 0); } .row:hover { background: var(--lr-json-viewer-row-hover-bg, var(--lr-color-brand-quiet)); } .row:hover [part="copy-button"], .row:focus-within [part="copy-button"] { opacity: 1; } [part="toggle"] { inline-size: var(--lr-size-1-25rem); block-size: var(--lr-size-1-25rem); ${iconHitTarget} margin-block-start: var(--lr-size-0-1875rem); flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; padding: 0; border: none; background: none; color: var(--lr-color-text-quiet); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); font: inherit; } [part="toggle"][hidden] { visibility: hidden; margin-block: var(--_lr-json-viewer-spacer-margin-block, var(--lr-size-0-1875rem) 0); } [part="toggle"] .chevron { display: inline-flex; transform: rotate(0deg); transition: transform var(--lr-transition-fast); } [part="toggle"][aria-expanded="true"] .chevron { transform: rotate(90deg); } :where([part="toggle"]):hover:where(:not([hidden])) { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } :where([part="toggle"]):active:where(:not([hidden])) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } [part="toggle"]:focus-visible, [part="copy-button"]:focus-visible { ${focusRing} } .toggle-space { inline-size: var(--lr-icon-button-size); flex: 0 0 auto; } [part="key"] { flex: 0 1 auto; min-inline-size: 0; overflow-wrap: anywhere; font-weight: var(--lr-font-weight-semibold); color: var(--lr-color-text); } .colon { flex: 0 0 auto; color: var(--lr-color-text-quiet); margin-inline-end: var(--lr-space-xs); } [part="bracket"] { flex: 0 0 auto; color: var(--lr-color-text-quiet); } [part="key"][data-match], [part="value"][data-match] { background: var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); border-radius: var(--lr-size-0-1875rem); box-shadow: 0 0 0 var(--lr-size-0-125rem) var(--lr-json-viewer-match-bg, var(--lr-color-warning-quiet)); } [part="value"] { min-inline-size: 0; overflow-wrap: anywhere; word-break: break-word; white-space: pre-wrap; } [part="value"][data-type="string"] { color: var( --lr-json-viewer-string-color, var(--_lr-json-viewer-string-color) ); } [part="value"][data-type="number"] { color: var( --lr-json-viewer-number-color, var(--_lr-json-viewer-number-color) ); } [part="value"][data-type="boolean"] { color: var( --lr-json-viewer-boolean-color, var(--_lr-json-viewer-boolean-color) ); } [part="value"][data-type="null"], [part="value"][data-type="undefined"], [part="value"][data-type="circular"] { color: var(--lr-json-viewer-null-color, var(--_lr-json-viewer-null-color)); font-style: italic; } [part="key"][data-active], [part="value"][data-active] { outline: var(--lr-focus-ring-width) solid var( --lr-json-viewer-active-outline, var(--_lr-json-viewer-active-outline) ); outline-offset: var(--lr-focus-ring-offset); } .preview { flex: 0 0 auto; color: var(--lr-color-text-quiet); font-style: italic; margin-inline: var(--lr-space-xs); } [part="copy-button"] { flex: 0 0 auto; margin-inline-start: auto; border: none; background: none; color: var(--lr-color-text-quiet); font: inherit; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); ${iconHitTarget} padding: var(--lr-size-0-125rem) var(--lr-space-xs); border-radius: var(--lr-radius); cursor: pointer; transition: var(--lr-transition-interactive); } [part="copy-button"]:hover { background: var(--lr-color-brand-quiet); color: var(--lr-color-brand); } [part="copy-button"]:active { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var(--lr-color-brand); } .row [part="copy-button"] { opacity: 0; } .row [part="copy-button"]:focus-visible { opacity: 1; } @media (hover: none), (pointer: coarse) { .row [part="copy-button"] { opacity: 1; } } @media (prefers-reduced-motion: reduce) { [part="toggle"], [part="copy-button"], [part="toggle"] .chevron { transition: none !important; } } `;export{styles};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings/utility.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old))}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed&&formatISO(parsed)===super.value||(parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value)}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
1
+ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings/utility.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old))}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed&&formatISO(parsed)===super.value||(parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value)}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot?.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
2
2
  <div part=${field==="day"?"field field-day":field==="month"?"field field-month":"field field-year"} data-field=${field}>
3
3
  <label part="field-label" for=${id}>${this.labelFor(field)}</label>
4
4
  <input