@aceshooting/lyra-ui 30.8.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/CHANGELOG.md +239 -329
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  4. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  5. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  6. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  7. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  8. package/dist/components/charts/chart/box-plot-loader.js +1 -1
  9. package/dist/components/charts/chart/box-plot.class.js +2 -2
  10. package/dist/components/charts/chart/chart-core-loader.js +1 -1
  11. package/dist/components/charts/chart/chart-feature-loader.js +1 -1
  12. package/dist/components/charts/chart/chart-sync.js +1 -1
  13. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  14. package/dist/components/charts/chart/chart.class.js +4 -4
  15. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  16. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  17. package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -1
  18. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  19. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  20. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  21. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  22. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  23. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  24. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  25. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  26. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  27. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  28. package/dist/components/conversation/code-block/code-loader.js +1 -1
  29. package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -1
  30. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  31. package/dist/components/conversation/markdown/katex-loader.js +1 -1
  32. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  33. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  34. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  35. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  36. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  37. package/dist/components/conversation/markdown/markdown-loader.js +1 -1
  38. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  39. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  40. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  41. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  42. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  43. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  44. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  45. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  46. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  47. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  48. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  49. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  50. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  51. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  52. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  53. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  54. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  55. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  56. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  57. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  58. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  59. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  60. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  61. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  62. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  63. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  64. package/dist/components/data/pagination/pagination.class.js +1 -1
  65. package/dist/components/data/table/table.class.d.ts +31 -2
  66. package/dist/components/data/table/table.class.js +3 -3
  67. package/dist/components/data/table/table.styles.js +1 -1
  68. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  69. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  70. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  71. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  72. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  73. package/dist/components/data/timeline/timeline.class.js +9 -5
  74. package/dist/components/data/tree/tree-item.class.js +1 -1
  75. package/dist/components/data/tree/tree.class.d.ts +2 -0
  76. package/dist/components/data/tree/tree.class.js +1 -1
  77. package/dist/components/forms/button/button.class.d.ts +8 -6
  78. package/dist/components/forms/button/button.class.js +2 -2
  79. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  80. package/dist/components/forms/color-picker/color-core.js +1 -1
  81. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  82. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  83. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  84. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  85. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  86. package/dist/components/forms/input/input-shared.js +2 -2
  87. package/dist/components/forms/input/number-input-locale.js +1 -0
  88. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  89. package/dist/components/forms/input/number-input.class.js +2 -2
  90. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  91. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  92. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  93. package/dist/components/layout/details/accordion-item.class.js +1 -1
  94. package/dist/components/layout/menu/menu.class.js +1 -1
  95. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  96. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  97. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  98. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  99. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  100. package/dist/components/layout/tab-group/tab.class.js +1 -1
  101. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  102. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  103. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  104. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  105. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  106. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  107. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  108. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  109. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  110. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  111. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  112. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -1
  113. package/dist/components/media/flag/flag-peer-bulk.js +1 -1
  114. package/dist/components/media/flag/flag-peer.js +1 -1
  115. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  116. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  117. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  118. package/dist/components/media/map/map-feature-loader.js +1 -1
  119. package/dist/components/media/map/map-loader.js +1 -1
  120. package/dist/components/media/map/map-owned-features.js +1 -1
  121. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  122. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  123. package/dist/components/media/map/map.class.d.ts +5 -5
  124. package/dist/components/media/map/map.class.js +3 -3
  125. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  126. package/dist/components/media/qr-code/qr-code-loader.js +1 -1
  127. package/dist/components/media/video/video.class.d.ts +3 -3
  128. package/dist/components/media/video/video.class.js +3 -1
  129. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  130. package/dist/components/overlays/chip/chip.class.js +1 -1
  131. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  132. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  133. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  134. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  135. package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -1
  136. package/dist/components/retrieval/graph/graph-loader.js +1 -1
  137. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  138. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  139. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  140. package/dist/components/retrieval/graph/graph.class.js +1 -1
  141. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  142. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  143. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  144. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  145. package/dist/components/utility/icon/dompurify-loader.js +1 -1
  146. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  147. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  148. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  149. package/dist/components/utility/known-date/known-date.class.js +1 -1
  150. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  151. package/dist/components/viewers/calendar-viewer/calendar-loader.js +1 -1
  152. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  153. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  154. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  155. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  156. package/dist/components/viewers/docx-viewer/docx-loader.js +1 -1
  157. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  158. package/dist/components/viewers/ebook-viewer/ebook-loader.js +1 -1
  159. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  160. package/dist/components/viewers/ebook-viewer/epub-unload-guard.js +1 -0
  161. package/dist/components/viewers/email-viewer/email-loader.js +1 -1
  162. package/dist/components/viewers/html-viewer/dompurify-loader.js +1 -1
  163. package/dist/components/viewers/include/include.class.js +1 -1
  164. package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
  165. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  166. package/dist/components/viewers/notebook-viewer/dompurify-loader.js +1 -1
  167. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  168. package/dist/components/viewers/pdf-viewer/pdf-loader.js +1 -1
  169. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  170. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  171. package/dist/components/viewers/pptx-viewer/pptx-loader.js +1 -1
  172. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-loader.js +1 -1
  173. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  174. package/dist/components/viewers/svg-viewer/dompurify-loader.js +1 -1
  175. package/dist/components/viewers/table-viewer-shared.js +4 -4
  176. package/dist/framework-types.d.ts +1 -1
  177. package/dist/internal/anchored-overlay-runtime.js +1 -1
  178. package/dist/internal/catalog-picker.js +1 -1
  179. package/dist/internal/document-tokens.js +2 -2
  180. package/dist/internal/dompurify-loader.js +1 -1
  181. package/dist/internal/drop-session-controller.js +1 -1
  182. package/dist/internal/engine-3d.js +1 -1
  183. package/dist/internal/icon-only-content.js +1 -1
  184. package/dist/internal/layered-layout.js +1 -1
  185. package/dist/internal/locale-loaders.generated.js +1 -1
  186. package/dist/internal/map-custom-layer-controller.js +1 -1
  187. package/dist/internal/map-scene-layer-runtime.js +1 -1
  188. package/dist/internal/media-panorama.js +1 -1
  189. package/dist/internal/package-metadata.js +1 -1
  190. package/dist/internal/papaparse-loader.js +1 -1
  191. package/dist/internal/safe-url.js +1 -1
  192. package/dist/internal/scoped-definitions.generated.js +1 -1
  193. package/dist/internal/scroll-overflow.js +1 -1
  194. package/dist/internal/source-window-controller.js +1 -1
  195. package/dist/internal/text-quote.js +1 -1
  196. package/dist/internal/viewer-search.js +1 -1
  197. package/dist/lyra.d.ts +1 -1
  198. package/dist/sequence-time-binding.js +1 -1
  199. package/dist/simulation-clock.js +1 -1
  200. package/dist/styles/reservations.css +1 -1
  201. package/dist/styles/reservations.styles.js +1 -1
  202. package/dist/testing/happy-dom-shims.js +1 -1
  203. package/dist/theme/theme.js +1 -1
  204. package/dist/theme-core.css +1 -0
  205. package/dist/utilities/scoped-registry.js +1 -1
  206. package/llms/components/lr-attachment-chip.md +27 -12
  207. package/llms/components/lr-attachment-trigger.md +27 -7
  208. package/llms/components/lr-button.md +6 -4
  209. package/llms/components/lr-chat-composer.md +13 -7
  210. package/llms/components/lr-chat-message.md +44 -3
  211. package/llms/components/lr-chat-viewport.md +39 -2
  212. package/llms/components/lr-data-grid.md +2 -0
  213. package/llms/components/lr-dialog.md +10 -0
  214. package/llms/components/lr-drop-zone.md +26 -2
  215. package/llms/components/lr-icon-button.md +2 -1
  216. package/llms/components/lr-json-viewer.md +17 -0
  217. package/llms/components/lr-locale-picker.md +5 -0
  218. package/llms/components/lr-markdown-core.md +2 -1
  219. package/llms/components/lr-markdown.md +20 -4
  220. package/llms/components/lr-menu.md +3 -1
  221. package/llms/components/lr-number-input.md +28 -1
  222. package/llms/components/lr-prompt-input.md +1 -1
  223. package/llms/components/lr-streaming-text-core.md +3 -2
  224. package/llms/components/lr-streaming-text.md +4 -1
  225. package/llms/components/lr-suggestion-chips.md +28 -5
  226. package/llms/components/lr-tab-group.md +13 -1
  227. package/llms/components/lr-tab.md +5 -0
  228. package/llms/components/lr-table.md +25 -4
  229. package/llms/components/lr-timeline-item.md +1 -1
  230. package/llms/components/lr-timeline.md +38 -4
  231. package/llms/components/lr-tooltip.md +3 -1
  232. package/llms/components/lr-tree.md +4 -0
  233. package/llms/components/lr-virtual-list.md +1 -0
  234. package/llms/peers.md +2 -2
  235. package/llms/shared/ai-and-peers.md +34 -0
  236. package/llms/shared/forms-and-accessibility.md +21 -4
  237. package/llms/shared/imports-and-registration.md +2 -0
  238. package/llms/shared/styles-and-tokens.md +47 -1
  239. package/llms/shared.md +104 -5
  240. package/package.json +25 -21
  241. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{SourceRequestController}from"../../../internal/source-request-controller.js";import{prepareChartModel,revealPreparedSourcePoint}from"./chart-prepared-data.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{LazyChartSyncController}from"./chart-sync-lazy.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{collectionSupport,snapshotPublicCollection,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues,chartSeriesValueLimit}from"./chart-series-bounds.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{decimalPlaces,finiteAdd,finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{bidiStyles,isolateHtml,isolatedMessage}from"./chart-bidi.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes,normalizeChartRecordLimit}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{categoryLabelGrowth,hasCategoryLabelText,sparseCategoryLabelExtent,visibleCategoryLabelIndexes,widestEstimatedCategoryLabel}from"./lite-chart-axis-layout.js";import{LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartInputLimit,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartPreparedSummary,LYRA_DEFAULT_chartPreparedUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";function isLiteChartSeries(value){return hasArraySeriesData(value)}function normalizeLiteChartSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isLiteChartSeries):[])}catch{return Object.freeze([])}}function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),autoNumberConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();return trimmed.toLowerCase()==="auto"?"auto":Number(trimmed)}},DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,AUTO_CATEGORY_LABEL_INSET=10,VALUE_AXIS_TICK_OFFSET=6,AUTO_VALUE_AXIS_SAFETY_INSET=8,MAX_AUTO_VALUE_AXIS_GUTTER=240,MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION=.4,MAX_SCROLL_CONTENT_WIDTH=1e6,CATEGORY_LABEL_SELECTION_BOUNDS=Object.freeze({characterWidth:APPROX_LABEL_CHARACTER_WIDTH,laneInset:AUTO_CATEGORY_LABEL_INSET,maxContentWidth:MAX_SCROLL_CONTENT_WIDTH,maxRenderedRecords:MAX_RENDERED_CHART_RECORDS});function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function snapToStep(value,step){return Number.isFinite(step)&&step>0?Number(value.toFixed(Math.min(decimalPlaces(step),100))):value}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return Number((lo*(1-ratio)+hi*ratio).toPrecision(15))}).filter(Number.isFinite)}function logarithmicTicks(lo,hi,count){if(!(lo>0&&hi>lo)||!Number.isFinite(lo)||!Number.isFinite(hi))return;const start=Math.log10(lo),end=Math.log10(hi),span=end-start;if(!(span>0))return;const decades=span>=1,step=decades?Math.ceil(span/count):niceStep(hi-lo,count);if(!Number.isFinite(step)||step<=0)return[...new Set(safeDomainTicks(lo,hi,count))];const ticks=[lo],minimumGap=decades?step/2:span/(count*2),first=Math.ceil((decades?start:lo)/step);for(let index=0;index<=count+1;index++){const value=decades?10**((first+index)*step):snapToStep((first+index)*step,step);if(!Number.isFinite(value)||value>=hi)break;if(value<=ticks.at(-1))continue;const logarithm=Math.log10(value);logarithm-Math.log10(ticks.at(-1))>=minimumGap&&end-logarithm>=minimumGap&&ticks.push(value)}return ticks.push(hi),ticks}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const snap=value=>snapToStep(value,step),roundedLo=snap(Math.floor(lo/step)*step),roundedHi=snap(Math.ceil(hi/step)*step);Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=snap(lo+index*step);Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this._preparedData=null,this.preparedDirty=!0,this.preparedActive=!1,this.preparedChanged=!1,this.preparedInvalid=!1,this.preparedPending=!1,this.preparedRequestFailed=!1,this.announcedPreparedInvalid=!1,this.preparedRequests=new SourceRequestController(this,{channels:["point"],onReset:()=>{this.preparedPending=!1}}),this.labels=[],this.maxRecords=1e3,this._datasets=Object.freeze([]),this.datasetsTruncated=!1,this.datasetsSources=new CollectionSourceTracker,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.stacked=!1,this.tableTotals=!1,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.hostAccessibleLabel=null,this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this._activeMarkIndex=0,this.syncPlot={y:0,height:0},this.syncCategoryPositions=new Map,this.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.themeWatcher=new ThemeWatcher(this,()=>this.requestUpdate()),this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.syncGroup="",this.chartSync=new LazyChartSyncController(this,(label,index)=>this.syncPresentation(label,index),void 0,target=>target.nodeType===1&&target.hasAttribute("data-mark-index"),()=>this.requestUpdate()),this.deferredTableGeneration=0,this.streamingTableUpdate=!1}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartInputLimit:LYRA_DEFAULT_chartInputLimit,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPreparedSummary:LYRA_DEFAULT_chartPreparedSummary,chartPreparedUnavailable:LYRA_DEFAULT_chartPreparedUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSummary:LYRA_DEFAULT_chartSummary,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}get preparedData(){return this._preparedData}set preparedData(value){const previous=this._preparedData;this._preparedData=value,this.requestUpdate("preparedData",previous),value===previous&&this.requestUpdate()}refreshPreparedModel(){if(!this.preparedDirty)return;this.preparedDirty=!1,this.preparedChanged=!0,this.preparedInvalid=!1,this.preparedRequestFailed=!1,this.preparedBaseModel=this.preparedModel=void 0,this.preparedEffective=void 0;const input=this._preparedData;this.preparedActive=input!==null;try{if(input!==null){const model=prepareChartModel(input,this.effectiveType,normalizeChartRecordLimit(this.maxRecords));if(model.kind==="series"&&this.stacked)throw new TypeError("Ordered series cannot be stacked");this.preparedBaseModel=this.preparedModel=model,this.preparedRequests.setSource(input,model.revision)}else this.preparedRequests.setSource(void 0,void 0)}catch{this.preparedInvalid=!0,this.preparedRequests.setSource(void 0,void 0)}}async revealSourcePoint(ref){if(!this.isConnected||!ref||typeof ref.seriesId!="string")return!1;ref=Object.freeze({seriesId:ref.seriesId,sourceIndex:ref.sourceIndex}),this.preparedDirty&&await this.updateComplete;const model=this.preparedBaseModel;if(!model||model.kind!=="series")return!1;const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series||!Number.isSafeInteger(ref.sourceIndex)||ref.sourceIndex<0||ref.sourceIndex>=series.counts.sourceCount)return!1;const lease=this.preparedRequests.begin("point",this.effectiveLocale);if(!lease)return!1;this.preparedPending=!0,this.preparedRequestFailed=!1,this.requestUpdate("preparedView",null);const signal=lease.context.signal;try{const result=await revealPreparedSourcePoint(model,ref,signal,()=>lease.isCurrent()&&this.preparedBaseModel===model);return result.status!=="ready"||!lease.isCurrent()||this.preparedBaseModel!==model||model.source.revision!==model.revision?!1:(this.preparedModel=result.model,this.preparedChanged=!0,this.preparedEffective=void 0,this.recordSampleMemo=void 0,this.marksMemo=void 0,this.dataTableRows=void 0,!0)}catch{return lease.isCurrent()&&(this.preparedRequestFailed=!0,this.announcements.announceAssertive(this.localize("chartPreparedUnavailable"))),!1}finally{lease.isCurrent()&&(this.preparedPending=!1,this.requestUpdate("preparedView",null))}}get displayDatasets(){if(!this.preparedActive)return this.datasets;const model=this.preparedModel;if(!model)return[];if(this.preparedEffective?.model===model)return this.preparedEffective.datasets;const datasets=model.series.map(series=>Object.freeze({label:series.label,data:model.kind==="series"?Object.freeze(series.samples.map(point=>point?.y??null)):series.values}));return this.preparedEffective={model,datasets},datasets}get displayLabels(){return this.preparedActive?this.preparedModel?.labels??[]:this.labels}datumLabel(datasetIndex,index){const point=this.preparedModel?.kind==="series"?this.preparedModel.series[datasetIndex]?.samples[index]:void 0;return point?`${point.sourceIndex}: ${this.localize("chartPointCoordinates",void 0,{x:formatChartValue(point.x,this.effectiveLocale),y:point.y===null?"":formatChartValue(point.y,this.effectiveLocale)})}`:this.displayLabels[index]??""}preparedX(datasetIndex,index,plotX,plotW){const model=this.preparedModel,point=model?.series[datasetIndex]?.samples[index];if(!model||!point)return plotX;let lo=1/0,hi=-1/0;for(const series of model.series)series.xDomain&&(lo=Math.min(lo,series.xDomain.min),hi=Math.max(hi,series.xDomain.max));const fraction=lo===hi?.5:domainFraction(point.x,lo,hi);return plotX+(this.effectiveDirection==="rtl"?1-fraction:fraction)*plotW}preparedDescription(){const model=this.preparedModel;if(!model)return this.description??"";const summary=this.localize("chartPreparedSummary",void 0,{validCount:formatChartValue(model.validCount,this.effectiveLocale),invalidCount:formatChartValue(model.invalidCount,this.effectiveLocale),displayedCount:formatChartValue(model.displayedCount,this.effectiveLocale)}),domains=(this.preparedBaseModel??model).series.flatMap(series=>{if(!series.yDomain)return[];const first=series.samples[0]?.y??0,last=series.samples.at(-1)?.y??0;return[this.localize("chartSummary",void 0,{label:series.label,count:formatChartValue(series.counts.validCount,this.effectiveLocale),min:formatChartValue(series.yDomain.min,this.effectiveLocale),max:formatChartValue(series.yDomain.max,this.effectiveLocale),trend:this.localize(last>first?"chartTrendIncreasing":last<first?"chartTrendDecreasing":"chartTrendFlat")})]});return[this.description,...domains,summary].filter(Boolean).join(this.localize("chartSummarySeparator"))}get datasets(){return this._datasets}set datasets(value){if(this.datasetsSources.isRebind("datasets",value,this._datasets))return;const previous=this._datasets,bounded=boundChartSeriesValues(value);this.datasetsTruncated=bounded!==void 0,this._datasets=normalizeLiteChartSeries(snapshotPublicCollection(bounded??value,this.ownerDocument?.defaultView,{onResult:result=>{this.datasetsTruncated||=result.truncated}})),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get activeMarkIndex(){return this._activeMarkIndex}set activeMarkIndex(index){index!==this._activeMarkIndex&&(this.renderRoot?.querySelector(`[data-mark-index="${this._activeMarkIndex}"]`)?.setAttribute("tabindex","-1"),this._activeMarkIndex=index,this.renderRoot?.querySelector(`[data-mark-index="${index}"]`)?.setAttribute("tabindex","0"))}appendData(label,values,maxPoints=0){if(this._preparedData===null){this.deferStreamedTable(),this.streamingTableUpdate=!0;try{const bound=chartSeriesValueLimit(this.datasets.length),requested=Math.max(0,finiteCount(maxPoints,0)),limit=requested>0?Math.min(requested,bound):bound;let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const retained=Math.min(domainLength+1,limit),start=domainLength+1-retained,labels=new Array(retained);for(let i=0;i<retained-1;i++)labels[i]=this.labels[start+i]??"";labels[retained-1]=label,this.labels=labels;const previous=this._datasets;this._datasets=Object.freeze(previous.map((series,index)=>{const data=new Array(retained);for(let i=0;i<retained-1;i++)data[i]=start+i<series.data.length?series.data[start+i]:null;return data[retained-1]=snapshotPublicCollection(values[index]??null,this.ownerDocument?.defaultView),Object.freeze({...series,data:Object.freeze(data)})})),this.datasetsSources.isRebind("datasets",this._datasets,previous),this.datasetsTruncated=!1,this.requestUpdate("datasets",previous)}finally{this.streamingTableUpdate=!1}}}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.displayDatasets.map(series=>series.label)].map(escapeCsvField).join(",");if(this.preparedModel?.kind==="series"){const rows2=[];return this.preparedModel.series.forEach((entry,datasetIndex)=>entry.samples.forEach((point,index)=>{if(!point||point.y===null)return;const label=this.datumLabel(datasetIndex,index),value=this.formatter?.({value:point.y,surface:"export",datasetIndex,index,label,seriesLabel:entry.label,axis:"y"})??point.y;rows2.push([label,...this.displayDatasets.map((_series,position)=>position===datasetIndex?value:"")].map(escapeCsvField).join(","))})),[header,...rows2].join(`\r
1
+ import{__decorate}from"tslib";import{SourceRequestController}from"../../../internal/source-request-controller.js";import{prepareChartModel,revealPreparedSourcePoint}from"./chart-prepared-data.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{LazyChartSyncController}from"./chart-sync-lazy.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{collectionSupport,snapshotPublicCollection,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues,chartSeriesValueLimit}from"./chart-series-bounds.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{decimalPlaces,finiteAdd,finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{bidiStyles,isolateHtml,isolatedMessage}from"./chart-bidi.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes,normalizeChartRecordLimit}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{categoryLabelGrowth,hasCategoryLabelText,sparseCategoryLabelExtent,visibleCategoryLabelIndexes,widestEstimatedCategoryLabel}from"./lite-chart-axis-layout.js";import{LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartInputLimit,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartPreparedSummary,LYRA_DEFAULT_chartPreparedUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";function isLiteChartSeries(value){return hasArraySeriesData(value)}function normalizeLiteChartSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isLiteChartSeries):[])}catch{return Object.freeze([])}}function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),autoNumberConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();return trimmed.toLowerCase()==="auto"?"auto":Number(trimmed)}},DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,AUTO_CATEGORY_LABEL_INSET=10,VALUE_AXIS_TICK_OFFSET=6,AUTO_VALUE_AXIS_SAFETY_INSET=8,MAX_AUTO_VALUE_AXIS_GUTTER=240,MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION=.4,MAX_SCROLL_CONTENT_WIDTH=1e6,CATEGORY_LABEL_SELECTION_BOUNDS=Object.freeze({characterWidth:APPROX_LABEL_CHARACTER_WIDTH,laneInset:AUTO_CATEGORY_LABEL_INSET,maxContentWidth:MAX_SCROLL_CONTENT_WIDTH,maxRenderedRecords:MAX_RENDERED_CHART_RECORDS});function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const relativeSpan=(top-bottom)/bottom,fraction=relativeSpan<=1?Math.log1p((value-bottom)/bottom)/Math.log1p(relativeSpan):(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function snapToStep(value,step){const places=decimalPlaces(step);return Number.isFinite(step)&&step>0&&places<=100?Number(value.toFixed(places)):value}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return Number((lo*(1-ratio)+hi*ratio).toPrecision(15))}).filter(Number.isFinite)}function logarithmicTicks(lo,hi,count){if(!(lo>0&&hi>lo)||!Number.isFinite(lo)||!Number.isFinite(hi))return;const start=Math.log10(lo),end=Math.log10(hi),span=end-start;if(!(span>0))return;const decades=span>=1,step=decades?Math.ceil(span/count):niceStep(hi-lo,count);if(!Number.isFinite(step)||step<=0)return[...new Set(safeDomainTicks(lo,hi,count))];const ticks=[lo],minimumGap=decades?step/2:span/(count*2),first=Math.ceil((decades?start:lo)/step);for(let index=0;index<=count+1;index++){const value=decades?10**((first+index)*step):snapToStep((first+index)*step,step);if(!Number.isFinite(value)||value>=hi)break;if(value<=ticks.at(-1))continue;const logarithm=Math.log10(value);logarithm-Math.log10(ticks.at(-1))>=minimumGap&&end-logarithm>=minimumGap&&ticks.push(value)}return ticks.push(hi),ticks}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const snap=value=>snapToStep(value,step),roundedLo=snap(Math.floor(lo/step)*step),roundedHi=snap(Math.ceil(hi/step)*step);Number.isFinite(roundedLo)&&(lo=Math.min(lo,roundedLo)),Number.isFinite(roundedHi)&&(hi=Math.max(hi,roundedHi));const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=snap(lo+index*step);Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this._preparedData=null,this.preparedDirty=!0,this.preparedActive=!1,this.preparedChanged=!1,this.preparedInvalid=!1,this.preparedPending=!1,this.preparedRequestFailed=!1,this.announcedPreparedInvalid=!1,this.preparedRequests=new SourceRequestController(this,{channels:["point"],onReset:()=>{this.preparedPending=!1}}),this.labels=[],this.maxRecords=1e3,this._datasets=Object.freeze([]),this.datasetsTruncated=!1,this.datasetsSources=new CollectionSourceTracker,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.stacked=!1,this.tableTotals=!1,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.hostAccessibleLabel=null,this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this._activeMarkIndex=0,this.syncPlot={y:0,height:0},this.syncCategoryPositions=new Map,this.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.themeWatcher=new ThemeWatcher(this,()=>this.requestUpdate()),this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.syncGroup="",this.chartSync=new LazyChartSyncController(this,(label,index)=>this.syncPresentation(label,index),void 0,target=>target.nodeType===1&&target.hasAttribute("data-mark-index"),()=>this.requestUpdate()),this.deferredTableGeneration=0,this.streamingTableUpdate=!1}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartInputLimit:LYRA_DEFAULT_chartInputLimit,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPreparedSummary:LYRA_DEFAULT_chartPreparedSummary,chartPreparedUnavailable:LYRA_DEFAULT_chartPreparedUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSummary:LYRA_DEFAULT_chartSummary,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}get preparedData(){return this._preparedData}set preparedData(value){const previous=this._preparedData;this._preparedData=value,this.requestUpdate("preparedData",previous),value===previous&&this.requestUpdate()}refreshPreparedModel(){if(!this.preparedDirty)return;this.preparedDirty=!1,this.preparedChanged=!0,this.preparedInvalid=!1,this.preparedRequestFailed=!1,this.preparedBaseModel=this.preparedModel=void 0,this.preparedEffective=void 0;const input=this._preparedData;this.preparedActive=input!==null;try{if(input!==null){const model=prepareChartModel(input,this.effectiveType,normalizeChartRecordLimit(this.maxRecords));if(model.kind==="series"&&this.stacked)throw new TypeError("Ordered series cannot be stacked");this.preparedBaseModel=this.preparedModel=model,this.preparedRequests.setSource(input,model.revision)}else this.preparedRequests.setSource(void 0,void 0)}catch{this.preparedInvalid=!0,this.preparedRequests.setSource(void 0,void 0)}}async revealSourcePoint(ref){if(!this.isConnected||!ref||typeof ref.seriesId!="string")return!1;ref=Object.freeze({seriesId:ref.seriesId,sourceIndex:ref.sourceIndex}),this.preparedDirty&&await this.updateComplete;const model=this.preparedBaseModel;if(!model||model.kind!=="series")return!1;const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series||!Number.isSafeInteger(ref.sourceIndex)||ref.sourceIndex<0||ref.sourceIndex>=series.counts.sourceCount)return!1;const lease=this.preparedRequests.begin("point",this.effectiveLocale);if(!lease)return!1;this.preparedPending=!0,this.preparedRequestFailed=!1,this.requestUpdate("preparedView",null);const signal=lease.context.signal;try{const result=await revealPreparedSourcePoint(model,ref,signal,()=>lease.isCurrent()&&this.preparedBaseModel===model);return result.status!=="ready"||!lease.isCurrent()||this.preparedBaseModel!==model||model.source.revision!==model.revision?!1:(this.preparedModel=result.model,this.preparedChanged=!0,this.preparedEffective=void 0,this.recordSampleMemo=void 0,this.marksMemo=void 0,this.dataTableRows=void 0,!0)}catch{return lease.isCurrent()&&(this.preparedRequestFailed=!0,this.announcements.announceAssertive(this.localize("chartPreparedUnavailable"))),!1}finally{lease.isCurrent()&&(this.preparedPending=!1,this.requestUpdate("preparedView",null))}}get displayDatasets(){if(!this.preparedActive)return this.datasets;const model=this.preparedModel;if(!model)return[];if(this.preparedEffective?.model===model)return this.preparedEffective.datasets;const datasets=model.series.map(series=>Object.freeze({label:series.label,data:model.kind==="series"?Object.freeze(series.samples.map(point=>point?.y??null)):series.values}));return this.preparedEffective={model,datasets},datasets}get displayLabels(){return this.preparedActive?this.preparedModel?.labels??[]:this.labels}datumLabel(datasetIndex,index){const point=this.preparedModel?.kind==="series"?this.preparedModel.series[datasetIndex]?.samples[index]:void 0;return point?`${point.sourceIndex}: ${this.localize("chartPointCoordinates",void 0,{x:formatChartValue(point.x,this.effectiveLocale),y:point.y===null?"":formatChartValue(point.y,this.effectiveLocale)})}`:this.displayLabels[index]??""}preparedX(datasetIndex,index,plotX,plotW){const model=this.preparedModel,point=model?.series[datasetIndex]?.samples[index];if(!model||!point)return plotX;let lo=1/0,hi=-1/0;for(const series of model.series)series.xDomain&&(lo=Math.min(lo,series.xDomain.min),hi=Math.max(hi,series.xDomain.max));const fraction=lo===hi?.5:domainFraction(point.x,lo,hi);return plotX+(this.effectiveDirection==="rtl"?1-fraction:fraction)*plotW}preparedDescription(){const model=this.preparedModel;if(!model)return this.description??"";const summary=this.localize("chartPreparedSummary",void 0,{validCount:formatChartValue(model.validCount,this.effectiveLocale),invalidCount:formatChartValue(model.invalidCount,this.effectiveLocale),displayedCount:formatChartValue(model.displayedCount,this.effectiveLocale)}),domains=(this.preparedBaseModel??model).series.flatMap(series=>{if(!series.yDomain)return[];const first=series.samples[0]?.y??0,last=series.samples.at(-1)?.y??0;return[this.localize("chartSummary",void 0,{label:series.label,count:formatChartValue(series.counts.validCount,this.effectiveLocale),min:formatChartValue(series.yDomain.min,this.effectiveLocale),max:formatChartValue(series.yDomain.max,this.effectiveLocale),trend:this.localize(last>first?"chartTrendIncreasing":last<first?"chartTrendDecreasing":"chartTrendFlat")})]});return[this.description,...domains,summary].filter(Boolean).join(this.localize("chartSummarySeparator"))}get datasets(){return this._datasets}set datasets(value){if(this.datasetsSources.isRebind("datasets",value,this._datasets))return;const previous=this._datasets,bounded=boundChartSeriesValues(value);this.datasetsTruncated=bounded!==void 0,this._datasets=normalizeLiteChartSeries(snapshotPublicCollection(bounded??value,this.ownerDocument?.defaultView,{onResult:result=>{this.datasetsTruncated||=result.truncated}})),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get activeMarkIndex(){return this._activeMarkIndex}set activeMarkIndex(index){index!==this._activeMarkIndex&&(this.renderRoot?.querySelector(`[data-mark-index="${this._activeMarkIndex}"]`)?.setAttribute("tabindex","-1"),this._activeMarkIndex=index,this.renderRoot?.querySelector(`[data-mark-index="${index}"]`)?.setAttribute("tabindex","0"))}appendData(label,values,maxPoints=0){if(this._preparedData===null){this.deferStreamedTable(),this.streamingTableUpdate=!0;try{const bound=chartSeriesValueLimit(this.datasets.length),requested=Math.max(0,finiteCount(maxPoints,0)),limit=requested>0?Math.min(requested,bound):bound;let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const retained=Math.min(domainLength+1,limit),start=domainLength+1-retained,labels=new Array(retained);for(let i=0;i<retained-1;i++)labels[i]=this.labels[start+i]??"";labels[retained-1]=label,this.labels=labels;const previous=this._datasets;this._datasets=Object.freeze(previous.map((series,index)=>{const data=new Array(retained);for(let i=0;i<retained-1;i++)data[i]=start+i<series.data.length?series.data[start+i]:null;return data[retained-1]=snapshotPublicCollection(values[index]??null,this.ownerDocument?.defaultView),Object.freeze({...series,data:Object.freeze(data)})})),this.datasetsSources.isRebind("datasets",this._datasets,previous),this.datasetsTruncated=!1,this.requestUpdate("datasets",previous)}finally{this.streamingTableUpdate=!1}}}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.displayDatasets.map(series=>series.label)].map(escapeCsvField).join(",");if(this.preparedModel?.kind==="series"){const rows2=[];return this.preparedModel.series.forEach((entry,datasetIndex)=>entry.samples.forEach((point,index)=>{if(!point||point.y===null)return;const label=this.datumLabel(datasetIndex,index),value=this.formatter?.({value:point.y,surface:"export",datasetIndex,index,label,seriesLabel:entry.label,axis:"y"})??point.y;rows2.push([label,...this.displayDatasets.map((_series,position)=>position===datasetIndex?value:"")].map(escapeCsvField).join(","))})),[header,...rows2].join(`\r
2
2
  `)}const rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.displayLabels[index]??"";return[label,...this.displayDatasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label,axis:"y"})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
3
3
  `)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.requestUpdate(),this.armResizeObserver()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const svgEntry=entries.find(entry=>entry.target===target);if(svgEntry){const box=svgEntry.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=target.getBoundingClientRect();this.plotWidth=rect.width,this.plotHeight=rect.height}}entries.some(entry=>this.axisTitleTargets.has(entry.target))&&this.queueAxisTitleFit()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target),this.syncAxisTitleTargets()}disconnectedCallback(){this.preparedRequests.refresh(),this.preparedModel=this.preparedBaseModel=void 0,this.preparedEffective=void 0,this.preparedDirty=!0,this.clearDeferredTable(),this.chartSync.disconnect(),super.disconnectedCallback(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver()}adoptedCallback(){this.preparedRequests.adopted(),this.clearDeferredTable(),this.chartSync.disconnect(),super.adoptedCallback(),this.requestUpdate(),this.resetResizeObserver(),this.announcements.adopted(),this.isConnected?this.themeWatcher.hostConnected():this.themeWatcher.hostDisconnected(),this.refreshFitMeasurementAvailability()}resetResizeObserver(){this.axisTitleFrame!==void 0&&(this.resizeObserverDocument?.defaultView?.cancelAnimationFrame(this.axisTitleFrame),this.axisTitleFrame=void 0),this.axisTitleTargets.clear(),this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){super.willUpdate(changed),this.refreshPreparedModel();const shouldSync=this.preparedModel?.kind!=="series"&&this.isConnected&&typeof this.syncGroup=="string"&&this.syncGroup.trim()!=="";if(this.chartSync.enabled!==shouldSync&&this.chartSync.update(this.syncGroup,shouldSync),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!(this.preparedChanged||["type","labels","datasets","skipZero","maxRecords","plotWidth","layout"].some(name=>changed.has(name))))return;const active=shadowFocusTarget(this)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.preparedChanged=!1,this.setAttribute("aria-busy",String(this.preparedPending)),!wasMounting&&this.preparedInvalid&&!this.announcedPreparedInvalid&&this.announcements.announceAssertive(this.localize("chartPreparedUnavailable")),this.announcedPreparedInvalid=this.preparedInvalid,this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const inputLimit=this.inputLimitMessage(),sampling=this.dataTruncationMessage(),dataTruncation=inputLimit&&sampling?[inputLimit,sampling].join(this.localize("chartSummarySeparator")):inputLimit||sampling;wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),(changed.size===0||[...changed.keys()].some(name=>!["selectedIndices","dataTableExpandedOverride","dataTable","dataTableToggle","description","label"].includes(String(name))))&&(this.fitAxisTitles(),this.fitCategoryLabels()),this.syncAxisTitleTargets();const dataChanged=["datasets","labels","type","skipZero","layout","maxRecords","maxSeries"].some(name=>changed.has(name));this.chartSync.update(this.syncGroup,this.preparedModel?.kind!=="series",dataChanged)}fitAxisTitles(){if(!(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length))for(const title of this.svgEl.querySelectorAll('[part="axis-title"]')){const text=Array.from(title.childNodes).find(node=>node.nodeType===3);if(!text)continue;const source=title.getAttribute("aria-label")??"",extent=finiteRange(Number(title.getAttribute("data-title-extent")),0,0,MAX_SCROLL_CONTENT_WIDTH),previous=this.axisTitleFits.get(title);if(!(previous?.source===source&&previous.extent===extent&&previous.display===text.data&&previous.width===title.getComputedTextLength())){if(title.style.removeProperty("opacity"),text.data=source,title.getComputedTextLength()>extent)if(text.data="…",title.getComputedTextLength()>extent)title.style.opacity="0";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=`${source.slice(0,middle)}…`,title.getComputedTextLength()<=extent?lower=middle:upper=middle-1}const last=source.charCodeAt(lower-1);last>=55296&&last<=56319&&(lower-=1),text.data=`${source.slice(0,lower)}…`}this.axisTitleFits.set(title,{source,extent,display:text.data,width:title.getComputedTextLength()})}}}fitOneCategoryLabel(tick,x,anchor,extent){const width=this.fitCategoryBatch([{tick,extent}])[0]??0;return anchor==="start"?x+width:anchor==="end"?x-width:x}fitCategoryBatch(items){const candidates=items.map(({tick,extent})=>{const text=Array.from(tick.childNodes).find(node=>node.nodeType===3),source=tick.getAttribute("data-full-label")??"",bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);return tick.setAttribute("data-label-extent",String(bounded)),text&&(text.data=source),{tick,text,source,bounded,lower:0,upper:source.length,middle:0,overflow:!1}}),fullWidths=candidates.map(item=>item.tick.getComputedTextLength());candidates.forEach((item,index)=>{item.overflow=!!item.text&&fullWidths[index]>item.bounded});let searching=candidates.filter(item=>item.overflow&&item.source.length>1);for(;searching.length;){for(const item of searching)item.middle=Math.ceil((item.lower+item.upper)/2),item.text.data=`${item.source.slice(0,item.middle)}…`;const widths2=searching.map(item=>item.tick.getComputedTextLength());searching.forEach((item,index)=>{widths2[index]<=item.bounded?item.lower=item.middle:item.upper=item.middle-1}),searching=searching.filter(item=>item.lower<item.upper)}for(const item of candidates)if(item.text){if(item.overflow){const last=item.source.charCodeAt(item.lower-1);last>=55296&&last<=56319&&item.lower--,item.text.data=item.source.length?`${item.source.slice(0,item.lower)}…`:""}item.text.data===item.source?item.tick.removeAttribute("aria-label"):item.tick.setAttribute("aria-label",item.source)}return candidates.map(item=>item.tick.getComputedTextLength())}fitCategoryLabels(){if(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length)return;const ticks=[...this.svgEl.querySelectorAll('[part="axis-label"][data-full-label]')].filter(tick=>hasCategoryLabelText(tick.getAttribute("data-full-label"))).sort((a,b)=>Number(a.getAttribute("x"))-Number(b.getAttribute("x"))),count=ticks.length;if(count===0)return;const MARGIN=BAR_CORNER_RADIUS,positionOf=tick=>Number(tick.getAttribute("x"))||0,anchorOf=tick=>tick.getAttribute("text-anchor")??"middle",first=ticks[0],last=ticks[count-1],firstIsBoundary=count>1&&anchorOf(first)!=="middle",lastIsBoundary=count>1&&anchorOf(last)!=="middle";let firstRightEdge=positionOf(first),lastLeftEdge=positionOf(last);if(firstIsBoundary&&lastIsBoundary&&count===2){const half=Math.max(0,(positionOf(last)-positionOf(first))/2-MARGIN);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),half),lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),half)}else{if(firstIsBoundary){const gap=positionOf(ticks[1])-positionOf(first);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),gap-MARGIN)}if(lastIsBoundary){const gap=positionOf(last)-positionOf(ticks[count-2]);lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),gap-MARGIN)}}const interiors=[];for(let index=0;index<count;index++){if(index===0&&firstIsBoundary||index===count-1&&lastIsBoundary)continue;const tick=ticks[index],x=positionOf(tick),leftAvailable=index===0?MAX_SCROLL_CONTENT_WIDTH:index===1&&firstIsBoundary?x-firstRightEdge:(x-positionOf(ticks[index-1]))/2,rightAvailable=index===count-1?MAX_SCROLL_CONTENT_WIDTH:index===count-2&&lastIsBoundary?lastLeftEdge-x:(positionOf(ticks[index+1])-x)/2,extent=2*Math.min(leftAvailable,rightAvailable)-MARGIN;interiors.push({tick,extent})}this.fitCategoryBatch(interiors)}syncAxisTitleTargets(){if(!this.resizeObserver||!this.svgEl)return;const current=new Set(this.svgEl.querySelectorAll('[part="axis-title"]'));for(const title of this.axisTitleTargets)current.has(title)||this.resizeObserver.unobserve(title);for(const title of current)this.axisTitleTargets.has(title)||this.resizeObserver.observe(title);this.axisTitleTargets=current}queueAxisTitleFit(){const document=this.resizeObserverDocument,window=document?.defaultView;if(!window||this.axisTitleFrame!==void 0)return;const generation=this.resizeObserverGeneration,frame=window.requestAnimationFrame(()=>{this.axisTitleFrame!==frame||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==document||(this.axisTitleFrame=void 0,this.fitAxisTitles())});this.axisTitleFrame=frame}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return this.forcedColorsMemo??=forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
