@aceshooting/lyra-ui 14.3.1 → 15.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 (221) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/custom-elements.json +1 -1
  3. package/design-tokens.json +1 -1
  4. package/dist/cli/migration-contract.json +1 -1
  5. package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +4 -0
  6. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +3 -3
  7. package/dist/components/agent-tools/approval-queue/approval-queue.class.js +3 -2
  8. package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +1 -1
  9. package/dist/components/agent-tools/commit-card/commit-card.styles.js +1 -1
  10. package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
  11. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +8 -3
  12. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -1
  13. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +10 -1
  14. package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +1 -1
  15. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  16. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +19 -1
  17. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +4 -4
  18. package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
  19. package/dist/components/agent-tools/task-list/task-list.class.d.ts +5 -0
  20. package/dist/components/agent-tools/task-list/task-list.class.js +3 -3
  21. package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
  22. package/dist/components/agent-tools/terminal/terminal.styles.js +1 -1
  23. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  24. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +10 -7
  25. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +15 -14
  26. package/dist/components/agent-tools/tool-param-form/tool-param-form.d.ts +1 -1
  27. package/dist/components/agent-tools/tool-param-form/tool-param-form.js +1 -1
  28. package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +1 -1
  29. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +5 -2
  30. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
  31. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.d.ts +3 -1
  32. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +9 -1
  33. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +1 -1
  34. package/dist/components/charts/chart/box-plot.class.d.ts +64 -4
  35. package/dist/components/charts/chart/box-plot.class.js +5 -5
  36. package/dist/components/charts/chart/chart-colors.d.ts +10 -0
  37. package/dist/components/charts/chart/chart-colors.js +1 -1
  38. package/dist/components/charts/chart/chart.class.d.ts +35 -10
  39. package/dist/components/charts/chart/chart.class.js +4 -4
  40. package/dist/components/charts/chart/lite-chart.class.d.ts +10 -2
  41. package/dist/components/charts/chart/lite-chart.styles.js +1 -1
  42. package/dist/components/conversation/markdown/markdown.class.d.ts +9 -1
  43. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  44. package/dist/components/conversation/message-parts/message-parts.class.d.ts +18 -1
  45. package/dist/components/conversation/message-parts/message-parts.class.js +4 -4
  46. package/dist/components/conversation/model-select/model-select.class.d.ts +6 -2
  47. package/dist/components/conversation/model-select/model-select.class.js +3 -3
  48. package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
  49. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
  50. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  51. package/dist/components/data/calendar/calendar.class.js +2 -2
  52. package/dist/components/data/context-meter/context-meter.styles.js +1 -1
  53. package/dist/components/data/data-grid/data-grid-types.d.ts +8 -2
  54. package/dist/components/data/data-grid/data-grid.class.d.ts +16 -3
  55. package/dist/components/data/data-grid/data-grid.class.js +3 -2
  56. package/dist/components/data/env-list/env-list.styles.js +1 -1
  57. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +22 -2
  58. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  59. package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +12 -4
  60. package/dist/components/data/flow-minimap/flow-minimap.class.js +2 -2
  61. package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
  62. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -1
  63. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  64. package/dist/components/data/heatmap/heatmap.class.d.ts +12 -1
  65. package/dist/components/data/heatmap/heatmap.class.js +3 -3
  66. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  67. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  68. package/dist/components/forms/combobox/combobox.class.js +1 -1
  69. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  70. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  71. package/dist/components/forms/date-picker/date-picker.class.d.ts +12 -1
  72. package/dist/components/forms/date-picker/date-picker.class.js +1 -1
  73. package/dist/components/forms/icon-button/icon-button.class.d.ts +27 -5
  74. package/dist/components/forms/icon-button/icon-button.class.js +7 -3
  75. package/dist/components/forms/input/input.styles.js +1 -1
  76. package/dist/components/forms/input/time-input.class.d.ts +13 -2
  77. package/dist/components/forms/input/time-input.class.js +1 -1
  78. package/dist/components/forms/otp-input/otp-input.class.d.ts +8 -1
  79. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  80. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -1
  81. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  82. package/dist/components/forms/select/select.class.d.ts +1 -1
  83. package/dist/components/forms/select/select.class.js +1 -1
  84. package/dist/components/forms/slider/slider.class.d.ts +4 -1
  85. package/dist/components/forms/slider/slider.class.js +1 -1
  86. package/dist/components/forms/textarea/textarea.class.d.ts +9 -4
  87. package/dist/components/forms/textarea/textarea.class.js +1 -1
  88. package/dist/components/forms/time-range/time-range.class.js +1 -1
  89. package/dist/components/layout/app-rail/app-rail.class.d.ts +7 -2
  90. package/dist/components/layout/app-rail/app-rail.class.js +1 -1
  91. package/dist/components/layout/card/card.class.js +2 -2
  92. package/dist/components/layout/card/card.styles.js +1 -1
  93. package/dist/components/layout/control-group/control-group.class.js +1 -1
  94. package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +1 -1
  95. package/dist/components/layout/details/details.styles.js +1 -1
  96. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +13 -3
  97. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  98. package/dist/components/layout/menu/dropdown-item.class.d.ts +2 -0
  99. package/dist/components/layout/menu/menu-item.class.d.ts +28 -1
  100. package/dist/components/layout/menu/menu-item.class.js +45 -35
  101. package/dist/components/layout/menu/menu-item.styles.js +1 -1
  102. package/dist/components/layout/menu/menu.class.js +1 -1
  103. package/dist/components/layout/multi-split/multi-split.class.d.ts +12 -2
  104. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  105. package/dist/components/layout/page/page.class.js +2 -1
  106. package/dist/components/layout/page/page.styles.js +1 -1
  107. package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
  108. package/dist/components/layout/responsive-panel/responsive-panel.class.js +2 -2
  109. package/dist/components/layout/responsive-panel/responsive-panel.styles.js +1 -1
  110. package/dist/components/layout/stepper/stepper.class.js +2 -2
  111. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  112. package/dist/components/layout/virtual-list/virtual-list.class.js +2 -2
  113. package/dist/components/layout/widget/widget.class.d.ts +12 -2
  114. package/dist/components/layout/widget/widget.class.js +2 -2
  115. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
  116. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  117. package/dist/components/media/file-icon/file-icon.class.d.ts +3 -1
  118. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  119. package/dist/components/media/file-input/file-input.class.d.ts +1 -1
  120. package/dist/components/media/file-input/file-input.class.js +1 -1
  121. package/dist/components/media/flag/flag.styles.js +1 -1
  122. package/dist/components/media/image-comparer/image-comparer.class.d.ts +5 -5
  123. package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
  124. package/dist/components/media/image-comparer/image-comparer.styles.js +1 -1
  125. package/dist/components/media/lightbox/lightbox.styles.js +1 -1
  126. package/dist/components/media/map/map.styles.js +1 -1
  127. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  128. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  129. package/dist/components/media/video-playlist/video-playlist.styles.js +1 -1
  130. package/dist/components/overlays/alert/alert.class.d.ts +6 -0
  131. package/dist/components/overlays/alert/alert.styles.js +1 -1
  132. package/dist/components/overlays/badge/tag.class.js +1 -1
  133. package/dist/components/overlays/chip/chip.class.js +1 -1
  134. package/dist/components/overlays/empty/empty.class.js +2 -2
  135. package/dist/components/overlays/kbd/kbd.styles.js +1 -1
  136. package/dist/components/overlays/progress/progress-ring.class.d.ts +4 -1
  137. package/dist/components/overlays/progress/progress.styles.js +1 -1
  138. package/dist/components/overlays/toast/toast.styles.js +1 -1
  139. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  140. package/dist/components/retrieval/graph/graph.class.d.ts +10 -3
  141. package/dist/components/retrieval/graph/graph.class.js +1 -1
  142. package/dist/components/retrieval/graph/graph.styles.js +1 -1
  143. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
  144. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +6 -6
  145. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +2 -2
  146. package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
  147. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -3
  148. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  149. package/dist/components/retrieval/node-palette/node-palette.class.d.ts +7 -1
  150. package/dist/components/retrieval/node-palette/node-palette.class.js +23 -13
  151. package/dist/components/retrieval/node-palette/node-palette.styles.js +1 -1
  152. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +4 -1
  153. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
  154. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  155. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +4 -3
  156. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  157. package/dist/components/retrieval/source-list/source-list.class.d.ts +7 -1
  158. package/dist/components/retrieval/source-list/source-list.class.js +1 -1
  159. package/dist/components/utility/export-button/export-button.class.d.ts +14 -2
  160. package/dist/components/utility/export-button/export-button.class.js +3 -3
  161. package/dist/components/utility/export-button/export-button.styles.js +1 -1
  162. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  163. package/dist/components/utility/known-date/known-date.class.js +1 -1
  164. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +4 -2
  165. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  166. package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +9 -1
  167. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +4 -4
  168. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +1 -1
  169. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +4 -4
  170. package/dist/components/viewers/document-compare/document-compare.class.d.ts +5 -0
  171. package/dist/components/viewers/document-compare/document-compare.class.js +9 -4
  172. package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
  173. package/dist/components/viewers/document-preview/document-preview.class.d.ts +9 -1
  174. package/dist/components/viewers/document-preview/document-preview.class.js +2 -1
  175. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +5 -0
  176. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  177. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +5 -0
  178. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +1 -1
  179. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +3 -3
  180. package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
  181. package/dist/custom-elements-jsx.d.ts +1 -1
  182. package/dist/events.d.ts +5 -4
  183. package/dist/internal/accessibility-visibility.d.ts +13 -2
  184. package/dist/internal/accessibility-visibility.js +1 -1
  185. package/dist/internal/package-metadata.d.ts +1 -1
  186. package/dist/internal/package-metadata.js +1 -1
  187. package/dist/lyra.d.ts +1 -1
  188. package/dist/svelte.d.ts +1 -1
  189. package/dist/vue.d.ts +1 -1
  190. package/llms/components/lr-alert.md +11 -3
  191. package/llms/components/lr-box-plot.md +21 -4
  192. package/llms/components/lr-chart.md +13 -4
  193. package/llms/components/lr-code-block.md +5 -4
  194. package/llms/components/lr-data-grid.md +24 -10
  195. package/llms/components/lr-document-compare.md +5 -0
  196. package/llms/components/lr-dropdown-item.md +31 -0
  197. package/llms/components/lr-eval-dataset.md +5 -4
  198. package/llms/components/lr-export-button.md +10 -5
  199. package/llms/components/lr-filter-bar.md +4 -1
  200. package/llms/components/lr-flow-minimap.md +7 -1
  201. package/llms/components/lr-icon-button.md +6 -1
  202. package/llms/components/lr-lite-chart.md +2 -1
  203. package/llms/components/lr-markdown.md +2 -2
  204. package/llms/components/lr-menu-item.md +31 -0
  205. package/llms/components/lr-menu.md +31 -0
  206. package/llms/components/lr-message-parts.md +7 -0
  207. package/llms/components/lr-model-settings-panel.md +4 -1
  208. package/llms/components/lr-node-palette.md +5 -4
  209. package/llms/components/lr-pdf-viewer.md +7 -0
  210. package/llms/components/lr-responsive-panel.md +2 -2
  211. package/llms/components/lr-subagent-panel.md +17 -2
  212. package/llms/components/lr-thinking-panel.md +4 -0
  213. package/llms/components/lr-timeline-item.md +1 -1
  214. package/llms/components/lr-timeline.md +1 -1
  215. package/llms/components/lr-tool-select-dialog.md +4 -3
  216. package/llms/components/lr-virtual-list.md +11 -11
  217. package/llms-full.txt +212 -59
  218. package/package.json +3 -3
  219. package/vscode-css-data.json +1 -1
  220. package/vscode-html-data.json +1 -1
  221. package/web-types.json +1 -1
