@aceshooting/lyra-ui 11.2.0 → 12.1.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 (222) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/README.md +11 -8
  3. package/custom-elements.json +1 -1
  4. package/dist/all.d.ts +1 -0
  5. package/dist/all.js +1 -1
  6. package/dist/autoloader.js +1 -1
  7. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
  8. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  9. package/dist/components/charts/chart/chart.class.d.ts +13 -1
  10. package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
  11. package/dist/components/charts/chart/histogram-bin.js +1 -1
  12. package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
  13. package/dist/components/charts/chart/lite-chart.class.js +6 -6
  14. package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
  15. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  16. package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
  17. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  18. package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
  19. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  20. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  21. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
  22. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  23. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  24. package/dist/components/data/funnel/funnel.class.d.ts +92 -0
  25. package/dist/components/data/funnel/funnel.class.js +25 -0
  26. package/dist/components/data/funnel/funnel.d.ts +1 -0
  27. package/dist/components/data/funnel/funnel.js +1 -0
  28. package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
  29. package/dist/components/data/funnel/funnel.styles.js +127 -0
  30. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
  31. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  32. package/dist/components/data/heatmap/heatmap.class.d.ts +199 -14
  33. package/dist/components/data/heatmap/heatmap.class.js +30 -22
  34. package/dist/components/data/heatmap/heatmap.styles.js +36 -0
  35. package/dist/components/data/index.d.ts +1 -0
  36. package/dist/components/data/index.js +1 -1
  37. package/dist/components/data/table/table.class.d.ts +18 -4
  38. package/dist/components/data/table/table.class.js +2 -2
  39. package/dist/components/data/table/table.styles.js +2 -1
  40. package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
  41. package/dist/components/data/timeline/timeline-cluster.js +1 -0
  42. package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
  43. package/dist/components/data/timeline/timeline-item.class.js +13 -2
  44. package/dist/components/data/timeline/timeline-item.styles.js +65 -0
  45. package/dist/components/data/timeline/timeline.class.d.ts +83 -27
  46. package/dist/components/data/timeline/timeline.class.js +3 -3
  47. package/dist/components/data/timeline/timeline.d.ts +1 -0
  48. package/dist/components/data/timeline/timeline.js +1 -1
  49. package/dist/components/data/timeline/timeline.styles.js +14 -0
  50. package/dist/components/forms/button/button.class.js +1 -1
  51. package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
  52. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  53. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
  54. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  55. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  56. package/dist/components/forms/color-picker/color-picker.class.js +1 -1
  57. package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
  58. package/dist/components/forms/combobox/combobox.class.js +3 -2
  59. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  60. package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
  61. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  62. package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
  63. package/dist/components/forms/input/native-time-input.class.js +1 -1
  64. package/dist/components/forms/input/time-input-shared.d.ts +2 -1
  65. package/dist/components/forms/input/time-input.class.js +1 -1
  66. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
  67. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  68. package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
  69. package/dist/components/forms/radio/radio-button.styles.js +1 -1
  70. package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
  71. package/dist/components/forms/radio/radio-group.class.js +1 -1
  72. package/dist/components/forms/radio/radio.class.d.ts +0 -1
  73. package/dist/components/forms/radio/radio.class.js +1 -1
  74. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
  75. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  76. package/dist/components/forms/select/select.class.d.ts +0 -1
  77. package/dist/components/forms/select/select.class.js +1 -1
  78. package/dist/components/forms/slider/slider.class.d.ts +0 -1
  79. package/dist/components/forms/slider/slider.class.js +1 -1
  80. package/dist/components/forms/switch/switch.class.d.ts +0 -1
  81. package/dist/components/forms/switch/switch.class.js +1 -1
  82. package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
  83. package/dist/components/forms/time-range/time-range.class.js +1 -1
  84. package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
  85. package/dist/components/forms/token-input/token-input.class.js +1 -1
  86. package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
  87. package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
  88. package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
  89. package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
  90. package/dist/components/layout/details/accordion-owner.d.ts +1 -1
  91. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
  92. package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
  93. package/dist/components/layout/menu/menu-item.class.js +1 -1
  94. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  95. package/dist/components/layout/widget/widget.class.d.ts +16 -0
  96. package/dist/components/layout/widget/widget.class.js +2 -2
  97. package/dist/components/lr-funnel.d.ts +1 -0
  98. package/dist/components/lr-funnel.js +1 -0
  99. package/dist/components/media/av-player/av-metadata.d.ts +0 -2
  100. package/dist/components/media/av-player/av-metadata.js +1 -1
  101. package/dist/components/media/file-input/file-input.class.d.ts +0 -1
  102. package/dist/components/media/file-input/file-input.class.js +1 -1
  103. package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
  104. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
  105. package/dist/components/media/flag/flag.class.d.ts +8 -0
  106. package/dist/components/media/flag/flag.class.js +1 -1
  107. package/dist/components/media/map/map-loader.d.ts +4 -1
  108. package/dist/components/media/map/map.class.d.ts +242 -23
  109. package/dist/components/media/map/map.class.js +2 -2
  110. package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
  111. package/dist/components/overlays/chip/chip-group.class.js +10 -3
  112. package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
  113. package/dist/components/overlays/overlay/popover.class.js +1 -1
  114. package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
  115. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  116. package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
  117. package/dist/components/overlays/progress/progress-shared.js +1 -1
  118. package/dist/components/overlays/rating/rating.class.js +1 -1
  119. package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
  120. package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
  121. package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
  122. package/dist/components/utility/format/format-options.d.ts +0 -2
  123. package/dist/components/utility/format/format-options.js +1 -1
  124. package/dist/components/utility/icon/icon-resource.d.ts +0 -2
  125. package/dist/components/utility/icon/icon-resource.js +1 -1
  126. package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
  127. package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
  128. package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
  129. package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
  130. package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
  131. package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
  132. package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
  133. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  134. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
  135. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
  136. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
  137. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
  138. package/dist/custom-elements-jsx.d.ts +16 -8
  139. package/dist/events.d.ts +15 -0
  140. package/dist/internal/accessibility-visibility.d.ts +1 -1
  141. package/dist/internal/anchor-target.d.ts +1 -3
  142. package/dist/internal/anchor-target.js +2 -2
  143. package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
  144. package/dist/internal/anchored-overlay-runtime.js +1 -0
  145. package/dist/internal/announcement-text.d.ts +1 -1
  146. package/dist/internal/ansi.d.ts +0 -4
  147. package/dist/internal/ansi.js +1 -1
  148. package/dist/internal/aria-ownership.d.ts +2 -1
  149. package/dist/internal/autoloader-manifest.js +1 -1
  150. package/dist/internal/autoloader-tags.d.ts +1 -1
  151. package/dist/internal/autoloader-tags.js +1 -1
  152. package/dist/internal/default-strings.generated.d.ts +1 -0
  153. package/dist/internal/default-strings.generated.js +1 -1
  154. package/dist/internal/focus-navigation.d.ts +3 -2
  155. package/dist/internal/form-associated.d.ts +0 -1
  156. package/dist/internal/form-associated.js +1 -1
  157. package/dist/internal/form-control-labels.d.ts +0 -3
  158. package/dist/internal/form-control-labels.js +1 -1
  159. package/dist/internal/localization-runtime.js +1 -1
  160. package/dist/internal/localization-types.d.ts +1 -1
  161. package/dist/internal/localization.js +1 -1
  162. package/dist/internal/lyra-element.d.ts +7 -14
  163. package/dist/internal/lyra-element.js +1 -1
  164. package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
  165. package/dist/internal/nonmodal-overlay-manager.js +1 -0
  166. package/dist/internal/overlay-manager.d.ts +4 -20
  167. package/dist/internal/overlay-manager.js +1 -1
  168. package/dist/internal/overlay-stack.d.ts +66 -0
  169. package/dist/internal/overlay-stack.js +1 -0
  170. package/dist/internal/package-metadata.d.ts +1 -1
  171. package/dist/internal/package-metadata.js +1 -1
  172. package/dist/internal/positioner.js +1 -1
  173. package/dist/internal/root-registration-allowlist.d.ts +1 -1
  174. package/dist/internal/root-registration-allowlist.js +1 -1
  175. package/dist/internal/text-quote.d.ts +1 -1
  176. package/dist/lyra.d.ts +5 -4
  177. package/dist/lyra.js +1 -1
  178. package/dist/ssr/all.d.ts +1 -0
  179. package/dist/ssr/all.js +1 -1
  180. package/dist/ssr.d.ts +4 -4
  181. package/dist/styles/tokens-root.css +488 -0
  182. package/dist/svelte.d.ts +17 -8
  183. package/dist/translations/ar.js +1 -1
  184. package/dist/translations/de.js +1 -1
  185. package/dist/translations/es.js +1 -1
  186. package/dist/translations/fa.js +1 -1
  187. package/dist/translations/fr.js +1 -1
  188. package/dist/translations/he.js +1 -1
  189. package/dist/translations/ja.js +1 -1
  190. package/dist/translations/pt-BR.js +1 -1
  191. package/dist/translations/ru.js +1 -1
  192. package/dist/translations/zh-CN.js +1 -1
  193. package/dist/utilities/localization.js +1 -1
  194. package/dist/vue.d.ts +16 -8
  195. package/llms/components/lr-app-rail-item.md +8 -1
  196. package/llms/components/lr-app-rail.md +6 -0
  197. package/llms/components/lr-chip-group.md +7 -0
  198. package/llms/components/lr-chip.md +7 -0
  199. package/llms/components/lr-combobox.md +42 -0
  200. package/llms/components/lr-date-input.md +19 -1
  201. package/llms/components/lr-date-picker.md +19 -1
  202. package/llms/components/lr-filter-bar.md +50 -1
  203. package/llms/components/lr-flag.md +14 -0
  204. package/llms/components/lr-funnel.md +122 -0
  205. package/llms/components/lr-heatmap.md +55 -8
  206. package/llms/components/lr-lite-chart.md +20 -8
  207. package/llms/components/lr-map.md +109 -22
  208. package/llms/components/lr-option.md +42 -0
  209. package/llms/components/lr-popover.md +39 -0
  210. package/llms/components/lr-table.md +7 -3
  211. package/llms/components/lr-timeline-item.md +49 -24
  212. package/llms/components/lr-timeline.md +49 -24
  213. package/llms/components/lr-widget.md +7 -1
  214. package/llms/index.md +3 -2
  215. package/llms/peers.md +1 -1
  216. package/llms/shared.md +110 -1
  217. package/llms-full.txt +681 -67
  218. package/llms.txt +1 -1
  219. package/package.json +26 -8
  220. package/vscode-css-data.json +63 -0
  221. package/vscode-html-data.json +108 -23
  222. package/web-types.json +32738 -310
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,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-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,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{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),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,MAX_SCROLL_CONTENT_WIDTH=1e6;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 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 lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}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 roundedLo=Math.floor(lo/step)*step,roundedHi=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=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.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!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.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.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}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))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}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.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.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})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,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-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,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{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";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;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 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 lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}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 roundedLo=Math.floor(lo/step)*step,roundedHi=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=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.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!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.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.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}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))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}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.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.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})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
2
2
  `)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.armResizeObserver(),this.armForcedColorsWatcher()}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 box=entries[0]?.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=this.svgEl?.getBoundingClientRect();rect&&(this.plotWidth=rect.width,this.plotHeight=rect.height)}});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target)}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver(),this.releaseAnnouncementSink(),this.syncAnnouncementSink(),this.refreshFitMeasurementAvailability(),this.armForcedColorsWatcher()}armForcedColorsWatcher(){const ownerWindow=this.ownerDocument?.defaultView??void 0;ownerWindow?.matchMedia&&(this.forcedColorsWindow===ownerWindow&&this.forcedColorsQuery||(this.disarmForcedColorsWatcher(),this.forcedColorsWindow=ownerWindow,this.forcedColorsQuery=ownerWindow.matchMedia("(forced-colors: active)"),this.forcedColorsQuery.addEventListener("change",this.onForcedColorsChange)))}disarmForcedColorsWatcher(){this.forcedColorsQuery?.removeEventListener("change",this.onForcedColorsChange),this.forcedColorsQuery=void 0,this.forcedColorsWindow=void 0}syncAnnouncementSink(){this.isConnected&&this.politeAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0}resetResizeObserver(){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){if(super.willUpdate(changed),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=activeElementIn(this.shadowRoot)??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.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 dataTruncation=this.dataTruncationMessage();wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus())}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return 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>
3
3
  ${this.recordSample().seriesIndexes.map(index=>{const series=this.datasets[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
4
4
  d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
@@ -19,15 +19,15 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
19
19
  <rect width=${size} height=${size} fill=${this.colorFor(index,series)}></rect>
20
20
  ${shapes}
21
21
  </pattern>`})}
