@aceshooting/lyra-ui 11.1.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +456 -0
  2. package/README.md +19 -8
  3. package/custom-elements.json +1 -1
  4. package/dist/all.d.ts +1 -0
  5. package/dist/all.js +1 -1
  6. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  7. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  8. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  9. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  10. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  11. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  12. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  13. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  14. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  15. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  16. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  17. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  18. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  19. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  20. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  21. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  22. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  23. package/dist/components/charts/chart/chart.class.d.ts +13 -1
  24. package/dist/components/charts/chart/chart.class.js +1 -1
  25. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  26. package/dist/components/charts/chart/histogram.class.js +1 -1
  27. package/dist/components/charts/chart/line-chart.class.js +1 -1
  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/funnel/funnel.class.d.ts +92 -0
  40. package/dist/components/data/funnel/funnel.class.js +25 -0
  41. package/dist/components/data/funnel/funnel.d.ts +1 -0
  42. package/dist/components/data/funnel/funnel.js +1 -0
  43. package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
  44. package/dist/components/data/funnel/funnel.styles.js +127 -0
  45. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  46. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  47. package/dist/components/data/heatmap/heatmap.class.d.ts +222 -5
  48. package/dist/components/data/heatmap/heatmap.class.js +30 -22
  49. package/dist/components/data/heatmap/heatmap.styles.js +36 -0
  50. package/dist/components/data/index.d.ts +1 -0
  51. package/dist/components/data/index.js +1 -1
  52. package/dist/components/data/table/table.class.js +1 -1
  53. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  54. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  55. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  56. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  57. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  58. package/dist/components/forms/combobox/combobox.class.js +1 -1
  59. package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
  60. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  61. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  62. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  63. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  64. package/dist/components/forms/radio/radio-group.class.js +1 -1
  65. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  66. package/dist/components/forms/radio/radio.class.js +1 -1
  67. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  68. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  69. package/dist/components/forms/select/select.class.d.ts +1 -0
  70. package/dist/components/forms/select/select.class.js +1 -1
  71. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  72. package/dist/components/forms/slider/slider.class.js +1 -1
  73. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  74. package/dist/components/forms/switch/switch.class.js +1 -1
  75. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  76. package/dist/components/forms/time-range/time-range.class.js +1 -1
  77. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  78. package/dist/components/forms/token-input/token-input.class.js +1 -1
  79. package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
  80. package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
  81. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
  82. package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
  83. package/dist/components/layout/widget/widget.class.d.ts +16 -0
  84. package/dist/components/layout/widget/widget.class.js +2 -2
  85. package/dist/components/lr-funnel.d.ts +1 -0
  86. package/dist/components/lr-funnel.js +1 -0
  87. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  88. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  89. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  90. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  91. package/dist/components/media/file-input/file-input.class.js +1 -1
  92. package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
  93. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
  94. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  95. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  96. package/dist/components/media/flag/flag.class.d.ts +36 -0
  97. package/dist/components/media/flag/flag.class.js +2 -2
  98. package/dist/components/media/map/map.class.d.ts +196 -15
  99. package/dist/components/media/map/map.class.js +1 -1
  100. package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
  101. package/dist/components/overlays/chip/chip-group.class.js +10 -3
  102. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  103. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  104. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  105. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  106. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  107. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  108. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  109. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  110. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  111. package/dist/custom-elements-jsx.d.ts +12 -4
  112. package/dist/events.d.ts +7 -0
  113. package/dist/internal/autoloader-manifest.js +1 -1
  114. package/dist/internal/autoloader-tags.d.ts +1 -1
  115. package/dist/internal/autoloader-tags.js +1 -1
  116. package/dist/internal/form-associated.d.ts +1 -0
  117. package/dist/internal/form-associated.js +1 -1
  118. package/dist/internal/form-control-labels.js +1 -1
  119. package/dist/internal/lyra-element.d.ts +7 -1
  120. package/dist/internal/lyra-element.js +1 -1
  121. package/dist/internal/package-metadata.d.ts +1 -1
  122. package/dist/internal/package-metadata.js +1 -1
  123. package/dist/internal/root-registration-allowlist.d.ts +1 -1
  124. package/dist/internal/root-registration-allowlist.js +1 -1
  125. package/dist/lyra.d.ts +4 -2
  126. package/dist/lyra.js +1 -1
  127. package/dist/ssr/all.d.ts +1 -0
  128. package/dist/ssr/all.js +1 -1
  129. package/dist/ssr.d.ts +4 -4
  130. package/dist/styles/tokens-root.css +488 -0
  131. package/dist/svelte.d.ts +13 -4
  132. package/dist/vue.d.ts +12 -4
  133. package/llms/components/lr-app-rail-item.md +8 -1
  134. package/llms/components/lr-app-rail.md +6 -0
  135. package/llms/components/lr-chip-group.md +7 -0
  136. package/llms/components/lr-chip.md +7 -0
  137. package/llms/components/lr-date-input.md +19 -1
  138. package/llms/components/lr-date-picker.md +19 -1
  139. package/llms/components/lr-filter-bar.md +50 -1
  140. package/llms/components/lr-flag.md +38 -1
  141. package/llms/components/lr-funnel.md +122 -0
  142. package/llms/components/lr-heatmap.md +64 -8
  143. package/llms/components/lr-map.md +65 -8
  144. package/llms/components/lr-widget.md +7 -1
  145. package/llms/index.md +3 -2
  146. package/llms/peers.md +2 -2
  147. package/llms/shared.md +129 -1
  148. package/llms-full.txt +526 -20
  149. package/llms.txt +1 -1
  150. package/package.json +28 -9
  151. package/vscode-css-data.json +42 -0
  152. package/vscode-html-data.json +96 -17
  153. package/web-types.json +32714 -317