@@ -19,13 +19,18 @@ readonly extension?:string;}export type LyraExportFormatOption=LyraExportFormat|
19
19
  * to substitute the built-in client-side download with a server-generated one.
20
20
  * @event lr-export-complete - Fired after a non-cancelled download completes.
21
21
  * @event lr-export-error - Fired when a built-in CSV/JSON export cannot be serialized or
22
- * downloaded. `detail: { format, error }`.
22
+ * downloaded. `detail: { format, error }`. The same failure is also announced through the
23
+ * shared light-DOM live region and marks the trigger with the `trigger-error` part token, so a
24
+ * screen-reader user and a sighted user both learn the export failed without needing to listen
25
+ * for this event.
23
26
  * @event lr-show - The format menu is about to open, however `open` became true. Cancelable —
24
27
  * `preventDefault()` leaves it closed. Not fired for markup that renders open from the start.
25
28
  * @event lr-hide - The format menu is about to close. Cancelable on the same terms as `lr-show`.
26
29
  * A close this component imposes on itself (disablement, `loading`, or a format list collapsing
27
30
  * to one entry) emits no lifecycle event and therefore offers no veto point.
28
31
  * @csspart trigger - The button that triggers the export (or opens the format menu).
32
+ * @csspart trigger-error - Present alongside `trigger` after a built-in CSV/JSON export fails,
33
+ * until the next export attempt. Style with `::part(trigger-error)`.
29
34
  * @csspart menu - The format-choice menu, shown when more than one format is configured.
30
35
  * @csspart menu-item - A single format option inside the menu.
31
36
  * @csspart format-label - A format option's primary label.
@@ -54,7 +59,14 @@ label?:string;
54
59
  /** Accessible name forwarded from the host to the native trigger button.
55
60
  * When unset, a nonempty visible `label` provides the name; an empty visible label uses the
56
61
  * localized default. An explicit empty `aria-label` remains authoritative by presence. */
57
- accessibleLabel:string|null;open:boolean;private triggerEl?;private menuEl?;private readonly menuId;private cleanup?;private overlay?;private menuPositioned;private pointerDocument?;private connectionGeneration;private connectedDocument?;private pendingDisconnectDocument?;private _isFirstUpdate;private openVetoed;
62
+ accessibleLabel:string|null;open:boolean;private triggerEl?;private menuEl?;
63
+ /** True from a failed built-in CSV/JSON export until the next export attempt starts; drives
64
+ * the visible `trigger-error` part token. */
65
+ private exportFailed;
66
+ /** Handle on the shared light-DOM live region export outcomes announce through -- a region
67
+ * rendered inside this shadow root is not reliably announced. Acquired on connect, not on the
68
+ * first failure, so assistive tech is already observing before any text arrives. */
69
+ private sink?;private readonly menuId;private cleanup?;private overlay?;private menuPositioned;private pointerDocument?;private connectionGeneration;private connectedDocument?;private pendingDisconnectDocument?;private _isFirstUpdate;private openVetoed;
58
70
  /** Which menu item to focus the next time `open` flips true; reset after use. */
59
71
  private pendingMenuFocusIndex;private formatsFocusSnapshot?;private forcedMenuClose?;
60
72
  /** Tracks only the temporary focus-rescue tabindex this component added itself. */