4
4
  ${this.recordSample().seriesIndexes.map(index=>{const series=this.displayDatasets[index],encoding=forcedColorEncoding(index).name,shapes=(()=>{switch(encoding){case"horizontal":return svg`<rect y=${half} width=${size} height="1" fill=${texture}></rect>`;case"vertical":return svg`<rect x=${half} width="1" height=${size} fill=${texture}></rect>`;case"diagonal":return svg`<path
@@ -1 +1 @@
1
- import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{Engine3dSelection,engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{finiteRange}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{normalizeChart3dCamera}from"./chart-3d-data.js";const chart3dPointsLoader=createEngine3dLoader({entry:"points",tag:tag("chart-3d"),load:()=>import("@aceshooting/lyra-3d/points")}),chart3dEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas")),visible:host=>isAccessibilityVisible(host)};class Chart3dEngineController{constructor(host,callbacks){this.host=host,this.callbacks=callbacks,this.selection=new Engine3dSelection(!1),this.notice=null,this.loading=!1,this.ready=!1,this.software=!1,this.generation=0,this.revision=0,this.disposed=new WeakSet,this.preference="builtin",this.selected=-1,this.cursor=-1,this.hover=-1,this.attempted=!1,this.configured=!1,this.contextLost=!1,this.intersecting=!1,this.cleanup=[]}dispose(engine){if(!(!engine||this.disposed.has(engine))){this.disposed.add(engine);try{engine.dispose()}catch{}}}invalidate(){const generation=++this.generation;this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.intersecting=!1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.styleObserver?.disconnect(),this.styleObserver=void 0;for(const cleanup of this.cleanup)cleanup();this.cleanup=[];const engine=this.engine;return this.engine=void 0,this.colorContext=void 0,this.loading=this.ready=this.configured=this.attempted=this.contextLost=this.software=!1,this.hover=-1,this.notice=null,this.selection.prefer(this.preference),this.dispose(engine),generation}disconnect(){this.invalidate()===this.generation&&(this.container=void 0,this.data=void 0)}update(data,container,preference,selected,cursor,camera){if(this.data!==data||this.container!==container||this.preference!==preference){if(this.invalidate()!==this.generation)return;this.data=data,this.container=container,this.preference=preference,this.selection.prefer(preference)}const cameraChanged=camera!==this.camera;if(this.camera=camera,this.selected=selected,this.cursor=cursor,this.engine&&this.configured&&!this.contextLost){const engine=this.engine,generation=this.generation,current=()=>generation===this.generation&&this.engine===engine;try{cameraChanged&&camera&&engine.setCamera(camera),current()&&this.syncState()}catch{current()&&this.fail("error")}if(!current())return}preference!=="webgl"||!data?.positions.length||!container||!this.host.isConnected||this.attempted||this.observer||this.eligibility||this.awaitAdmission(container)}awaitAdmission(container){const view=this.host.ownerDocument.defaultView,generation=this.generation;this.intersecting=view?.IntersectionObserver===void 0;const admit=()=>{generation!==this.generation||this.attempted||!this.intersecting||chart3dEngineEnvironment.visible(this.host)&&(this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.start())};if(view?.IntersectionObserver&&(this.observer=new view.IntersectionObserver(entries=>{if(generation===this.generation){for(const entry of entries)entry.target===container&&(this.intersecting=entry.isIntersecting);admit()}}),this.observer.observe(container)),view?.MutationObserver){this.eligibility=new view.MutationObserver(admit);let ancestor=this.host;for(let depth=0;ancestor&&depth<=256;depth++){this.eligibility.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","inert","hidden","style","class","open"]});const root=ancestor.getRootNode();ancestor=ancestor.assignedSlot??ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}admit()}fail(reason){const previous=this.notice,detail=this.selection.renderer==="webgl"?this.selection.fail(reason):null;if(reason==="context-lost")this.contextLost=!0,this.ready=this.loading=!1;else{if(this.invalidate()!==this.generation)return;this.selection.prefer("webgl"),this.selection.fail(reason),this.attempted=!0}if(this.notice=detail??previous,!detail){previous&&reason!=="context-lost"&&this.callbacks.changed();return}this.callbacks.changed(),this.callbacks.fallback(detail)}syncState(){this.engine?.setState?.({selected:new Set(this.selected<0?[]:[this.selected]),dimmed:new Set,hover:this.hover,focus:this.cursor})}async start(){const container=this.container,data=this.data,owner=this.host.ownerDocument;if(!container||!data||!this.host.isConnected||this.preference!=="webgl"||this.attempted)return;const generation=this.generation,current=()=>generation===this.generation&&this.host.isConnected&&this.host.ownerDocument===owner&&this.container===container;if(this.attempted=!0,!chart3dEngineEnvironment.available(owner)){this.fail("unsupported");return}this.loading=!0,this.callbacks.changed();let engine=null;try{if(engine=await chart3dPointsLoader.create(),!current()){this.dispose(engine??void 0);return}if(!engine){this.fail("unavailable");return}this.engine=engine;const mounted=engine,rowCount=data.positions.length/3,valid=index=>index!==null&&Number.isSafeInteger(index)&&index>=0&&index<rowCount;if(await engine.mount(container,{hover:index=>{if(!(!current()||!this.ready)){this.hover=valid(index)?index:-1;try{this.syncState()}catch{current()&&this.fail("error")}}},pick:index=>{current()&&this.ready&&valid(index)&&this.callbacks.pick(index)},camera:value=>{!current()||!this.ready||(this.camera=normalizeChart3dCamera(value),this.callbacks.camera(this.camera))},lost:reason=>{current()&&this.fail(reason)},rendering:info=>{current()&&(this.software=info.software,this.callbacks.changed())},restored:()=>{if(current()&&(this.contextLost=!1,!(!this.configured||!this.selection.restore())))try{if(mounted.setStyle(this.style()),!current()||(this.camera&&mounted.setCamera(this.camera),!current()||this.contextLost))return;this.ready=!0,this.notice=null,this.syncState(),current()&&this.callbacks.changed()}catch{current()&&this.fail("error")}}}),!current()){this.dispose(engine);return}if(engine.setStyle(this.style()),!current()||(engine.setData(data,++this.revision),!current())||(this.camera?engine.setCamera(this.camera):engine.fit?.(),!current()))return;const resize=()=>{if(!current())return;const rect=container.getBoundingClientRect();mounted.resize(Math.max(1,rect.width),Math.max(1,rect.height))};if(resize(),!current())return;this.observe(container,resize,current),this.configured=!0,this.loading=!1,this.ready=!this.contextLost,this.ready&&(this.selection.restore(),this.notice=null),this.syncState(),current()&&this.callbacks.changed()}catch(error){current()?this.fail(engine3dFailureReason(error)):this.dispose(engine??void 0)}}observe(container,resize,current){const view=this.host.ownerDocument.defaultView,engine=this.engine,refresh=()=>{if(!(!current()||!this.ready||!engine))try{engine.setStyle(this.style()),current()&&resize()}catch{current()&&this.fail("error")}};if(view?.ResizeObserver&&(this.resizeObserver=new view.ResizeObserver(refresh),this.resizeObserver.observe(container)),view?.MutationObserver){this.styleObserver=new view.MutationObserver(refresh);let ancestor=this.host;for(;ancestor;){this.styleObserver.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view?.matchMedia(query);media?.addEventListener("change",refresh),media&&this.cleanup.push(()=>media.removeEventListener("change",refresh))}}style(){const view=this.host.ownerDocument.defaultView,computed=view.getComputedStyle(this.host),probe=this.host.shadowRoot?.querySelector("[data-style-probe]"),measured=probe?view.getComputedStyle(probe):computed;if(this.colorContext===void 0){const canvas=this.host.ownerDocument.createElement("canvas");canvas.width=canvas.height=1,this.colorContext=canvas.getContext("2d",{willReadFrequently:!0})}const context=this.colorContext,color=name=>{const resolved=resolveCanvasColor(this.host,`var(${name})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:Array.from({length:8},(_,index)=>color(`--lr-color-chart-${index+1}`)),fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:finiteRange(Number.parseFloat(measured.inlineSize),8,1,1024),lineWidth:finiteRange(Number.parseFloat(measured.borderBlockStartWidth),1,0,64),devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}}export{Chart3dEngineController,chart3dEngineEnvironment,chart3dPointsLoader};
1
+ import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{Engine3dSelection,engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{finiteRange}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{normalizeChart3dCamera}from"./chart-3d-data.js";const chart3dPointsLoader=createEngine3dLoader({entry:"points",tag:tag("chart-3d"),load:()=>(async()=>{try{return await import("@aceshooting/lyra-3d/points")}catch(e){throw e}})()}),chart3dEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas")),visible:host=>isAccessibilityVisible(host)};class Chart3dEngineController{constructor(host,callbacks){this.host=host,this.callbacks=callbacks,this.selection=new Engine3dSelection(!1),this.notice=null,this.loading=!1,this.ready=!1,this.software=!1,this.generation=0,this.revision=0,this.disposed=new WeakSet,this.preference="builtin",this.selected=-1,this.cursor=-1,this.hover=-1,this.attempted=!1,this.configured=!1,this.contextLost=!1,this.intersecting=!1,this.cleanup=[]}dispose(engine){if(!(!engine||this.disposed.has(engine))){this.disposed.add(engine);try{engine.dispose()}catch{}}}invalidate(){const generation=++this.generation;this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.intersecting=!1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.styleObserver?.disconnect(),this.styleObserver=void 0;for(const cleanup of this.cleanup)cleanup();this.cleanup=[];const engine=this.engine;return this.engine=void 0,this.colorContext=void 0,this.loading=this.ready=this.configured=this.attempted=this.contextLost=this.software=!1,this.hover=-1,this.notice=null,this.selection.prefer(this.preference),this.dispose(engine),generation}disconnect(){this.invalidate()===this.generation&&(this.container=void 0,this.data=void 0)}update(data,container,preference,selected,cursor,camera){if(this.data!==data||this.container!==container||this.preference!==preference){if(this.invalidate()!==this.generation)return;this.data=data,this.container=container,this.preference=preference,this.selection.prefer(preference)}const cameraChanged=camera!==this.camera;if(this.camera=camera,this.selected=selected,this.cursor=cursor,this.engine&&this.configured&&!this.contextLost){const engine=this.engine,generation=this.generation,current=()=>generation===this.generation&&this.engine===engine;try{cameraChanged&&camera&&engine.setCamera(camera),current()&&this.syncState()}catch{current()&&this.fail("error")}if(!current())return}preference!=="webgl"||!data?.positions.length||!container||!this.host.isConnected||this.attempted||this.observer||this.eligibility||this.awaitAdmission(container)}awaitAdmission(container){const view=this.host.ownerDocument.defaultView,generation=this.generation;this.intersecting=view?.IntersectionObserver===void 0;const admit=()=>{generation!==this.generation||this.attempted||!this.intersecting||chart3dEngineEnvironment.visible(this.host)&&(this.observer?.disconnect(),this.observer=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.start())};if(view?.IntersectionObserver&&(this.observer=new view.IntersectionObserver(entries=>{if(generation===this.generation){for(const entry of entries)entry.target===container&&(this.intersecting=entry.isIntersecting);admit()}}),this.observer.observe(container)),view?.MutationObserver){this.eligibility=new view.MutationObserver(admit);let ancestor=this.host;for(let depth=0;ancestor&&depth<=256;depth++){this.eligibility.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","inert","hidden","style","class","open"]});const root=ancestor.getRootNode();ancestor=ancestor.assignedSlot??ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}admit()}fail(reason){const previous=this.notice,detail=this.selection.renderer==="webgl"?this.selection.fail(reason):null;if(reason==="context-lost")this.contextLost=!0,this.ready=this.loading=!1;else{if(this.invalidate()!==this.generation)return;this.selection.prefer("webgl"),this.selection.fail(reason),this.attempted=!0}if(this.notice=detail??previous,!detail){previous&&reason!=="context-lost"&&this.callbacks.changed();return}this.callbacks.changed(),this.callbacks.fallback(detail)}syncState(){this.engine?.setState?.({selected:new Set(this.selected<0?[]:[this.selected]),dimmed:new Set,hover:this.hover,focus:this.cursor})}async start(){const container=this.container,data=this.data,owner=this.host.ownerDocument;if(!container||!data||!this.host.isConnected||this.preference!=="webgl"||this.attempted)return;const generation=this.generation,current=()=>generation===this.generation&&this.host.isConnected&&this.host.ownerDocument===owner&&this.container===container;if(this.attempted=!0,!chart3dEngineEnvironment.available(owner)){this.fail("unsupported");return}this.loading=!0,this.callbacks.changed();let engine=null;try{if(engine=await chart3dPointsLoader.create(),!current()){this.dispose(engine??void 0);return}if(!engine){this.fail("unavailable");return}this.engine=engine;const mounted=engine,rowCount=data.positions.length/3,valid=index=>index!==null&&Number.isSafeInteger(index)&&index>=0&&index<rowCount;if(await engine.mount(container,{hover:index=>{if(!(!current()||!this.ready)){this.hover=valid(index)?index:-1;try{this.syncState()}catch{current()&&this.fail("error")}}},pick:index=>{current()&&this.ready&&valid(index)&&this.callbacks.pick(index)},camera:value=>{!current()||!this.ready||(this.camera=normalizeChart3dCamera(value),this.callbacks.camera(this.camera))},lost:reason=>{current()&&this.fail(reason)},rendering:info=>{current()&&(this.software=info.software,this.callbacks.changed())},restored:()=>{if(current()&&(this.contextLost=!1,!(!this.configured||!this.selection.restore())))try{if(mounted.setStyle(this.style()),!current()||(this.camera&&mounted.setCamera(this.camera),!current()||this.contextLost))return;this.ready=!0,this.notice=null,this.syncState(),current()&&this.callbacks.changed()}catch{current()&&this.fail("error")}}}),!current()){this.dispose(engine);return}if(engine.setStyle(this.style()),!current()||(engine.setData(data,++this.revision),!current())||(this.camera?engine.setCamera(this.camera):engine.fit?.(),!current()))return;const resize=()=>{if(!current())return;const rect=container.getBoundingClientRect();mounted.resize(Math.max(1,rect.width),Math.max(1,rect.height))};if(resize(),!current())return;this.observe(container,resize,current),this.configured=!0,this.loading=!1,this.ready=!this.contextLost,this.ready&&(this.selection.restore(),this.notice=null),this.syncState(),current()&&this.callbacks.changed()}catch(error){current()?this.fail(engine3dFailureReason(error)):this.dispose(engine??void 0)}}observe(container,resize,current){const view=this.host.ownerDocument.defaultView,engine=this.engine,refresh=()=>{if(!(!current()||!this.ready||!engine))try{engine.setStyle(this.style()),current()&&resize()}catch{current()&&this.fail("error")}};if(view?.ResizeObserver&&(this.resizeObserver=new view.ResizeObserver(refresh),this.resizeObserver.observe(container)),view?.MutationObserver){this.styleObserver=new view.MutationObserver(refresh);let ancestor=this.host;for(;ancestor;){this.styleObserver.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view?.matchMedia(query);media?.addEventListener("change",refresh),media&&this.cleanup.push(()=>media.removeEventListener("change",refresh))}}style(){const view=this.host.ownerDocument.defaultView,computed=view.getComputedStyle(this.host),probe=this.host.shadowRoot?.querySelector("[data-style-probe]"),measured=probe?view.getComputedStyle(probe):computed;if(this.colorContext===void 0){const canvas=this.host.ownerDocument.createElement("canvas");canvas.width=canvas.height=1,this.colorContext=canvas.getContext("2d",{willReadFrequently:!0})}const context=this.colorContext,color=name=>{const resolved=resolveCanvasColor(this.host,`var(${name})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:Array.from({length:8},(_,index)=>color(`--lr-color-chart-${index+1}`)),fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:finiteRange(Number.parseFloat(measured.inlineSize),8,1,1024),lineWidth:finiteRange(Number.parseFloat(measured.borderBlockStartWidth),1,0,64),devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}}export{Chart3dEngineController,chart3dEngineEnvironment,chart3dPointsLoader};
@@ -9,8 +9,9 @@ export type ChatComposerWrap=LyraTextWrap;
9
9
  /** Retained name for the shared native `selectionDirection` vocabulary.*/
10
10
  export type ChatComposerSelectionDirection=LyraSelectionDirection;
11
11
  /** Arrangement of the `start`/`end` action slots relative to the textarea. `'inline'` is today's
12
- * single flex row; `'stacked'` arranges them as a compact rail beside a multi-row textarea. */
13
- export type ChatComposerActionsLayout='inline'|'stacked';export interface LyraChatComposerEventMap{input:InputEvent;change:Event;'lr-invalid':CustomEvent<null>;'lr-input':CustomEvent<{value:string;}>;'lr-change':CustomEvent<{value:string;}>;'lr-stop':CustomEvent<null>;'lr-submit':CustomEvent<{value:string;}>;blur:FocusEvent;focus:FocusEvent;}declare class LyraChatComposerBase extends LyraElement<LyraChatComposerEventMap>{}declare const LyraChatComposer_base:typeof LyraChatComposerBase&(new(...args:any[])=>import("../../../lyra.js").FormAssociatedInterface<string> &import("../../../internal/form-associated.js").FormAssociatedSubclassInterface<string>);
12
+ * single flex row; `'stacked'` arranges them as a compact rail beside a multi-row textarea;
13
+ * `'below'` gives the textarea its own full-width line with `start` and `end` on one row under it. */
14
+ export type ChatComposerActionsLayout='inline'|'stacked'|'below';export interface LyraChatComposerEventMap{input:InputEvent;change:Event;'lr-invalid':CustomEvent<null>;'lr-input':CustomEvent<{value:string;}>;'lr-change':CustomEvent<{value:string;}>;'lr-stop':CustomEvent<null>;'lr-submit':CustomEvent<{value:string;}>;blur:FocusEvent;focus:FocusEvent;}declare class LyraChatComposerBase extends LyraElement<LyraChatComposerEventMap>{}declare const LyraChatComposer_base:typeof LyraChatComposerBase&(new(...args:any[])=>import("../../../lyra.js").FormAssociatedInterface<string> &import("../../../internal/form-associated.js").FormAssociatedSubclassInterface<string>);
14
15
  /**
15
16
  * `<lr-chat-composer>` — the message input for a chat/agent conversation
16
17
  * surface: an auto-resizing textarea plus a send/stop button. Form-
@@ -121,8 +122,12 @@ frame:ChatComposerFrame;private actionsLayoutValue;
121
122
  * `'inline'` (the default) keeps today's single flex row. `'stacked'` arranges `start` above
122
123
  * `end` as a compact rail in one column, beside a `textarea` that spans both rows -- for a
123
124
  * multi-row composer where the action buttons would otherwise stretch to the row's full
124
- * cross-axis height. Layout only; slot content, empty-slot hiding and the built-in button are
125
- * unchanged. Invalid direct or attribute values normalize and reflect as `'inline'`. */
125
+ * cross-axis height. `'below'` puts the `textarea` on its own full-width line and `start` and
126
+ * `end` on one row beneath it (`start` at the inline start, `end` at the inline end, even while
127
+ * `start` is empty) -- the usual phone-width chat input with attach buttons; `min-rows`/
128
+ * `max-rows` growth and inner scrolling are unchanged. Layout only; slot content, empty-slot
129
+ * hiding and the built-in button are unchanged. Invalid direct or attribute values normalize and
130
+ * reflect as `'inline'`. */
126
131
  get actionsLayout():ChatComposerActionsLayout;set actionsLayout(next:ChatComposerActionsLayout);
127
132
  /** Turns off Enter-to-send: plain Enter inserts a newline, as Shift+Enter always does.*/
128
133
  withoutEnterSubmit:boolean;
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sendIcon,stopIcon}from"../../../internal/icons.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./chat-composer.styles.js";import{normalizeChatComposerStatus}from"./chat-composer-status.js";import{CHAT_COMPOSER_STATUSES,normalizeChatComposerStatus as normalizeChatComposerStatus2}from"./chat-composer-status.js";import{autocorrectConverter,literalSetConverter,normalizeAutocorrect,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_composerLabel,LYRA_DEFAULT_sendMessage,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const CHAT_COMPOSER_ACTIONS_LAYOUT=literalSetConverter(["inline","stacked"],"inline");class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,styles]}get status(){return this.statusValue}set status(value){const previous=this.statusValue,normalized=normalizeChatComposerStatus(value);this.statusValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("status")!==normalized&&this.setAttribute("status",normalized),this.requestUpdate("status",previous,{reflect:!0,hasChanged:()=>!0})}get actionsLayout(){return this.actionsLayoutValue}set actionsLayout(next){const normalized=CHAT_COMPOSER_ACTIONS_LAYOUT.normalizeReflected(this,"actions-layout",next),previous=this.actionsLayoutValue;previous!==normalized&&(this.actionsLayoutValue=normalized,this.requestUpdate("actionsLayout",previous))}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super(),this.placeholder="",this.minRows=1,this.maxRows=8,this.statusValue="idle",this.frame="card",this.actionsLayoutValue="inline",this.withoutEnterSubmit=!1,this.submitDisabled=!1,this.withoutStop=!1,this.readOnly=!1,this.accessibleLabel=null,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.hasToolbarSlot=!1,this.hasStartSlot=!1,this.hasChipsSlot=!1,this.hasEndSlot=!1,this.touched=!1,this.textareaResizeGeneration=0,this.onTextareaInput=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,this.resizeTextarea(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value})},this.onTextareaChange=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value})},this.onTextareaKeyDown=e=>{e.defaultPrevented||e.key==="Enter"&&(e.shiftKey||this.withoutEnterSubmit||e.isComposing||e.keyCode===229||this.status==="idle"&&(e.preventDefault(),this.submit()))},this.onActionClick=()=>{this.effectiveDisabled||(this.status==="idle"?this.submit():this.withoutStop||this.emit("lr-stop",null))},this.syncToolbarSlot=()=>{this.hasToolbarSlot=this.hasSlotted("toolbar")},this.syncStartSlot=()=>{this.hasStartSlot=this.hasSlotted("start")},this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncEndSlot=()=>{this.hasEndSlot=this.hasSlotted("end")},this.onTextareaBlur=event=>{this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onTextareaFocus=event=>{if(this.effectiveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){this.effectiveDisabled||this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;textarea&&(setNativeRangeText(textarea,replacement,start,end,selectMode),this.value=textarea.value,this.resizeTextarea())}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{this.syncToolbarSlot(),this.syncStartSlot(),this.hasChipsSlot=this.hasSlotted("chips"),this.syncEndSlot()})}firstUpdated(changed){super.firstUpdated(changed),this.resizeTextarea(),this.armTextareaResizeObserver(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby")}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.armTextareaResizeObserver(),this.resizeTextarea(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}disconnectedCallback(){super.disconnectedCallback(),this.resetTextareaResizeWork(),this.descriptionLease?.release(),this.descriptionLease=void 0}adoptedCallback(){super.adoptedCallback(),this.resetTextareaResizeWork()}updated(changed){super.updated(changed),(changed.has("value")||changed.has("minRows")||changed.has("maxRows"))&&this.resizeTextarea(),(changed.has("minLength")||changed.has("maxLength")||changed.has("readOnly"))&&this.updateValidity()}updateValidity(){if(isBarredFromValidation({effectiveDisabled:this.effectiveDisabled,readonly:this.readOnly},this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const textarea=this.textareaEl;textarea&&textarea.value!==this.value&&(textarea.value=this.value);const own=lengthViolations(this.value,this.minLength,this.maxLength),tooShort=!!textarea?.validity.tooShort||own.tooShort,tooLong=!!textarea?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},textarea?.validationMessage||this.localize("valueInvalid"))}formResetCallback(){super.formResetCallback(),this.touched=!1}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style,lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2,paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom),borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth),minRows=this.effectiveMinRows,maxRows=this.effectiveMaxRows,minHeight=lineHeight*minRows+paddingBlock+borderBlock,maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock,next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`,ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver||this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta)return;this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf);const handle=ownerWindow.requestAnimationFrame(()=>{this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||(this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0,this.resizeTextarea())});this.textareaResizeRaf=handle,this.textareaResizeRafOwner=ownerWindow,this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer,this.textareaResizeObserverDocument=ownerDocument,this.textareaResizeObserverTarget=ta,observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1,this.textareaResizeObserver?.disconnect(),this.textareaResizeObserver=void 0,this.textareaResizeObserverDocument=void 0,this.textareaResizeObserverTarget=void 0,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf),this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0}submit(){this.submitDisabled||this.effectiveDisabled||this.status!=="idle"||this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle",showStop=busy&&!this.withoutStop;return html`
1
+ import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sendIcon,stopIcon}from"../../../internal/icons.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./chat-composer.styles.js";import{normalizeChatComposerStatus}from"./chat-composer-status.js";import{CHAT_COMPOSER_STATUSES,normalizeChatComposerStatus as normalizeChatComposerStatus2}from"./chat-composer-status.js";import{autocorrectConverter,literalSetConverter,normalizeAutocorrect,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_composerLabel,LYRA_DEFAULT_sendMessage,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const CHAT_COMPOSER_ACTIONS_LAYOUT=literalSetConverter(["inline","stacked","below"],"inline");class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,styles]}get status(){return this.statusValue}set status(value){const previous=this.statusValue,normalized=normalizeChatComposerStatus(value);this.statusValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("status")!==normalized&&this.setAttribute("status",normalized),this.requestUpdate("status",previous,{reflect:!0,hasChanged:()=>!0})}get actionsLayout(){return this.actionsLayoutValue}set actionsLayout(next){const normalized=CHAT_COMPOSER_ACTIONS_LAYOUT.normalizeReflected(this,"actions-layout",next),previous=this.actionsLayoutValue;previous!==normalized&&(this.actionsLayoutValue=normalized,this.requestUpdate("actionsLayout",previous))}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super(),this.placeholder="",this.minRows=1,this.maxRows=8,this.statusValue="idle",this.frame="card",this.actionsLayoutValue="inline",this.withoutEnterSubmit=!1,this.submitDisabled=!1,this.withoutStop=!1,this.readOnly=!1,this.accessibleLabel=null,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.hasToolbarSlot=!1,this.hasStartSlot=!1,this.hasChipsSlot=!1,this.hasEndSlot=!1,this.touched=!1,this.textareaResizeGeneration=0,this.onTextareaInput=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,this.resizeTextarea(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value})},this.onTextareaChange=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value})},this.onTextareaKeyDown=e=>{e.defaultPrevented||e.key==="Enter"&&(e.shiftKey||this.withoutEnterSubmit||e.isComposing||e.keyCode===229||this.status==="idle"&&(e.preventDefault(),this.submit()))},this.onActionClick=()=>{this.effectiveDisabled||(this.status==="idle"?this.submit():this.withoutStop||this.emit("lr-stop",null))},this.syncToolbarSlot=()=>{this.hasToolbarSlot=this.hasSlotted("toolbar")},this.syncStartSlot=()=>{this.hasStartSlot=this.hasSlotted("start")},this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncEndSlot=()=>{this.hasEndSlot=this.hasSlotted("end")},this.onTextareaBlur=event=>{this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onTextareaFocus=event=>{if(this.effectiveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){this.effectiveDisabled||this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;textarea&&(setNativeRangeText(textarea,replacement,start,end,selectMode),this.value=textarea.value,this.resizeTextarea())}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{this.syncToolbarSlot(),this.syncStartSlot(),this.hasChipsSlot=this.hasSlotted("chips"),this.syncEndSlot()})}firstUpdated(changed){super.firstUpdated(changed),this.resizeTextarea(),this.armTextareaResizeObserver(),this.isConnected&&(this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.armTextareaResizeObserver(),this.resizeTextarea(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}disconnectedCallback(){super.disconnectedCallback(),this.resetTextareaResizeWork(),this.descriptionLease?.release(),this.descriptionLease=void 0}adoptedCallback(){super.adoptedCallback(),this.resetTextareaResizeWork()}updated(changed){super.updated(changed),(changed.has("value")||changed.has("minRows")||changed.has("maxRows"))&&this.resizeTextarea(),(changed.has("minLength")||changed.has("maxLength")||changed.has("readOnly"))&&this.updateValidity()}updateValidity(){if(isBarredFromValidation({effectiveDisabled:this.effectiveDisabled,readonly:this.readOnly},this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const textarea=this.textareaEl;textarea&&textarea.value!==this.value&&(textarea.value=this.value);const own=lengthViolations(this.value,this.minLength,this.maxLength),tooShort=!!textarea?.validity.tooShort||own.tooShort,tooLong=!!textarea?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},textarea?.validationMessage||this.localize("valueInvalid"))}formResetCallback(){super.formResetCallback(),this.touched=!1}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style,lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2,paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom),borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth),minRows=this.effectiveMinRows,maxRows=this.effectiveMaxRows,minHeight=lineHeight*minRows+paddingBlock+borderBlock,maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock,next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`,ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver||this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta)return;this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf);const handle=ownerWindow.requestAnimationFrame(()=>{this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||(this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0,this.resizeTextarea())});this.textareaResizeRaf=handle,this.textareaResizeRafOwner=ownerWindow,this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer,this.textareaResizeObserverDocument=ownerDocument,this.textareaResizeObserverTarget=ta,observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1,this.textareaResizeObserver?.disconnect(),this.textareaResizeObserver=void 0,this.textareaResizeObserverDocument=void 0,this.textareaResizeObserverTarget=void 0,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf),this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0}submit(){this.submitDisabled||this.effectiveDisabled||this.status!=="idle"||this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle",showStop=busy&&!this.withoutStop;return html`
2
2
  <button