22
- </defs>`}resolvePointText(label,value,datasetIndex){return this.formatter?.({value,surface:"visual",datasetIndex,label,seriesLabel:this.datasets[datasetIndex]?.label})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markAnnouncement(index,marks=this.interactiveMarks()){const mark=marks[index];if(!mark)return"";const series=this.datasets[mark.datasetIndex]?.label??this.localize("chartSeriesLabel"),custom=this.formatter?.({value:mark.value,surface:"spoken",datasetIndex:mark.datasetIndex,index:mark.index,label:mark.label,seriesLabel:series})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex);return custom?this.localize("liteChartCustomMarkSummary",void 0,{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)}):this.localize("liteChartMarkSummary",void 0,{series,label:mark.label,value:getNumberFormat(this.effectiveLocale).format(mark.value),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)})}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.liveRegion?.announce(this.markAnnouncement(index,marks),{force:!0}))}focusMark(index){this.interactiveMarks()[index]&&(this.activeMarkIndex=index,this.updateComplete.then(()=>{const mark=Array.from(this.renderRoot.querySelectorAll('[part="bar"], [part="point"]'))[index];mark&&(activeElementIn(this.shadowRoot)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const domainMax=hi>0?hi:1,frac=Math.sqrt(Math.min(domainMax,Math.max(0,value))/domainMax);return plotY+plotH-frac*plotH}return plotY+plotH-this.valueFraction(value,lo,hi)*plotH}valueFraction(value,lo,hi){return this.scale==="logarithmic"?logDomainFraction(value,this.logDomainFloor(lo,hi),hi):domainFraction(value,lo,hi)}logDomainFloor(lo,hi){if(lo>0)return lo;let smallest=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest&&(smallest=value);return Number.isFinite(smallest)?smallest:hi>0?hi/10:1}effectiveMinBarHeight(){return this.minBarHeight==null?void 0:finiteRange(this.minBarHeight,0,0,MAX_SCROLL_CONTENT_WIDTH)}roundedBarPath(x,y,w,h){const r=Math.max(0,Math.min(BAR_CORNER_RADIUS,w/2,h));return r<=0?`M${x},${y} h${w} v${h} h${-w} Z`:`M${x},${y+r} Q${x},${y} ${x+r},${y} H${x+w-r} Q${x+w},${y} ${x+w},${y+r} V${y+h} H${x} Z`}domain(){let lo=1/0,hi=-1/0;if(this.effectiveType==="bar"&&this.stacked)for(let i=0;i<this.recordCount();i++){let pos=0,neg=0;for(const s of this.datasets){const v=s.data[i];v==null||!Number.isFinite(v)||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}lo=Math.min(lo,neg),hi=Math.max(hi,pos)}else for(const s of this.datasets)for(const v of s.data)v==null||!Number.isFinite(v)||(lo=Math.min(lo,v),hi=Math.max(hi,v));return(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1),niceDomain(lo,hi,this.beginAtZero,TICK_COUNT)}emitPoint(datasetIndex,index){const label=this.labels[index],value=this.datasets[datasetIndex]?.data[index]??null;this.emit("lr-datum-activate",{kind:this.effectiveType==="bar"?"bar":"point",datasetIndex,index,label,value}),this.emit("lr-point-click",{datasetIndex,index,label,value})}emitNearestLinePoint(event,points,fallbackDatasetIndex,fallbackIndex){let selected=points.find(point=>point.datasetIndex===fallbackDatasetIndex&&point.index===fallbackIndex);const currentTarget=event.currentTarget,svgElement=currentTarget instanceof SVGElement?currentTarget.ownerSVGElement:null,screenMatrix=svgElement?.getScreenCTM();if(event.detail>0&&svgElement&&screenMatrix&&points.length){const renderedPoint=svgElement.createSVGPoint(),squaredDistance=point=>{renderedPoint.x=point.x,renderedPoint.y=point.y;const screenPoint=renderedPoint.matrixTransform(screenMatrix),dx=event.clientX-screenPoint.x,dy=event.clientY-screenPoint.y;return dx*dx+dy*dy};let bestDistance=selected?squaredDistance(selected):Number.POSITIVE_INFINITY;for(const point of points){const distance=squaredDistance(point);distance<bestDistance&&(selected=point,bestDistance=distance)}}this.emitPoint(selected?.datasetIndex??fallbackDatasetIndex,selected?.index??fallbackIndex)}onPointKeyDown(e,datasetIndex,index,markIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onMarkFocus(markIndex),this.emitPoint(datasetIndex,index);return}const marks=this.interactiveMarks();if(!marks.length)return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=markIndex;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(marks.length-1,markIndex+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,markIndex-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=marks.length-1;else return;e.preventDefault(),this.focusMark(next)}renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi){const rtl=this.effectiveDirection==="rtl";return ticks.map(t=>{const y=plotY+plotH-this.valueFraction(t,lo,hi)*plotH;return svg`
22
+ </defs>`}resolvePointText(label,value,datasetIndex){return this.formatter?.({value,surface:"visual",datasetIndex,label,seriesLabel:this.datasets[datasetIndex]?.label})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markAnnouncement(index,marks=this.interactiveMarks()){const mark=marks[index];if(!mark)return"";const series=this.datasets[mark.datasetIndex]?.label??this.localize("chartSeriesLabel"),custom=this.formatter?.({value:mark.value,surface:"spoken",datasetIndex:mark.datasetIndex,index:mark.index,label:mark.label,seriesLabel:series})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex);return custom?this.localize("liteChartCustomMarkSummary",void 0,{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)}):this.localize("liteChartMarkSummary",void 0,{series,label:mark.label,value:getNumberFormat(this.effectiveLocale).format(mark.value),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)})}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.liveRegion?.announce(this.markAnnouncement(index,marks),{force:!0}))}focusMark(index){this.interactiveMarks()[index]&&(this.activeMarkIndex=index,this.updateComplete.then(()=>{const mark=Array.from(this.renderRoot.querySelectorAll('[part="bar"], [part="point"]'))[index];mark&&(activeElementIn(this.shadowRoot)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const domainMax=hi>0?hi:1,frac=Math.sqrt(Math.min(domainMax,Math.max(0,value))/domainMax);return plotY+plotH-frac*plotH}return plotY+plotH-this.valueFraction(value,lo,hi)*plotH}valueFraction(value,lo,hi){return this.scale==="logarithmic"?logDomainFraction(value,this.logDomainFloor(lo,hi),hi):domainFraction(value,lo,hi)}logDomainFloor(lo,hi){if(lo>0)return lo;let smallest=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest&&(smallest=value);return Number.isFinite(smallest)?smallest:hi>0?hi/10:1}effectiveMinBarHeight(){return this.minBarHeight==null?void 0:finiteRange(this.minBarHeight,0,0,MAX_SCROLL_CONTENT_WIDTH)}roundedBarPath(x,y,w,h){const r=Math.max(0,Math.min(BAR_CORNER_RADIUS,w/2,h));return r<=0?`M${x},${y} h${w} v${h} h${-w} Z`:`M${x},${y+r} Q${x},${y} ${x+r},${y} H${x+w-r} Q${x+w},${y} ${x+w},${y+r} V${y+h} H${x} Z`}domain(){let lo=1/0,hi=-1/0;if(this.effectiveType==="bar"&&this.stacked)for(let i=0;i<this.recordCount();i++){let pos=0,neg=0;for(const s of this.datasets){const v=s.data[i];v==null||!Number.isFinite(v)||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}lo=Math.min(lo,neg),hi=Math.max(hi,pos)}else for(const s of this.datasets)for(const v of s.data)v==null||!Number.isFinite(v)||(lo=Math.min(lo,v),hi=Math.max(hi,v));return(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1),niceDomain(lo,hi,this.beginAtZero,TICK_COUNT)}emitPoint(datasetIndex,index){const label=this.labels[index],value=this.datasets[datasetIndex]?.data[index]??null;this.emit("lr-datum-activate",{kind:this.effectiveType==="bar"?"bar":"point",datasetIndex,index,label,value}),this.emit("lr-point-click",{datasetIndex,index,label,value})}emitNearestLinePoint(event,points,fallbackDatasetIndex,fallbackIndex){let selected=points.find(point=>point.datasetIndex===fallbackDatasetIndex&&point.index===fallbackIndex);const currentTarget=event.currentTarget,svgElement=currentTarget instanceof SVGElement?currentTarget.ownerSVGElement:null,screenMatrix=svgElement?.getScreenCTM();if(event.detail>0&&svgElement&&screenMatrix&&points.length){const renderedPoint=svgElement.createSVGPoint(),squaredDistance=point=>{renderedPoint.x=point.x,renderedPoint.y=point.y;const screenPoint=renderedPoint.matrixTransform(screenMatrix),dx=event.clientX-screenPoint.x,dy=event.clientY-screenPoint.y;return dx*dx+dy*dy};let bestDistance=selected?squaredDistance(selected):Number.POSITIVE_INFINITY;for(const point of points){const distance=squaredDistance(point);distance<bestDistance&&(selected=point,bestDistance=distance)}}this.emitPoint(selected?.datasetIndex??fallbackDatasetIndex,selected?.index??fallbackIndex)}onPointKeyDown(e,datasetIndex,index,markIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onMarkFocus(markIndex),this.emitPoint(datasetIndex,index);return}const marks=this.interactiveMarks();if(!marks.length)return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=markIndex;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(marks.length-1,markIndex+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,markIndex-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=marks.length-1;else return;e.preventDefault(),this.focusMark(next)}formatValueAxisTick(value){return this.formatter?.({value,surface:"tick"})??(this.tickFormat?this.tickFormat(value):formatTick(value,this.effectiveLocale))}renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi){const rtl=this.effectiveDirection==="rtl";return ticks.map(({value,label})=>{const y=plotY+plotH-this.valueFraction(value,lo,hi)*plotH;return svg`
23
23
  <line part="grid-line" x1=${plotX} y1=${y} x2=${plotX+plotW} y2=${y}></line>
