@aceshooting/lyra-ui 11.0.0 → 11.2.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 (135) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +8 -0
  3. package/custom-elements.json +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  5. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  6. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  7. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  8. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  9. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  10. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  11. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  12. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  13. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  14. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  15. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  16. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  17. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  18. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  19. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  20. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  21. package/dist/components/charts/chart/chart.class.js +1 -1
  22. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  23. package/dist/components/charts/chart/histogram.class.js +1 -1
  24. package/dist/components/charts/chart/line-chart.class.js +1 -1
  25. package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
  26. package/dist/components/charts/chart/lite-chart.class.js +17 -4
  27. package/dist/components/charts/chart/lite-chart.styles.js +29 -0
  28. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  29. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  30. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  31. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  32. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  33. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  34. package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
  35. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  36. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  37. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
  38. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  39. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  40. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  41. package/dist/components/data/heatmap/heatmap.class.d.ts +36 -1
  42. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  43. package/dist/components/data/table/table.class.d.ts +19 -0
  44. package/dist/components/data/table/table.class.js +3 -3
  45. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  46. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  47. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  48. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  49. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  50. package/dist/components/forms/combobox/combobox.class.js +1 -1
  51. package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
  52. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  53. package/dist/components/forms/date-picker/date-picker.class.d.ts +30 -4
  54. package/dist/components/forms/date-picker/date-picker.class.js +4 -4
  55. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  56. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  57. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  58. package/dist/components/forms/radio/radio-group.class.js +1 -1
  59. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  60. package/dist/components/forms/radio/radio.class.js +1 -1
  61. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  62. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  63. package/dist/components/forms/select/select.class.d.ts +1 -0
  64. package/dist/components/forms/select/select.class.js +1 -1
  65. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  66. package/dist/components/forms/slider/slider.class.js +1 -1
  67. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  68. package/dist/components/forms/switch/switch.class.js +1 -1
  69. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  70. package/dist/components/forms/time-range/time-range.class.js +1 -1
  71. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  72. package/dist/components/forms/token-input/token-input.class.js +1 -1
  73. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  74. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  75. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  76. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  77. package/dist/components/media/file-input/file-input.class.js +1 -1
  78. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  79. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  80. package/dist/components/media/flag/flag.class.d.ts +28 -0
  81. package/dist/components/media/flag/flag.class.js +2 -2
  82. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  83. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  84. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  85. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  86. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  87. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  88. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  89. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  90. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  91. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  92. package/dist/custom-elements-jsx.d.ts +5 -3
  93. package/dist/events.d.ts +7 -0
  94. package/dist/internal/canvas.js +1 -1
  95. package/dist/internal/form-associated.d.ts +1 -0
  96. package/dist/internal/form-associated.js +1 -1
  97. package/dist/internal/form-control-labels.js +1 -1
  98. package/dist/internal/lyra-element.js +1 -1
  99. package/dist/internal/package-metadata.d.ts +1 -1
  100. package/dist/internal/package-metadata.js +1 -1
  101. package/dist/lyra.d.ts +1 -1
  102. package/dist/svelte.d.ts +5 -3
  103. package/dist/theme.css +32 -0
  104. package/dist/vue.d.ts +5 -3
  105. package/llms/components/lr-agent-eval-dashboard.md +1 -1
  106. package/llms/components/lr-agent-workspace.md +1 -1
  107. package/llms/components/lr-box-plot.md +2 -2
  108. package/llms/components/lr-chart.md +1 -1
  109. package/llms/components/lr-chunk-inspector.md +1 -1
  110. package/llms/components/lr-combobox.md +3 -3
  111. package/llms/components/lr-date-input.md +22 -6
  112. package/llms/components/lr-date-picker.md +21 -5
  113. package/llms/components/lr-entity-dossier.md +1 -1
  114. package/llms/components/lr-eval-run.md +1 -1
  115. package/llms/components/lr-flag.md +24 -1
  116. package/llms/components/lr-grounding-summary.md +1 -1
  117. package/llms/components/lr-heatmap.md +18 -6
  118. package/llms/components/lr-lite-chart.md +19 -3
  119. package/llms/components/lr-map.md +2 -2
  120. package/llms/components/lr-memory-panel.md +1 -1
  121. package/llms/components/lr-option.md +3 -3
  122. package/llms/components/lr-popover.md +1 -1
  123. package/llms/components/lr-provenance-panel.md +1 -1
  124. package/llms/components/lr-rag-answer.md +1 -1
  125. package/llms/components/lr-rag-eval-dashboard.md +1 -1
  126. package/llms/components/lr-retrieval-results.md +1 -1
  127. package/llms/components/lr-retrieval-trace.md +1 -1
  128. package/llms/peers.md +10 -10
  129. package/llms/shared.md +19 -0
  130. package/llms/tokens.md +12 -0
  131. package/llms-full.txt +109 -21
  132. package/package.json +6 -6
  133. package/vscode-css-data.json +14 -0
  134. package/vscode-html-data.json +17 -3
  135. package/web-types.json +30 -4
@@ -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._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 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"),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
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`}
@@ -155,9 +155,22 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
155
155
  <lr-live-region part="live-region"></lr-live-region>
156
156
  ${this.description?html`<p part="description" id=${this.descriptionId} class="sr-only">${this.description}</p>`:nothing}
157
157
  ${dataTruncation?html`<p part="data-truncation">${dataTruncation}</p>`:nothing}
158
- <div part="data-table" ?data-visually-hidden=${!hasCustomDataTable}>
158
+ ${this.dataTableToggle?html`<button
159
+ part="data-table-toggle"
160
+ type="button"
161
+ aria-expanded=${this.dataTableVisible?"true":"false"}
162
+ aria-controls=${this.dataTableId}
163
+ @click=${()=>this.toggleDataTable()}
164
+ >
165
+ ${this.localize("chartData")}
166
+ </button>`:nothing}
167
+ <div
168
+ id=${this.dataTableId}
169
+ part="data-table"
170
+ ?data-visually-hidden=${!hasCustomDataTable&&!this.dataTableVisible}
171
+ >
159
172
  <slot name="data-table" @slotchange=${()=>this.requestUpdate()}></slot>
160
- ${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class="sr-only">
173
+ ${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class=${this.dataTableVisible?nothing:"sr-only"}>
161
174
  <caption>${this.localize("chartData")}</caption>
162
175
  <thead>
163
176
  <tr>
@@ -190,4 +203,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
190
203
  `})}