3
3
  part="action-button"
4
4
  type="button"
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-chat-composer-gap, var(--lr-space-xs)); box-sizing: border-box; border: var(--lr-border-width-thin) solid var(--lr-chat-composer-border-color, var(--lr-color-border)); border-radius: var(--lr-chat-composer-radius, var(--lr-radius)); background: var(--lr-chat-composer-bg, var(--lr-color-surface)); padding: var(--lr-chat-composer-padding, var(--lr-space-s)); transition: border-color var(--lr-transition-fast); } [part='base']:focus-within { border-color: var(--lr-color-brand); } :host([frame='plain']) [part='base'] { padding: 0; border: 0; border-radius: 0; background: transparent; } :host([frame='plain']) [part='base']:focus-within { box-shadow: var( --lr-chat-composer-focus-shadow, inset 0 calc(-1 * var(--lr-focus-ring-width)) 0 0 var(--lr-focus-ring-color) ); } :host(:disabled) [part='base'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='toolbar'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } [part='toolbar'][hidden] { display: none; } [part='chips'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='chips'][hidden] { display: none; } [part='row'] { display: flex; align-items: flex-end; gap: var(--lr-space-s); } [part='start'] { display: flex; flex: 0 0 auto; align-items: center; padding-block-end: var(--lr-space-xs); } [part='start'][hidden] { display: none; } [part='textarea'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; resize: none; border: none; outline: none; background: transparent; color: inherit; font: inherit; line-height: var(--lr-line-height-normal); padding-block: var(--lr-space-xs); overflow-x: hidden; overflow-y: hidden; } [part='textarea'][wrap='off'] { overflow-x: auto; } [part='textarea']::placeholder { color: var(--lr-color-text-quiet); } [part='textarea']:disabled { cursor: not-allowed; } [part='end'] { display: flex; flex: 0 0 auto; align-items: center; gap: var(--lr-space-xs); } :host([actions-layout='stacked']) [part='row'] { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: stretch; } :host([actions-layout='stacked']) [part='start'] { grid-column: 1; grid-row: 1; padding-block-end: 0; } :host([actions-layout='stacked']) [part='textarea'] { grid-column: 2; grid-row: 1 / span 2; } :host([actions-layout='stacked']) [part='end'] { grid-column: 1; grid-row: 2; } [part='action-button'] { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; box-sizing: border-box; ${iconHitTarget} border: none; border-radius: var(--lr-radius); background: var(--lr-color-brand); color: var(--lr-color-on-brand); font-size: var(--lr-font-size-lg); line-height: var(--lr-line-height-none); cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='action-button']:focus-visible { ${focusRing} } [part='action-button']:disabled { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='send-glyph'], [part='stop-glyph'] { display: inline-flex; } :host(:dir(rtl)) [part='send-glyph'] { transform: scaleX(-1); } :host([status='sending']) [part='action-button'], :host([status='streaming']) [part='action-button'] { background: var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)); } :host([status='sending']) :where([part='action-button']):hover:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } :host([status='sending']) :where([part='action-button']):active:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } @media (prefers-reduced-motion: reduce) { [part='base'], [part='action-button'] { transition: none !important; } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-chat-composer-gap, var(--lr-space-xs)); box-sizing: border-box; border: var(--lr-border-width-thin) solid var(--lr-chat-composer-border-color, var(--lr-color-border)); border-radius: var(--lr-chat-composer-radius, var(--lr-radius)); background: var(--lr-chat-composer-bg, var(--lr-color-surface)); padding: var(--lr-chat-composer-padding, var(--lr-space-s)); transition: border-color var(--lr-transition-fast); } [part='base']:focus-within { border-color: var(--lr-color-brand); } :host([frame='plain']) [part='base'] { padding: 0; border: 0; border-radius: 0; background: transparent; } :host([frame='plain']) [part='base']:focus-within { box-shadow: var( --lr-chat-composer-focus-shadow, inset 0 calc(-1 * var(--lr-focus-ring-width)) 0 0 var(--lr-focus-ring-color) ); } :host(:disabled) [part='base'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='toolbar'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } [part='toolbar'][hidden] { display: none; } [part='chips'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='chips'][hidden] { display: none; } [part='row'] { display: flex; align-items: flex-end; gap: var(--lr-space-s); } [part='start'] { display: flex; flex: 0 0 auto; align-items: center; padding-block-end: var(--lr-space-xs); } [part='start'][hidden] { display: none; } [part='textarea'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; resize: none; border: none; outline: none; background: transparent; color: inherit; font: inherit; line-height: var(--lr-line-height-normal); padding-block: var(--lr-space-xs); overflow-x: hidden; overflow-y: hidden; } [part='textarea'][wrap='off'] { overflow-x: auto; } [part='textarea']::placeholder { color: var(--lr-color-text-quiet); } [part='textarea']:disabled { cursor: not-allowed; } [part='end'] { display: flex; flex: 0 0 auto; align-items: center; gap: var(--lr-space-xs); } :host([actions-layout='stacked']) [part='row'] { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: stretch; } :host([actions-layout='stacked']) [part='start'] { grid-column: 1; grid-row: 1; padding-block-end: 0; } :host([actions-layout='stacked']) [part='textarea'] { grid-column: 2; grid-row: 1 / span 2; } :host([actions-layout='stacked']) [part='end'] { grid-column: 1; grid-row: 2; } :host([actions-layout='below']) [part='row'] { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto auto; align-items: center; } :host([actions-layout='below']) [part='textarea'] { grid-column: 1 / -1; grid-row: 1; } :host([actions-layout='below']) [part='start'] { grid-column: 1; grid-row: 2; justify-self: start; padding-block-end: 0; } :host([actions-layout='below']) [part='end'] { grid-column: 2; grid-row: 2; } [part='action-button'] { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; box-sizing: border-box; ${iconHitTarget} border: none; border-radius: var(--lr-radius); background: var(--lr-color-brand); color: var(--lr-color-on-brand); font-size: var(--lr-font-size-lg); line-height: var(--lr-line-height-none); cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='action-button']:focus-visible { ${focusRing} } [part='action-button']:disabled { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='send-glyph'], [part='stop-glyph'] { display: inline-flex; } :host(:dir(rtl)) [part='send-glyph'] { transform: scaleX(-1); } :host([status='sending']) [part='action-button'], :host([status='streaming']) [part='action-button'] { background: var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)); } :host([status='sending']) :where([part='action-button']):hover:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } :host([status='sending']) :where([part='action-button']):active:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } @media (prefers-reduced-motion: reduce) { [part='base'], [part='action-button'] { transition: none !important; } } `;export{styles};
@@ -4,6 +4,9 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
4
4
  export type ChatMessageActionsPlacement=ChatMessageActionsPosition;
5
5
  /** Where `<lr-chat-message>`'s `attachments` slot renders relative to the message body.*/
6
6
  export type ChatMessageAttachmentsPlacement='before'|'after';
7
+ /** Where `<lr-chat-message>`'s `avatar` slot renders: in the header row above the body (`'top'`),
8
+ * or in its own column beside the body at the inline start (`'start'`) or end (`'end'`). */
9
+ export type ChatMessageAvatarPlacement='top'|'start'|'end';
7
10
  /** `lr-toggle-request`/`lr-toggle` detail of `<lr-chat-message>`.*/
8
11
  export interface ChatMessageToggleDetail{
9
12
  /** Whether the message body is shown in the resulting (on `lr-toggle-request`, the proposed)
@@ -38,7 +41,9 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
38
41
  * `failure` slot has content, in which case this internal announcement is
39
42
  * skipped: the host's own `role="alert"` failure content is expected to
40
43
  * announce itself, and firing both would double-announce the same failure
41
- * with two different (and differently specific) messages.
44
+ * with two different (and differently specific) messages. `announce-status="false"` turns both
45
+ * built-in announcements off for an application that announces replies itself; the visible status
46
+ * text is unaffected.
42
47
  *
43
48
  * `messageRole` identifies the author (`user`/`assistant`/`system`, matching
44
49
  * the vocabulary of chat/completion APIs). The platform `role` property remains available for
@@ -48,6 +53,12 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
48
53
  * `actions-placement="outside"` renders the `actions` slot as a sibling immediately after the
49
54
  * message bubble instead of nested inside the footer.
50
55
  *
56
+ * `avatar-placement="start"` (or `"end"`) moves the `avatar` slot out of the header row into its own
57
+ * column beside the body; badges and the collapse toggle stay in the header. Combine it with
58
+ * `--lr-chat-message-bubble-border-width: 0` and a transparent `--lr-chat-message-bubble-bg` for a
59
+ * plain-text message with a side avatar. Set `--lr-chat-message-width: fit-content` to size each
60
+ * bubble to its content (up to `--lr-chat-message-max-width`) while it stays on its role's side.
61
+ *
51
62
  * @customElement lr-chat-message
52
63
  * @slot - The message body.
53
64
  * @slot avatar - An avatar/icon for the message author.
@@ -76,7 +87,7 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
76
87
  * @event lr-toggle - Collapse state committed. `detail: { expanded }` carries the resulting state.
77
88
  * @csspart bubble - The message article and bubble root. Programmatically focusable (`tabindex="-1"`) so focus has a stable place to land when the built-in retry button is removed. Its fill, text, and geometry derive from the documented theme hooks.
78
89
  * @csspart header - The row above the message body — avatar, badges, and the collapse toggle. Hidden entirely when none of those have anything to show.
79
- * @csspart avatar - The wrapper around the `avatar` slot.
90
+ * @csspart avatar - The wrapper around the `avatar` slot. Inside `header` by default; a column of `bubble` beside the body when `avatar-placement` is `start` or `end`.
80
91
  * @csspart badges - The wrapper around the `badges` slot.
81
92
  * @csspart collapse-button - The built-in collapse/expand toggle (only rendered when `collapsible`).
82
93
  * @csspart body - The wrapper around the default slot (the message content). Hidden while `collapsed`.
@@ -91,6 +102,10 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
91
102
  * @csspart retry-button - The built-in retry button (only rendered when `status="failed"`).
92
103
  * @csspart actions - The wrapper around the `actions` slot. Rendered inside the footer by default; a sibling immediately after `bubble` when `actions-placement="outside"`.
93
104
  * @cssprop [--lr-chat-message-max-width=80%] - Maximum inline size of the message bubble.
105
+ * @cssprop [--lr-chat-message-width=auto] - Inline size of the message bubble. `fit-content` shrinks the bubble to its content, capped by `--lr-chat-message-max-width`, while it stays aligned to its role's side.
106
+ * @cssprop [--lr-chat-message-bubble-border-width=var(--lr-border-width-thin)] - Bubble border width for every role and status; `0` removes the border.
107
+ * @cssprop [--lr-chat-message-bubble-border-color=var(--lr-color-border-subtle)] - Bubble border color for every role except `user`.
108
+ * @cssprop [--lr-chat-message-user-bubble-border-color=transparent] - Bubble border color for `message-role="user"`.
94
109
  * @cssprop [--lr-chat-message-bubble-bg=var(--lr-color-surface)] - Bubble fill for every role except `user`.
95
110
  * @cssprop [--lr-chat-message-bubble-color=var(--lr-color-text)] - Bubble text color for every role except `user`.
96
111
  * @cssprop [--lr-chat-message-user-bubble-bg=var(--lr-color-brand-quiet)] - Bubble fill for `message-role="user"`.
@@ -99,6 +114,7 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
99
114
  * @cssprop [--lr-chat-message-streaming-border-color=var(--lr-color-brand)] - Streaming bubble border.
100
115
  * @cssprop [--lr-chat-message-failed-border-color=var(--lr-color-danger)] - Failed bubble border.
101
116
  * @cssprop [--lr-chat-message-failed-bg=var(--lr-color-danger-quiet)] - Failed bubble fill.
117
+ * @cssprop [--lr-chat-message-failed-color=var(--lr-color-text)] - Failed bubble text color, for every role; pairs with `--lr-chat-message-failed-bg` so the role text color never lands on the failed fill.
102
118
  * @cssprop [--lr-chat-message-footer-color=var(--lr-color-text-quiet)] - Default footer text.
103
119
  * @cssprop [--lr-chat-message-user-footer-color=var(--lr-color-text)] - User-message footer text.
104
120
  * @cssprop [--lr-chat-message-failed-footer-color=var(--lr-color-danger)] - Failed-message footer text.
@@ -140,7 +156,15 @@ collapsed:boolean;
140
156
  * always matches what's on screen. */
141
157
  attachmentsPlacement:ChatMessageAttachmentsPlacement;
142
158
  /** Where the actions row renders relative to the bubble.*/
143
- actionsPlacement:ChatMessageActionsPlacement;private hasAvatarSlot;private hasBadgesSlot;private hasAttachmentsSlot;private hasActionsSlot;private hasFailureSlot;private politeSink?;private assertiveSink?;private bubbleEl?;private readonly bodyId;private _status;private previousStatus;private isMounting;private statusAtDisconnect?;
159
+ actionsPlacement:ChatMessageActionsPlacement;
160
+ /** Where the `avatar` slot renders. `'top'` (the default) keeps it in the header row above the
161
+ * body; `'start'`/`'end'` lay it beside the body at the inline start/end, mirroring under RTL.
162
+ * Any other value behaves as `'top'`. */
163
+ avatarPlacement:ChatMessageAvatarPlacement;
164
+ /** Whether status transitions are announced through the shared live region (the failure and
165
+ * streaming-complete announcements described above). `announce-status="false"` silences both
166
+ * while keeping the visible status text, for an application that announces replies itself. */
167
+ announceStatus:boolean;private hasAvatarSlot;private hasBadgesSlot;private hasAttachmentsSlot;private hasActionsSlot;private hasFailureSlot;private politeSink?;private assertiveSink?;private bubbleEl?;private readonly bodyId;private _status;private previousStatus;private isMounting;private statusAtDisconnect?;
144
168
  /** Delivery/generation state. Drives the footer's status dot/text and,
145
169
  * for `"failed"`, the bubble's danger treatment and the built-in retry
146
170
  * button. Declared via `static properties` above with a hand-written
@@ -1,18 +1,12 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,retryIcon}from"../../../internal/icons.js";import{formatTimeOfDay}from"../../../internal/intl-cache.js";import{literalSetConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_expandMessage}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"},CHAT_MESSAGE_STATUS=literalSetConverter(["sending","sent","failed","streaming"],"sent");class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPlacement="after",this.actionsPlacement="inside",this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=()=>{this.hasAvatarSlot=this.hasSlotted("avatar")},this.onBadgesSlotChange=()=>{this.hasBadgesSlot=this.hasSlotted("badges")},this.onAttachmentsSlotChange=()=>{this.hasAttachmentsSlot=this.hasSlotted("attachments")},this.onActionsSlotChange=()=>{this.hasActionsSlot=this.hasSlotted("actions")},this.onFailureSlotChange=()=>{this.hasFailureSlot=this.hasSlotted("failure")},this.toggleCollapsed=()=>{const detail={expanded:this.collapsed};requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-toggle-request",requestDetail,init),commit:()=>{this.collapsed=!detail.expanded,this.emit("lr-toggle",detail)}})},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0,converter:CHAT_MESSAGE_STATUS}}}get status(){return this._status}set status(value){const normalized=CHAT_MESSAGE_STATUS.normalizeReflected(this,"status",value),old=this._status;normalized!==old&&(this.previousStatus=old,this._status=normalized,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,this.politeSink?.release(),this.assertiveSink?.release(),this.politeSink=this.assertiveSink=void 0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const root=this.getRootNode(),active=activeElementIn(!this.isConnected||root.nodeType===Node.ELEMENT_NODE?null:root);try{return!active||active.nodeType!==Node.ELEMENT_NODE?!1:Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active))}catch{return!1}}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(previous!==this.status)if(this.status==="failed"){if(this.hasFailureSlot)return;this.assertiveSink?.announce(this.localize("chatFailedAnnounce"))}else previous==="streaming"&&this.status==="sent"&&this.politeSink?.announce(this.localize("chatCompleteAnnounce"))}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>formatTimeOfDay(date,this.effectiveLocale)),suppressBuiltInFailedUi=this.status==="failed"&&this.hasFailureSlot,statusText=suppressBuiltInFailedUi?void 0:this.statusText,showHeader=this.hasAvatarSlot||this.hasBadgesSlot||this.collapsible,actionsOutside=this.actionsPlacement==="outside",showFooter=!!statusText||!!ts||!actionsOutside&&this.hasActionsSlot,authorLabel=this.localize(this.messageRole==="user"?"promptStudioRoleUser":this.messageRole==="system"?"promptStudioRoleSystem":"promptStudioRoleAssistant"),articleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label")??"":authorLabel,actionsBlock=html`<span part="actions" ?hidden=${!this.hasActionsSlot}
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,retryIcon}from"../../../internal/icons.js";import{formatTimeOfDay}from"../../../internal/intl-cache.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_expandMessage}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"},CHAT_MESSAGE_STATUS=literalSetConverter(["sending","sent","failed","streaming"],"sent");class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPlacement="after",this.actionsPlacement="inside",this.avatarPlacement="top",this.announceStatus=!0,this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=()=>{this.hasAvatarSlot=this.hasSlotted("avatar")},this.onBadgesSlotChange=()=>{this.hasBadgesSlot=this.hasSlotted("badges")},this.onAttachmentsSlotChange=()=>{this.hasAttachmentsSlot=this.hasSlotted("attachments")},this.onActionsSlotChange=()=>{this.hasActionsSlot=this.hasSlotted("actions")},this.onFailureSlotChange=()=>{this.hasFailureSlot=this.hasSlotted("failure")},this.toggleCollapsed=()=>{const detail={expanded:this.collapsed};requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-toggle-request",requestDetail,init),commit:()=>{this.collapsed=!detail.expanded,this.emit("lr-toggle",detail)}})},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0,converter:CHAT_MESSAGE_STATUS}}}get status(){return this._status}set status(value){const normalized=CHAT_MESSAGE_STATUS.normalizeReflected(this,"status",value),old=this._status;normalized!==old&&(this.previousStatus=old,this._status=normalized,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,this.politeSink?.release(),this.assertiveSink?.release(),this.politeSink=this.assertiveSink=void 0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const root=this.getRootNode(),active=activeElementIn(!this.isConnected||root.nodeType===Node.ELEMENT_NODE?null:root);try{return!active||active.nodeType!==Node.ELEMENT_NODE?!1:Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active))}catch{return!1}}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(!(previous===this.status||!this.announceStatus))if(this.status==="failed"){if(this.hasFailureSlot)return;this.assertiveSink?.announce(this.localize("chatFailedAnnounce"))}else previous==="streaming"&&this.status==="sent"&&this.politeSink?.announce(this.localize("chatCompleteAnnounce"))}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>formatTimeOfDay(date,this.effectiveLocale)),suppressBuiltInFailedUi=this.status==="failed"&&this.hasFailureSlot,statusText=suppressBuiltInFailedUi?void 0:this.statusText,avatarBeside=this.avatarPlacement==="start"||this.avatarPlacement==="end",showHeader=!avatarBeside&&this.hasAvatarSlot||this.hasBadgesSlot||this.collapsible,actionsOutside=this.actionsPlacement==="outside",showFooter=!!statusText||!!ts||!actionsOutside&&this.hasActionsSlot,authorLabel=this.localize(this.messageRole==="user"?"promptStudioRoleUser":this.messageRole==="system"?"promptStudioRoleSystem":"promptStudioRoleAssistant"),articleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label")??"":authorLabel,actionsBlock=html`<span part="actions" ?hidden=${!this.hasActionsSlot}
2
2
  ><slot name="actions" @slotchange=${this.onActionsSlotChange}></slot
3
3
  ></span>`,attachmentsBlock=html`<div part="attachments" ?hidden=${!this.hasAttachmentsSlot}>
4
4
  <slot name="attachments" @slotchange=${this.onAttachmentsSlotChange}></slot>
5
- </div>`;return html`
6
- <div
7
- part="bubble"
8
- role="article"
9
- aria-label=${articleLabel}
10
- tabindex="-1"
11
- >
5
+ </div>`,avatarBlock=html`<span part="avatar" ?hidden=${!this.hasAvatarSlot}
6
+ ><slot name="avatar" @slotchange=${this.onAvatarSlotChange}></slot
7
+ ></span>`,content=html`
12
8
  <div part="header" ?hidden=${!showHeader}>
13
- <span part="avatar" ?hidden=${!this.hasAvatarSlot}
14
- ><slot name="avatar" @slotchange=${this.onAvatarSlotChange}></slot
15
- ></span>
9
+ ${avatarBeside?nothing:avatarBlock}
16
10
  <span part="badges" ?hidden=${!this.hasBadgesSlot}
17
11
  ><slot name="badges" @slotchange=${this.onBadgesSlotChange}></slot
18
12
  ></span>
@@ -43,6 +37,14 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
43
37
  </button>`:nothing}