24
24
  <text
25
25
  part="axis-label"
26
- x=${rtl?plotX+plotW+6:plotX-6}
26
+ x=${rtl?plotX+plotW+VALUE_AXIS_TICK_OFFSET:plotX-VALUE_AXIS_TICK_OFFSET}
27
27
  y=${y}
28
28
  text-anchor="end"
29
29
  dominant-baseline="middle"
30
- >${this.formatter?.({value:t,surface:"tick"})??(this.tickFormat?this.tickFormat(t):formatTick(t,this.effectiveLocale))}</text>
30
+ >${label}</text>
31
31
  `})}renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices){const groupCount=this.stacked?1:Math.max(1,recordSample.seriesIndexes.length),groupGap=finiteRange(this.barGapRatio??BAR_GROUP_GAP,BAR_GROUP_GAP,0,1),groupW=slot*(1-groupGap),barW=(groupW-BAR_GAP*slot*(groupCount-1))/groupCount,markIndexes=this.markIndexMap(),activeMarkIndex=this.normalizedMarkIndex(),numberFormat=getNumberFormat(this.effectiveLocale),minBarHeight=this.effectiveMinBarHeight(),stackedSqrt=this.stacked&&this.scale==="sqrt",domainMax=hi>0?hi:1,negDomainMax=lo<0?-lo:1,zeroY=plotY+plotH-domainFraction(0,lo,hi)*plotH,clampSvgCoordinate=(value,fallback=zeroY)=>finiteRange(value,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH),clampSvgLength=value=>finiteRange(value,0,0,MAX_SCROLL_CONTENT_WIDTH),posAvailH=zeroY-plotY,negAvailH=plotY+plotH-zeroY,posTotals=new Map,negTotals=new Map;if(stackedSqrt)for(const i of recordSample.rowIndexes){let pos=0,neg=0;for(const datasetIndex of recordSample.seriesIndexes){const s=this.datasets[datasetIndex];if(!s)continue;const v=s.data[i];v==null||!Number.isFinite(v)||this.skipZero&&v===0||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}posTotals.set(i,pos),negTotals.set(i,neg)}const bars=[];for(const i of recordSample.rowIndexes){const slotStart=(barOrigins.get(i)??plotX+i*slot)+(slot-groupW)/2;let stackPos=0,stackNeg=0,posPixelTop=zeroY,negPixelBottom=zeroY;const posCompressedH=stackedSqrt?Math.sqrt(Math.min(domainMax,posTotals.get(i)??0)/domainMax)*posAvailH:0,negCompressedH=stackedSqrt?Math.sqrt(Math.min(negDomainMax,-(negTotals.get(i)??0))/negDomainMax)*negAvailH:0;recordSample.seriesIndexes.forEach((di,sampledDatasetIndex)=>{const s=this.datasets[di];if(!s)return;const v=s.data[i];if(v==null||!Number.isFinite(v)||this.skipZero&&v===0)return;const color=this.colorFor(di,s),paint=this.markPaint(di,s);let rectX,y1,y2;if(this.stacked&&stackedSqrt)if(rectX=slotStart,v>=0){const total=posTotals.get(i)??0,shareLo=total>0?stackPos/total:0,nextStackPos=finiteAdd(stackPos,v),shareHi=total>0?nextStackPos/total:0;y1=zeroY-shareHi*posCompressedH,y2=zeroY-shareLo*posCompressedH,stackPos=nextStackPos}else{const total=-(negTotals.get(i)??0),shareLo=-stackNeg/total,nextStackNeg=finiteAdd(stackNeg,v),shareHi=-nextStackNeg/total;y1=zeroY+shareLo*negCompressedH,y2=zeroY+shareHi*negCompressedH,stackNeg=nextStackNeg}else if(this.stacked)if(rectX=slotStart,v>=0){const naturalH=clampSvgLength(Math.max(0,zeroY-this.barValueToY(v,plotY,plotH,lo,hi))),segH=clampSvgLength(minBarHeight!=null&&v!==0&&naturalH<minBarHeight?minBarHeight:naturalH);y2=posPixelTop,y1=clampSvgCoordinate(finiteAdd(posPixelTop,-segH),posPixelTop),posPixelTop=y1}else{const naturalH=clampSvgLength(Math.max(0,this.barValueToY(v,plotY,plotH,lo,hi)-zeroY)),segH=clampSvgLength(minBarHeight!=null&&v!==0&&naturalH<minBarHeight?minBarHeight:naturalH);y1=negPixelBottom,y2=clampSvgCoordinate(finiteAdd(negPixelBottom,segH),negPixelBottom),negPixelBottom=y2}else{rectX=slotStart+sampledDatasetIndex*(barW+BAR_GAP*slot);const zeroClamped=Math.min(hi,Math.max(lo,0)),barValLo=Math.min(zeroClamped,v),barValHi=Math.max(zeroClamped,v);y1=this.barValueToY(barValHi,plotY,plotH,lo,hi),y2=this.barValueToY(barValLo,plotY,plotH,lo,hi)}rectX=clampSvgCoordinate(rectX,plotX),y1=clampSvgCoordinate(y1),y2=clampSvgCoordinate(y2);const label=this.labels[i]??"",titleText=this.resolvePointText(label,v,di)??this.localize("liteChartBarLabel",void 0,{series:s.label,label,value:numberFormat.format(v)}),w=clampSvgLength(Math.max(0,barW));let h=clampSvgLength(Math.max(0,y2-y1));if(!(this.stacked&&!stackedSqrt)&&minBarHeight!=null&&v!==0&&h<minBarHeight){const extra=minBarHeight-h;y1=clampSvgCoordinate(finiteAdd(y1,-extra),y1),h=clampSvgLength(Math.max(0,y2-y1))}const markIndex=markIndexes.get(`${di}:${i}`),selected=selectedIndices.has(i),intraGroupSpacing=barW+BAR_GAP*slot,crossCategorySpacing=slot-Math.max(0,groupCount-1)*intraGroupSpacing,horizontalSpacing=Math.max(0,groupCount>1?Math.min(intraGroupSpacing,crossCategorySpacing):slot),hitWidth=clampSvgLength(Math.max(w,Math.min(24,horizontalSpacing))),hitHeight=this.stacked?h:clampSvgLength(Math.max(24,h)),hitX=clampSvgCoordinate(rectX-(hitWidth-w)/2,rectX),hitY=clampSvgCoordinate(y1-(hitHeight-h)/2,y1),hitTarget=svg`
32
32
  <rect
33
33
  data-mark-hit-target="bar"
@@ -120,7 +120,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
120
120
  d=${d.trim()}
121
121
  stroke=${color}
122
122
  stroke-dasharray=${this.markDash(di)}