@@ -1,6 +1,6 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{nextId}from"../../../internal/a11y.js";import{buildCsv,downloadBlob}from"./csv.js";import{styles}from"./export-button.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_exportButtonLabel,LYRA_DEFAULT_exportFormatMenuLabel}from"../../../internal/default-strings.generated.js";const MAX_EXPORT_FORMATS=1e4;function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}function formatArrayLength(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");return length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0?void 0:{source:value,length:Math.min(length.value,MAX_EXPORT_FORMATS)}}catch{return}}function projectExportFormat(value){if(value==="csv"||value==="json")return value;if(value===null||typeof value!="object")return;const formatId=getOwnDataDescriptor(value,"formatId"),label=getOwnDataDescriptor(value,"label");if(formatId===MISSING_OWN_DATA_DESCRIPTOR||formatId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof formatId.value!="string"||formatId.value.trim().length===0||typeof label.value!="string"||label.value.trim().length===0)return;const description=getOwnDataDescriptor(value,"description"),extension=getOwnDataDescriptor(value,"extension");return Object.freeze({formatId:formatId.value,label:label.value,...description!==MISSING_OWN_DATA_DESCRIPTOR&&description!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof description.value=="string"?{description:description.value}:{},...extension!==MISSING_OWN_DATA_DESCRIPTOR&&extension!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof extension.value=="string"?{extension:extension.value}:{}})}class LyraExportButton extends LyraElement{constructor(){super(...arguments),this._rows=Object.freeze([]),this._columns=Object.freeze([]),this.filename="export",this._formats=Object.freeze(["csv"]),this.disabled=!1,this.loading=!1,this.accessibleLabel=null,this.open=!1,this.menuId=nextId("export-menu"),this.menuPositioned=!1,this.connectionGeneration=0,this._isFirstUpdate=!0,this.openVetoed=!1,this.pendingMenuFocusIndex=0,this.injectedHostTabIndex=!1,this.restoreFocusOnMenuClose=!1,this.onDocPointer=e=>{e.composedPath().includes(this)||(this.overlay?.isActive()?this.overlay.dismissBackdrop():this.closeMenu())},this.syncMenuOverlay=()=>{if(this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),!this.open||!this.isConnected){const restoreFocus=this.restoreFocusOnMenuClose;this.restoreFocusOnMenuClose=!1,this.deactivateMenuOverlay(restoreFocus);return}this.activateMenuOverlay(),this.bindDocumentPointer();const anchor=this.triggerEl,menu=this.menuEl,ownerDocument=this.ownerDocument;if(!anchor||!menu)return;const placement=place(anchor,menu);this.cleanup=placement,placement.ready.then(positioned=>{if(!(this.cleanup!==placement||!this.open||!this.isConnected||this.ownerDocument!==ownerDocument)){if(!positioned){this.forcedMenuClose="state",this.open=!1;return}this.menuPositioned=!0,this.focusMenuItem(this.pendingMenuFocusIndex),this.pendingMenuFocusIndex=0}})},this.onKeyDown=e=>{if(this.formats.length<=1||this.disabled||this.loading)return;const items=this.menuItemEls(),currentIndex=items.indexOf(e.target);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?0:currentIndex+1);break;case"ArrowUp":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?items.length-1:currentIndex-1);break;case"Home":this.open&&(e.preventDefault(),this.focusMenuItem(0));break;case"End":this.open&&(e.preventDefault(),this.focusMenuItem(items.length-1));break}}}static{this.defaultStrings={...super.defaultStrings,exportButtonLabel:LYRA_DEFAULT_exportButtonLabel,exportFormatMenuLabel:LYRA_DEFAULT_exportFormatMenuLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={rows:{attribute:!1,noAccessor:!0},columns:{attribute:!1,noAccessor:!0},formats:{attribute:!1,noAccessor:!0}}}get rows(){return this._rows}set rows(next){const previous=this._rows,source=Array.isArray(next)?next:[];this._rows=Object.freeze(source.map(row=>Object.freeze({...row}))),this.requestUpdate("rows",previous)}get columns(){return this._columns}set columns(next){const previous=this._columns,source=Array.isArray(next)?next:[];this._columns=Object.freeze(source.map(column=>Object.freeze({...column}))),this.requestUpdate("columns",previous)}get formats(){return this._formats}set formats(next){const previous=this._formats,source=formatArrayLength(next),seen=new Set,formats=[];for(let index=0;source&&index<source.length;index+=1){const descriptor=getOwnDataDescriptor(source.source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const snapshot=projectExportFormat(descriptor.value);if(!snapshot)continue;const id=typeof snapshot=="string"?snapshot:snapshot.formatId;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),formats.push(snapshot))}this._formats=Object.freeze(formats),this.requestUpdate("formats",previous)}connectedCallback(){const pendingDisconnectDocument=this.pendingDisconnectDocument;if(this.pendingDisconnectDocument=void 0,this.connectionGeneration+=1,this.connectedDocument=this.ownerDocument,super.connectedCallback(),pendingDisconnectDocument){if(pendingDisconnectDocument===this.ownerDocument){this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1;return}this.hasUpdated&&this.open&&this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay");return}this.hasUpdated&&this.open&&this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay")}disconnectedCallback(){const generation=++this.connectionGeneration,disconnectDocument=this.connectedDocument??this.ownerDocument;this.pendingDisconnectDocument=disconnectDocument,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),this.overlay?.suspend(),this.restoreFocusOnMenuClose=!1,queueDocumentMicrotask(disconnectDocument,()=>{this.connectionGeneration!==generation||this.isConnected||this.pendingDisconnectDocument!==disconnectDocument||(this.pendingDisconnectDocument=void 0,this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1)})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlay?.suspend()}bindDocumentPointer(){if(!this.isConnected)return;const owner=this.ownerDocument;this.pointerDocument!==owner&&(this.unbindDocumentPointer(),owner.addEventListener("pointerdown",this.onDocPointer),this.pointerDocument=owner)}unbindDocumentPointer(){this.pointerDocument?.removeEventListener("pointerdown",this.onDocPointer),this.pointerDocument=void 0}openMenu(){this.open||(this.open=!0)}closeMenu(restoreFocus=!1){this.open&&(this.restoreFocusOnMenuClose||=restoreFocus,this.open=!1)}activateMenuOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.menuEl??null,onEscape:()=>this.closeMenu(!0),onBackdrop:()=>this.closeMenu(),onTab:()=>this.closeMenu(),restoreFocusTo:()=>this.triggerEl??null})}deactivateMenuOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}menuItemEls(){return Array.from(this.renderRoot.querySelectorAll('[part="menu-item"]'))}focusMenuItem(index){const items=this.menuItemEls();items.length!==0&&items[Math.max(0,Math.min(items.length-1,index))]?.focus()}focusMenuItemOnOpen(index){this.open&&this.menuPositioned?this.focusMenuItem(index):(this.pendingMenuFocusIndex=index,this.open||this.openMenu())}firstUpdated(changed){super.firstUpdated(changed),this.renderRoot.addEventListener("keydown",this.onKeyDown)}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.setAttribute("aria-busy",String(this.loading)),(changed.has("disabled")||changed.has("loading"))&&!this.disabled&&!this.loading&&this.injectedHostTabIndex&&(this.getAttribute("tabindex")==="-1"&&this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1),(changed.has("disabled")||changed.has("loading"))&&(this.disabled||this.loading)){const active=activeElementIn(this.shadowRoot);if(active===this.triggerEl||active?.getAttribute("part")==="menu-item"){this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0);const ownerHTMLElement=this.ownerDocument.defaultView?.HTMLElement,nativeFocus=ownerHTMLElement?Reflect.get(ownerHTMLElement.prototype,"focus",this):void 0;typeof nativeFocus=="function"&&nativeFocus.call(this,{preventScroll:!0})}this.open&&(this.open=!1,this.forcedMenuClose="state")}if(changed.has("formats")){const active=activeElementIn(this.shadowRoot),index=this.menuItemEls().indexOf(active),previous=changed.get("formats")?.[index];this.formatsFocusSnapshot=index>=0&&previous?{index,id:this.formatId(previous)}:void 0}if(this.open&&this.formats.length<=1){const previousOpen=changed.get("open");this.forcedMenuClose=changed.has("formats")&&changed.get("formats")?.length?"formats":previousOpen===!1||previousOpen===void 0?"invalid-open":"state",this.open=!1}this.announceMenuTransition(changed)}announceMenuTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.forcedMenuClose)return;const name=this.open?"lr-show":"lr-hide";this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open)}updated(changed){super.updated(changed);const forcedMenuClose=this.forcedMenuClose;if(this.forcedMenuClose=void 0,(changed.has("open")||forcedMenuClose==="formats"||forcedMenuClose==="state")&&!this.openVetoed?this.syncMenuOverlay():this.openVetoed&&(this.restoreFocusOnMenuClose=!1),changed.has("formats")&&this.formatsFocusSnapshot){const{index,id}=this.formatsFocusSnapshot;this.formatsFocusSnapshot=void 0,this.scheduleAfterUpdate(()=>{if(this.formats.length<=1)this.closeMenu(),this.triggerEl?.focus();else if(this.open){const nextIndex=this.formats.findIndex(format=>this.formatId(format)===id);this.focusMenuItemOnOpen(nextIndex>=0?nextIndex:index)}})}}effectiveColumns(){if(this.columns.length>0)return this.columns;const keys=new Set;for(const row of this.rows)for(const key of Object.keys(row))keys.add(key);return Array.from(keys,key=>({key,label:key}))}rowsForExport(){const keys=this.effectiveColumns().map(c=>c.key);return this.rows.map(row=>{const picked=Object.create(null);for(const key of keys)picked[key]=row[key];return picked})}formatId(format){return typeof format=="string"?format:format.formatId}formatLabel(format){return typeof format=="string"?format.toUpperCase():format.label}doExport(formatOption){if(this.disabled||this.loading)return;this.closeMenu(),this.triggerEl?.focus();const format=this.formatId(formatOption);if(!this.emit("lr-export",Object.freeze({format}),{cancelable:!0}).defaultPrevented&&!(format!=="csv"&&format!=="json"))try{format==="csv"?downloadBlob(buildCsv(this.rows,this.effectiveColumns()),`${this.filename}.csv`,"text/csv;charset=utf-8;",this.ownerDocument):downloadBlob(JSON.stringify(this.rowsForExport(),null,2),`${this.filename}.json`,"application/json",this.ownerDocument),this.emit("lr-export-complete",Object.freeze({format}))}catch(error){this.emit("lr-export-error",Object.freeze({format,error}))}}onTriggerClick(){this.disabled||this.loading||this.formats.length!==0&&(this.formats.length===1?this.doExport(this.formats[0]):this.open?this.closeMenu():this.openMenu())}focus(options){this.triggerEl?.focus(options)}blur(){this.triggerEl?.blur()}click(){this.triggerEl?.click()}get effectiveLabel(){return this.label==null?this.localize("exportButtonLabel"):this.label}render(){const label=this.effectiveLabel,labelNamesTrigger=label.trim().length>0,accessibleLabel=this.accessibleLabel??(labelNamesTrigger?label:this.localize("exportButtonLabel")),triggerAriaLabel=this.accessibleLabel!==null||!labelNamesTrigger?accessibleLabel:nothing;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{nextId}from"../../../internal/a11y.js";import{buildCsv,downloadBlob}from"./csv.js";import{styles}from"./export-button.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_exportButtonLabel,LYRA_DEFAULT_exportFormatMenuLabel,LYRA_DEFAULT_statusError}from"../../../internal/default-strings.generated.js";const MAX_EXPORT_FORMATS=1e4;function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}function formatArrayLength(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");return length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0?void 0:{source:value,length:Math.min(length.value,MAX_EXPORT_FORMATS)}}catch{return}}function projectExportFormat(value){if(value==="csv"||value==="json")return value;if(value===null||typeof value!="object")return;const formatId=getOwnDataDescriptor(value,"formatId"),label=getOwnDataDescriptor(value,"label");if(formatId===MISSING_OWN_DATA_DESCRIPTOR||formatId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof formatId.value!="string"||formatId.value.trim().length===0||typeof label.value!="string"||label.value.trim().length===0)return;const description=getOwnDataDescriptor(value,"description"),extension=getOwnDataDescriptor(value,"extension");return Object.freeze({formatId:formatId.value,label:label.value,...description!==MISSING_OWN_DATA_DESCRIPTOR&&description!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof description.value=="string"?{description:description.value}:{},...extension!==MISSING_OWN_DATA_DESCRIPTOR&&extension!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof extension.value=="string"?{extension:extension.value}:{}})}class LyraExportButton extends LyraElement{constructor(){super(...arguments),this._rows=Object.freeze([]),this._columns=Object.freeze([]),this.filename="export",this._formats=Object.freeze(["csv"]),this.disabled=!1,this.loading=!1,this.accessibleLabel=null,this.open=!1,this.exportFailed=!1,this.menuId=nextId("export-menu"),this.menuPositioned=!1,this.connectionGeneration=0,this._isFirstUpdate=!0,this.openVetoed=!1,this.pendingMenuFocusIndex=0,this.injectedHostTabIndex=!1,this.restoreFocusOnMenuClose=!1,this.onDocPointer=e=>{e.composedPath().includes(this)||(this.overlay?.isActive()?this.overlay.dismissBackdrop():this.closeMenu())},this.syncMenuOverlay=()=>{if(this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),!this.open||!this.isConnected){const restoreFocus=this.restoreFocusOnMenuClose;this.restoreFocusOnMenuClose=!1,this.deactivateMenuOverlay(restoreFocus);return}this.activateMenuOverlay(),this.bindDocumentPointer();const anchor=this.triggerEl,menu=this.menuEl,ownerDocument=this.ownerDocument;if(!anchor||!menu)return;const placement=place(anchor,menu);this.cleanup=placement,placement.ready.then(positioned=>{if(!(this.cleanup!==placement||!this.open||!this.isConnected||this.ownerDocument!==ownerDocument)){if(!positioned){this.forcedMenuClose="state",this.open=!1;return}this.menuPositioned=!0,this.focusMenuItem(this.pendingMenuFocusIndex),this.pendingMenuFocusIndex=0}})},this.onKeyDown=e=>{if(this.formats.length<=1||this.disabled||this.loading)return;const items=this.menuItemEls(),currentIndex=items.indexOf(e.target);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?0:currentIndex+1);break;case"ArrowUp":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?items.length-1:currentIndex-1);break;case"Home":this.open&&(e.preventDefault(),this.focusMenuItem(0));break;case"End":this.open&&(e.preventDefault(),this.focusMenuItem(items.length-1));break}}}static{this.defaultStrings={...super.defaultStrings,exportButtonLabel:LYRA_DEFAULT_exportButtonLabel,exportFormatMenuLabel:LYRA_DEFAULT_exportFormatMenuLabel,statusError:LYRA_DEFAULT_statusError}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={rows:{attribute:!1,noAccessor:!0},columns:{attribute:!1,noAccessor:!0},formats:{attribute:!1,noAccessor:!0}}}get rows(){return this._rows}set rows(next){const previous=this._rows,source=Array.isArray(next)?next:[];this._rows=Object.freeze(source.map(row=>Object.freeze({...row}))),this.requestUpdate("rows",previous)}get columns(){return this._columns}set columns(next){const previous=this._columns,source=Array.isArray(next)?next:[];this._columns=Object.freeze(source.map(column=>Object.freeze({...column}))),this.requestUpdate("columns",previous)}get formats(){return this._formats}set formats(next){const previous=this._formats,source=formatArrayLength(next),seen=new Set,formats=[];for(let index=0;source&&index<source.length;index+=1){const descriptor=getOwnDataDescriptor(source.source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const snapshot=projectExportFormat(descriptor.value);if(!snapshot)continue;const id=typeof snapshot=="string"?snapshot:snapshot.formatId;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),formats.push(snapshot))}this._formats=Object.freeze(formats),this.requestUpdate("formats",previous)}connectedCallback(){const pendingDisconnectDocument=this.pendingDisconnectDocument;if(this.pendingDisconnectDocument=void 0,this.connectionGeneration+=1,this.connectedDocument=this.ownerDocument,super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),pendingDisconnectDocument){if(pendingDisconnectDocument===this.ownerDocument){this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1;return}this.hasUpdated&&this.open&&this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay");return}this.hasUpdated&&this.open&&this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay")}disconnectedCallback(){const generation=++this.connectionGeneration,disconnectDocument=this.connectedDocument??this.ownerDocument;this.pendingDisconnectDocument=disconnectDocument,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),this.overlay?.suspend(),this.restoreFocusOnMenuClose=!1,this.sink?.release(),this.sink=void 0,queueDocumentMicrotask(disconnectDocument,()=>{this.connectionGeneration!==generation||this.isConnected||this.pendingDisconnectDocument!==disconnectDocument||(this.pendingDisconnectDocument=void 0,this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1)})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0}bindDocumentPointer(){if(!this.isConnected)return;const owner=this.ownerDocument;this.pointerDocument!==owner&&(this.unbindDocumentPointer(),owner.addEventListener("pointerdown",this.onDocPointer),this.pointerDocument=owner)}unbindDocumentPointer(){this.pointerDocument?.removeEventListener("pointerdown",this.onDocPointer),this.pointerDocument=void 0}openMenu(){this.open||(this.open=!0)}closeMenu(restoreFocus=!1){this.open&&(this.restoreFocusOnMenuClose||=restoreFocus,this.open=!1)}activateMenuOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.menuEl??null,onEscape:()=>this.closeMenu(!0),onBackdrop:()=>this.closeMenu(),onTab:()=>this.closeMenu(),restoreFocusTo:()=>this.triggerEl??null})}deactivateMenuOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}menuItemEls(){return Array.from(this.renderRoot.querySelectorAll('[part="menu-item"]'))}focusMenuItem(index){const items=this.menuItemEls();items.length!==0&&items[Math.max(0,Math.min(items.length-1,index))]?.focus()}focusMenuItemOnOpen(index){this.open&&this.menuPositioned?this.focusMenuItem(index):(this.pendingMenuFocusIndex=index,this.open||this.openMenu())}firstUpdated(changed){super.firstUpdated(changed),this.renderRoot.addEventListener("keydown",this.onKeyDown)}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.setAttribute("aria-busy",String(this.loading)),(changed.has("disabled")||changed.has("loading"))&&!this.disabled&&!this.loading&&this.injectedHostTabIndex&&(this.getAttribute("tabindex")==="-1"&&this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1),(changed.has("disabled")||changed.has("loading"))&&(this.disabled||this.loading)){const active=activeElementIn(this.shadowRoot);if(active===this.triggerEl||active?.getAttribute("part")==="menu-item"){this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0);const ownerHTMLElement=this.ownerDocument.defaultView?.HTMLElement,nativeFocus=ownerHTMLElement?Reflect.get(ownerHTMLElement.prototype,"focus",this):void 0;typeof nativeFocus=="function"&&nativeFocus.call(this,{preventScroll:!0})}this.open&&(this.open=!1,this.forcedMenuClose="state")}if(changed.has("formats")){const active=activeElementIn(this.shadowRoot),index=this.menuItemEls().indexOf(active),previous=changed.get("formats")?.[index];this.formatsFocusSnapshot=index>=0&&previous?{index,id:this.formatId(previous)}:void 0}if(this.open&&this.formats.length<=1){const previousOpen=changed.get("open");this.forcedMenuClose=changed.has("formats")&&changed.get("formats")?.length?"formats":previousOpen===!1||previousOpen===void 0?"invalid-open":"state",this.open=!1}this.announceMenuTransition(changed)}announceMenuTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.forcedMenuClose)return;const name=this.open?"lr-show":"lr-hide";this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open)}updated(changed){super.updated(changed);const forcedMenuClose=this.forcedMenuClose;if(this.forcedMenuClose=void 0,(changed.has("open")||forcedMenuClose==="formats"||forcedMenuClose==="state")&&!this.openVetoed?this.syncMenuOverlay():this.openVetoed&&(this.restoreFocusOnMenuClose=!1),changed.has("formats")&&this.formatsFocusSnapshot){const{index,id}=this.formatsFocusSnapshot;this.formatsFocusSnapshot=void 0,this.scheduleAfterUpdate(()=>{if(this.formats.length<=1)this.closeMenu(),this.triggerEl?.focus();else if(this.open){const nextIndex=this.formats.findIndex(format=>this.formatId(format)===id);this.focusMenuItemOnOpen(nextIndex>=0?nextIndex:index)}})}}effectiveColumns(){if(this.columns.length>0)return this.columns;const keys=new Set;for(const row of this.rows)for(const key of Object.keys(row))keys.add(key);return Array.from(keys,key=>({key,label:key}))}rowsForExport(){const keys=this.effectiveColumns().map(c=>c.key);return this.rows.map(row=>{const picked=Object.create(null);for(const key of keys)picked[key]=row[key];return picked})}formatId(format){return typeof format=="string"?format:format.formatId}formatLabel(format){return typeof format=="string"?format.toUpperCase():format.label}doExport(formatOption){if(this.disabled||this.loading)return;this.closeMenu(),this.triggerEl?.focus(),this.exportFailed=!1;const format=this.formatId(formatOption);if(!this.emit("lr-export",Object.freeze({format}),{cancelable:!0}).defaultPrevented&&!(format!=="csv"&&format!=="json"))try{format==="csv"?downloadBlob(buildCsv(this.rows,this.effectiveColumns()),`${this.filename}.csv`,"text/csv;charset=utf-8;",this.ownerDocument):downloadBlob(JSON.stringify(this.rowsForExport(),null,2),`${this.filename}.json`,"application/json",this.ownerDocument),this.emit("lr-export-complete",Object.freeze({format}))}catch(error){this.exportFailed=!0,this.sink?.announce(this.localize("statusError")),this.emit("lr-export-error",Object.freeze({format,error}))}}onTriggerClick(){this.disabled||this.loading||this.formats.length!==0&&(this.formats.length===1?this.doExport(this.formats[0]):this.open?this.closeMenu():this.openMenu())}focus(options){this.triggerEl?.focus(options)}blur(){this.triggerEl?.blur()}click(){this.triggerEl?.click()}get effectiveLabel(){return this.label==null?this.localize("exportButtonLabel"):this.label}render(){const label=this.effectiveLabel,labelNamesTrigger=label.trim().length>0,accessibleLabel=this.accessibleLabel??(labelNamesTrigger?label:this.localize("exportButtonLabel")),triggerAriaLabel=this.accessibleLabel!==null||!labelNamesTrigger?accessibleLabel:nothing;return html`
2
2
  <button
3
- part="trigger"
3
+ part=${this.exportFailed?"trigger trigger-error":"trigger"}
4
4
  type="button"
5
5
  ?disabled=${this.disabled||this.loading||this.formats.length===0}
6
6
  aria-label=${triggerAriaLabel}
@@ -29,4 +29,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
29
29
  ${typeof f!="string"&&f.description?html`<span part="format-description">${f.description}</span>`:nothing}
30
30
  </button>`)}