44
38
  ${actionsOutside?nothing:actionsBlock}
45
39
  </div>
40
+ `;return html`
41
+ <div
42
+ part="bubble"
43
+ role="article"
44
+ aria-label=${articleLabel}
45
+ tabindex="-1"
46
+ >
47
+ ${avatarBeside?html`${this.avatarPlacement==="start"?avatarBlock:nothing}<div class="content">${content}</div>${this.avatarPlacement==="end"?avatarBlock:nothing}`:content}
46
48
  </div>
47
49
  ${actionsOutside?actionsBlock:nothing}
48
- `}}__decorate([property({reflect:!0,attribute:"message-role"})],LyraChatMessage.prototype,"messageRole",void 0),__decorate([property({attribute:"message-id",reflect:!0})],LyraChatMessage.prototype,"messageId",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"timestamp",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"formatTimestamp",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsed",void 0),__decorate([property({attribute:"attachments-placement"})],LyraChatMessage.prototype,"attachmentsPlacement",void 0),__decorate([property({reflect:!0,attribute:"actions-placement"})],LyraChatMessage.prototype,"actionsPlacement",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAvatarSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasBadgesSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAttachmentsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasFailureSlot",void 0),__decorate([query('[part="bubble"]')],LyraChatMessage.prototype,"bubbleEl",void 0);export{LyraChatMessage};
50
+ `}}__decorate([property({reflect:!0,attribute:"message-role"})],LyraChatMessage.prototype,"messageRole",void 0),__decorate([property({attribute:"message-id",reflect:!0})],LyraChatMessage.prototype,"messageId",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"timestamp",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"formatTimestamp",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsed",void 0),__decorate([property({attribute:"attachments-placement"})],LyraChatMessage.prototype,"attachmentsPlacement",void 0),__decorate([property({reflect:!0,attribute:"actions-placement"})],LyraChatMessage.prototype,"actionsPlacement",void 0),__decorate([property({reflect:!0,attribute:"avatar-placement"})],LyraChatMessage.prototype,"avatarPlacement",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"announce-status",converter:trueDefaultBooleanConverter})],LyraChatMessage.prototype,"announceStatus",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAvatarSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasBadgesSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAttachmentsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasFailureSlot",void 0),__decorate([query('[part="bubble"]')],LyraChatMessage.prototype,"bubbleEl",void 0);export{LyraChatMessage};
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; font-size: var(--lr-font-size-md-sm); line-height: var(--lr-line-height-normal); } [part='bubble'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); max-inline-size: var(--lr-chat-message-max-width, 80%); padding: var(--lr-chat-message-bubble-padding, var(--lr-space-m)); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-chat-message-bubble-radius, var(--lr-radius)); background: var(--lr-chat-message-bubble-bg, var(--lr-color-surface)); color: var(--lr-chat-message-bubble-color, var(--lr-color-text)); overflow-wrap: anywhere; } :host([message-role='user']) [part='bubble'] { margin-inline-start: auto; background: var(--lr-chat-message-user-bubble-bg, var(--lr-color-brand-quiet)); color: var(--lr-chat-message-user-bubble-color, var(--lr-color-text)); border-color: transparent; } :host([message-role='assistant']) [part='bubble'] { margin-inline-end: auto; } :host([message-role='system']) [part='bubble'] { margin-inline-end: auto; color: var(--lr-chat-message-system-color, var(--lr-color-text-quiet)); font-style: italic; border-style: dashed; } :host([status='failed']) [part='bubble'] { border-color: var(--lr-chat-message-failed-border-color, var(--lr-color-danger)); background: var(--lr-chat-message-failed-bg, var(--lr-color-danger-quiet)); } :host([status='streaming']) [part='bubble'] { border-color: var(--lr-chat-message-streaming-border-color, var(--lr-color-brand)); } [part='header'] { display: flex; align-items: center; gap: var(--lr-space-xs); } [part='header'][hidden], [part='avatar'][hidden], [part='badges'][hidden], [part='attachments'][hidden], [part='footer'][hidden], [part='actions'][hidden], [part='body'][hidden] { display: none; } [part='avatar'] { flex: 0 0 auto; display: inline-flex; } [part='badges'] { flex: 1 1 auto; display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; } [part='collapse-button'] { font: inherit; flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} margin-inline-start: auto; border: none; background: var(--lr-icon-button-bg, transparent); color: var(--lr-icon-button-color, var(--lr-color-text-quiet)); border-radius: var(--lr-icon-button-radius, var(--lr-radius)); cursor: pointer; } [part='collapse-button']:hover { background: var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)); color: var(--lr-icon-button-color-hover, var(--lr-color-text)); } [part='collapse-button']:active { background: var( --lr-icon-button-bg-active, color-mix( in oklab, var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); color: var(--lr-icon-button-color-active, var(--lr-icon-button-color-hover, var(--lr-color-text))); } [part~='bubble']:focus-visible { ${focusRing} } [part='collapse-button']:focus-visible, [part='retry-button']:focus-visible { ${focusRing} } [part='collapse-button'] .chevron { display: inline-flex; transition: transform var(--lr-transition-fast); } :host(:not([collapsed])) [part='collapse-button'] .chevron { transform: rotate(90deg); } :host([collapsed]:dir(rtl)) [part='collapse-button'] .chevron { transform: scaleX(-1); } [part='attachments'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='failure'] { display: contents; } [part='footer'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); font-size: var(--lr-font-size-xs); color: var(--lr-chat-message-footer-color, var(--lr-color-text-quiet)); } [part='actions'] { display: flex; align-items: center; gap: var(--lr-space-xs); } :host([message-role='user']) [part='actions'] { margin-inline-start: auto; } :host([message-role='assistant']) [part='actions'], :host([message-role='system']) [part='actions'] { margin-inline-end: auto; } :host([actions-placement='outside']) [part='actions'] { margin-block-start: var(--lr-space-2xs); } :host([actions-placement='outside'][message-role='user']) [part='actions'] { justify-content: flex-end; } :host([actions-placement='outside'][message-role='assistant']) [part='actions'], :host([actions-placement='outside'][message-role='system']) [part='actions'] { justify-content: flex-start; } [part='timestamp'] { white-space: nowrap; } :host([message-role='user']) [part='footer'] { color: var(--lr-chat-message-user-footer-color, var(--lr-color-text)); } :host([status='failed']) [part='footer'] { color: var(--lr-chat-message-failed-footer-color, var(--lr-color-danger)); } [part='status-indicator'] { flex: 0 0 auto; inline-size: var(--lr-size-0-5rem); block-size: var(--lr-size-0-5rem); border-radius: 50%; background: var(--lr-chat-message-indicator-color, var(--lr-color-text-quiet)); } :host([status='streaming']) [part='status-indicator'] { background: var(--lr-chat-message-streaming-indicator-color, var(--lr-color-brand)); animation: var(--_lr-motion-animation, lr-chat-message-pulse var(--lr-transition-ambient) infinite); } :host([status='failed']) [part='status-indicator'] { background: var(--lr-chat-message-failed-indicator-color, var(--lr-color-danger)); } [part='status-text'] { white-space: nowrap; } :host([status='failed']) [part='status-text'] { color: var(--lr-chat-message-failed-status-color, var(--lr-color-danger)); font-weight: var(--lr-font-weight-semibold); } @keyframes lr-chat-message-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } } [part='retry-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; gap: var(--lr-space-xs); padding: var(--lr-size-0-125rem) var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-danger); border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-danger); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; } [part='retry-button']:hover { background: var(--lr-color-danger-quiet); } [part='retry-button']:active { background: color-mix(in oklab, var(--lr-color-danger-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='retry-button'] svg { inline-size: var(--lr-size-0-875em); block-size: var(--lr-size-0-875em); } @media (prefers-reduced-motion: reduce) { [part='status-indicator'] { animation: none !important; opacity: 1; } [part='collapse-button'] .chevron { transition: none !important; } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; font-size: var(--lr-font-size-md-sm); line-height: var(--lr-line-height-normal); } [part='bubble'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); inline-size: var(--lr-chat-message-width, auto); max-inline-size: var(--lr-chat-message-max-width, 80%); padding: var(--lr-chat-message-bubble-padding, var(--lr-space-m)); border: var(--lr-chat-message-bubble-border-width, var(--lr-border-width-thin)) solid var(--lr-chat-message-bubble-border-color, var(--lr-color-border-subtle)); border-radius: var(--lr-chat-message-bubble-radius, var(--lr-radius)); background: var(--lr-chat-message-bubble-bg, var(--lr-color-surface)); color: var(--lr-chat-message-bubble-color, var(--lr-color-text)); overflow-wrap: anywhere; } :host([message-role='user']) [part='bubble'] { margin-inline-start: auto; background: var(--lr-chat-message-user-bubble-bg, var(--lr-color-brand-quiet)); color: var(--lr-chat-message-user-bubble-color, var(--lr-color-text)); border-color: var(--lr-chat-message-user-bubble-border-color, transparent); } :host([message-role='assistant']) [part='bubble'] { margin-inline-end: auto; } :host([message-role='system']) [part='bubble'] { margin-inline-end: auto; color: var(--lr-chat-message-system-color, var(--lr-color-text-quiet)); font-style: italic; border-style: dashed; } :host([status='failed']) [part='bubble'] { border-color: var(--lr-chat-message-failed-border-color, var(--lr-color-danger)); background: var(--lr-chat-message-failed-bg, var(--lr-color-danger-quiet)); color: var(--lr-chat-message-failed-color, var(--lr-color-text)); } :host([status='streaming']) [part='bubble'] { border-color: var(--lr-chat-message-streaming-border-color, var(--lr-color-brand)); } :host([avatar-placement='start']) [part='bubble'], :host([avatar-placement='end']) [part='bubble'] { flex-direction: row; align-items: flex-start; gap: var(--lr-space-s); } .content { flex: 1 1 auto; min-inline-size: 0; display: flex; flex-direction: column; gap: var(--lr-space-xs); } [part='header'] { display: flex; align-items: center; gap: var(--lr-space-xs); } [part='header'][hidden], [part='avatar'][hidden], [part='badges'][hidden], [part='attachments'][hidden], [part='footer'][hidden], [part='actions'][hidden], [part='body'][hidden] { display: none; } [part='avatar'] { flex: 0 0 auto; display: inline-flex; } [part='badges'] { flex: 1 1 auto; display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; } [part='collapse-button'] { font: inherit; flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} margin-inline-start: auto; border: none; background: var(--lr-icon-button-bg, transparent); color: var(--lr-icon-button-color, var(--lr-color-text-quiet)); border-radius: var(--lr-icon-button-radius, var(--lr-radius)); cursor: pointer; } [part='collapse-button']:hover { background: var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)); color: var(--lr-icon-button-color-hover, var(--lr-color-text)); } [part='collapse-button']:active { background: var( --lr-icon-button-bg-active, color-mix( in oklab, var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); color: var(--lr-icon-button-color-active, var(--lr-icon-button-color-hover, var(--lr-color-text))); } [part~='bubble']:focus-visible { ${focusRing} } [part='collapse-button']:focus-visible, [part='retry-button']:focus-visible { ${focusRing} } [part='collapse-button'] .chevron { display: inline-flex; transition: transform var(--lr-transition-fast); } :host(:not([collapsed])) [part='collapse-button'] .chevron { transform: rotate(90deg); } :host([collapsed]:dir(rtl)) [part='collapse-button'] .chevron { transform: scaleX(-1); } [part='attachments'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='failure'] { display: contents; } [part='footer'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); font-size: var(--lr-font-size-xs); color: var(--lr-chat-message-footer-color, var(--lr-color-text-quiet)); } [part='actions'] { display: flex; align-items: center; gap: var(--lr-space-xs); } :host([message-role='user']) [part='actions'] { margin-inline-start: auto; } :host([message-role='assistant']) [part='actions'], :host([message-role='system']) [part='actions'] { margin-inline-end: auto; } :host([actions-placement='outside']) [part='actions'] { margin-block-start: var(--lr-space-2xs); } :host([actions-placement='outside'][message-role='user']) [part='actions'] { justify-content: flex-end; } :host([actions-placement='outside'][message-role='assistant']) [part='actions'], :host([actions-placement='outside'][message-role='system']) [part='actions'] { justify-content: flex-start; } [part='timestamp'] { white-space: nowrap; } :host([message-role='user']) [part='footer'] { color: var(--lr-chat-message-user-footer-color, var(--lr-color-text)); } :host([status='failed']) [part='footer'] { color: var(--lr-chat-message-failed-footer-color, var(--lr-color-danger)); } [part='status-indicator'] { flex: 0 0 auto; inline-size: var(--lr-size-0-5rem); block-size: var(--lr-size-0-5rem); border-radius: 50%; background: var(--lr-chat-message-indicator-color, var(--lr-color-text-quiet)); } :host([status='streaming']) [part='status-indicator'] { background: var(--lr-chat-message-streaming-indicator-color, var(--lr-color-brand)); animation: var(--_lr-motion-animation, lr-chat-message-pulse var(--lr-transition-ambient) infinite); } :host([status='failed']) [part='status-indicator'] { background: var(--lr-chat-message-failed-indicator-color, var(--lr-color-danger)); } [part='status-text'] { white-space: nowrap; } :host([status='failed']) [part='status-text'] { color: var(--lr-chat-message-failed-status-color, var(--lr-color-danger)); font-weight: var(--lr-font-weight-semibold); } @keyframes lr-chat-message-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } } [part='retry-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; gap: var(--lr-space-xs); padding: var(--lr-size-0-125rem) var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-danger); border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-danger); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; } [part='retry-button']:hover { background: var(--lr-color-danger-quiet); } [part='retry-button']:active { background: color-mix(in oklab, var(--lr-color-danger-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='retry-button'] svg { inline-size: var(--lr-size-0-875em); block-size: var(--lr-size-0-875em); } @media (prefers-reduced-motion: reduce) { [part='status-indicator'] { animation: none !important; opacity: 1; } [part='collapse-button'] .chevron { transition: none !important; } } `;export{styles};
@@ -30,6 +30,19 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
30
30
  * Existing declarative children stay silent on mount, and appending the same text again creates a
31
31
  * new announcement. The shadow log itself always remains `aria-live="off"`.
32
32
  *
33
+ * **Streamed messages: announce when settled.** Setting `live-settle` (a delay in ms) alongside a
34
+ * `polite`/`assertive` `live` defers each appended child's announcement until its text has stopped
35
+ * changing for that long and it no longer reports work in progress (`aria-busy="true"`,
36
+ * `status="streaming"`, or a `streaming` descendant), then announces its final text once. An
37
+ * `<lr-chat-message>` moving from `streaming` to `sent` also makes its own short completion
38
+ * announcement; the settled announcement carries the reply text and follows it.
39
+ *
40
+ * **Host layout contract.** The host is a flex column (`display: flex; flex-direction: column`)
41
+ * whose `[part="base"]` and `[part="scroll"]` grow with `flex: 1` -- do not override the host's
42
+ * `display`. The viewport also needs a bounded block size: an explicit height, a definite-height
43
+ * flex/grid track, or a positioned container. With `display: block`, or an unbounded parent, the
44
+ * transcript grows with its content and nothing scrolls, without any error.
45
+ *
33
46
  * **`scrollToUnread()` in virtual mode.** The target row is scrolled with `align: 'start'` so the
34
47
  * divider boundary lands at the top of the view with the unread content visible below it -- the
35
48
  * only alignment that matches what "scroll to the divider" means here. The underlying virtual list
@@ -63,6 +76,11 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
63
76
  * @csspart content - The slotted-content wrapper the growth observers watch.
64
77
  * @csspart jump-pill - The built-in jump-to-latest button, absent while `follow` is engaged.
65
78
  * @csspart unread-divider - The "New messages" separator (slotted mode only).
79
+ * @cssprop [--lr-chat-viewport-padding=var(--lr-space-m)] - Padding of the scroll container around
80
+ * the transcript (slotted mode; in virtual mode the slotted list owns its own spacing).
81
+ * @cssprop [--lr-chat-viewport-gap=0] - Block-direction gap between slotted messages (slotted mode).
82
+ * @cssprop [--lr-chat-viewport-content-max-inline-size=none] - Maximum inline size of the transcript
83
+ * column; a narrower column is centred in the scroll container.
66
84
  * @status stable
67
85
  * @since 4.0.0
68
86
  */
@@ -72,6 +90,15 @@ export declare class LyraChatViewport extends LyraElement<LyraChatViewportEventM
72
90
  * cadence. Only accessibility-exposed text is copied. The shadow `role="log"` remains non-live;
73
91
  * announcements use a shared light-DOM sink. */
74
92
  live:ChatViewportLive;
93
+ /** Announce-when-settled delay in ms for streamed messages, or `null` (the default) to announce
94
+ * each appended direct child once, at append time. When set and `live` is `polite` or
95
+ * `assertive`, a newly appended child is announced once, with its final accessibility-exposed
96
+ * text, after that text has stayed unchanged for at least this long and the child no longer
97
+ * reports work in progress (`aria-busy="true"`, `status="streaming"`, or a `streaming`
98
+ * descendant such as a streaming `<lr-streaming-text>`). Values below 50 are raised to 50;
99
+ * a non-finite value uses 1000. A child that is removed first, or never gains text, is not
100
+ * announced. */
101
+ liveSettle:number|null;
75
102
  /** Px distance from the end still counted as "at bottom."*/
76
103
  bottomThreshold:number;
77
104
  /** Index of the first unread item -- element-child index in slotted mode, `items` index in virtual
@@ -84,11 +111,11 @@ label?:string;
84
111
  /** Host `aria-label`, forwarded to the internal `role="log"` element -- an `aria-label` left
85
112
  * on the custom-element host itself names nothing, because the log role lives inside the
86
113
  * shadow root. Wins over `label` and the localized default. */
87
- accessibleLabel:string|null;private unreadDividerTop;private scrollEl?;private contentEl?;private contentSlot?;private pendingUserIntent;private keyboardScrollIntent?;private pendingUserIntentExpiryFrame;private scrollbarDragActive;private scrollbarDragWindow?;private isMounting;private pendingScrollBehavior?;private contentResizeObserver?;private contentMutationObserver?;private readonly announcements;private get announcementSink();private get livePoliteness();private scrollResizeObserver?;private growthFrame;private listenedVirtualList?;private observerWindow?;private armedMode;private armGeneration;private followFocusRepair;private readonly knownProjectedNodes;private unreadBoundaryEl?;private messageElementsCache;private get messageElements();private collectMessageElements;private get virtualListEl();private get effectiveBottomThreshold();private get effectiveUnreadStartIndex();connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues<this>):void;firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private transcriptFocusOwner;
114
+ accessibleLabel:string|null;private unreadDividerTop;private scrollEl?;private contentEl?;private contentSlot?;private pendingUserIntent;private keyboardScrollIntent?;private pendingUserIntentExpiryFrame;private scrollbarDragActive;private scrollbarDragWindow?;private isMounting;private pendingScrollBehavior?;private contentResizeObserver?;private contentMutationObserver?;private readonly announcements;private get announcementSink();private get livePoliteness();private scrollResizeObserver?;private growthFrame;private listenedVirtualList?;private observerWindow?;private armedMode;private armGeneration;private followFocusRepair;private readonly knownProjectedNodes;private readonly settlingNodes;private unreadBoundaryEl?;private messageElementsCache;private get messageElements();private collectMessageElements;private get virtualListEl();private get effectiveBottomThreshold();private get effectiveUnreadStartIndex();connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues<this>):void;firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private transcriptFocusOwner;
88
115
  /** Scrolls to the end and re-engages `follow`. Default `smooth`, forced to `auto` under
89
116
  * `prefers-reduced-motion`. */
90
117
  scrollToBottom(options?:{behavior?:'auto'|'smooth';}):void;
91
118
  /** Scrolls the unread divider to the top of the view; `false` when `unreadStartIndex` is
92
119
  * `null`/out of range. Does not re-engage `follow`. See the class doc for why virtual mode uses
93
120
  * `align: 'start'` and what that trades off. */
94
- scrollToUnread(options?:{behavior?:'auto'|'smooth';}):boolean;private performScrollToEnd;private get totalCount();private get unreadCount();private pillLabel;private updateUnreadDividerPosition;private syncSemanticUnreadBoundary;private markUserIntent;private readonly passiveIntent;private cancelPendingUserIntentExpiry;private clearUserIntent;private consumeUserIntent;private onPointerDown;private onPointerUp;private releaseScrollbarDragListeners;private clearKeyboardScrollIntent;private onKeyDown;private onScroll;private onVirtualScroll;private onSlotChange;private scheduleGrowthTick;private announcementTextFor;private onContentMutations;private announceProjectedNode;private announceAfterRender;private announceNewProjectedNodes;private armObservers;private teardownObservers;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-viewport':LyraChatViewport;}}
121
+ scrollToUnread(options?:{behavior?:'auto'|'smooth';}):boolean;private performScrollToEnd;private get totalCount();private get unreadCount();private pillLabel;private updateUnreadDividerPosition;private syncSemanticUnreadBoundary;private markUserIntent;private readonly passiveIntent;private cancelPendingUserIntentExpiry;private clearUserIntent;private consumeUserIntent;private onPointerDown;private onPointerUp;private releaseScrollbarDragListeners;private clearKeyboardScrollIntent;private onKeyDown;private onScroll;private onVirtualScroll;private onSlotChange;private scheduleGrowthTick;private announcementTextFor;private onContentMutations;private announceProjectedNode;private announceAfterRender;private get effectiveLiveSettle();private trackSettlingNode;private scheduleSettleSample;private sampleSettlingNode;private reportsWorkInProgress;private clearSettlingNodes;private announceNewProjectedNodes;private armObservers;private teardownObservers;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-viewport':LyraChatViewport;}}