123
- ></path>${dots}`})}render(){return this.renderChart()}visibleLabelIndexes(n){if(this.maxLabels==null)return;const max=finiteCount(this.maxLabels,n);if(n<=max)return;const count=Math.min(n,MAX_RENDERED_CHART_RECORDS,Math.max(2,max));return count<=1?new Set(n===1?[0]:[]):new Set(Array.from({length:count},(_,index)=>Math.round(index*(n-1)/(count-1))))}displayCategoryLabel(label,availableWidth){const maxCharacters=Math.max(1,Math.floor(availableWidth/APPROX_LABEL_CHARACTER_WIDTH));return label.length<=maxCharacters?label:maxCharacters===1?"\u2026":`${label.slice(0,maxCharacters-1)}\u2026`}renderChart(){const n=this.recordCount(),awaitingFitMeasurement=this.awaitingFitMeasurement(),h=finiteRange(this.plotHeight||200,200,0,MAX_SCROLL_CONTENT_WIDTH),axisGutter=(this.valueAxisGutter==null?PAD_LEFT:finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH))+(this.yLabel?AXIS_TITLE_SPACE:0),rtl=this.effectiveDirection==="rtl",padBottom=PAD_BOTTOM+(this.xLabel?AXIS_TITLE_SPACE:0),plotX=rtl?PAD_RIGHT:axisGutter,plotY=PAD_TOP,plotH=Math.max(0,h-plotY-padBottom);let w,plotW,slot;if(this.layout==="scroll"){const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;slot=finiteRange(this.barWidth,32,0,maxSlot),plotW=n*slot,w=axisGutter+plotW+PAD_RIGHT}else w=finiteRange(this.plotWidth||400,400,0,MAX_SCROLL_CONTENT_WIDTH),plotW=Math.max(0,w-axisGutter-PAD_RIGHT),slot=n>0?plotW/n:0;const{lo,hi,ticks}=this.domain(),recordSample=this.recordSample(),selectedIndices=new Set,renderedRows=new Set(recordSample.rowIndexes);for(let index=0;index<Math.min(this.selectedIndices.length,MAX_RENDERED_CHART_RECORDS);index++){const candidate=this.selectedIndices[index];typeof candidate=="number"&&Number.isInteger(candidate)&&renderedRows.has(candidate)&&selectedIndices.add(candidate)}const barOrigins=this.effectiveType==="bar"&&!awaitingFitMeasurement?new Map(recordSample.rowIndexes.map(index=>{const fallback=plotX+index*slot,candidate=typeof this.barX=="function"?this.barX(index):fallback;return[index,finiteRange(candidate,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH)]})):new Map,grid=awaitingFitMeasurement||this.withoutValueAxis?[]:this.renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi),marks=awaitingFitMeasurement?[]:this.effectiveType==="bar"?this.renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices):this.renderLines(plotX,plotY,plotW,plotH,lo,hi,recordSample,selectedIndices),visibleLabelIndexes=this.visibleLabelIndexes(n),decimationStride=visibleLabelIndexes?n/visibleLabelIndexes.size:1,categoryLabelWidth=Math.max(0,decimationStride*(this.effectiveType==="bar"?slot:n>1?plotW/(n-1):plotW)-BAR_CORNER_RADIUS),categoryLabels=awaitingFitMeasurement?[]:recordSample.rowIndexes.map(i=>{const label=this.labels[i]??"";if(visibleLabelIndexes&&!visibleLabelIndexes.has(i))return nothing;const fullLabel=label??"",x=this.effectiveType==="bar"&&n>0?(barOrigins.get(i)??plotX+i*slot)+slot/2:plotX+(n>1?i/(n-1)*plotW:plotW/2),displayLabel=this.displayCategoryLabel(fullLabel,categoryLabelWidth);return svg`<text
123
+ ></path>${dots}`})}render(){return this.renderChart()}resolvedValueAxisGutter(ticks,measuredWidth){if(typeof this.valueAxisGutter=="number")return finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH);if(this.valueAxisGutter!=="auto"||ticks.length===0)return PAD_LEFT;let widest=0;for(const tick of ticks)widest=Math.max(widest,tick.label.length*APPROX_LABEL_CHARACTER_WIDTH);const requested=Math.ceil(widest)+VALUE_AXIS_TICK_OFFSET+AUTO_VALUE_AXIS_SAFETY_INSET,maximum=this.layout==="scroll"?MAX_AUTO_VALUE_AXIS_GUTTER:Math.max(PAD_LEFT,Math.min(MAX_AUTO_VALUE_AXIS_GUTTER,measuredWidth*MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION));return finiteRange(requested,PAD_LEFT,PAD_LEFT,maximum)}automaticMaxLabels(n,plotW,renderedIndexes){if(n<=1)return n;let widest=0;for(const index of renderedIndexes){const label=this.labels[index]??"";widest=Math.max(widest,label.length*APPROX_LABEL_CHARACTER_WIDTH)}if(widest===0)return n;const lane=widest+AUTO_CATEGORY_LABEL_INSET,fits=Math.floor(finiteRange(plotW,0,0,MAX_SCROLL_CONTENT_WIDTH)/lane);return Math.min(n,Math.max(2,fits))}visibleLabelIndexes(n,plotW,renderedIndexes){if(this.maxLabels==null)return;const requested=this.maxLabels==="auto"?this.automaticMaxLabels(n,plotW,renderedIndexes):this.maxLabels;if(typeof requested!="number")return;const max=finiteCount(requested,n);if(n<=max)return;const count=Math.min(n,MAX_RENDERED_CHART_RECORDS,Math.max(2,max));return count<=1?new Set(n===1?[0]:[]):new Set(Array.from({length:count},(_,index)=>Math.round(index*(n-1)/(count-1))))}displayCategoryLabel(label,availableWidth){const maxCharacters=Math.max(1,Math.floor(availableWidth/APPROX_LABEL_CHARACTER_WIDTH));return label.length<=maxCharacters?label:maxCharacters===1?"\u2026":`${label.slice(0,maxCharacters-1)}\u2026`}renderChart(){const n=this.recordCount(),awaitingFitMeasurement=this.awaitingFitMeasurement(),h=finiteRange(this.plotHeight||200,200,0,MAX_SCROLL_CONTENT_WIDTH),measuredWidth=finiteRange(this.plotWidth||400,400,0,MAX_SCROLL_CONTENT_WIDTH),{lo,hi,ticks}=this.domain(),formattedTicks=awaitingFitMeasurement||this.withoutValueAxis?[]:ticks.map(value=>({value,label:this.formatValueAxisTick(value)})),axisGutter=this.resolvedValueAxisGutter(formattedTicks,measuredWidth)+(this.yLabel?AXIS_TITLE_SPACE:0),rtl=this.effectiveDirection==="rtl",padBottom=PAD_BOTTOM+(this.xLabel?AXIS_TITLE_SPACE:0),plotX=rtl?PAD_RIGHT:axisGutter,plotY=PAD_TOP,plotH=Math.max(0,h-plotY-padBottom);let w,plotW,slot;if(this.layout==="scroll"){const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;slot=finiteRange(this.barWidth,32,0,maxSlot),plotW=n*slot,w=axisGutter+plotW+PAD_RIGHT}else w=measuredWidth,plotW=Math.max(0,w-axisGutter-PAD_RIGHT),slot=n>0?plotW/n:0;const recordSample=this.recordSample(),selectedIndices=new Set,renderedRows=new Set(recordSample.rowIndexes);for(let index=0;index<Math.min(this.selectedIndices.length,MAX_RENDERED_CHART_RECORDS);index++){const candidate=this.selectedIndices[index];typeof candidate=="number"&&Number.isInteger(candidate)&&renderedRows.has(candidate)&&selectedIndices.add(candidate)}const barOrigins=this.effectiveType==="bar"&&!awaitingFitMeasurement?new Map(recordSample.rowIndexes.map(index=>{const fallback=plotX+index*slot,candidate=typeof this.barX=="function"?this.barX(index):fallback;return[index,finiteRange(candidate,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH)]})):new Map,grid=awaitingFitMeasurement||this.withoutValueAxis?[]:this.renderGrid(plotX,plotY,plotW,plotH,formattedTicks,lo,hi),marks=awaitingFitMeasurement?[]:this.effectiveType==="bar"?this.renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices):this.renderLines(plotX,plotY,plotW,plotH,lo,hi,recordSample,selectedIndices),visibleLabelIndexes=this.visibleLabelIndexes(n,plotW,recordSample.rowIndexes),decimationStride=visibleLabelIndexes?n/visibleLabelIndexes.size:1,categoryLabelWidth=Math.max(0,decimationStride*(this.effectiveType==="bar"?slot:n>1?plotW/(n-1):plotW)-BAR_CORNER_RADIUS),categoryLabels=awaitingFitMeasurement?[]:recordSample.rowIndexes.map(i=>{const label=this.labels[i]??"";if(visibleLabelIndexes&&!visibleLabelIndexes.has(i))return nothing;const fullLabel=label??"",x=this.effectiveType==="bar"&&n>0?(barOrigins.get(i)??plotX+i*slot)+slot/2:plotX+(n>1?i/(n-1)*plotW:plotW/2),displayLabel=this.displayCategoryLabel(fullLabel,categoryLabelWidth);return svg`<text
124
124
  part="axis-label"
125
125
  x=${x}
126
126
  y=${plotY+plotH+CATEGORY_LABEL_OFFSET}
@@ -203,4 +203,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
203
203
  `})}
204
204
  </div>`:nothing}
205
205
  </div>