31
31
  </div>`:nothing}
32
- `}}__decorate([property()],LyraExportButton.prototype,"filename",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"loading",void 0),__decorate([property()],LyraExportButton.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraExportButton.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"open",void 0),__decorate([query('[part="trigger"]')],LyraExportButton.prototype,"triggerEl",void 0),__decorate([query('[part="menu"]')],LyraExportButton.prototype,"menuEl",void 0);export{LyraExportButton};
32
+ `}}__decorate([property()],LyraExportButton.prototype,"filename",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"loading",void 0),__decorate([property()],LyraExportButton.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraExportButton.prototype,"accessibleLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraExportButton.prototype,"open",void 0),__decorate([query('[part~="trigger"]')],LyraExportButton.prototype,"triggerEl",void 0),__decorate([query('[part="menu"]')],LyraExportButton.prototype,"menuEl",void 0),__decorate([state()],LyraExportButton.prototype,"exportFailed",void 0);export{LyraExportButton};
@@ -1 +1 @@
1
- import{css}from"lit";const styles=css`:host{display:inline-block;position:relative}[part=trigger]{align-items:center;gap:var(--lr-space-xs);padding:var(--lr-space-xs) var(--lr-space-m);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);background:var(--lr-color-surface);color:var(--lr-color-text);font:inherit;min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);cursor:pointer;display:inline-flex}:where([part=trigger]):hover:where(:not(:disabled)){border-color:var(--lr-color-brand)}:where([part=trigger]):active:where(:not(:disabled)){border-color:var(--lr-color-brand);background:color-mix(in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active))}[part=trigger]:disabled{opacity:var(--lr-opacity-disabled);cursor:not-allowed}[part=trigger]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=menu]{visibility:hidden;z-index:var(--lr-layer-dropdown);box-sizing:border-box;inline-size:max-content;min-inline-size:min(var(--lr-popover-viewport-clamp), var(--lr-size-8rem), var(--lr-positioner-available-inline-size,100vw));max-inline-size:min(var(--lr-popover-viewport-clamp), var(--lr-size-20rem), var(--lr-positioner-available-inline-size,100vw));max-block-size:var(--lr-positioner-available-block-size,100vh);padding:var(--lr-space-xs);background:var(--lr-color-surface);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);box-shadow:var(--lr-shadow-m);opacity:0;transform:translateY(var(--lr-size-neg-4px));transition:opacity var(--lr-transition-fast), transform var(--lr-transition-fast);position:fixed;overflow:auto}:host([open]) [part=menu]{visibility:visible;opacity:1;transform:none}@media (prefers-reduced-motion:reduce){[part=menu]{transition:none}}[part=menu-item]{justify-content:center;align-items:center;gap:var(--lr-size-1px);box-sizing:border-box;inline-size:100%;min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);text-align:center;padding:var(--lr-space-xs) var(--lr-space-s);color:inherit;font:inherit;cursor:pointer;border-radius:var(--lr-radius);background:0 0;border:none;flex-direction:column;display:flex}:where([part=menu-item]):hover:where(:not(:disabled)){background:var(--lr-color-brand-quiet)}:where([part=menu-item]):active:where(:not(:disabled)){background:color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))}[part=menu-item]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=menu-item]:disabled{opacity:var(--lr-opacity-disabled);cursor:not-allowed}[part=format-description]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm)}[part=format-label],[part=format-description]{overflow-wrap:anywhere;max-inline-size:100%}`;export{styles};
1
+ import{css}from"lit";const styles=css`:host{display:inline-block;position:relative}[part~=trigger]{justify-content:center;align-items:center;gap:var(--lr-space-xs);padding:var(--lr-space-xs) var(--lr-space-m);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);background:var(--lr-color-surface);color:var(--lr-color-text);font:inherit;min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);cursor:pointer;display:inline-flex}:where([part~=trigger]):hover:where(:not(:disabled)){border-color:var(--lr-color-brand)}:where([part~=trigger]):active:where(:not(:disabled)){border-color:var(--lr-color-brand);background:color-mix(in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active))}[part~=trigger]:disabled{opacity:var(--lr-opacity-disabled);cursor:not-allowed}[part~=trigger]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part~=trigger-error]{border-color:var(--lr-color-danger);color:var(--lr-color-danger)}[part=menu]{visibility:hidden;z-index:var(--lr-layer-dropdown);box-sizing:border-box;inline-size:max-content;min-inline-size:min(var(--lr-popover-viewport-clamp), var(--lr-size-8rem), var(--lr-positioner-available-inline-size,100vw));max-inline-size:min(var(--lr-popover-viewport-clamp), var(--lr-size-20rem), var(--lr-positioner-available-inline-size,100vw));max-block-size:var(--lr-positioner-available-block-size,100vh);padding:var(--lr-space-xs);background:var(--lr-color-surface);border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);box-shadow:var(--lr-shadow-m);opacity:0;transform:translateY(var(--lr-size-neg-4px));transition:opacity var(--lr-transition-fast), transform var(--lr-transition-fast);position:fixed;overflow:auto}:host([open]) [part=menu]{visibility:visible;opacity:1;transform:none}@media (prefers-reduced-motion:reduce){[part=menu]{transition:none}}[part=menu-item]{justify-content:center;align-items:center;gap:var(--lr-size-1px);box-sizing:border-box;inline-size:100%;min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);text-align:center;padding:var(--lr-space-xs) var(--lr-space-s);color:inherit;font:inherit;cursor:pointer;border-radius:var(--lr-radius);background:0 0;border:none;flex-direction:column;display:flex}:where([part=menu-item]):hover:where(:not(:disabled)){background:var(--lr-color-brand-quiet)}:where([part=menu-item]):active:where(:not(:disabled)){background:color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))}[part=menu-item]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=menu-item]:disabled{opacity:var(--lr-opacity-disabled);cursor:not-allowed}[part=format-description]{color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm)}[part=format-label],[part=format-description]{overflow-wrap:anywhere;max-inline-size:100%}`;export{styles};
@@ -1 +1 @@
1
- import{css}from"lit";const styles=css`:host{--_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);display:block}[part=base]{max-block-size:var(--lr-json-viewer-max-height,var(--_lr-json-viewer-max-height));border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);background:var(--lr-color-surface);display:block;overflow:auto}[part=toolbar]{z-index:var(--lr-layer-content);padding:var(--lr-space-xs) var(--lr-space-s);border-block-end:var(--lr-border-width-thin) solid var(--lr-color-border);background:var(--lr-color-surface);justify-content:flex-end;display:flex;position:sticky;inset-block-start:0}[part=tree]{padding:var(--lr-space-s);direction:ltr}.row{align-items:flex-start;gap:var(--lr-space-xs);border-radius:var(--lr-radius);min-inline-size:0;display:flex}.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);min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);color:var(--lr-color-text-quiet);border-radius:var(--lr-radius);cursor:pointer;background:0 0;border:none;flex:none;justify-content:center;align-items:center;margin-block-start:var(--lr-size-0-1875rem);padding:0;display:inline-flex}[part=toggle][hidden]{visibility:hidden}[part=toggle] .chevron{transition:transform var(--lr-transition-fast);display:inline-flex;transform:rotate(0)}[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{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}.toggle-space{inline-size:var(--lr-icon-button-size);flex:none}[part=key]{overflow-wrap:anywhere;min-inline-size:0;font-weight:var(--lr-font-weight-semibold);color:var(--lr-color-text);flex:0 auto}.colon{color:var(--lr-color-text-quiet);flex:none;margin-inline-end:var(--lr-space-xs)}[part=bracket]{color:var(--lr-color-text-quiet);flex:none}[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]{overflow-wrap:anywhere;word-break:break-word;white-space:pre-wrap;min-inline-size:0}[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{color:var(--lr-color-text-quiet);margin-inline:var(--lr-space-xs);flex:none;font-style:italic}[part=copy-button]{color:var(--lr-color-text-quiet);font:inherit;font-size:var(--lr-font-size-xs);line-height:var(--lr-line-height-none);min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);padding:var(--lr-size-0-125rem) var(--lr-space-xs);border-radius:var(--lr-radius);cursor:pointer;background:0 0;border:none;flex:none;margin-inline-start:auto}[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] .chevron{transition:none!important}}`;export{styles};
1
+ import{css}from"lit";const styles=css`:host{--_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);display:block}[part=base]{max-block-size:var(--lr-json-viewer-max-height,var(--_lr-json-viewer-max-height));border:var(--lr-border-width-thin) solid var(--lr-color-border);border-radius:var(--lr-radius);background:var(--lr-color-surface);display:block;overflow:auto}[part=toolbar]{z-index:var(--lr-layer-content);padding:var(--lr-space-xs) var(--lr-space-s);border-block-end:var(--lr-border-width-thin) solid var(--lr-color-border);background:var(--lr-color-surface);justify-content:flex-end;display:flex;position:sticky;inset-block-start:0}[part=tree]{padding:var(--lr-space-s);direction:ltr}.row{align-items:flex-start;gap:var(--lr-space-xs);border-radius:var(--lr-radius);min-inline-size:0;display:flex}.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);min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);color:var(--lr-color-text-quiet);border-radius:var(--lr-radius);cursor:pointer;font:inherit;background:0 0;border:none;flex:none;justify-content:center;align-items:center;margin-block-start:var(--lr-size-0-1875rem);padding:0;display:inline-flex}[part=toggle][hidden]{visibility:hidden}[part=toggle] .chevron{transition:transform var(--lr-transition-fast);display:inline-flex;transform:rotate(0)}[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{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}.toggle-space{inline-size:var(--lr-icon-button-size);flex:none}[part=key]{overflow-wrap:anywhere;min-inline-size:0;font-weight:var(--lr-font-weight-semibold);color:var(--lr-color-text);flex:0 auto}.colon{color:var(--lr-color-text-quiet);flex:none;margin-inline-end:var(--lr-space-xs)}[part=bracket]{color:var(--lr-color-text-quiet);flex:none}[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]{overflow-wrap:anywhere;word-break:break-word;white-space:pre-wrap;min-inline-size:0}[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{color:var(--lr-color-text-quiet);margin-inline:var(--lr-space-xs);flex:none;font-style:italic}[part=copy-button]{color:var(--lr-color-text-quiet);font:inherit;font-size:var(--lr-font-size-xs);line-height:var(--lr-line-height-none);min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);padding:var(--lr-size-0-125rem) var(--lr-space-xs);border-radius:var(--lr-radius);cursor:pointer;background:0 0;border:none;flex:none;margin-inline-start:auto}[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] .chevron{transition:none!important}}`;export{styles};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{composedParentElement,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{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}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{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};function localDate(year,month,day){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function parseISO(value){const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(value);if(!match)return null;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=localDate(year,month-1,day);return isNaN(date.getTime())||date.getFullYear()!==year||date.getMonth()!==month-1||date.getDate()!==day?null:date}function formatISO(date){const mm=String(date.getMonth()+1).padStart(2,"0"),dd=String(date.getDate()).padStart(2,"0");return`${String(date.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function localeDateOrder(locale){try{const order=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","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}}}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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindErrorObserverTargets(),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.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},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,event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),this.detailFor(field));this.dispatchEvent(event),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(),this.emit("focus")},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=activeElementIn(this.shadowRoot);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),this.emit("blur"))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.errorObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindErrorObserverTargets(),this.announceVisibleError()}):void 0,this.addEventListener("slotchange",this.onForwardedSlotChange),this.bindErrorObserverTargets(),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)})}observeErrorNode(node){if(this.errorObserver){if(node.nodeType===3){this.errorObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.errorObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],characterData:!0,childList:!0,subtree:!0})}}bindErrorObserverTargets(){if(!this.errorObserver)return;this.errorObserver.disconnect(),this.observeErrorNode(this);let ancestor=composedParentElement(this);for(;ancestor;)this.errorObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]}),ancestor=composedParentElement(ancestor);const forwardedSlots=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error").flatMap(branch=>[...branch.localName==="slot"?[branch]:[],...branch.querySelectorAll("slot")]);for(const slot of forwardedSlots)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeErrorNode(assigned)}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorObserver?.disconnect(),this.errorObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),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){this.setParts(next,!0)}setParts(next,programmatic){const old=this._parts;this._parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")},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?(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(){return localeDateOrder(this.effectiveLocale)}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,event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),this.detailFor(this.lastEditedField));this.dispatchEvent(event)}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)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error"))}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 digitMap=new Map([["٠","0"],["١","1"],["٢","2"],["٣","3"],["٤","4"],["٥","5"],["٦","6"],["٧","7"],["٨","8"],["٩","9"],["۰","0"],["۱","1"],["۲","2"],["۳","3"],["۴","4"],["۵","5"],["۶","6"],["۷","7"],["۸","8"],["۹","9"]]);try{const formatter=getNumberFormat(this.effectiveLocale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++)digitMap.set(formatter.format(digit),String(digit))}catch{}let normalized="";for(const character of value)character>="0"&&character<="9"?normalized+=character:normalized+=digitMap.get(character)??"";return normalized}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
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{composedParentElement,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{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}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{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};function localDate(year,month,day){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function parseISO(value){const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(value);if(!match)return null;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=localDate(year,month-1,day);return isNaN(date.getTime())||date.getFullYear()!==year||date.getMonth()!==month-1||date.getDate()!==day?null:date}function formatISO(date){if(!Number.isFinite(date.getTime())||date.getFullYear()<0||date.getFullYear()>9999)return"";const mm=String(date.getMonth()+1).padStart(2,"0"),dd=String(date.getDate()).padStart(2,"0");return`${String(date.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function localeDateOrder(locale){try{const order=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","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}}}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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.bindErrorObserverTargets(),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.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},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,event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),this.detailFor(field));this.dispatchEvent(event),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(),this.emit("focus")},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=activeElementIn(this.shadowRoot);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),this.emit("blur"))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.errorObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindErrorObserverTargets(),this.announceVisibleError()}):void 0,this.addEventListener("slotchange",this.onForwardedSlotChange),this.bindErrorObserverTargets(),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)})}observeErrorNode(node){if(this.errorObserver){if(node.nodeType===3){this.errorObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.errorObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],characterData:!0,childList:!0,subtree:!0})}}bindErrorObserverTargets(){if(!this.errorObserver)return;this.errorObserver.disconnect(),this.observeErrorNode(this);let ancestor=composedParentElement(this);for(;ancestor;)this.errorObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]}),ancestor=composedParentElement(ancestor);const forwardedSlots=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error").flatMap(branch=>[...branch.localName==="slot"?[branch]:[],...branch.querySelectorAll("slot")]);for(const slot of forwardedSlots)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeErrorNode(assigned)}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorObserver?.disconnect(),this.errorObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),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){this.setParts(next,!0)}setParts(next,programmatic){const old=this._parts;this._parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")},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?(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(){return localeDateOrder(this.effectiveLocale)}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,event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),this.detailFor(this.lastEditedField));this.dispatchEvent(event)}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)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error"))}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 digitMap=new Map([["٠","0"],["١","1"],["٢","2"],["٣","3"],["٤","4"],["٥","5"],["٦","6"],["٧","7"],["٨","8"],["٩","9"],["۰","0"],["۱","1"],["۲","2"],["۳","3"],["۴","4"],["۵","5"],["۶","6"],["۷","7"],["۸","8"],["۹","9"]]);try{const formatter=getNumberFormat(this.effectiveLocale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++)digitMap.set(formatter.format(digit),String(digit))}catch{}let normalized="";for(const character of value)character>="0"&&character<="9"?normalized+=character:normalized+=digitMap.get(character)??"";return normalized}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
@@ -160,8 +160,10 @@ emptyText?:string;
160
160
  * this property when present -- matches `<lr-combobox>`'s/`<lr-table>`'s identical host
161
161
  * `aria-label` fallback. */
162
162
  label?:string;private activeIndex;private readonly _listId;private cleanup?;private virtualAnchor;private _isFirstUpdate;private _silentClose;private _ownsFocus;private _focusOwnerPredicate?;private _focusTransferGeneration;private anchorRelationship?;private announcementSink?;private announcedResultCount?;private announcedResultPosition?;connectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private syncAnnouncementSink;private resetResultAnnouncements;private announceResultState;private snapshotAttribute;private restoreAttribute;private captureAnchorCaret;private restoreRelationshipFocus;private restoreAnchorFocus;private attachAnchorRelationship;private detachAnchorRelationship;private syncAnchorRelationship;
163
- /** The current candidate set: runtime rows without a string `label` are omitted, then the
164
- * remaining `items` are filtered by `query` via `filter` (or the built-in default). */
163
+ /** The current candidate set: runtime rows without a non-blank string `label` are omitted (a
164
+ * blank/whitespace-only label would otherwise render a focusable `role="option"` with no
165
+ * accessible name), then the remaining `items` are filtered by `query` via `filter` (or the
166
+ * built-in default). */
165
167
  get filteredItems():readonly Readonly<LyraMentionItem>[];
166
168
  /** The internal id of the currently highlighted row, for same-tree consumers only. */
167
169
  get activeDescendantId():string|null;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=Math.min(rows.length-1,this.clampedIndex(rows)+1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=Math.max(0,this.clampedIndex(rows)-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){return rows.length?Math.min(Math.max(this.activeIndex,0),rows.length-1):-1}rowId(index){return`${this._listId}-opt-${index}`}commit(item){const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start"});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=Math.min(rows.length-1,this.clampedIndex(rows)+1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=Math.max(0,this.clampedIndex(rows)-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){return rows.length?Math.min(Math.max(this.activeIndex,0),rows.length-1):-1}rowId(index){return`${this._listId}-opt-${index}`}commit(item){const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start"});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
2
2
  <div
3
3
  part="option"
4
4
  id=${id}
@@ -93,4 +93,12 @@ searchNext():Promise<boolean>;
93
93
  searchPrevious():Promise<boolean>;
94
94
  /** Clears the query, matches, and active index, and resets `lr-search-change` to a
95
95
  * 0-match/no-active-index state. */
96
- clearSearch():void;private emitSearchChange;private stopInternalEvent;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-csv-viewer':LyraCsvViewer;}}export{};
96
+ clearSearch():void;private emitSearchChange;private stopInternalEvent;
97
+ /** Memoized `<lr-virtual-list>.items`/`.renderItem` inputs, keyed on the exact `rows` array
98
+ * reference and `hasHeaderRow` -- a fresh `body` array and `renderItem` closure on every
99
+ * render() (a search keystroke, active-row change, locale change, all unrelated to the data
100
+ * itself) would otherwise defeat the virtual list's own offset-cache memoization on every one
101
+ * of those, forcing its O(n) `recomputeOffsets()` and clearing measured row heights. `renderItem`
102
+ * still reads live `this` state (highlights, etc.) on every call -- only its own identity is
103
+ * cached, not its output. */
104
+ private virtualListInputsCache?;private virtualListInputs;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-csv-viewer':LyraCsvViewer;}}export{};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{parseCellRange}from"../../../internal/cell-range.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{styles}from"./csv-viewer.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{delimitedCellText as cell,delimitedColumnCount as columns,parseDelimitedGrid}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_csvViewerLabel,LYRA_DEFAULT_csvViewerUnavailable,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3;function headerOffset(hasHeaderRow){return hasHeaderRow?1:0}class LyraCsvViewerBase extends LyraElement{}class LyraCsvViewer extends DocumentAnchorTarget(LyraCsvViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.hasHeaderRow=!0,this.maxHeight="",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.loadLibrary=loadPapaParseCached,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,csvViewerLabel:LYRA_DEFAULT_csvViewerLabel,csvViewerUnavailable:LYRA_DEFAULT_csvViewerUnavailable,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const library=await this.loadLibrary();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!library){const error=new LyraUserFacingError(this.localize("csvViewerUnavailable"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const result=parseDelimitedGrid(library,source);if(!this.isConnected||!this.loadTask.isCurrent(generation)||(this.fetchState={kind:"loaded",rows:result.data},this.searchQuery&&await this.search(this.searchQuery),!this.isConnected||!this.loadTask.isCurrent(generation)))return;result.errors.length&&this.emit("lr-render-error",{error:result.errors})}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol);if(!colHighlights.length)return html`<div part="cell" role=${role}>${cell(value)}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],text=cell(value),accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value:text,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:text});return html`<div
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{parseCellRange}from"../../../internal/cell-range.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{styles}from"./csv-viewer.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{delimitedCellText as cell,delimitedColumnCount as columns,parseDelimitedGrid}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_csvViewerLabel,LYRA_DEFAULT_csvViewerUnavailable,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3;function headerOffset(hasHeaderRow){return hasHeaderRow?1:0}function indexKeyFunction(_item,index){return index}class LyraCsvViewerBase extends LyraElement{}class LyraCsvViewer extends DocumentAnchorTarget(LyraCsvViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.hasHeaderRow=!0,this.maxHeight="",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.loadLibrary=loadPapaParseCached,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,csvViewerLabel:LYRA_DEFAULT_csvViewerLabel,csvViewerUnavailable:LYRA_DEFAULT_csvViewerUnavailable,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,noData:LYRA_DEFAULT_noData}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const library=await this.loadLibrary();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!library){const error=new LyraUserFacingError(this.localize("csvViewerUnavailable"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const result=parseDelimitedGrid(library,source);if(!this.isConnected||!this.loadTask.isCurrent(generation)||(this.fetchState={kind:"loaded",rows:result.data},this.searchQuery&&await this.search(this.searchQuery),!this.isConnected||!this.loadTask.isCurrent(generation)))return;result.errors.length&&this.emit("lr-render-error",{error:result.errors})}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol);if(!colHighlights.length)return html`<div part="cell" role=${role}>${cell(value)}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],text=cell(value),accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value:text,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:text});return html`<div
2
2
  part="cell cell-highlight"
3
3
  role=${role}
4
4
  ?data-active=${!!active}
@@ -19,7 +19,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
19
19
  style=${`grid-template-columns:repeat(${count},minmax(var(--lr-size-8rem),1fr))`}
20
20
  >
21
21
  ${Array.from({length:count},(_unused,index)=>this.renderCell(row[index],index,rowHighlights,header?"columnheader":"cell"))}
22
- </div>`}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{rows}=loadedState;if(rawRow<1||rawRow>rows.length||col<0||col>=columns(rows))return!1;const bodyIndex=rawRow-1-headerOffset(this.hasHeaderRow);if(bodyIndex<0){const target=this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="cell"]')[col];return target?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"}),!!target}return this.activeRowKey=bodyIndex,await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async scrollColumnIntoView(col){const list=this.renderRoot.querySelector("lr-virtual-list");if(list?.updateComplete&&await list.updateComplete,!await this.waitForOwnerAnimationFrame())return;list?.shadowRoot?.querySelector('[part="row"][aria-current="true"]')?.querySelectorAll('[part~="cell"]')[col]?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"})}async search(query){this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale),trimmed=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&trimmed&&this.fetchState.kind==="loaded"){const budget=new ViewerSearchWorkBudget,{rows}=this.fetchState;searchRows:for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<row.length;c++){if(budget.includes(cell(row[c]),trimmed,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break searchRows}matches.push({row:r+1,col:c})}if(!budget.complete){matchCountExact=!1;break searchRows}}}}return this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.jumpToCell(matches[0].row,matches[0].col),matches.length}async searchNext(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}async searchPrevious(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}render(){const label=viewerSemanticLabel(this,this.name||this.localize("csvViewerLabel"));let content;if(this.fetchState.kind==="loaded"){const rows=this.fetchState.rows;if(!rows.length)content=html`<p class="empty-note">${this.localize("noData")}</p>`;else{const header=this.hasHeaderRow?rows[0]:void 0,body=this.hasHeaderRow?rows.slice(1):rows,count=columns(rows),tableLabel=hostAriaLabel(this)??(this.name||this.localize("csvViewerLabel"));content=html`<div
22
+ </div>`}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{rows}=loadedState;if(rawRow<1||rawRow>rows.length||col<0||col>=columns(rows))return!1;const bodyIndex=rawRow-1-headerOffset(this.hasHeaderRow);if(bodyIndex<0){const target=this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="cell"]')[col];return target?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"}),!!target}return this.activeRowKey=bodyIndex,await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async scrollColumnIntoView(col){const list=this.renderRoot.querySelector("lr-virtual-list");if(list?.updateComplete&&await list.updateComplete,!await this.waitForOwnerAnimationFrame())return;list?.shadowRoot?.querySelector('[part="row"][aria-current="true"]')?.querySelectorAll('[part~="cell"]')[col]?.scrollIntoView({behavior:prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth",block:"nearest",inline:"nearest"})}async search(query){this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale),trimmed=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&trimmed&&this.fetchState.kind==="loaded"){const budget=new ViewerSearchWorkBudget,{rows}=this.fetchState;searchRows:for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<row.length;c++){if(budget.includes(cell(row[c]),trimmed,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break searchRows}matches.push({row:r+1,col:c})}if(!budget.complete){matchCountExact=!1;break searchRows}}}}return this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.jumpToCell(matches[0].row,matches[0].col),matches.length}async searchNext(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}async searchPrevious(){if(!this.searchMatches.length)return!1;this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange();const match=this.searchMatches[this.searchActiveIndex];return await this.jumpToCell(match.row,match.col),!0}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex})}virtualListInputs(rows,hasHeaderRow){const cached=this.virtualListInputsCache;if(cached&&cached.rows===rows&&cached.hasHeaderRow===hasHeaderRow)return cached;const body=hasHeaderRow?rows.slice(1):rows,count=columns(rows),next={rows,hasHeaderRow,body,renderItem:(row,index)=>this.renderRow(row,count,"data-row",index+1+headerOffset(hasHeaderRow))};return this.virtualListInputsCache=next,next}render(){const label=viewerSemanticLabel(this,this.name||this.localize("csvViewerLabel"));let content;if(this.fetchState.kind==="loaded"){const rows=this.fetchState.rows;if(!rows.length)content=html`<p class="empty-note">${this.localize("noData")}</p>`;else{const header=this.hasHeaderRow?rows[0]:void 0,count=columns(rows),{body,renderItem}=this.virtualListInputs(rows,this.hasHeaderRow),tableLabel=hostAriaLabel(this)??(this.name||this.localize("csvViewerLabel"));content=html`<div
23
23
  part="sheet"