191
204
  </div>`:nothing}
192
205
  </div>
193
- `}}__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({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({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};
@@ -187,4 +187,33 @@ import{css}from"lit";import{forcedColorLegendSwatchStyles}from"./chart-forced-co
187
187
  grid-template-columns: minmax(0, 1fr);
188
188
  }
189
189
  }
190
+
191
+ [part='data-table-toggle'] {
192
+ align-self: flex-start;
193
+ font: inherit;
194
+ font-size: var(--lr-font-size-xs);
195
+ min-block-size: var(--lr-icon-button-size);
196
+ padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem);
197
+ border: var(--lr-border-width-thin) solid var(--lr-color-border);
198
+ border-radius: var(--lr-radius);
199
+ background: var(--lr-color-surface);
200
+ color: var(--lr-color-text);
201
+ max-inline-size: 100%;
202
+ white-space: normal;
203
+ overflow-wrap: break-word;
204
+ cursor: pointer;
205
+ }
206
+ [part='data-table-toggle']:hover {
207
+ background: var(--lr-lite-chart-data-table-toggle-hover-bg, var(--lr-color-brand-quiet));
208
+ }
209
+ [part='data-table-toggle']:active {
210
+ background: var(
211
+ --lr-lite-chart-data-table-toggle-active-bg,
212
+ color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))
213
+ );
214
+ }
215
+ [part='data-table-toggle']:focus-visible {
216
+ outline: var(--lr-focus-ring);
217
+ outline-offset: var(--lr-focus-ring-offset);
218
+ }
190
219
  `;export{styles};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraPieChart extends LyraChart{constructor(){super(...arguments),this.type="pie"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraPieChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraPieChart extends LyraChart{constructor(){super(...arguments),this.type="pie"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraPieChart};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraPolarAreaChart extends LyraChart{constructor(){super(...arguments),this.type="polarArea"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraPolarAreaChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraPolarAreaChart extends LyraChart{constructor(){super(...arguments),this.type="polarArea"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraPolarAreaChart};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraRadarChart extends LyraChart{constructor(){super(...arguments),this.type="radar"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraRadarChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraRadarChart extends LyraChart{constructor(){super(...arguments),this.type="radar"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraRadarChart};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraScatterChart extends LyraChart{constructor(){super(...arguments),this.type="scatter"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraScatterChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraScatterChart extends LyraChart{constructor(){super(...arguments),this.type="scatter"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraScatterChart};
@@ -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,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapse,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_details,LYRA_DEFAULT_expandMessage,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
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,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapse,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_details,LYRA_DEFAULT_expandMessage,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  aria-hidden="true"
12
12
  focusable="false"
13
13
  ><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
14
- `}function defaultFormatTimestamp(date,locale){return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit"}).format(date)}const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"};class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPosition="after",this.actionsPosition="inside",this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=e=>{this.hasAvatarSlot=e.target.assignedElements({flatten:!0}).length>0},this.onBadgesSlotChange=e=>{this.hasBadgesSlot=e.target.assignedElements({flatten:!0}).length>0},this.onAttachmentsSlotChange=e=>{this.hasAttachmentsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onFailureSlotChange=e=>{this.hasFailureSlot=e.target.assignedElements({flatten:!0}).length>0},this.toggleCollapsed=()=>{const detail={collapsed:!this.collapsed};this.emit("lr-toggle-request",detail,{cancelable:!0}).defaultPrevented||(this.collapsed=detail.collapsed,this.emit("lr-toggle",detail))},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0}}}get status(){return this._status}set status(value){const old=this._status;value!==old&&(this.previousStatus=old,this._status=value,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const active=this.ownerDocument.activeElement;return active?Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active)):!1}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(previous===this.status)return;const region=this.liveRegion;if(region)if(this.status==="failed"){if(this.hasFailureSlot)return;region.mode="assertive",region.announce(this.localize("chatFailedAnnounce"),{force:!0})}else previous==="streaming"&&this.status==="sent"&&(region.mode="polite",region.announce(this.localize("chatCompleteAnnounce"),{force:!0}))}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale)),suppressBuiltInFailedUi=this.status==="failed"&&this.hasFailureSlot,statusText=suppressBuiltInFailedUi?void 0:this.statusText,showHeader=this.hasAvatarSlot||this.hasBadgesSlot||this.collapsible,actionsOutside=this.actionsPosition==="outside",showFooter=!!statusText||!!ts||!actionsOutside&&this.hasActionsSlot,authorLabel=this.localize(this.messageRole==="user"?"promptStudioRoleUser":this.messageRole==="system"?"promptStudioRoleSystem":"promptStudioRoleAssistant"),articleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label")??"":authorLabel,actionsBlock=html`<span part="actions" ?hidden=${!this.hasActionsSlot}
14
+ `}function defaultFormatTimestamp(date,locale){return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit"}).format(date)}const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"};class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPosition="after",this.actionsPosition="inside",this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=e=>{this.hasAvatarSlot=e.target.assignedElements({flatten:!0}).length>0},this.onBadgesSlotChange=e=>{this.hasBadgesSlot=e.target.assignedElements({flatten:!0}).length>0},this.onAttachmentsSlotChange=e=>{this.hasAttachmentsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onFailureSlotChange=e=>{this.hasFailureSlot=e.target.assignedElements({flatten:!0}).length>0},this.toggleCollapsed=()=>{const detail={collapsed:!this.collapsed};this.emit("lr-toggle-request",detail,{cancelable:!0}).defaultPrevented||(this.collapsed=detail.collapsed,this.emit("lr-toggle",detail))},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0}}}get status(){return this._status}set status(value){const old=this._status;value!==old&&(this.previousStatus=old,this._status=value,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const active=this.ownerDocument.activeElement;return active?Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active)):!1}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(previous===this.status)return;const region=this.liveRegion;if(region)if(this.status==="failed"){if(this.hasFailureSlot)return;region.mode="assertive",region.announce(this.localize("chatFailedAnnounce"),{force:!0})}else previous==="streaming"&&this.status==="sent"&&(region.mode="polite",region.announce(this.localize("chatCompleteAnnounce"),{force:!0}))}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale)),suppressBuiltInFailedUi=this.status==="failed"&&this.hasFailureSlot,statusText=suppressBuiltInFailedUi?void 0:this.statusText,showHeader=this.hasAvatarSlot||this.hasBadgesSlot||this.collapsible,actionsOutside=this.actionsPosition==="outside",showFooter=!!statusText||!!ts||!actionsOutside&&this.hasActionsSlot,authorLabel=this.localize(this.messageRole==="user"?"promptStudioRoleUser":this.messageRole==="system"?"promptStudioRoleSystem":"promptStudioRoleAssistant"),articleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label")??"":authorLabel,actionsBlock=html`<span part="actions" ?hidden=${!this.hasActionsSlot}
15
15
  ><slot name="actions" @slotchange=${this.onActionsSlotChange}></slot