206
- `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
206
+ `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({converter:autoNumberConverter,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({converter:autoNumberConverter,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
@@ -23,24 +23,7 @@ import type { ShikiTransformer } from './shiki-types.js';
23
23
  import type { LyraAnchor, LyraHighlight, TextSelectRect } from '../../viewers/document-viewer/anchors.js';
24
24
  /** Matches `LyraElement.localize()`'s signature so either component's bound
25
25
  * method can be passed straight through. */
26
- export type LyraLocalizeFn = (key: string, fallback?: string, values?: Record<string, string | number>) => string;
27
- /** The collapse/expand header toggle button's `aria-label`. */
28
- export declare function codeBlockToggleLabel(localize: LyraLocalizeFn, collapsed: boolean): string;
29
- /** The copy-to-clipboard header button's `aria-label`. */
30
- export declare function codeBlockCopyLabel(localize: LyraLocalizeFn, justCopied: boolean, copyFailed: boolean): string;
31
- /** The `[part="body"]` region's `aria-label`: the filename when set, else a
32
- * language-aware "Code" region label. */
33
- export declare function codeBlockBodyLabel(localize: LyraLocalizeFn, filename: string, language: string): string;
34
- /**
35
- * Parses a `highlight-lines` attribute value (e.g. `"3-5,7"`) into the set of one-based line
36
- * numbers it addresses: comma-separated segments, each either a single line number or an
37
- * inclusive range, whitespace around commas/dashes tolerated, a reversed range (`"5-3"`)
38
- * normalized to ascending order. An invalid segment is skipped (with a `console.warn`) rather
39
- * than throwing or discarding the otherwise-valid segments around it.
40
- */
41
- export declare function addBoundedLineRange(lines: Set<number>, start: number, end: number, maxLine: number): void;
42
- /** How long the copy button's confirmation state lasts before reverting. */
43
- export declare const CODE_BLOCK_COPY_CONFIRM_MS = 1500;
26
+ type LyraLocalizeFn = (key: string, fallback?: string, values?: Record<string, string | number>) => string;
44
27
  /** One-based line count of `code`, the upper bound every line-addressing helper below clamps to.
45
28
  * A trailing newline still yields the (empty) line after it, matching the rendered line count. */
46
29
  export declare function codeBlockLineCount(code: string): number;
@@ -80,26 +63,12 @@ export declare function scrollCodeBlockToAnchor(host: CodeBlockAnchorHost, targe
80
63
  /** The one-based gutter line an event originated in, or `null` when it didn't come from a line
81
64
  * button at all. */
82
65
  export declare function codeBlockEventLine(e: Event): number | null;
83
- /** What a keystroke on a gutter line button means. `null` covers both an unhandled key and a
84
- * movement key that would land on the line already focused -- neither of which may
85
- * `preventDefault()`, so the caller must not treat them differently. */
86
- export type CodeBlockLineKeyAction = {
87
- kind: 'activate';
88
- } | {
89
- kind: 'move';
90
- line: number;
91
- } | null;
92
- /** The roving-tabindex keyboard contract for the (`line-numbers`-gated) gutter. */
93
- export declare function codeBlockLineKeyAction(key: string, line: number, total: number): CodeBlockLineKeyAction;
94
66
  /** An `lr-text-select` payload for a selection ending inside `[part="body"]`. */
95
- export interface CodeBlockSelection {
67
+ interface CodeBlockSelection {
96
68
  readonly text: string;
97
69
  readonly anchor: LyraAnchor;
98
70
  readonly rects: readonly TextSelectRect[];
99
71
  }
100
- /** Anchors the current selection to the `line-range` it spans. `null` whenever there's nothing to
101
- * report: no selection, a collapsed/whitespace-only one, or endpoints outside any `[data-line]`. */
102
- export declare function codeBlockSelectionAnchor(shadowRoot: ShadowRoot | null): CodeBlockSelection | null;
103
72
  /** Every property whose change invalidates the cached `highlightedHtml`. */
104
73
  export declare function codeBlockNeedsHighlightResync(changed: PropertyValues): boolean;
105
74
  /**
@@ -182,26 +151,6 @@ export interface CodeBlockPlainCodeOptions {
182
151
  * separate real button, leaving source text selectable in both plain and highlighted output.
183
152
  */
184
153
  export declare function renderCodeBlockPlainCode(options: CodeBlockPlainCodeOptions): TemplateResult;
185
- export interface CodeBlockHeaderOptions {
186
- collapsible: boolean;
187
- collapsed: boolean;
188
- /** `id` of `[part="body"]`, for the toggle's `aria-controls`. */
189
- bodyId: string;
190
- filename: string;
191
- language: string;
192
- copyable: boolean;
193
- justCopied: boolean;
194
- copyFailed: boolean;
195
- localize: LyraLocalizeFn;
196
- onToggle: () => void;
197
- onCopy: () => void;
198
- }
199
- /**
200
- * The header row above the code (filename/language/copy/toggle) shared by `<lr-code-block>` and
201
- * `<lr-code-block-core>`. `aria-expanded` renders both `"true"` and `"false"` rather than being
202
- * conditionally omitted -- the collapse toggle's state is meaningless to assistive tech otherwise.
203
- */
204
- export declare function renderCodeBlockHeader(options: CodeBlockHeaderOptions): TemplateResult;
205
154
  export interface CodeBlockShellOptions {
206
155
  filename: string;
207
156
  language: string;
@@ -244,7 +193,7 @@ export declare function renderCodeBlockShell(options: CodeBlockShellOptions): Te
244
193
  /** The element surface {@linkcode CodeBlockInteractionController} reads. Every member is either
245
194
  * native to `HTMLElement` or already public on both code-block variants, so routing through the
246
195
  * controller widens neither component's own API. */
247
- export interface CodeBlockInteractionHost extends HTMLElement {
196
+ interface CodeBlockInteractionHost extends HTMLElement {
248
197
  readonly renderRoot: HTMLElement | DocumentFragment;
249
198
  readonly updateComplete: Promise<boolean>;
250
199
  readonly code: string;
@@ -306,3 +255,4 @@ export declare class CodeBlockInteractionController {
306
255
  copy: () => Promise<void>;
307
256
  toggleCollapsed: () => void;
308
257
  }
258
+ export {};
@@ -71,4 +71,4 @@ import{html,nothing}from"lit";import{unsafeHTML}from"lit/directives/unsafe-html.
71
71
  ${options.showSkeleton?html`<lr-skeleton shape="rect" .announce=${!1}></lr-skeleton>`:options.highlightedHtml!==null?unsafeHTML(options.highlightedHtml):html`<pre part="pre" class=${options.lineNumbers?"line-numbers":nothing}>${options.renderPlainCode()}</pre>`}
72
72
  </div>
73
73
  </div>
74
- `}class CodeBlockInteractionController{constructor(options){this.options=options,this.copyGeneration=0,this.onLineActivate=line=>{this.setFocusedLine(line),this.options.emitLineActivate(line)},this.onLineKeyDown=(e,line)=>{const{host}=this.options,action=codeBlockLineKeyAction(e.key,line,codeBlockLineCount(host.code));if(action===null)return;if(e.preventDefault(),action.kind==="activate"){this.onLineActivate(line);return}const next=action.line;this.setFocusedLine(next),host.updateComplete.then(()=>{host.renderRoot.querySelector(`[part~="line-button"][data-line="${next}"]`)?.focus()})},this.onBodyClick=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineActivate(line)},this.onBodyKeyDown=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineKeyDown(e,line)},this.onBodyFocusIn=e=>{const line=codeBlockEventLine(e);line!==null&&this.setFocusedLine(line)},this.onBodyMouseUp=()=>{const selection=codeBlockSelectionAnchor(this.options.host.shadowRoot);selection&&this.options.emitTextSelect(selection)},this.copy=async()=>{const{host}=this.options,owner=host.isConnected?host.ownerDocument.defaultView:null,text=host.code,generation=++this.copyGeneration;this.cancelCopyTimer(),this.setCopyStatus("rest");const outcome=await writeClipboardText(owner,text);if(!owner||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration)return;outcome.ok?(this.options.emitCopy(outcome),this.setCopyStatus("success")):(this.setCopyStatus("error"),this.options.emitError(),this.options.emitCopyError(outcome));let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration||(this.copyTimer=void 0,this.setCopyStatus("rest"))},CODE_BLOCK_COPY_CONFIRM_MS),this.copyTimer={owner,handle}},this.toggleCollapsed=()=>{const{host}=this.options,collapsed=!host.collapsed;this.options.requestToggle(collapsed)&&(host.collapsed=collapsed,this.options.emitToggle(host.collapsed))}}refreshTheme(){this.options.setDarkTheme(resolveIsDarkTheme(this.options.host))}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}disconnect(){this.copyGeneration++,this.cancelCopyTimer(),this.options.setJustCopied(!1),this.options.setCopyFailed(!1)}setCopyStatus(status){this.options.setJustCopied(status==="success"),this.options.setCopyFailed(status==="error")}setFocusedLine(line){this.options.setFocusedLine(line);for(const target of this.options.host.renderRoot.querySelectorAll('[data-line][part~="line-button"]'))target.tabIndex=Number(target.dataset.line)===line?0:-1}}export{CODE_BLOCK_COPY_CONFIRM_MS,CodeBlockInteractionController,addBoundedLineRange,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockBodyLabel,codeBlockCopyLabel,codeBlockEventLine,codeBlockLineCount,codeBlockLineHasFocus,codeBlockLineHighlightSet,codeBlockLineKeyAction,codeBlockLineTransformer,codeBlockNeedsHighlightResync,codeBlockPreSuppliedGrammar,codeBlockSelectionAnchor,codeBlockShowsSkeleton,codeBlockToggleLabel,parseHighlightLines,renderCodeBlockHeader,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock};
74
+ `}class CodeBlockInteractionController{constructor(options){this.options=options,this.copyGeneration=0,this.onLineActivate=line=>{this.setFocusedLine(line),this.options.emitLineActivate(line)},this.onLineKeyDown=(e,line)=>{const{host}=this.options,action=codeBlockLineKeyAction(e.key,line,codeBlockLineCount(host.code));if(action===null)return;if(e.preventDefault(),action.kind==="activate"){this.onLineActivate(line);return}const next=action.line;this.setFocusedLine(next),host.updateComplete.then(()=>{host.renderRoot.querySelector(`[part~="line-button"][data-line="${next}"]`)?.focus()})},this.onBodyClick=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineActivate(line)},this.onBodyKeyDown=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineKeyDown(e,line)},this.onBodyFocusIn=e=>{const line=codeBlockEventLine(e);line!==null&&this.setFocusedLine(line)},this.onBodyMouseUp=()=>{const selection=codeBlockSelectionAnchor(this.options.host.shadowRoot);selection&&this.options.emitTextSelect(selection)},this.copy=async()=>{const{host}=this.options,owner=host.isConnected?host.ownerDocument.defaultView:null,text=host.code,generation=++this.copyGeneration;this.cancelCopyTimer(),this.setCopyStatus("rest");const outcome=await writeClipboardText(owner,text);if(!owner||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration)return;outcome.ok?(this.options.emitCopy(outcome),this.setCopyStatus("success")):(this.setCopyStatus("error"),this.options.emitError(),this.options.emitCopyError(outcome));let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration||(this.copyTimer=void 0,this.setCopyStatus("rest"))},CODE_BLOCK_COPY_CONFIRM_MS),this.copyTimer={owner,handle}},this.toggleCollapsed=()=>{const{host}=this.options,collapsed=!host.collapsed;this.options.requestToggle(collapsed)&&(host.collapsed=collapsed,this.options.emitToggle(host.collapsed))}}refreshTheme(){this.options.setDarkTheme(resolveIsDarkTheme(this.options.host))}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}disconnect(){this.copyGeneration++,this.cancelCopyTimer(),this.options.setJustCopied(!1),this.options.setCopyFailed(!1)}setCopyStatus(status){this.options.setJustCopied(status==="success"),this.options.setCopyFailed(status==="error")}setFocusedLine(line){this.options.setFocusedLine(line);for(const target of this.options.host.renderRoot.querySelectorAll('[data-line][part~="line-button"]'))target.tabIndex=Number(target.dataset.line)===line?0:-1}}export{CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockEventLine,codeBlockLineCount,codeBlockLineHasFocus,codeBlockLineHighlightSet,codeBlockLineTransformer,codeBlockNeedsHighlightResync,codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton,parseHighlightLines,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock};
@@ -36,7 +36,7 @@ export interface ShikiLanguageInput {
36
36
  repository?: Record<string, unknown>;
37
37
  }
38
38
  /** The subset of a Shiki/HAST element node that Lyra's transformers mutate. */
39
- export interface ShikiTransformerNode {
39
+ interface ShikiTransformerNode {
40
40
  properties: Record<string, unknown> & {
41
41
  part?: unknown;
42
42
  role?: unknown;
@@ -64,3 +64,4 @@ export declare function normalizeShikiLanguage(lang: string): string;
64
64
  * unreachable from lean component graphs.
65
65
  */
66
66
  export declare function loadShikiHighlighterCore(languages: Record<string, ShikiLanguageInput>): Promise<ShikiHighlighterCore | null>;
67
+ export {};
@@ -8,7 +8,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
8
8
  aria-hidden="true"
9
9
  focusable="false"
10
10
  ><rect x="6" y="6" width="12" height="12" rx="1.5"></rect></svg>
11
- `}function formatElapsed(ms,locale){const totalSeconds=Math.max(0,ms)/1e3;if(totalSeconds<59.95)return{key:"generationStatusElapsedSeconds",values:{seconds:getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1}).format(Math.round(totalSeconds*10)/10)}};const wholeSeconds=Math.round(totalSeconds),minutes=Math.floor(wholeSeconds/60),seconds=wholeSeconds%60,numberFormat=getNumberFormat(locale,{maximumFractionDigits:0});return{key:"elapsedMinutesSecondsTemplate",values:{minutes:numberFormat.format(minutes),seconds:numberFormat.format(seconds)}}}function formatTokenCount(count,locale){const rounded=Math.max(0,Math.round(count));return{rounded,formatted:getNumberFormat(locale).format(rounded)}}function formatThroughput(value,locale){const clamped=Math.max(0,value),rounded=clamped<10?Math.round(clamped*10)/10:Math.round(clamped);return getNumberFormat(locale,{maximumFractionDigits:clamped<10?1:0}).format(rounded)}const showStopConverter={fromAttribute(value){return value!=="false"},toAttribute(value){return value?null:"false"}},GENERATION_METRICS_STATUS=literalSetConverter(["idle","running","complete"],"idle");class LyraGenerationMetrics extends LyraElement{static{this.defaultStrings={...super.defaultStrings,elapsedMinutesSecondsTemplate:LYRA_DEFAULT_elapsedMinutesSecondsTemplate,generationStatusElapsedSeconds:LYRA_DEFAULT_generationStatusElapsedSeconds,generationStatusThroughput:LYRA_DEFAULT_generationStatusThroughput,generationStatusTokenCount:LYRA_DEFAULT_generationStatusTokenCount,generationStatusTokensCount:LYRA_DEFAULT_generationStatusTokensCount,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get status(){return this._status}set status(next){const normalized=GENERATION_METRICS_STATUS.normalize(next),old=this._status;old!==normalized&&(this._status=normalized,this.requestUpdate("status",old))}constructor(){super(),this._status="idle",this.showStop=!0,this.elapsedMs=0,this.tickerGeneration=0,this.onStopClick=()=>{this.emit("lr-stop",null)},this.requestUpdate("status",void 0)}connectedCallback(){super.connectedCallback(),this.status==="running"&&(this.elapsedMs=this.computeElapsedMs(),this.startTicker())}disconnectedCallback(){this.stopTicker(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopTicker(),this.isConnected&&this.status==="running"&&this.startTicker()}willUpdate(changed){super.willUpdate(changed),changed.has("status")?this.status==="running"?(this.validStartedAt==null&&(this.fallbackStartMs=Date.now()),this.elapsedMs=this.computeElapsedMs()):this.status==="idle"&&(this.fallbackStartMs=void 0,this.elapsedMs=0):this.status==="running"&&changed.has("startedAt")&&(this.validStartedAt==null?this.fallbackStartMs=Date.now()-this.elapsedMs:this.fallbackStartMs=void 0,this.elapsedMs=this.computeElapsedMs())}updated(changed){super.updated(changed),changed.has("status")&&(this.status==="running"?this.startTicker():this.stopTicker())}startTicker(){if(this.stopTicker(),!this.isConnected||this.status!=="running")return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const generation=this.tickerGeneration,handle=ownerWindow.setInterval(()=>{this.tickTimer!==handle||this.tickTimerOwner!==ownerWindow||this.tickTimerDocument!==ownerDocument||this.tickerGeneration!==generation||!this.isConnected||this.status!=="running"||this.ownerDocument!==ownerDocument||(this.elapsedMs=this.computeElapsedMs())},1e3);this.tickTimer=handle,this.tickTimerOwner=ownerWindow,this.tickTimerDocument=ownerDocument}stopTicker(){this.tickerGeneration+=1,this.tickTimer!==void 0&&this.tickTimerOwner?.clearInterval(this.tickTimer),this.tickTimer=void 0,this.tickTimerOwner=void 0,this.tickTimerDocument=void 0}get validStartedAt(){if(!(this.startedAt==null||!Number.isFinite(this.startedAt)))return finiteRange(this.startedAt,this.startedAt,0)}computeElapsedMs(){const start=this.validStartedAt??this.fallbackStartMs;return start==null?0:Math.max(0,Date.now()-start)}get validTokenCount(){if(!(this.tokenCount==null||!Number.isFinite(this.tokenCount)))return finiteCount(Math.round(this.tokenCount))}get effectiveTokensPerSecond(){if(this.tokensPerSecond!=null&&Number.isFinite(this.tokensPerSecond))return finiteRange(this.tokensPerSecond,this.tokensPerSecond,0);const tokenCount=this.validTokenCount;if(tokenCount!==void 0){const elapsedSeconds=this.elapsedMs/1e3;if(elapsedSeconds>=1)return tokenCount/elapsedSeconds}}render(){const validTokenCount=this.validTokenCount,hasTokens=validTokenCount!==void 0,throughput=this.effectiveTokensPerSecond,hasThroughput=throughput!==void 0,locale=this.effectiveLocale,elapsed=formatElapsed(this.elapsedMs,locale),tokenCount=hasTokens?formatTokenCount(validTokenCount,locale):void 0,tokenMessageKey=tokenCount&&getPluralRules(locale).select(tokenCount.rounded)==="one"?"generationStatusTokenCount":"generationStatusTokensCount";return html`
11
+ `}function formatElapsed(ms,locale){const totalSeconds=Math.max(0,ms)/1e3;if(totalSeconds<59.95)return{key:"generationStatusElapsedSeconds",values:{seconds:getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1}).format(Math.round(totalSeconds*10)/10)}};const wholeSeconds=Math.round(totalSeconds),minutes=Math.floor(wholeSeconds/60),seconds=wholeSeconds%60,numberFormat=getNumberFormat(locale,{maximumFractionDigits:0});return{key:"elapsedMinutesSecondsTemplate",values:{minutes:numberFormat.format(minutes),seconds:numberFormat.format(seconds)}}}function formatTokenCount(count,locale){const rounded=Math.max(0,Math.round(count));return{rounded,formatted:getNumberFormat(locale).format(rounded)}}function formatThroughput(value,locale){const clamped=Math.max(0,value),rounded=clamped<10?Math.round(clamped*10)/10:Math.round(clamped);return getNumberFormat(locale,{maximumFractionDigits:clamped<10?1:0}).format(rounded)}const showStopConverter={fromAttribute(value){return value!=="false"}},GENERATION_METRICS_STATUS=literalSetConverter(["idle","running","complete"],"idle");class LyraGenerationMetrics extends LyraElement{static{this.defaultStrings={...super.defaultStrings,elapsedMinutesSecondsTemplate:LYRA_DEFAULT_elapsedMinutesSecondsTemplate,generationStatusElapsedSeconds:LYRA_DEFAULT_generationStatusElapsedSeconds,generationStatusThroughput:LYRA_DEFAULT_generationStatusThroughput,generationStatusTokenCount:LYRA_DEFAULT_generationStatusTokenCount,generationStatusTokensCount:LYRA_DEFAULT_generationStatusTokensCount,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get status(){return this._status}set status(next){const normalized=GENERATION_METRICS_STATUS.normalize(next),old=this._status;old!==normalized&&(this._status=normalized,this.requestUpdate("status",old))}constructor(){super(),this._status="idle",this.showStop=!0,this.elapsedMs=0,this.tickerGeneration=0,this.onStopClick=()=>{this.emit("lr-stop",null)},this.requestUpdate("status",void 0)}connectedCallback(){super.connectedCallback(),this.status==="running"&&(this.elapsedMs=this.computeElapsedMs(),this.startTicker())}disconnectedCallback(){this.stopTicker(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopTicker(),this.isConnected&&this.status==="running"&&this.startTicker()}willUpdate(changed){super.willUpdate(changed),changed.has("status")?this.status==="running"?(this.validStartedAt==null&&(this.fallbackStartMs=Date.now()),this.elapsedMs=this.computeElapsedMs()):this.status==="idle"&&(this.fallbackStartMs=void 0,this.elapsedMs=0):this.status==="running"&&changed.has("startedAt")&&(this.validStartedAt==null?this.fallbackStartMs=Date.now()-this.elapsedMs:this.fallbackStartMs=void 0,this.elapsedMs=this.computeElapsedMs())}updated(changed){super.updated(changed),changed.has("status")&&(this.status==="running"?this.startTicker():this.stopTicker())}startTicker(){if(this.stopTicker(),!this.isConnected||this.status!=="running")return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const generation=this.tickerGeneration,handle=ownerWindow.setInterval(()=>{this.tickTimer!==handle||this.tickTimerOwner!==ownerWindow||this.tickTimerDocument!==ownerDocument||this.tickerGeneration!==generation||!this.isConnected||this.status!=="running"||this.ownerDocument!==ownerDocument||(this.elapsedMs=this.computeElapsedMs())},1e3);this.tickTimer=handle,this.tickTimerOwner=ownerWindow,this.tickTimerDocument=ownerDocument}stopTicker(){this.tickerGeneration+=1,this.tickTimer!==void 0&&this.tickTimerOwner?.clearInterval(this.tickTimer),this.tickTimer=void 0,this.tickTimerOwner=void 0,this.tickTimerDocument=void 0}get validStartedAt(){if(!(this.startedAt==null||!Number.isFinite(this.startedAt)))return finiteRange(this.startedAt,this.startedAt,0)}computeElapsedMs(){const start=this.validStartedAt??this.fallbackStartMs;return start==null?0:Math.max(0,Date.now()-start)}get validTokenCount(){if(!(this.tokenCount==null||!Number.isFinite(this.tokenCount)))return finiteCount(Math.round(this.tokenCount))}get effectiveTokensPerSecond(){if(this.tokensPerSecond!=null&&Number.isFinite(this.tokensPerSecond))return finiteRange(this.tokensPerSecond,this.tokensPerSecond,0);const tokenCount=this.validTokenCount;if(tokenCount!==void 0){const elapsedSeconds=this.elapsedMs/1e3;if(elapsedSeconds>=1)return tokenCount/elapsedSeconds}}render(){const validTokenCount=this.validTokenCount,hasTokens=validTokenCount!==void 0,throughput=this.effectiveTokensPerSecond,hasThroughput=throughput!==void 0,locale=this.effectiveLocale,elapsed=formatElapsed(this.elapsedMs,locale),tokenCount=hasTokens?formatTokenCount(validTokenCount,locale):void 0,tokenMessageKey=tokenCount&&getPluralRules(locale).select(tokenCount.rounded)==="one"?"generationStatusTokenCount":"generationStatusTokensCount";return html`
12
12
  <div part="base">
13
13
  <span part="elapsed">${this.localize(elapsed.key,void 0,elapsed.values)}</span>
14
14
  ${hasTokens?html`<span part="tokens"
@@ -1,6 +1,5 @@
1
1
  import { type TemplateResult, type PropertyValues } from 'lit';
2
2
  import { LyraElement } from '../../../internal/lyra-element.js';
3
- import '../../../internal/form-control-labels.js';
4
3
  import type { LyraSize } from '../../../internal/variants.js';
5
4
  import type { LyraSelectionDirection } from '../../../internal/shared-unions.js';
6
5
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
@@ -204,9 +203,7 @@ export declare class LyraModelSelect extends LyraElement<LyraModelSelectEventMap
204
203
  * or Shoelace needs no attribute rewrite. */
205
204
  size: LyraSize;
206
205
  private get activeIndex();
207
- private set activeIndex(value);
208
206
  private get query();
209
- private set query(value);
210
207
  private touched;
211
208
  private readonly slotPresence;
212
209
  private internals;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{activeElementIn}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings.generated.js";class LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog}}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}set activeIndex(next){this.catalogPicker.setActiveIndex(next)}get query(){return this.catalogPicker.query}set query(next){this.catalogPicker.setQuery(next)}constructor(){super(),this.provider="",this.allowCustom=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.listId=nextId("model-select-list"),this.controlId=nextId("model-select-control"),this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this.suppressControlBlur=!1,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label],emitChange:detail=>this.emit("lr-change",detail),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?this.requestUpdate("open",oldValue):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)},forwardFreeInputClick:!0}),this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onTriggerFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}click(){this.catalogPicker.click()}focus(options){this.catalogPicker.focus(options)}blur(){this.catalogPicker.blur()}get input(){return this.catalogPicker.input}get selectionStart(){return this.input?.selectionStart??null}set selectionStart(value){this.input&&(this.input.selectionStart=value)}get selectionEnd(){return this.input?.selectionEnd??null}set selectionEnd(value){this.input&&(this.input.selectionEnd=value)}get selectionDirection(){return this.input?.selectionDirection??null}set selectionDirection(value){this.input&&(this.input.selectionDirection=value)}select(){this.catalogPicker.select()}setSelectionRange(start,end,direction){this.catalogPicker.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){this.catalogPicker.setRangeText(replacement,start,end,selectMode)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);let modeChanged=!1;if(this.hasUpdated){const renderedControl=this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]');modeChanged=renderedControl?.getAttribute("part")==="trigger"!==this.closedMode,this.suppressControlBlur=modeChanged,this.catalogPicker.suppressControlEvents=modeChanged,this.modeFocusRepair=modeChanged&&renderedControl!==null&&activeElementIn(this.shadowRoot)===renderedControl?captureComposedFocusRepair(this,this.modeFocusFallback()??renderedControl)??void 0:modeChanged?this.focusedModeRepair:void 0}this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))&&this.catalogPicker.reconcileRows(void 0,changed.has("value")||changed.has("allowCustom")||modeChanged,!1)}disconnectedCallback(){super.disconnectedCallback(),this.modeFocusRepair=void 0,this.focusedModeRepair=void 0,this.focusReturnTarget=void 0,this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.modeFocusRepair=void 0,this.focusedModeRepair=void 0,this.focusReturnTarget=void 0,this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("modelSelectRequired")):this.validityController.setValidity({}),this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.publishValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishValidityStates()}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("touched")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.publishValidityStates(),this.suppressControlBlur=!1,this.catalogPicker.suppressControlEvents=!1;const focusRepair=this.modeFocusRepair;this.modeFocusRepair=void 0,focusRepair&&this.scheduleAfterUpdate(()=>{const replacement=this[VALIDITY_ANCHOR](),target=replacement&&isComposedFocusAvailable(replacement)?replacement:this.modeFocusFallback();applyComposedFocusRepair(focusRepair,target),this.focusedModeRepair===focusRepair&&(this.focusedModeRepair=void 0)},"model-select-mode-focus")}rememberFocusReturn(event){const related=event.relatedTarget;related&&related.nodeType===1&&isComposedFocusAvailable(related)&&(this.focusReturnTarget=related)}captureModeFocus(event){this.rememberFocusReturn(event);const control=event.currentTarget;!control||control.nodeType!==1||(this.focusedModeRepair=captureComposedFocusRepair(this,this.modeFocusFallback()??control)??void 0)}retireModeFocusAfterBlur(event){const destination=event.relatedTarget;if(destination&&destination.nodeType===1){this.focusedModeRepair=void 0;return}queueMicrotask(()=>{!this.suppressControlBlur&&!this.effectiveDisabled&&!this.hasAttribute("inert")&&(this.focusedModeRepair=void 0)})}modeFocusFallback(){if(this.focusReturnTarget&&isComposedFocusAvailable(this.focusReturnTarget))return this.focusReturnTarget;const owner=this.renderRoot.querySelector('[part="form-control"]');return owner&&isComposedFocusAvailable(owner)?owner:null}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value;return html`<div
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{activeElementIn}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings.generated.js";class LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog}}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}constructor(){super(),this.provider="",this.allowCustom=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.listId=nextId("model-select-list"),this.controlId=nextId("model-select-control"),this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this.suppressControlBlur=!1,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label],emitChange:detail=>this.emit("lr-change",detail),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?this.requestUpdate("open",oldValue):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)},forwardFreeInputClick:!0}),this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onTriggerFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}click(){this.catalogPicker.click()}focus(options){this.catalogPicker.focus(options)}blur(){this.catalogPicker.blur()}get input(){return this.catalogPicker.input}get selectionStart(){return this.input?.selectionStart??null}set selectionStart(value){this.input&&(this.input.selectionStart=value)}get selectionEnd(){return this.input?.selectionEnd??null}set selectionEnd(value){this.input&&(this.input.selectionEnd=value)}get selectionDirection(){return this.input?.selectionDirection??null}set selectionDirection(value){this.input&&(this.input.selectionDirection=value)}select(){this.catalogPicker.select()}setSelectionRange(start,end,direction){this.catalogPicker.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){this.catalogPicker.setRangeText(replacement,start,end,selectMode)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);let modeChanged=!1;if(this.hasUpdated){const renderedControl=this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]');modeChanged=renderedControl?.getAttribute("part")==="trigger"!==this.closedMode,this.suppressControlBlur=modeChanged,this.catalogPicker.suppressControlEvents=modeChanged,this.modeFocusRepair=modeChanged&&renderedControl!==null&&activeElementIn(this.shadowRoot)===renderedControl?captureComposedFocusRepair(this,this.modeFocusFallback()??renderedControl)??void 0:modeChanged?this.focusedModeRepair:void 0}this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))&&this.catalogPicker.reconcileRows(void 0,changed.has("value")||changed.has("allowCustom")||modeChanged,!1)}disconnectedCallback(){super.disconnectedCallback(),this.modeFocusRepair=void 0,this.focusedModeRepair=void 0,this.focusReturnTarget=void 0,this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.modeFocusRepair=void 0,this.focusedModeRepair=void 0,this.focusReturnTarget=void 0,this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("modelSelectRequired")):this.validityController.setValidity({}),this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.publishValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishValidityStates()}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("touched")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.publishValidityStates(),this.suppressControlBlur=!1,this.catalogPicker.suppressControlEvents=!1;const focusRepair=this.modeFocusRepair;this.modeFocusRepair=void 0,focusRepair&&this.scheduleAfterUpdate(()=>{const replacement=this[VALIDITY_ANCHOR](),target=replacement&&isComposedFocusAvailable(replacement)?replacement:this.modeFocusFallback();applyComposedFocusRepair(focusRepair,target),this.focusedModeRepair===focusRepair&&(this.focusedModeRepair=void 0)},"model-select-mode-focus")}rememberFocusReturn(event){const related=event.relatedTarget;related&&related.nodeType===1&&isComposedFocusAvailable(related)&&(this.focusReturnTarget=related)}captureModeFocus(event){this.rememberFocusReturn(event);const control=event.currentTarget;!control||control.nodeType!==1||(this.focusedModeRepair=captureComposedFocusRepair(this,this.modeFocusFallback()??control)??void 0)}retireModeFocusAfterBlur(event){const destination=event.relatedTarget;if(destination&&destination.nodeType===1){this.focusedModeRepair=void 0;return}queueMicrotask(()=>{!this.suppressControlBlur&&!this.effectiveDisabled&&!this.hasAttribute("inert")&&(this.focusedModeRepair=void 0)})}modeFocusFallback(){if(this.focusReturnTarget&&isComposedFocusAvailable(this.focusReturnTarget))return this.focusReturnTarget;const owner=this.renderRoot.querySelector('[part="form-control"]');return owner&&isComposedFocusAvailable(owner)?owner:null}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value;return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssLength}from"../../../internal/css-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isActionableElement,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{styles}from"./selection-toolbar.styles.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings.generated.js";const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{constructor(){super(...arguments),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.label="",this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.authoredActionTabIndex=new WeakMap,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{for(const record of records){if(record.type!=="attributes"||record.attributeName!=="tabindex")continue;const target=record.target;this.authoredActionTabIndex.has(target)&&this.authoredActionTabIndex.set(target,target.getAttribute("tabindex"))}this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{const buttons=this.actionButtons();if(buttons.length===0)return;const originIndex=buttons.findIndex(button=>event.composedPath().includes(button)),currentIndex=originIndex>=0?originIndex:this.activeActionIndex,forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let next;if(event.key===forward)next=(currentIndex+1)%buttons.length;else if(event.key===backward)next=(currentIndex-1+buttons.length)%buttons.length;else if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const gap=this.placementGapPx(),edge=gap,viewport=this.viewportBounds(view),rect=this.safeRect(this.rect??new view.DOMRect(viewport.left+viewport.width/2,viewport.top,0,0));toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",`${Math.max(0,viewport.width-edge*2)}px`),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",`${Math.max(0,viewport.height-edge*2)}px`);const width=toolbar.offsetWidth,height=toolbar.offsetHeight,desiredInline=rect.left+rect.width/2,desiredLeft=desiredInline-width/2,minLeft=viewport.left+edge,maxLeft=Math.max(minLeft,viewport.right-width-edge),left=Math.min(maxLeft,Math.max(minLeft,desiredLeft)),above=rect.top-height-gap,below=rect.bottom+gap,minTop=viewport.top+edge,desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,viewport.bottom-height-edge),top=Math.min(maxTop,Math.max(minTop,desiredTop)),logicalInline=this.effectiveDirection==="rtl"?viewport.layoutWidth-desiredInline:desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",`${logicalInline}px`),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",`${rect.top}px`),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",`${left-(desiredInline-width/2)}px`),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",`${top-(rect.top-height)}px`),toolbar.toggleAttribute("data-positioned",!0)}}static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.retirePositioning(),this.overlay?.suspend(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0;return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0;return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss(),modal:!1,trapFocus:!1}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>!!isSemanticActionElement(button)||(this.authoredActionTabIndex.has(button)?this.authoredActionTabIndex.get(button)!==null:button.hasAttribute("tabindex"))):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll("lr-button[data-action]")],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll("lr-button[data-action]")].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}setRovingStops(buttons,index){this.actionObserver?.disconnect();for(const button of buttons)this.authoredActionTabIndex.has(button)||this.authoredActionTabIndex.set(button,button.getAttribute("tabindex"));for(const previous of this.managedActionStops)!buttons.includes(previous)&&(previous.hasAttribute("tabindex")||isActionableElement(previous))&&(previous.tabIndex=-1);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{button.tabIndex=buttonIndex===this.activeActionIndex?0:-1}),this.managedActionStops=new Set(buttons),this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&&current!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options={attributes:!0,attributeOldValue:!0,attributeFilter:["aria-disabled","aria-hidden","contenteditable","controls","disabled","hidden","href","inert","open","role","tabindex","type"],childList:!0,subtree:!0};for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){return{left:finiteNumber(rect.left,0),top:finiteNumber(rect.top,0),width:finiteNumber(rect.width,0),bottom:finiteNumber(rect.bottom,0)}}viewportBounds(view){const layoutWidth=Math.max(0,finiteNumber(view.innerWidth,0)),layoutHeight=Math.max(0,finiteNumber(view.innerHeight,0)),viewport=view.visualViewport,left=Math.max(0,finiteNumber(viewport?.offsetLeft??0,0)),top=Math.max(0,finiteNumber(viewport?.offsetTop??0,0)),width=Math.max(0,finiteNumber(viewport?.width??layoutWidth,layoutWidth)),height=Math.max(0,finiteNumber(viewport?.height??layoutHeight,layoutHeight));return{left,top,width,height,right:left+width,bottom:top+height,layoutWidth}}coordinates(){const view=this.ownerDocument.defaultView,viewport=view?this.viewportBounds(view):{left:0,top:0,width:0,height:0,right:0,bottom:0,layoutWidth:0},rect=this.rect?this.safeRect(this.rect):void 0,desiredInline=rect?rect.left+rect.width/2:viewport.left+viewport.width/2,block=rect?.top??viewport.top;return{"--_lr-selection-toolbar-inline-start":`${this.effectiveDirection==="rtl"?viewport.layoutWidth-desiredInline:desiredInline}px`,"--_lr-selection-toolbar-block-start":`${block}px`}}placementGapPx(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"";return finiteRange(resolveCssLength(raw,{host:this})??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label||this.localize("selectionToolbarLabel"));return html`<div
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssLength}from"../../../internal/css-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isActionableElement,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{styles}from"./selection-toolbar.styles.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings.generated.js";const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{constructor(){super(...arguments),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.label="",this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.authoredActionTabIndex=new WeakMap,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{for(const record of records){if(record.type!=="attributes"||record.attributeName!=="tabindex")continue;const target=record.target;this.authoredActionTabIndex.has(target)&&this.authoredActionTabIndex.set(target,target.getAttribute("tabindex"))}this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{const buttons=this.actionButtons();if(buttons.length===0)return;const originIndex=buttons.findIndex(button=>event.composedPath().includes(button)),currentIndex=originIndex>=0?originIndex:this.activeActionIndex,forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let next;if(event.key===forward)next=(currentIndex+1)%buttons.length;else if(event.key===backward)next=(currentIndex-1+buttons.length)%buttons.length;else if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const gap=this.placementGapPx(),edge=gap,viewport=this.viewportBounds(view),rect=this.safeRect(this.rect??new view.DOMRect(viewport.left+viewport.width/2,viewport.top,0,0));toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",`${Math.max(0,viewport.width-edge*2)}px`),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",`${Math.max(0,viewport.height-edge*2)}px`);const width=toolbar.offsetWidth,height=toolbar.offsetHeight,desiredInline=rect.left+rect.width/2,desiredLeft=desiredInline-width/2,minLeft=viewport.left+edge,maxLeft=Math.max(minLeft,viewport.right-width-edge),left=Math.min(maxLeft,Math.max(minLeft,desiredLeft)),above=rect.top-height-gap,below=rect.bottom+gap,minTop=viewport.top+edge,desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,viewport.bottom-height-edge),top=Math.min(maxTop,Math.max(minTop,desiredTop)),logicalInline=this.effectiveDirection==="rtl"?viewport.layoutWidth-desiredInline:desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",`${logicalInline}px`),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",`${rect.top}px`),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",`${left-(desiredInline-width/2)}px`),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",`${top-(rect.top-height)}px`),toolbar.toggleAttribute("data-positioned",!0)}}static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.retirePositioning(),this.overlay?.suspend(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0;return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0;return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss()}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>!!isSemanticActionElement(button)||(this.authoredActionTabIndex.has(button)?this.authoredActionTabIndex.get(button)!==null:button.hasAttribute("tabindex"))):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll("lr-button[data-action]")],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll("lr-button[data-action]")].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}setRovingStops(buttons,index){this.actionObserver?.disconnect();for(const button of buttons)this.authoredActionTabIndex.has(button)||this.authoredActionTabIndex.set(button,button.getAttribute("tabindex"));for(const previous of this.managedActionStops)!buttons.includes(previous)&&(previous.hasAttribute("tabindex")||isActionableElement(previous))&&(previous.tabIndex=-1);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{button.tabIndex=buttonIndex===this.activeActionIndex?0:-1}),this.managedActionStops=new Set(buttons),this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&&current!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options={attributes:!0,attributeOldValue:!0,attributeFilter:["aria-disabled","aria-hidden","contenteditable","controls","disabled","hidden","href","inert","open","role","tabindex","type"],childList:!0,subtree:!0};for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){return{left:finiteNumber(rect.left,0),top:finiteNumber(rect.top,0),width:finiteNumber(rect.width,0),bottom:finiteNumber(rect.bottom,0)}}viewportBounds(view){const layoutWidth=Math.max(0,finiteNumber(view.innerWidth,0)),layoutHeight=Math.max(0,finiteNumber(view.innerHeight,0)),viewport=view.visualViewport,left=Math.max(0,finiteNumber(viewport?.offsetLeft??0,0)),top=Math.max(0,finiteNumber(viewport?.offsetTop??0,0)),width=Math.max(0,finiteNumber(viewport?.width??layoutWidth,layoutWidth)),height=Math.max(0,finiteNumber(viewport?.height??layoutHeight,layoutHeight));return{left,top,width,height,right:left+width,bottom:top+height,layoutWidth}}coordinates(){const view=this.ownerDocument.defaultView,viewport=view?this.viewportBounds(view):{left:0,top:0,width:0,height:0,right:0,bottom:0,layoutWidth:0},rect=this.rect?this.safeRect(this.rect):void 0,desiredInline=rect?rect.left+rect.width/2:viewport.left+viewport.width/2,block=rect?.top??viewport.top;return{"--_lr-selection-toolbar-inline-start":`${this.effectiveDirection==="rtl"?viewport.layoutWidth-desiredInline:desiredInline}px`,"--_lr-selection-toolbar-block-start":`${block}px`}}placementGapPx(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"";return finiteRange(resolveCssLength(raw,{host:this})??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label||this.localize("selectionToolbarLabel"));return html`<div
2
2
  part="toolbar"
3
3
  role="toolbar"
4
4
  aria-label=${label}
@@ -1,6 +1,5 @@
1
1
  import { type TemplateResult, type PropertyValues } from 'lit';
2
2
  import { LyraElement } from '../../../internal/lyra-element.js';
3
- import '../../../internal/form-control-labels.js';
4
3
  import type { LyraSize } from '../../../internal/variants.js';
5
4
  import type { LyraSelectionDirection } from '../../../internal/shared-unions.js';
6
5
  import { type FormOwnerValue } from '../../../internal/form-associated.js';