@@ -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"
@@ -0,0 +1,92 @@
1
+ import { type TemplateResult } from 'lit';
2
+ import { LyraElement } from '../../../internal/lyra-element.js';
3
+ /** One ordered step of a conversion funnel. */
4
+ export interface LyraFunnelStage {
5
+ /** Stage name, rendered beside the bar and read as the row's own text. Caller-owned copy. */
6
+ readonly label: string;
7
+ /** Absolute count or measure for the stage. Non-finite input is treated as 0. */
8
+ readonly value: number;
9
+ /** CSS color for this stage's bar. Unparseable values fall back to the shared bar color. */
10
+ readonly color?: string;
11
+ }
12
+ /**
13
+ * `<lr-funnel>` — a dependency-free conversion funnel: an ordered set of stages, each drawn as a
14
+ * bar whose length is that stage's share of the FIRST stage, read top-to-bottom as progressive
15
+ * drop-off.
16
+ *
17
+ * This is an analytics primitive rather than a general chart type — a sibling of `<lr-gauge>` and
18
+ * `<lr-heatmap>` rather than of the Chart.js-backed chart family, and it pulls no charting peer.
19
+ * It renders plain HTML, so stage names, absolute values, shares and drop-off percentages are real
20
+ * text in the DOM rather than a sighted-only drawing with a separate transcript bolted on.
21
+ *
22
+ * A funnel is deliberately not a sorted bar chart: it normalizes to the first stage instead of the
23
+ * data maximum, draws no value axis, and reads as stage-to-stage retention rather than category
24
+ * comparison.
25
+ *
26
+ * Degenerate inputs are defined rather than avoided:
27
+ *
28
+ * - An empty series renders the localized empty state and no list.
29
+ * - A single stage renders one full-length bar and no drop-off row.
30
+ * - A zero or negative first stage cannot define a share, so shares and drop-off percentages are
31
+ * omitted, every bar is zero-length, and the absolute values still render.
32
+ * - A stage larger than its predecessor (funnel re-entry) reports its true share above 100% in
33
+ * text while its bar clamps to the track, carrying the extra bar-overflow part token.
34
+ * - A comparison series of a different length pairs by index: extra comparison entries are
35
+ * ignored, and stages past its end simply get no comparison bar.
36
+ *
37
+ * @customElement lr-funnel
38
+ * @csspart base - The container element.
39
+ * @csspart stages - The ordered list of stages.
40
+ * @csspart stage - One stage row.
41
+ * @csspart dropoff - The change from the previous stage, above each stage after the first.
42
+ * @csspart stage-header - The text row above a stage's bar.
43
+ * @csspart stage-label - A stage's name.
44
+ * @csspart stage-value - A stage's absolute value.
45
+ * @csspart stage-share - A stage's share of the first stage.
46
+ * @csspart comparison-value - The comparison series' share for a stage.
47
+ * @csspart track - The full-length groove a stage's bar is drawn in.
48
+ * @csspart bar - A stage's bar.
49
+ * @csspart bar-overflow - Added to bar when the stage exceeds the first stage.
50
+ * @csspart comparison-bar - The comparison series' outline drawn behind a stage's bar.
51
+ * @csspart empty - The empty state shown when there are no stages.
52
+ * @cssprop [--lr-funnel-bar-color=var(--lr-color-brand)] - Fill of every stage bar that has no own color.
53
+ * @cssprop [--lr-funnel-comparison-color=var(--lr-color-border-strong)] - Outline of the comparison bars.
54
+ * @cssprop [--lr-funnel-track-color=var(--lr-color-surface-raised)] - Background of the bar track.
55
+ * @cssprop [--lr-funnel-bar-size=var(--lr-size-1-5rem)] - Thickness of a stage's track.
56
+ * @status experimental
57
+ * @since 12.0.0
58
+ */
59
+ export declare class LyraFunnel extends LyraElement {
60
+ static styles: import("lit").CSSResultGroup[];
61
+ /** The ordered stages, first to last. Every share is measured against the first entry. */
62
+ stages: readonly LyraFunnelStage[];
63
+ /**
64
+ * An optional baseline/peer cohort drawn behind each bar as an outline. It is normalized to its
65
+ * OWN first stage, so a funnel's shape stays comparable against a baseline whose absolute
66
+ * volumes are not comparable at all.
67
+ */
68
+ comparison: readonly LyraFunnelStage[];
69
+ /** Name for the comparison series. Falls back to a localized generic label. */
70
+ comparisonLabel: string;
71
+ /** Accessible name for the stage list. A host `aria-label` wins over it. */
72
+ label: string;
73
+ /** Whether the change from the previous stage is rendered above each later stage. */
74
+ dropoff: boolean;
75
+ /** Fraction digits used for every share and drop-off percentage. */
76
+ sharePrecision: number;
77
+ private get precision();
78
+ private formatValue;
79
+ private formatShare;
80
+ /** Resolves every stage's geometry and text inputs in one pass so render stays declarative. */
81
+ private resolveStages;
82
+ /** Clamped bar length as a CSS percentage; a share above 1 fills the track without spilling. */
83
+ private barLength;
84
+ private changeText;
85
+ private renderStage;
86
+ render(): TemplateResult;
87
+ }
88
+ declare global {
89
+ interface HTMLElementTagNameMap {
90
+ 'lr-funnel': LyraFunnel;
91
+ }
92
+ }
@@ -0,0 +1,25 @@
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}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{styles}from"./funnel.styles.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_comparePanel,LYRA_DEFAULT_contextMeterLabeledSummary,LYRA_DEFAULT_noData,LYRA_DEFAULT_statTrendDecreased,LYRA_DEFAULT_statTrendIncreased,LYRA_DEFAULT_trendUnchanged}from"../../../internal/default-strings.generated.js";const MAX_SHARE_PRECISION=20;class LyraFunnel extends LyraElement{constructor(){super(...arguments),this.stages=[],this.comparison=[],this.comparisonLabel="",this.label="",this.dropoff=!0,this.sharePrecision=0}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,comparePanel:LYRA_DEFAULT_comparePanel,contextMeterLabeledSummary:LYRA_DEFAULT_contextMeterLabeledSummary,noData:LYRA_DEFAULT_noData,statTrendDecreased:LYRA_DEFAULT_statTrendDecreased,statTrendIncreased:LYRA_DEFAULT_statTrendIncreased,trendUnchanged:LYRA_DEFAULT_trendUnchanged}}static{this.styles=[LyraElement.styles,styles]}get precision(){return finiteInteger(this.sharePrecision,0,0,MAX_SHARE_PRECISION)}formatValue(value){return getNumberFormat(this.effectiveLocale).format(value)}formatShare(ratio){const precision=this.precision;return getNumberFormat(this.effectiveLocale,{style:"percent",minimumFractionDigits:precision,maximumFractionDigits:precision}).format(ratio)}resolveStages(){const values=this.stages.map(stage=>finiteNumber(stage.value,0)),base=values[0]??0,hasBase=base>0,comparisonValues=this.comparison.map(stage=>finiteNumber(stage.value,0)),comparisonBase=comparisonValues[0]??0,hasComparisonBase=comparisonBase>0;return this.stages.map((stage,index)=>{const value=values[index]??0,previous=values[index-1],comparisonValue=comparisonValues[index];return{stage,value,share:hasBase?value/base:null,change:index>0&&previous!==void 0&&previous>0?(value-previous)/previous:null,comparisonShare:hasComparisonBase&&comparisonValue!==void 0?comparisonValue/comparisonBase:null}})}barLength(share){return`${(share===null?0:Math.min(1,Math.max(0,finiteNumber(share,0))))*100}%`}changeText(change){return change===0?this.localize("trendUnchanged"):this.localize(change>0?"statTrendIncreased":"statTrendDecreased",void 0,{value:this.formatShare(Math.abs(change))})}renderStage(resolved){const{stage,value,share,change,comparisonShare}=resolved,barColor=sanitizeCssColor(stage.color),barPart=share!==null&&share>1?"bar bar-overflow":"bar",comparisonName=this.comparisonLabel||this.localize("comparePanel");return html`<li part="stage">
2
+ ${this.dropoff&&change!==null?html`<span part="dropoff">${this.changeText(change)}</span>`:nothing}
3
+ <span part="stage-header">
4
+ <span part="stage-label">${stage.label}</span>
5
+ <span part="stage-value">${this.formatValue(value)}</span>
6
+ ${share===null?nothing:html`<span part="stage-share">${this.formatShare(share)}</span>`}
7
+ ${comparisonShare===null?nothing:html`<span part="comparison-value"
8
+ >${this.localize("contextMeterLabeledSummary",void 0,{label:comparisonName,summary:this.formatShare(comparisonShare)})}</span
9
+ >`}
10
+ </span>
11
+ <span part="track">
12
+ ${comparisonShare===null?nothing:html`<span
13
+ part="comparison-bar"
14
+ style=${styleMap({inlineSize:this.barLength(comparisonShare)})}
15
+ ></span>`}
16
+ <span
17
+ part=${barPart}
18
+ style=${styleMap({inlineSize:this.barLength(share),...barColor===void 0?{}:{backgroundColor:barColor}})}
19
+ ></span>
20
+ </span>
21
+ </li>`}render(){const resolved=this.resolveStages();if(resolved.length===0)return html`<div part="base"><p part="empty">${this.localize("noData")}</p></div>`;const name=hostAriaLabel(this)??(this.label||this.localize("chart"));return html`<div part="base">
22
+ <ol part="stages" aria-label=${name}>
23
+ ${resolved.map(entry=>this.renderStage(entry))}
24
+ </ol>
25
+ </div>`}}__decorate([property({attribute:!1})],LyraFunnel.prototype,"stages",void 0),__decorate([property({attribute:!1})],LyraFunnel.prototype,"comparison",void 0),__decorate([property({attribute:"comparison-label"})],LyraFunnel.prototype,"comparisonLabel",void 0),__decorate([property()],LyraFunnel.prototype,"label",void 0),__decorate([property({type:Boolean,reflect:!0,converter:trueDefaultBooleanConverter})],LyraFunnel.prototype,"dropoff",void 0),__decorate([property({type:Number,attribute:"share-precision"})],LyraFunnel.prototype,"sharePrecision",void 0);export{LyraFunnel};
@@ -0,0 +1 @@
1
+ export * from './funnel.class.js';
@@ -0,0 +1 @@
1
+ export*from"./funnel.class.js";import{LyraFunnel}from"./funnel.class.js";import{defineElement}from"../../../internal/prefix.js";defineElement("funnel",LyraFunnel);
@@ -0,0 +1 @@
1
+ export declare const styles: import("lit").CSSResult;
@@ -0,0 +1,127 @@
1
+ import{css}from"lit";const styles=css`
2
+ :host {
3
+ display: block;
4
+ font-family: var(--lr-font);
5
+ color: var(--lr-color-text);
6
+ }
7
+
8
+ [part='base'] {
9
+ min-inline-size: 0;
10
+ container-type: inline-size;
11
+ contain-intrinsic-inline-size: var(--lr-size-16rem);
12
+ }
13
+
14
+ [part='stages'] {
15
+ list-style: none;
16
+ margin: 0;
17
+ padding: 0;
18
+ display: flex;
19
+ flex-direction: column;
20
+ gap: var(--lr-space-s);
21
+ }
22
+
23
+ [part='stage'] {
24
+ display: flex;
25
+ flex-direction: column;
26
+ gap: var(--lr-space-2xs);
27
+ min-inline-size: 0;
28
+ }
29
+
30
+ [part='dropoff'] {
31
+ font-size: var(--lr-font-size-xs);
32
+ color: var(--lr-color-text-quiet);
33
+ align-self: flex-start;
34
+ }
35
+
36
+ [part='stage-header'] {
37
+ display: flex;
38
+ flex-wrap: wrap;
39
+ align-items: baseline;
40
+ gap: var(--lr-space-2xs) var(--lr-space-xs);
41
+ min-inline-size: 0;
42
+ }
43
+
44
+ [part='stage-label'] {
45
+ flex: 1 1 auto;
46
+ min-inline-size: 0;
47
+ font-size: var(--lr-font-size-sm);
48
+ overflow-wrap: anywhere;
49
+ text-align: start;
50
+ }
51
+
52
+ [part='stage-value'] {
53
+ font-size: var(--lr-font-size-sm);
54
+ font-weight: var(--lr-font-weight-semibold);
55
+ font-variant-numeric: tabular-nums;
56
+ }
57
+
58
+ [part='stage-share'] {
59
+ font-size: var(--lr-font-size-sm);
60
+ color: var(--lr-color-text-quiet);
61
+ font-variant-numeric: tabular-nums;
62
+ }
63
+
64
+ [part='comparison-value'] {
65
+ flex-basis: 100%;
66
+ font-size: var(--lr-font-size-xs);
67
+ color: var(--lr-color-text-quiet);
68
+ text-align: start;
69
+ }
70
+
71
+ [part='track'] {
72
+ position: relative;
73
+ display: block;
74
+ inline-size: 100%;
75
+ block-size: var(--lr-funnel-bar-size, var(--lr-size-1-5rem));
76
+ background: var(--lr-funnel-track-color, var(--lr-color-surface-raised));
77
+ border-radius: var(--lr-radius-xs);
78
+ }
79
+
80
+ [part~='bar'],
81
+ [part='comparison-bar'] {
82
+ position: absolute;
83
+ inset-inline-start: 0;
84
+ border-radius: inherit;
85
+ transition: inline-size var(--lr-transition-base);
86
+ }
87
+
88
+ [part='comparison-bar'] {
89
+ inset-block: 0;
90
+ border: var(--lr-size-1px) dashed
91
+ var(--lr-funnel-comparison-color, var(--lr-color-border-strong));
92
+ background: none;
93
+ }
94
+
95
+ [part~='bar'] {
96
+ inset-block: 0;
97
+ background: var(--lr-funnel-bar-color, var(--lr-color-brand));
98
+ }
99
+
100
+ [part='comparison-bar'] ~ [part~='bar'] {
101
+ inset-block: var(--lr-size-0-25rem);
102
+ }
103
+
104
+ [part~='bar-overflow'] {
105
+ border-inline-end: var(--lr-size-3px) solid var(--lr-color-text);
106
+ }
107
+
108
+ [part='empty'] {
109
+ margin: 0;
110
+ font-size: var(--lr-font-size-sm);
111
+ color: var(--lr-color-text-quiet);
112
+ text-align: start;
113
+ }
114
+
115
+ @container (max-inline-size: 18rem) {
116
+ [part='stage-label'] {
117
+ flex-basis: 100%;
118
+ }
119
+ }
120
+
121
+ @media (prefers-reduced-motion: reduce) {
122
+ [part~='bar'],
123
+ [part='comparison-bar'] {
124
+ transition: none;
125
+ }
126
+ }
127
+ `;export{styles};