16
16
  ></span>`,attachmentsBlock=html`<div part="attachments" ?hidden=${!this.hasAttachmentsSlot}>
17
17
  <slot name="attachments" @slotchange=${this.onAttachmentsSlotChange}></slot>
@@ -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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{LyraVirtualList}from"../../layout/virtual-list/virtual-list.class.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LYRA_DEFAULT_chatViewportLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_newMessageCount,LYRA_DEFAULT_newMessages,LYRA_DEFAULT_newMessagesCount,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.label="",this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.markUserIntent=()=>{this.pendingUserIntent=!0,this.cancelPendingUserIntentExpiry();const owner=this.ownerDocument.defaultView;if(!owner){this.pendingUserIntent=!1;return}const firstFrame={owner,handle:0};firstFrame.handle=owner.requestAnimationFrame(()=>{if(this.pendingUserIntentExpiryFrame!==firstFrame)return;if(!this.isConnected||this.ownerDocument.defaultView!==owner){this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1;return}const secondFrame={owner,handle:0};secondFrame.handle=owner.requestAnimationFrame(()=>{this.pendingUserIntentExpiryFrame===secondFrame&&(this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1)}),this.pendingUserIntentExpiryFrame=secondFrame}),this.pendingUserIntentExpiryFrame=firstFrame},this.onPointerDown=event=>{const scroll=this.scrollEl;if(!scroll||event.button!==0||event.target!==scroll)return;const computed=getComputedStyle(scroll),borderLeft=Number.parseFloat(computed.borderLeftWidth)||0,borderRight=Number.parseFloat(computed.borderRightWidth)||0,gutter=scroll.offsetWidth-scroll.clientWidth-borderLeft-borderRight;if(gutter<=0)return;const rect=scroll.getBoundingClientRect();if(!(computed.direction==="rtl"?event.clientX<=rect.left+borderLeft+gutter:event.clientX>=rect.right-borderRight-gutter))return;this.scrollbarDragActive=!0;const owner=this.ownerDocument.defaultView;!owner||this.scrollbarDragWindow===owner||(this.releaseScrollbarDragListeners(),this.scrollbarDragWindow=owner,owner.addEventListener("pointerup",this.onPointerUp),owner.addEventListener("pointercancel",this.onPointerUp),owner.addEventListener("lostpointercapture",this.onPointerUp))},this.onPointerUp=()=>{this.scrollbarDragActive=!1,this.releaseScrollbarDragListeners()},this.onKeyDown=e=>{(e.key==="PageUp"||e.key==="ArrowUp"||e.key==="Home")&&this.markUserIntent()},this.onScroll=()=>{const el=this.scrollEl;if(!el)return;if(el.scrollHeight-el.scrollTop-el.clientHeight<=this.effectiveBottomThreshold){this.clearUserIntent(),this.follow||(this.follow=!0);return}(this.consumeUserIntent()||this.scrollbarDragActive)&&this.follow&&(this.follow=!1)},this.onVirtualRangeChanged=e=>{const list=this.virtualListEl;if(!list||e.composedPath()[0]!==list)return;const detail=e.detail;if(!detail||!Number.isFinite(detail.start)||!Number.isFinite(detail.end)||detail.start<0||detail.end<detail.start)return;if(list.items.length>0&&detail.end>=list.items.length-1){this.clearUserIntent(),this.follow||(this.follow=!0);return}if(this.consumeUserIntent()||this.scrollbarDragActive){this.follow&&(this.follow=!1);return}this.follow&&this.performScrollToEnd("auto")},this.onSlotChange=()=>{this.announceNewProjectedNodes();const wasVirtual=this.armedMode==="virtual";this.armObservers(),this.armedMode==="virtual"!==wasVirtual&&this.requestUpdate()},this.onContentMutations=records=>{this.scheduleGrowthTick();const sink=this.announcementSink;if(sink)for(const record of records)for(const node of record.addedNodes){if(this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary"))continue;this.knownProjectedNodes.add(node);const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,jumpToLatest:LYRA_DEFAULT_jumpToLatest,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,newMessageCount:LYRA_DEFAULT_newMessageCount,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get messageElements(){let elements=this.contentSlot?.assignedElements({flatten:!0})??Array.from(this.children);for(let depth=0;depth<4&&elements.some(element=>element.localName==="slot");depth++)elements=elements.flatMap(element=>element.localName==="slot"?element.assignedElements({flatten:!0}):[element]);return elements.filter(element=>!element.hasAttribute("data-lr-chat-viewport-unread-boundary"))}get virtualListEl(){const children=this.messageElements;return children.length===1&&children[0]instanceof LyraVirtualList?children[0]:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.teardownObservers(),this.releaseScrollbarDragListeners(),this.clearUserIntent(),this.scrollbarDragActive=!1,this.followFocusRepair=null,this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated&&changed.has("follow")&&this.follow&&changed.get("follow")===!1){const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}this.hasUpdated&&changed.has("unreadStartIndex")&&this.updateUnreadDividerPosition()}firstUpdated(changed){super.firstUpdated(changed),this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.syncAnnouncementSink();const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}const focusRepair=this.followFocusRepair;this.followFocusRepair=null,focusRepair&&applyComposedFocusRepair(focusRepair)}transcriptFocusOwner(){const list=this.virtualListEl;return list?collectComposedFocusTargets(list,{includeRoot:!1,mode:"programmatic"}).elements[0]??null:this.scrollEl??null}scrollToBottom(options){const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.follow?this.performScrollToEnd(behavior):(this.pendingScrollBehavior=behavior,this.follow=!0)}scrollToUnread(options){const unreadStartIndex=this.effectiveUnreadStartIndex;if(unreadStartIndex==null)return!1;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=list.items.length?!1:(list.scrollToIndex(unreadStartIndex,{align:"start",behavior}),!0);const scrollEl=this.scrollEl;return!scrollEl||this.unreadDividerTop==null?!1:(scrollEl.scrollTo({top:this.unreadDividerTop,behavior}),!0)}performScrollToEnd(behavior){const list=this.virtualListEl;if(list){list.items.length>0&&list.scrollToIndex(list.items.length-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.virtualListEl;return list?list.items.length:this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;if(count<=0)return this.localize("jumpToLatest");const key=getPluralRules(this.effectiveLocale).select(count)==="one"?"newMessageCount":"newMessagesCount";return this.localize(key,void 0,{count:getNumberFormat(this.effectiveLocale).format(count)})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.virtualListEl||unreadStartIndex==null){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}const content=this.contentEl,target=this.messageElements[unreadStartIndex];if(!target||!content){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}this.syncSemanticUnreadBoundary(target),this.unreadDividerTop=target.getBoundingClientRect().top-content.getBoundingClientRect().top}syncSemanticUnreadBoundary(target){if(!target||this.virtualListEl){this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0;return}const parent=target.parentNode;if(!parent)return;const boundary=this.unreadBoundaryEl??this.ownerDocument.createElement("div");boundary.setAttribute("data-lr-chat-viewport-unread-boundary",""),boundary.setAttribute("role","separator"),boundary.setAttribute("aria-label",this.localize("newMessages"));const targetSlot=target.getAttribute("slot");targetSlot===null?boundary.removeAttribute("slot"):boundary.setAttribute("slot",targetSlot),(boundary.parentNode!==parent||boundary.nextSibling!==target)&&parent.insertBefore(boundary,target),this.unreadBoundaryEl=boundary,this.knownProjectedNodes.add(boundary)}cancelPendingUserIntentExpiry(){const frame=this.pendingUserIntentExpiryFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.pendingUserIntentExpiryFrame=null}clearUserIntent(){this.pendingUserIntent=!1,this.cancelPendingUserIntentExpiry()}consumeUserIntent(){const wasPending=this.pendingUserIntent;return this.clearUserIntent(),wasPending}releaseScrollbarDragListeners(){const owner=this.scrollbarDragWindow;owner&&(owner.removeEventListener("pointerup",this.onPointerUp),owner.removeEventListener("pointercancel",this.onPointerUp),owner.removeEventListener("lostpointercapture",this.onPointerUp),this.scrollbarDragWindow=void 0)}scheduleGrowthTick(){if(this.growthFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.growthFrame===frame&&(this.growthFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.updateUnreadDividerPosition(),this.follow&&this.performScrollToEnd("auto")))}),this.growthFrame=frame}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){const politeness=this.live==="polite"||this.live==="assertive"?this.live:void 0;if(!this.isConnected||politeness===void 0){this.releaseAnnouncementSink();return}this.announcementSink?.politeness===politeness&&this.announcementSink.element.ownerDocument===this.ownerDocument||(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink(politeness,{document:this.ownerDocument,source:this}))}announcementTextFor(node){const primary=composedAccessibilityText(node);if(!(node instanceof Element)||!node.shadowRoot)return primary;const content=composedAccessibilityText(node.childNodes),normalizedPrimary=primary.replace(/\s+/g," ").trim(),normalizedContent=content.replace(/\s+/g," ").trim();return!normalizedContent||normalizedPrimary.includes(normalizedContent)?primary:primary?`${primary} ${content}`:content}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements){if(this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!sink||!this.hasUpdated))continue;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";for(const node of this.messageElements)this.knownProjectedNodes.add(node);if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;if(this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode,list)this.listenedVirtualList=list,list.addEventListener("lr-visible-range-change",this.onVirtualRangeChanged);else{const content=this.contentEl;if(content){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.scheduleGrowthTick()}}),this.contentResizeObserver=observer,this.contentResizeObserver.observe(content)}}const MutationObserverCtor=owner?.MutationObserver;if(MutationObserverCtor){let observer;observer=new MutationObserverCtor(records=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentMutationObserver!==observer||this.onContentMutations(records)}),this.contentMutationObserver=observer,this.contentMutationObserver.observe(this,{childList:!0})}}const scrollEl=this.scrollEl;if(scrollEl){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.scrollResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.follow&&this.performScrollToEnd("auto")}}),this.scrollResizeObserver=observer,this.scrollResizeObserver.observe(scrollEl)}}const generation=++this.armGeneration;queueMicrotask(()=>{!this.isConnected||generation!==this.armGeneration||this.updateUnreadDividerPosition()})}teardownObservers(){this.scrollResizeObserver?.disconnect(),this.scrollResizeObserver=void 0,this.contentResizeObserver?.disconnect(),this.contentResizeObserver=void 0,this.contentMutationObserver?.disconnect(),this.contentMutationObserver=void 0,this.listenedVirtualList?.removeEventListener("lr-visible-range-change",this.onVirtualRangeChanged),this.listenedVirtualList=void 0,this.observerWindow=void 0,this.armedMode=null,this.armGeneration++;const frame=this.growthFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.growthFrame=null}render(){const label=this.accessibleLabel??(this.label||this.localize("chatViewportLabel")),virtual=this.virtualListEl!==null;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{LyraVirtualList}from"../../layout/virtual-list/virtual-list.class.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LYRA_DEFAULT_chatViewportLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_newMessageCount,LYRA_DEFAULT_newMessages,LYRA_DEFAULT_newMessagesCount,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.label="",this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.markUserIntent=()=>{this.pendingUserIntent=!0,this.cancelPendingUserIntentExpiry();const owner=this.ownerDocument.defaultView;if(!owner){this.pendingUserIntent=!1;return}const firstFrame={owner,handle:0};firstFrame.handle=owner.requestAnimationFrame(()=>{if(this.pendingUserIntentExpiryFrame!==firstFrame)return;if(!this.isConnected||this.ownerDocument.defaultView!==owner){this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1;return}const secondFrame={owner,handle:0};secondFrame.handle=owner.requestAnimationFrame(()=>{this.pendingUserIntentExpiryFrame===secondFrame&&(this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1)}),this.pendingUserIntentExpiryFrame=secondFrame}),this.pendingUserIntentExpiryFrame=firstFrame},this.onPointerDown=event=>{const scroll=this.scrollEl;if(!scroll||event.button!==0||event.target!==scroll)return;const computed=getComputedStyle(scroll),borderLeft=Number.parseFloat(computed.borderLeftWidth)||0,borderRight=Number.parseFloat(computed.borderRightWidth)||0,gutter=scroll.offsetWidth-scroll.clientWidth-borderLeft-borderRight;if(gutter<=0)return;const rect=scroll.getBoundingClientRect();if(!(computed.direction==="rtl"?event.clientX<=rect.left+borderLeft+gutter:event.clientX>=rect.right-borderRight-gutter))return;this.scrollbarDragActive=!0;const owner=this.ownerDocument.defaultView;!owner||this.scrollbarDragWindow===owner||(this.releaseScrollbarDragListeners(),this.scrollbarDragWindow=owner,owner.addEventListener("pointerup",this.onPointerUp),owner.addEventListener("pointercancel",this.onPointerUp),owner.addEventListener("lostpointercapture",this.onPointerUp))},this.onPointerUp=()=>{this.scrollbarDragActive=!1,this.releaseScrollbarDragListeners()},this.onKeyDown=e=>{(e.key==="PageUp"||e.key==="ArrowUp"||e.key==="Home")&&this.markUserIntent()},this.onScroll=()=>{const el=this.scrollEl;if(!el)return;if(el.scrollHeight-el.scrollTop-el.clientHeight<=this.effectiveBottomThreshold){this.clearUserIntent(),this.follow||(this.follow=!0);return}(this.consumeUserIntent()||this.scrollbarDragActive)&&this.follow&&(this.follow=!1)},this.onVirtualRangeChanged=e=>{const list=this.virtualListEl;if(!list||e.composedPath()[0]!==list)return;const detail=e.detail;if(!detail||!Number.isFinite(detail.start)||!Number.isFinite(detail.end)||detail.start<0||detail.end<detail.start)return;if(list.items.length>0&&detail.end>=list.items.length-1){this.clearUserIntent(),this.follow||(this.follow=!0);return}if(this.consumeUserIntent()||this.scrollbarDragActive){this.follow&&(this.follow=!1);return}this.follow&&this.performScrollToEnd("auto")},this.onSlotChange=()=>{this.announceNewProjectedNodes();const wasVirtual=this.armedMode==="virtual";this.armObservers(),this.armedMode==="virtual"!==wasVirtual&&this.requestUpdate()},this.onContentMutations=records=>{this.scheduleGrowthTick();const sink=this.announcementSink;if(sink)for(const record of records)for(const node of record.addedNodes){if(this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary"))continue;this.knownProjectedNodes.add(node);const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,jumpToLatest:LYRA_DEFAULT_jumpToLatest,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,newMessageCount:LYRA_DEFAULT_newMessageCount,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get messageElements(){let elements=this.contentSlot?.assignedElements({flatten:!0})??Array.from(this.children);for(let depth=0;depth<4&&elements.some(element=>element.localName==="slot");depth++)elements=elements.flatMap(element=>element.localName==="slot"?element.assignedElements({flatten:!0}):[element]);return elements.filter(element=>!element.hasAttribute("data-lr-chat-viewport-unread-boundary"))}get virtualListEl(){const children=this.messageElements;return children.length===1&&children[0]instanceof LyraVirtualList?children[0]:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.teardownObservers(),this.releaseScrollbarDragListeners(),this.clearUserIntent(),this.scrollbarDragActive=!1,this.followFocusRepair=null,this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated&&changed.has("follow")&&this.follow&&changed.get("follow")===!1){const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}this.hasUpdated&&changed.has("unreadStartIndex")&&this.updateUnreadDividerPosition()}firstUpdated(changed){super.firstUpdated(changed),this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.syncAnnouncementSink();const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}const focusRepair=this.followFocusRepair;this.followFocusRepair=null,focusRepair&&applyComposedFocusRepair(focusRepair)}transcriptFocusOwner(){const list=this.virtualListEl;return list?collectComposedFocusTargets(list,{includeRoot:!1,mode:"programmatic"}).elements[0]??null:this.scrollEl??null}scrollToBottom(options){const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.follow?this.performScrollToEnd(behavior):(this.pendingScrollBehavior=behavior,this.follow=!0)}scrollToUnread(options){const unreadStartIndex=this.effectiveUnreadStartIndex;if(unreadStartIndex==null)return!1;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=list.items.length?!1:(list.scrollToIndex(unreadStartIndex,{align:"start",behavior}),!0);const scrollEl=this.scrollEl;return!scrollEl||this.unreadDividerTop==null?!1:(scrollEl.scrollTo({top:this.unreadDividerTop,behavior}),!0)}performScrollToEnd(behavior){const list=this.virtualListEl;if(list){list.items.length>0&&list.scrollToIndex(list.items.length-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.virtualListEl;return list?list.items.length:this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;if(count<=0)return this.localize("jumpToLatest");const key=getPluralRules(this.effectiveLocale).select(count)==="one"?"newMessageCount":"newMessagesCount";return this.localize(key,void 0,{count:getNumberFormat(this.effectiveLocale).format(count)})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.virtualListEl||unreadStartIndex==null){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}const content=this.contentEl,target=this.messageElements[unreadStartIndex];if(!target||!content){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}this.syncSemanticUnreadBoundary(target),this.unreadDividerTop=target.getBoundingClientRect().top-content.getBoundingClientRect().top}syncSemanticUnreadBoundary(target){if(!target||this.virtualListEl){this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0;return}const parent=target.parentNode;if(!parent)return;const boundary=this.unreadBoundaryEl??this.ownerDocument.createElement("div");boundary.setAttribute("data-lr-chat-viewport-unread-boundary",""),boundary.setAttribute("role","separator"),boundary.setAttribute("aria-label",this.localize("newMessages"));const targetSlot=target.getAttribute("slot");targetSlot===null?boundary.removeAttribute("slot"):boundary.setAttribute("slot",targetSlot),(boundary.parentNode!==parent||boundary.nextSibling!==target)&&parent.insertBefore(boundary,target),this.unreadBoundaryEl=boundary,this.knownProjectedNodes.add(boundary)}cancelPendingUserIntentExpiry(){const frame=this.pendingUserIntentExpiryFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.pendingUserIntentExpiryFrame=null}clearUserIntent(){this.pendingUserIntent=!1,this.cancelPendingUserIntentExpiry()}consumeUserIntent(){const wasPending=this.pendingUserIntent;return this.clearUserIntent(),wasPending}releaseScrollbarDragListeners(){const owner=this.scrollbarDragWindow;owner&&(owner.removeEventListener("pointerup",this.onPointerUp),owner.removeEventListener("pointercancel",this.onPointerUp),owner.removeEventListener("lostpointercapture",this.onPointerUp),this.scrollbarDragWindow=void 0)}scheduleGrowthTick(){if(this.growthFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.growthFrame===frame&&(this.growthFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.updateUnreadDividerPosition(),this.follow&&this.performScrollToEnd("auto")))}),this.growthFrame=frame}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){const politeness=this.live==="polite"||this.live==="assertive"?this.live:void 0;if(!this.isConnected||politeness===void 0){this.releaseAnnouncementSink();return}this.announcementSink?.politeness===politeness&&this.announcementSink.element.ownerDocument===this.ownerDocument||(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink(politeness,{document:this.ownerDocument,source:this}))}announcementTextFor(node){const primary=composedAccessibilityText(node);if(!(node instanceof Element)||!node.shadowRoot)return primary;const content=composedAccessibilityText(node.childNodes),normalizedPrimary=primary.replace(/\s+/g," ").trim(),normalizedContent=content.replace(/\s+/g," ").trim();return!normalizedContent||normalizedPrimary.includes(normalizedContent)?primary:primary?`${primary} ${content}`:content}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements){if(this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!sink||!this.hasUpdated))continue;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";for(const node of this.messageElements)this.knownProjectedNodes.add(node);if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;if(this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode,list)this.listenedVirtualList=list,list.addEventListener("lr-visible-range-change",this.onVirtualRangeChanged);else{const content=this.contentEl;if(content){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.scheduleGrowthTick()}}),this.contentResizeObserver=observer,this.contentResizeObserver.observe(content)}}const MutationObserverCtor=owner?.MutationObserver;if(MutationObserverCtor){let observer;observer=new MutationObserverCtor(records=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentMutationObserver!==observer||this.onContentMutations(records)}),this.contentMutationObserver=observer,this.contentMutationObserver.observe(this,{childList:!0})}}const scrollEl=this.scrollEl;if(scrollEl){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.scrollResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.follow&&this.performScrollToEnd("auto")}}),this.scrollResizeObserver=observer,this.scrollResizeObserver.observe(scrollEl)}}const generation=++this.armGeneration;queueMicrotask(()=>{!this.isConnected||generation!==this.armGeneration||this.updateUnreadDividerPosition()})}teardownObservers(){this.scrollResizeObserver?.disconnect(),this.scrollResizeObserver=void 0,this.contentResizeObserver?.disconnect(),this.contentResizeObserver=void 0,this.contentMutationObserver?.disconnect(),this.contentMutationObserver=void 0,this.listenedVirtualList?.removeEventListener("lr-visible-range-change",this.onVirtualRangeChanged),this.listenedVirtualList=void 0,this.observerWindow=void 0,this.armedMode=null,this.armGeneration++;const frame=this.growthFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.growthFrame=null}render(){const label=this.accessibleLabel??(this.label||this.localize("chatViewportLabel")),virtual=this.virtualListEl!==null;return html`
2
2
  <div part="base" ?data-virtual=${virtual}>
3
3
  <div
4
4
  part="scroll"
@@ -1,5 +1,6 @@
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';
3
4
  import type { LyraSize } from '../../../internal/variants.js';
4
5
  import type { LyraSelectionDirection } from '../../../internal/shared-unions.js';
5
6
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
@@ -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{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"../../../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
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,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{place}from"../../../internal/positioner.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_usageBadgeCostLabel,LYRA_DEFAULT_usageBadgeLabel,LYRA_DEFAULT_usageBadgeLatencyLabel,LYRA_DEFAULT_usageBadgeTokensIn,LYRA_DEFAULT_usageBadgeTokensInLabel,LYRA_DEFAULT_usageBadgeTokensOut,LYRA_DEFAULT_usageBadgeTokensOutLabel,LYRA_DEFAULT_usageBadgeTotalTokensLabel}from"../../../internal/default-strings.generated.js";class LyraUsageBadge extends LyraElement{constructor(){super(...arguments),this.costText="",this.summary="",this.abbreviate=!1,this.tooltipOpen=!1,this.hasDetailsSlot=!1,this.hasSummarySlot=!1,this.detailsText="",this.tooltipId=nextId("usage-badge-tooltip"),this.hovering=!1,this.focused=!1,this.onDetailsSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.hasDetailsSlot=assigned.length>0,this.detailsText=assigned.slice(0,64).map(element=>{const renderedText=element.innerText;return typeof renderedText=="string"?renderedText:element.textContent??""}).join(" ").replace(/\s+/g," ").trim().slice(0,4096),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0,this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onMouseEnter=()=>{this.hovering=!0,this.showTooltip()},this.onMouseLeave=()=>{this.hovering=!1,!this.focused&&this.hideTooltip()},this.onFocus=()=>{this.focused=!0,this.showTooltip()},this.onBlur=()=>{this.focused=!1,!this.hovering&&this.hideTooltip()},this.onKeyDown=e=>{e.key==="Escape"&&this.tooltipOpen&&(e.stopPropagation(),this.hideTooltip())}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,usageBadgeCostLabel:LYRA_DEFAULT_usageBadgeCostLabel,usageBadgeLabel:LYRA_DEFAULT_usageBadgeLabel,usageBadgeLatencyLabel:LYRA_DEFAULT_usageBadgeLatencyLabel,usageBadgeTokensIn:LYRA_DEFAULT_usageBadgeTokensIn,usageBadgeTokensInLabel:LYRA_DEFAULT_usageBadgeTokensInLabel,usageBadgeTokensOut:LYRA_DEFAULT_usageBadgeTokensOut,usageBadgeTokensOutLabel:LYRA_DEFAULT_usageBadgeTokensOutLabel,usageBadgeTotalTokensLabel:LYRA_DEFAULT_usageBadgeTotalTokensLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{const children=Array.from(this.children);this.hasDetailsSlot=children.some(child=>child.getAttribute("slot")==="details"),this.hasSummarySlot=children.some(child=>child.getAttribute("slot")==="summary")}),this.hasUpdated&&(changed.has("tokensIn")||changed.has("tokensOut")||changed.has("costText")||changed.has("latencyMs")||changed.has("summary"))&&!this.hasInteractiveTooltip&&this.closeTooltipLifecycle()}updated(changed){if(super.updated(changed),changed.has("tooltipOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen)){const anchor=this.renderRoot.querySelector('[part="base"]'),tooltip=this.renderRoot.querySelector('[part="tooltip"]');anchor&&tooltip&&(this.cleanupPositioner=place(anchor,tooltip,{placement:"top-start"}))}}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen=!1,this.hovering=!1,this.focused=!1}get hasTokensIn(){return this.tokensIn!=null&&Number.isFinite(this.tokensIn)}get hasTokensOut(){return this.tokensOut!=null&&Number.isFinite(this.tokensOut)}get hasCost(){return this.costText.length>0}get validLatencyMs(){if(!(this.latencyMs==null||!Number.isFinite(this.latencyMs)))return finiteRange(this.latencyMs,this.latencyMs,0)}get hasLatency(){return this.validLatencyMs!==void 0}get hasVisibleContent(){return this.hasTokensIn||this.hasTokensOut||this.hasCost||this.hasLatency}get hasVisibleSummary(){return this.summary.length>0||this.hasSummarySlot}get hasDisplayContent(){return this.hasVisibleContent||this.hasVisibleSummary}get hasTooltipContent(){return this.hasVisibleContent||this.hasDetailsSlot}get hasInteractiveTooltip(){return this.hasDisplayContent&&this.hasTooltipContent}formatTokenCount(n){return getNumberFormat(this.effectiveLocale,this.abbreviate?{notation:"compact"}:{}).format(n)}formatTokenCountFull(n){return getNumberFormat(this.effectiveLocale).format(n)}localizedDuration(ms){if(this.formatLatency)return this.formatLatency(ms);const duration=durationMessageValue(ms),value=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationMilliseconds"?0:1}).format(duration.value);return this.localize(duration.key,void 0,{value})}showTooltip(){!this.hasInteractiveTooltip||this.tooltipOpen||(this.tooltipOpen=!0)}hideTooltip(){this.tooltipOpen&&(this.tooltipOpen=!1)}closeTooltipLifecycle(){this.tooltipOpen=!1,this.hovering=!1,this.focused=!1,this.cleanupPositioner?.(),this.cleanupPositioner=void 0}render(){const interactive=this.hasInteractiveTooltip,tokensIn=this.hasTokensIn?finiteCount(this.tokensIn):void 0,tokensOut=this.hasTokensOut?finiteCount(this.tokensOut):void 0,hasBoth=tokensIn!==void 0&&tokensOut!==void 0;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{place}from"../../../internal/positioner.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_usageBadgeCostLabel,LYRA_DEFAULT_usageBadgeLabel,LYRA_DEFAULT_usageBadgeLatencyLabel,LYRA_DEFAULT_usageBadgeTokensIn,LYRA_DEFAULT_usageBadgeTokensInLabel,LYRA_DEFAULT_usageBadgeTokensOut,LYRA_DEFAULT_usageBadgeTokensOutLabel,LYRA_DEFAULT_usageBadgeTotalTokensLabel}from"../../../internal/default-strings.generated.js";class LyraUsageBadge extends LyraElement{constructor(){super(...arguments),this.costText="",this.summary="",this.abbreviate=!1,this.tooltipOpen=!1,this.hasDetailsSlot=!1,this.hasSummarySlot=!1,this.detailsText="",this.tooltipId=nextId("usage-badge-tooltip"),this.hovering=!1,this.focused=!1,this.onDetailsSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.hasDetailsSlot=assigned.length>0,this.detailsText=assigned.slice(0,64).map(element=>{const renderedText=element.innerText;return typeof renderedText=="string"?renderedText:element.textContent??""}).join(" ").replace(/\s+/g," ").trim().slice(0,4096),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0,this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onMouseEnter=()=>{this.hovering=!0,this.showTooltip()},this.onMouseLeave=()=>{this.hovering=!1,!this.focused&&this.hideTooltip()},this.onFocus=()=>{this.focused=!0,this.showTooltip()},this.onBlur=()=>{this.focused=!1,!this.hovering&&this.hideTooltip()},this.onKeyDown=e=>{e.key==="Escape"&&this.tooltipOpen&&(e.stopPropagation(),this.hideTooltip())}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,usageBadgeCostLabel:LYRA_DEFAULT_usageBadgeCostLabel,usageBadgeLabel:LYRA_DEFAULT_usageBadgeLabel,usageBadgeLatencyLabel:LYRA_DEFAULT_usageBadgeLatencyLabel,usageBadgeTokensIn:LYRA_DEFAULT_usageBadgeTokensIn,usageBadgeTokensInLabel:LYRA_DEFAULT_usageBadgeTokensInLabel,usageBadgeTokensOut:LYRA_DEFAULT_usageBadgeTokensOut,usageBadgeTokensOutLabel:LYRA_DEFAULT_usageBadgeTokensOutLabel,usageBadgeTotalTokensLabel:LYRA_DEFAULT_usageBadgeTotalTokensLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{const children=Array.from(this.children);this.hasDetailsSlot=children.some(child=>child.getAttribute("slot")==="details"),this.hasSummarySlot=children.some(child=>child.getAttribute("slot")==="summary")}),this.hasUpdated&&(changed.has("tokensIn")||changed.has("tokensOut")||changed.has("costText")||changed.has("latencyMs")||changed.has("summary"))&&!this.hasInteractiveTooltip&&this.closeTooltipLifecycle()}updated(changed){if(super.updated(changed),changed.has("tooltipOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen)){const anchor=this.renderRoot.querySelector('[part="base"]'),tooltip=this.renderRoot.querySelector('[part="tooltip"]');anchor&&tooltip&&(this.cleanupPositioner=place(anchor,tooltip,{placement:"top-start"}))}}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen=!1,this.hovering=!1,this.focused=!1}get hasTokensIn(){return this.tokensIn!=null&&Number.isFinite(this.tokensIn)}get hasTokensOut(){return this.tokensOut!=null&&Number.isFinite(this.tokensOut)}get hasCost(){return this.costText.length>0}get validLatencyMs(){if(!(this.latencyMs==null||!Number.isFinite(this.latencyMs)))return finiteRange(this.latencyMs,this.latencyMs,0)}get hasLatency(){return this.validLatencyMs!==void 0}get hasVisibleContent(){return this.hasTokensIn||this.hasTokensOut||this.hasCost||this.hasLatency}get hasVisibleSummary(){return this.summary.length>0||this.hasSummarySlot}get hasDisplayContent(){return this.hasVisibleContent||this.hasVisibleSummary}get hasTooltipContent(){return this.hasVisibleContent||this.hasDetailsSlot}get hasInteractiveTooltip(){return this.hasDisplayContent&&this.hasTooltipContent}formatTokenCount(n){return getNumberFormat(this.effectiveLocale,this.abbreviate?{notation:"compact"}:{}).format(n)}formatTokenCountFull(n){return getNumberFormat(this.effectiveLocale).format(n)}localizedDuration(ms){if(this.formatLatency)return this.formatLatency(ms);const duration=durationMessageValue(ms),value=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationMilliseconds"?0:1}).format(duration.value);return this.localize(duration.key,void 0,{value})}showTooltip(){!this.hasInteractiveTooltip||this.tooltipOpen||(this.tooltipOpen=!0)}hideTooltip(){this.tooltipOpen&&(this.tooltipOpen=!1)}closeTooltipLifecycle(){this.tooltipOpen=!1,this.hovering=!1,this.focused=!1,this.cleanupPositioner?.(),this.cleanupPositioner=void 0}render(){const interactive=this.hasInteractiveTooltip,tokensIn=this.hasTokensIn?finiteCount(this.tokensIn):void 0,tokensOut=this.hasTokensOut?finiteCount(this.tokensOut):void 0,hasBoth=tokensIn!==void 0&&tokensOut!==void 0;return html`
2
2
  <div
3
3
  part="base"
4
4
  role=${interactive?"group":nothing}
@@ -1,5 +1,6 @@
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';
3
4
  import type { LyraSize } from '../../../internal/variants.js';
4
5
  import type { LyraSelectionDirection } from '../../../internal/shared-unions.js';
5
6
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";const MAX_VOICE_CATALOG_ENTRIES=1e4;function ownString(value,key){try{const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function snapshotVoiceCatalog(value){if(!Array.isArray(value))return;const stringSnapshot=[],entrySnapshot=[];let objectCatalog=!1,length=0;try{length=Math.min(value.length,MAX_VOICE_CATALOG_ENTRIES)}catch{return Object.freeze(stringSnapshot)}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const candidate=descriptor.value;if(typeof candidate=="string"){objectCatalog?entrySnapshot.push(Object.freeze({id:candidate,label:candidate})):stringSnapshot.push(candidate);continue}if(candidate===null||typeof candidate!="object")continue;const id=ownString(candidate,"id"),label=ownString(candidate,"label");if(id===void 0||label===void 0)continue;objectCatalog||(entrySnapshot.push(...stringSnapshot.map(entry=>Object.freeze({id:entry,label:entry}))),objectCatalog=!0);const language=ownString(candidate,"language"),description=ownString(candidate,"description"),previewUrl=ownString(candidate,"previewUrl");entrySnapshot.push(Object.freeze({id,label,...language===void 0?{}:{language},...description===void 0?{}:{description},...previewUrl===void 0?{}:{previewUrl}}))}return Object.freeze(objectCatalog?entrySnapshot:stringSnapshot)}class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}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:!1,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get catalog(){return this._catalog}set catalog(next){const old=this._catalog;next!==old&&(this.internalPreviewTargetId!==null&&this.stopInternalPreview(),this._catalog=snapshotVoiceCatalog(next),this.requestUpdate("catalog",old))}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.preview=!0,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.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this.transferControlFocus=!1,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),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.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlBlur:()=>{this.effectiveDisabled||(this.touched=!0)}}),this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=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.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("")}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}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)}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated){const switchingMode=this.renderRoot.querySelector('[part="trigger"]')!==null!==this.closedMode,focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.catalogPicker.suppressControlEvents=switchingMode,this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("preview")&&!this.preview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),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.stopInternalPreview()),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("voicePickerRequired")):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.stopInternalPreview()),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}get malformedCatalogEntries(){const raw=this.catalog;if(!raw||raw.length===0)return[];const out=[];for(const item of raw){const record=typeof item=="string"?{id:item,label:item}:item;typeof record?.id=="string"&&record.id.trim()!==""||out.push({...record,id:"",synthetic:!1})}return out}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.transferControlFocus&&(this.transferControlFocus=!1,this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&&currentTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.effectiveEntries.find(e=>e.id===voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id!==""&&entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");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{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,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";const MAX_VOICE_CATALOG_ENTRIES=1e4;function ownString(value,key){try{const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor&&typeof descriptor.value=="string"?descriptor.value:void 0}catch{return}}function snapshotVoiceCatalog(value){if(!Array.isArray(value))return;const stringSnapshot=[],entrySnapshot=[];let objectCatalog=!1,length=0;try{length=Math.min(value.length,MAX_VOICE_CATALOG_ENTRIES)}catch{return Object.freeze(stringSnapshot)}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const candidate=descriptor.value;if(typeof candidate=="string"){objectCatalog?entrySnapshot.push(Object.freeze({id:candidate,label:candidate})):stringSnapshot.push(candidate);continue}if(candidate===null||typeof candidate!="object")continue;const id=ownString(candidate,"id"),label=ownString(candidate,"label");if(id===void 0||label===void 0)continue;objectCatalog||(entrySnapshot.push(...stringSnapshot.map(entry=>Object.freeze({id:entry,label:entry}))),objectCatalog=!0);const language=ownString(candidate,"language"),description=ownString(candidate,"description"),previewUrl=ownString(candidate,"previewUrl");entrySnapshot.push(Object.freeze({id,label,...language===void 0?{}:{language},...description===void 0?{}:{description},...previewUrl===void 0?{}:{previewUrl}}))}return Object.freeze(objectCatalog?entrySnapshot:stringSnapshot)}class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}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:!1,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get catalog(){return this._catalog}set catalog(next){const old=this._catalog;next!==old&&(this.internalPreviewTargetId!==null&&this.stopInternalPreview(),this._catalog=snapshotVoiceCatalog(next),this.requestUpdate("catalog",old))}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.preview=!0,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.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this.transferControlFocus=!1,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),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.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlBlur:()=>{this.effectiveDisabled||(this.touched=!0)}}),this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=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.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("")}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}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)}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated){const switchingMode=this.renderRoot.querySelector('[part="trigger"]')!==null!==this.closedMode,focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.catalogPicker.suppressControlEvents=switchingMode,this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("preview")&&!this.preview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),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.stopInternalPreview()),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("voicePickerRequired")):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.stopInternalPreview()),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}get malformedCatalogEntries(){const raw=this.catalog;if(!raw||raw.length===0)return[];const out=[];for(const item of raw){const record=typeof item=="string"?{id:item,label:item}:item;typeof record?.id=="string"&&record.id.trim()!==""||out.push({...record,id:"",synthetic:!1})}return out}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.transferControlFocus&&(this.transferControlFocus=!1,this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&&currentTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.effectiveEntries.find(e=>e.id===voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id!==""&&entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -1,6 +1,7 @@
1
1
  import type { LyraEventDetailSnapshot } from '../../../internal/lyra-element.js';
2
2
  import { type TemplateResult, type PropertyValues } from 'lit';
3
3
  import { LyraElement } from '../../../internal/lyra-element.js';
4
+ import '../../../internal/form-control-labels.js';
4
5
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
5
6
  /** Traversal direction relative to the matched node(s): `'out'` (outgoing edges), `'in'`
6
7
  * (incoming edges), or `'both'`. */