24
24
  role="table"
25
25
  aria-label=${tableLabel}
@@ -30,8 +30,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
30
30
  part="rows"
31
31
  exportparts="data-row:data-row, cell:cell, cell-highlight:cell-highlight, cell-highlight-action:cell-highlight-action"
32
32
  .items=${body}
33
- .renderItem=${(row,index)=>this.renderRow(row,count,"data-row",index+1+headerOffset(this.hasHeaderRow))}
34
- .keyFunction=${(_item,index)=>index}
33
+ .renderItem=${renderItem}
34
+ .keyFunction=${indexKeyFunction}
35
35
  .activeItemId=${this.activeRowKey}
36
36
  item-role="row"
37
37
  row-index-offset=${this.hasHeaderRow?"1":"0"}
@@ -113,4 +113,4 @@ searchNext():Promise<boolean>;
113
113
  searchPrevious():Promise<boolean>;
114
114
  /** Clears the query, matches, and active index, and resets `lr-search-change` to a
115
115
  * 0-match/no-active-index state. */
116
- clearSearch():void;private emitSearchChange;private stopInternalEvent;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dataset-viewer':LyraDatasetViewer;}}export{};
116
+ clearSearch():void;private emitSearchChange;private stopInternalEvent;private readonly virtualListKeyFunction;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dataset-viewer':LyraDatasetViewer;}}export{};
@@ -1,6 +1,6 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{literalSetConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3,DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.cellHighlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{literalSetConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";const MAX_SEARCH_MATCHES=1e3,DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.activeRowKey="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.loadTask=new LatestTask,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.pendingAnimationFrames=new Set,this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.cellHighlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
2
2
  ${fields.map((field,col)=>this.renderCell(row[field]??"",col,rowHighlights))}
3
- </div>`},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.searchQuery&&await this.search(this.searchQuery),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-render-error",{error:parsed.errors})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}async parse(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role="cell"){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol),part=role==="columnheader"?"header-cell":"cell";if(!colHighlights.length)return html`<div part=${part} role=${role}>${value}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:value});return html`<div
3
+ </div>`},this.stopInternalEvent=event=>{event.stopPropagation()},this.virtualListKeyFunction=(_item,index)=>index}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.loadTask.next(),this.cancelPendingAnimationFrames(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelPendingAnimationFrames(),this.announcements.adopted()}waitForOwnerAnimationFrame(){const owner=this.ownerDocument.defaultView;return!owner||!this.isConnected?Promise.resolve(!1):new Promise(resolve=>{const pending={owner,resolve};this.pendingAnimationFrames.add(pending),pending.handle=owner.requestAnimationFrame(()=>{this.pendingAnimationFrames.delete(pending)&&resolve(this.isConnected&&this.ownerDocument.defaultView===owner)})})}cancelPendingAnimationFrames(){const pendingFrames=[...this.pendingAnimationFrames];this.pendingAnimationFrames.clear();for(const pending of pendingFrames)pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle),pending.resolve(!1)}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.activeRowKey="")}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}async load(){this.lastLoadSrc=this.src;const generation=this.loadTask.next(),signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.searchQuery&&await this.search(this.searchQuery),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-render-error",{error:parsed.errors})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(generation))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}async parse(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}cellHighlightsForRow(rawRow){const seen=new Set;return this.highlights.filter(highlight=>seen.has(highlight.id)?!1:(seen.add(highlight.id),!0)).flatMap(highlight=>{if(highlight.anchor.kind!=="cell-range"||highlight.anchor.sheet)return[];const parsed=parseCellRange(highlight.anchor.range);return parsed?rawRow-1>=parsed.startRow&&rawRow-1<=parsed.endRow?[{highlight,parsed}]:[]:[]})}renderCell(value,colIndex,rowHighlights,role="cell"){const colHighlights=rowHighlights.filter(entry=>colIndex>=entry.parsed.startCol&&colIndex<=entry.parsed.endCol),part=role==="columnheader"?"header-cell":"cell";if(!colHighlights.length)return html`<div part=${part} role=${role}>${value}</div>`;const active=colHighlights.find(entry=>entry.highlight.id===this.activeHighlightId),primary=active??colHighlights[0],accessibleLabel=primary.highlight.label?this.localize("cellHighlightWithLabel",void 0,{value,label:primary.highlight.label}):this.localize("highlightWithLabel",void 0,{label:value});return html`<div
4
4
  part="${part} cell-highlight"
5
5
  role=${role}
6
6
  ?data-active=${!!active}
@@ -27,9 +27,9 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
27
27
  </div>
28
28
  <lr-virtual-list
29
29
  exportparts="data-row:data-row, cell:cell, cell-highlight:cell-highlight, cell-highlight-action:cell-highlight-action"
30
- .items=${rows}
30
+ .items=${guard([rows],()=>rows)}
31
31
  .renderItem=${(row,index)=>this.renderRow(row,index,fields)}
32
- .keyFunction=${(_item,index)=>index}
32
+ .keyFunction=${this.virtualListKeyFunction}
33
33
  .activeItemId=${this.activeRowKey}
34
34
  item-role="row"
35
35
  row-index-offset="1"
@@ -115,6 +115,11 @@ languages?:Readonly<Record<string,ShikiLanguageInput>>;
115
115
  /** Whether scrolling one `view="side-by-side"` pane proportionally scrolls the other. See the
116
116
  * class doc's "Synchronized anchors" section. */
117
117
  syncScroll:boolean;
118
+ /** A CSS length (e.g. `"30rem"`); once set, overrides `--lr-document-compare-pane-max-height` --
119
+ * the max block size of each `view="side-by-side"` pane -- declaratively, the same `max-height`
120
+ * attribute every other content-viewer sibling exposes, rather than requiring a consumer to set
121
+ * the differently-named CSS custom property inline. Invalid values are ignored. */
122
+ maxHeight:string;
118
123
  /** A shared scroll-to-anchor target forwarded to both `view="side-by-side"` panes'
119
124
  * `scrollToAnchor()`. `hasChanged: () => true` so re-assigning the same value (e.g. re-clicking
120
125
  * the same source reference) still re-fires, mirroring `<lr-document-viewer>`'s identical