@aceshooting/lyra-ui 11.0.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +8 -0
  3. package/custom-elements.json +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  5. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  6. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  7. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  8. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  9. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  10. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  11. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  12. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  13. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  14. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  15. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  16. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  17. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  18. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  19. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  20. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  21. package/dist/components/charts/chart/chart.class.js +1 -1
  22. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  23. package/dist/components/charts/chart/histogram.class.js +1 -1
  24. package/dist/components/charts/chart/line-chart.class.js +1 -1
  25. package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
  26. package/dist/components/charts/chart/lite-chart.class.js +17 -4
  27. package/dist/components/charts/chart/lite-chart.styles.js +29 -0
  28. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  29. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  30. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  31. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  32. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  33. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  34. package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
  35. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  36. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  37. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
  38. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  39. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  40. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  41. package/dist/components/data/heatmap/heatmap.class.d.ts +36 -1
  42. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  43. package/dist/components/data/table/table.class.d.ts +19 -0
  44. package/dist/components/data/table/table.class.js +3 -3
  45. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  46. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  47. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  48. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  49. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  50. package/dist/components/forms/combobox/combobox.class.js +1 -1
  51. package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
  52. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  53. package/dist/components/forms/date-picker/date-picker.class.d.ts +30 -4
  54. package/dist/components/forms/date-picker/date-picker.class.js +4 -4
  55. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  56. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  57. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  58. package/dist/components/forms/radio/radio-group.class.js +1 -1
  59. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  60. package/dist/components/forms/radio/radio.class.js +1 -1
  61. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  62. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  63. package/dist/components/forms/select/select.class.d.ts +1 -0
  64. package/dist/components/forms/select/select.class.js +1 -1
  65. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  66. package/dist/components/forms/slider/slider.class.js +1 -1
  67. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  68. package/dist/components/forms/switch/switch.class.js +1 -1
  69. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  70. package/dist/components/forms/time-range/time-range.class.js +1 -1
  71. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  72. package/dist/components/forms/token-input/token-input.class.js +1 -1
  73. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  74. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  75. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  76. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  77. package/dist/components/media/file-input/file-input.class.js +1 -1
  78. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  79. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  80. package/dist/components/media/flag/flag.class.d.ts +28 -0
  81. package/dist/components/media/flag/flag.class.js +2 -2
  82. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  83. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  84. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  85. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  86. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  87. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  88. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  89. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  90. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  91. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  92. package/dist/custom-elements-jsx.d.ts +5 -3
  93. package/dist/events.d.ts +7 -0
  94. package/dist/internal/canvas.js +1 -1
  95. package/dist/internal/form-associated.d.ts +1 -0
  96. package/dist/internal/form-associated.js +1 -1
  97. package/dist/internal/form-control-labels.js +1 -1
  98. package/dist/internal/lyra-element.js +1 -1
  99. package/dist/internal/package-metadata.d.ts +1 -1
  100. package/dist/internal/package-metadata.js +1 -1
  101. package/dist/lyra.d.ts +1 -1
  102. package/dist/svelte.d.ts +5 -3
  103. package/dist/theme.css +32 -0
  104. package/dist/vue.d.ts +5 -3
  105. package/llms/components/lr-agent-eval-dashboard.md +1 -1
  106. package/llms/components/lr-agent-workspace.md +1 -1
  107. package/llms/components/lr-box-plot.md +2 -2
  108. package/llms/components/lr-chart.md +1 -1
  109. package/llms/components/lr-chunk-inspector.md +1 -1
  110. package/llms/components/lr-combobox.md +3 -3
  111. package/llms/components/lr-date-input.md +22 -6
  112. package/llms/components/lr-date-picker.md +21 -5
  113. package/llms/components/lr-entity-dossier.md +1 -1
  114. package/llms/components/lr-eval-run.md +1 -1
  115. package/llms/components/lr-flag.md +24 -1
  116. package/llms/components/lr-grounding-summary.md +1 -1
  117. package/llms/components/lr-heatmap.md +18 -6
  118. package/llms/components/lr-lite-chart.md +19 -3
  119. package/llms/components/lr-map.md +2 -2
  120. package/llms/components/lr-memory-panel.md +1 -1
  121. package/llms/components/lr-option.md +3 -3
  122. package/llms/components/lr-popover.md +1 -1
  123. package/llms/components/lr-provenance-panel.md +1 -1
  124. package/llms/components/lr-rag-answer.md +1 -1
  125. package/llms/components/lr-rag-eval-dashboard.md +1 -1
  126. package/llms/components/lr-retrieval-results.md +1 -1
  127. package/llms/components/lr-retrieval-trace.md +1 -1
  128. package/llms/peers.md +10 -10
  129. package/llms/shared.md +19 -0
  130. package/llms/tokens.md +12 -0
  131. package/llms-full.txt +109 -21
  132. package/package.json +6 -6
  133. package/vscode-css-data.json +14 -0
  134. package/vscode-html-data.json +17 -3
  135. package/web-types.json +30 -4
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamBooleanFalse,LYRA_DEFAULT_toolParamBooleanTrue,LYRA_DEFAULT_toolParamBooleanUnset,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_toolParamSchemaLimit,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const MAX_SCHEMA_FIELDS=100,MAX_ENUM_OPTIONS=500,MAX_VALUE_ENTRIES=1e4,MAX_VALUE_NODES=5e4,MAX_VALUE_DEPTH=16,OMIT_VALUE=Symbol("omit-tool-param-value");function isPlainRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotValueEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_VALUE_DEPTH||budget.remaining<=0)return budget.truncated=!0,OMIT_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return budget.invalid=!0,OMIT_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(descriptor.value>MAX_VALUE_ENTRIES&&(budget.truncated=!0),length=Math.min(descriptor.value,MAX_VALUE_ENTRIES))}catch{budget.invalid=!0}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{budget.invalid=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){budget.invalid=!0;continue}budget.remaining-=1;const entry=snapshotValueEntry(descriptor.value,budget,depth+1);entry!==OMIT_VALUE&&output2.push(entry)}return budget.remaining<=0&&length>output2.length&&(budget.truncated=!0),Object.freeze(output2)}if(!isPlainRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return budget.invalid=!0,OMIT_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){const descriptor=descriptors[key];if(!descriptor?.enumerable)continue;if(retained>=MAX_VALUE_ENTRIES||budget.remaining<=0){budget.truncated=!0;break}if(!("value"in descriptor)){budget.invalid=!0;continue}retained+=1,budget.remaining-=1;const entry=snapshotValueEntry(descriptor.value,budget,depth+1);entry!==OMIT_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFormValue(value){if(value==null)return{value:Object.freeze({}),invalid:!1,truncated:!1};let isArray=!1;try{isArray=Array.isArray(value)}catch{return{value:Object.freeze({}),invalid:!0,truncated:!1}}if(typeof value!="object"||isArray||!isPlainRecord(value))return{value:Object.freeze({}),invalid:!0,truncated:!1};const budget={remaining:MAX_VALUE_NODES,seen:new WeakMap,invalid:!1,truncated:!1},snapshot=snapshotValueEntry(value,budget,0);return{value:snapshot===OMIT_VALUE?Object.freeze({}):snapshot,invalid:budget.invalid||snapshot===OMIT_VALUE,truncated:budget.truncated}}const EMPTY_SCHEMA=Object.freeze({type:"object",properties:Object.freeze({})});function snapshotSchemaStringArray(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return{isArray:!1,exceededLimit:!1}}if(!isArray)return{isArray:!1,exceededLimit:!1};let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return{isArray:!0,value:Object.freeze([]),exceededLimit:!1}}const output=[];for(let index=0;index<Math.min(sourceLength,MAX_SCHEMA_FIELDS);index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return{isArray:!0,value:Object.freeze(output),exceededLimit:sourceLength>MAX_SCHEMA_FIELDS}}function snapshotSchema(value){if(value==null)return{schema:EMPTY_SCHEMA,shapeError:"",exceededLimits:!1};let isArray=!1;try{isArray=Array.isArray(value)}catch{return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1}}if(typeof value!="object"||isArray)return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1};let rootDescriptors;try{rootDescriptors=Object.getOwnPropertyDescriptors(value)}catch{return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1}}const typeDescriptor=rootDescriptors.type;if(!typeDescriptor||!("value"in typeDescriptor)||typeDescriptor.value!=="object")return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1};const propertiesDescriptor=rootDescriptors.properties,propertiesValue=propertiesDescriptor&&"value"in propertiesDescriptor?propertiesDescriptor.value:void 0;if(propertiesValue===null||typeof propertiesValue!="object"||!isPlainRecord(propertiesValue))return{schema:EMPTY_SCHEMA,shapeError:"properties",exceededLimits:!1};const properties=Object.create(null);let shapeError="",exceededLimits=!1,seenFields=0,propertyDescriptors;try{propertyDescriptors=Object.getOwnPropertyDescriptors(propertiesValue)}catch{return{schema:EMPTY_SCHEMA,shapeError:"properties",exceededLimits:!1}}for(const key of Reflect.ownKeys(propertyDescriptors)){const descriptor=propertyDescriptors[key];if(typeof key!="string"||!descriptor?.enumerable)continue;if(seenFields+=1,seenFields>MAX_SCHEMA_FIELDS){exceededLimits=!0;break}if(!("value"in descriptor)||descriptor.value===null||typeof descriptor.value!="object"||!isPlainRecord(descriptor.value)){shapeError="properties";continue}const propertySnapshot=snapshotFormValue(descriptor.value);if(propertySnapshot.invalid||propertySnapshot.truncated){shapeError="properties";continue}const property=propertySnapshot.value;let choices=property.enum;Array.isArray(choices)&&choices.length>MAX_ENUM_OPTIONS&&(exceededLimits=!0,choices=Object.freeze(choices.slice(0,MAX_ENUM_OPTIONS))),properties[key]=Object.freeze({...property,...choices===void 0?{}:{enum:choices}})}const requiredDescriptor=rootDescriptors.required;let required;if(requiredDescriptor&&"value"in requiredDescriptor){const requiredSnapshot=snapshotSchemaStringArray(requiredDescriptor.value);requiredSnapshot.isArray?(required=requiredSnapshot.value,requiredSnapshot.exceededLimit&&(exceededLimits=!0)):requiredDescriptor.enumerable&&(shapeError="properties")}else requiredDescriptor?.enumerable&&(shapeError="properties");return{schema:Object.freeze({type:"object",properties:Object.freeze(properties),...required===void 0?{}:{required}}),shapeError,exceededLimits}}function cloneFormValue(value,_ownerWindow){return snapshotFormValue(value).value}class LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamBooleanFalse:LYRA_DEFAULT_toolParamBooleanFalse,toolParamBooleanTrue:LYRA_DEFAULT_toolParamBooleanTrue,toolParamBooleanUnset:LYRA_DEFAULT_toolParamBooleanUnset,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,toolParamSchemaLimit:LYRA_DEFAULT_toolParamSchemaLimit,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change","lr-input"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},schema:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this._errors={},this._formError="",this.showFormError=!1,this.touchedFields=new Set,this.baseId=nextId("tool-param-form"),this._fieldsetDisabled=!1,this._name="",this._schema=EMPTY_SCHEMA,this.schemaInputShapeError="",this.schemaInputExceededLimits=!1,this._value=Object.freeze({}),this.valueInputInvalid=!1,this.valueInputTruncated=!1,this.defaultValueSnapshot=Object.freeze({}),this.defaultValueCaptured=!1,this._effectiveValue=Object.freeze({}),this._validityFlags={},this._disabled=!1,this.hasInteracted=!1,this.visibleErrorSnapshot=new Map,this.suppressNextErrorAnnouncement=!0,this.stopNestedControlEvent=e=>{e.stopPropagation()},this.onFieldFocus=()=>{this.emit("focus")},this.onFieldBlur=()=>{this.emit("blur")},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.syncFormState()}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](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset.key===key);if(field)return field}}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&!!this._errors[key])}firstMissingPropertyError(){if(!this.renderRoot)return;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset.key===key);if(error)return error}}focusFirstControl(){if(!this.renderRoot)return;const controls=this.renderRoot.querySelectorAll("input.control, lr-select");for(const control of controls)if(!(control.disabled||control.getAttribute("aria-disabled")==="true")){control.focus();return}}click(){this.effectiveDisabled||this.focusFirstControl()}connectedCallback(){this.defaultValueCaptured||(this.defaultValueSnapshot=cloneFormValue(this._value,this.ownerDocument.defaultView),this.defaultValueCaptured=!0),super.connectedCallback(),this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.hasUpdated&&(this.suppressNextErrorAnnouncement=!0,this.requestUpdate()),this.syncFormState()}disconnectedCallback(){super.disconnectedCallback(),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.suppressNextErrorAnnouncement=!0}get effectiveValue(){return snapshotFormValue(this._effectiveValue).value}get schemaProperties(){return this._schema.properties}get requiredKeys(){return this._schema.required??Object.freeze([])}resolveEffectiveValue(){const props=this.schemaProperties,out={...this.value};for(const[key,prop]of Object.entries(props))!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0&&Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:prop.default});return snapshotFormValue(out).value}get schema(){return this._schema}set schema(next){const old=this._schema,snapshot=snapshotSchema(next);this._schema=snapshot.schema,this.schemaInputShapeError=snapshot.shapeError,this.schemaInputExceededLimits=snapshot.exceededLimits,this.syncFormState(),this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value,snapshot=snapshotFormValue(next);this._value=snapshot.value,this.valueInputInvalid=snapshot.invalid,this.valueInputTruncated=snapshot.truncated,this.syncFormState(),this.requestUpdate("value",old)}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.applyValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&(this.validityController.customValidityMessage||this._formError)&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties,required=new Set(this.requiredKeys),out={},flags={},addError=(key,message)=>{Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)})),flags.customError=!0;continue}if(!(Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0)){required.has(key)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);continue}const v=effective[key];if(type==="string"&&typeof v!="string"){addError(key,this.localize("fieldMustBeString")),flags.typeMismatch=!0;continue}if(type==="number"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber")),flags.typeMismatch=!0;continue}if(type==="integer"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger")),flags.typeMismatch=!0;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger")),flags.stepMismatch=!0;continue}if(type==="boolean"&&typeof v!="boolean"){addError(key,this.localize("fieldMustBeBoolean")),flags.typeMismatch=!0;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)})),flags.customError=!0;continue}prop.const!==void 0&&v!==prop.const&&(addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)})),flags.customError=!0)}for(const key of required)Object.prototype.hasOwnProperty.call(props,key)||(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);return{errors:out,flags}}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this._formError&&(this.showFormError=!0);const valid=this.internals.reportValidity();return!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0&&this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor(),error?.focus()}),valid}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot()}formResetCallback(){this.hasInteracted=!1,this.value=cloneFormValue(this.defaultValueSnapshot,this.ownerDocument.defaultView),this.touchedFields=new Set,this.showFormError=!1}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.applyValidity(),this.requestUpdate()}schemaShapeError(){return this.schemaInputShapeError==="object"?this.localize("schemaMustBeObject"):this.schemaInputShapeError==="properties"?this.localize("schemaPropertiesMustBeFlat"):this.schemaInputExceededLimits?this.localize("toolParamSchemaLimit",void 0,{fields:getNumberFormat(this.effectiveLocale).format(MAX_SCHEMA_FIELDS),options:getNumberFormat(this.effectiveLocale).format(MAX_ENUM_OPTIONS)}):""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value=="number"&&!Number.isFinite(value))throw new TypeError("Non-finite numbers are not JSON values.");return value});if(typeof serialized!="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue),this.applyValidity()}applyValidity(){if(this.validityController){if(this.barredFromValidation||Object.keys(this._validityFlags).length===0)this.validityController.setValidity({});else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective=Object.freeze({}),errors={},flags={},formError="",formValue=null;try{if(formError=this.schemaShapeError(),this.valueInputInvalid||this.valueInputTruncated)throw new TypeError("The value could not be retained within the public snapshot boundary.");effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors,flags=validation.flags,formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable"),formValue=null}formError&&(flags.customError=!0,formValue=null),this._effectiveValue=effective,JSON.stringify(this._errors)!==JSON.stringify(errors)&&(this._errors=errors),this._formError=formError,this._validityFlags=flags,this.syncInternals(formValue)}updated(changed){if(super.updated(changed),this.publishValiditySnapshot(),changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]=="function").map(element=>element.updateComplete).filter(update=>update!==void 0);nestedUpdates.length>0&&Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset.key,key=node.dataset.key??fieldKey??"form",text=node.textContent?.trim()??"";text&&currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors)this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)&&freshMessages.push(text);freshMessages.length>0&&this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors,this.suppressNextErrorAnnouncement=!1}setFieldValue(key,val){this.effectiveDisabled||(this.hasInteracted=!0,this.value={...this.value,[key]:val},this.emit("lr-input",{value:this.effectiveValue}))}markTouched(key){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(key)&&(this.touchedFields=new Set(this.touchedFields).add(key))}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const n=e.target.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value)}onBooleanSelectChange(key,e){e.stopPropagation();const value=e.target.value;if(value===""){if(this.effectiveDisabled)return;this.hasInteracted=!0;const next={...this.value};Reflect.deleteProperty(next,key),this.value=next,this.emit("lr-input",{value:this.effectiveValue});return}this.setFieldValue(key,value==="true")}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0)return html`<lr-select
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{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamBooleanFalse,LYRA_DEFAULT_toolParamBooleanTrue,LYRA_DEFAULT_toolParamBooleanUnset,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_toolParamSchemaLimit,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const MAX_SCHEMA_FIELDS=100,MAX_ENUM_OPTIONS=500,MAX_VALUE_ENTRIES=1e4,MAX_VALUE_NODES=5e4,MAX_VALUE_DEPTH=16,OMIT_VALUE=Symbol("omit-tool-param-value");function isPlainRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotValueEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_VALUE_DEPTH||budget.remaining<=0)return budget.truncated=!0,OMIT_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return budget.invalid=!0,OMIT_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(descriptor.value>MAX_VALUE_ENTRIES&&(budget.truncated=!0),length=Math.min(descriptor.value,MAX_VALUE_ENTRIES))}catch{budget.invalid=!0}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{budget.invalid=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){budget.invalid=!0;continue}budget.remaining-=1;const entry=snapshotValueEntry(descriptor.value,budget,depth+1);entry!==OMIT_VALUE&&output2.push(entry)}return budget.remaining<=0&&length>output2.length&&(budget.truncated=!0),Object.freeze(output2)}if(!isPlainRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return budget.invalid=!0,OMIT_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){const descriptor=descriptors[key];if(!descriptor?.enumerable)continue;if(retained>=MAX_VALUE_ENTRIES||budget.remaining<=0){budget.truncated=!0;break}if(!("value"in descriptor)){budget.invalid=!0;continue}retained+=1,budget.remaining-=1;const entry=snapshotValueEntry(descriptor.value,budget,depth+1);entry!==OMIT_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFormValue(value){if(value==null)return{value:Object.freeze({}),invalid:!1,truncated:!1};let isArray=!1;try{isArray=Array.isArray(value)}catch{return{value:Object.freeze({}),invalid:!0,truncated:!1}}if(typeof value!="object"||isArray||!isPlainRecord(value))return{value:Object.freeze({}),invalid:!0,truncated:!1};const budget={remaining:MAX_VALUE_NODES,seen:new WeakMap,invalid:!1,truncated:!1},snapshot=snapshotValueEntry(value,budget,0);return{value:snapshot===OMIT_VALUE?Object.freeze({}):snapshot,invalid:budget.invalid||snapshot===OMIT_VALUE,truncated:budget.truncated}}const EMPTY_SCHEMA=Object.freeze({type:"object",properties:Object.freeze({})});function snapshotSchemaStringArray(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return{isArray:!1,exceededLimit:!1}}if(!isArray)return{isArray:!1,exceededLimit:!1};let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return{isArray:!0,value:Object.freeze([]),exceededLimit:!1}}const output=[];for(let index=0;index<Math.min(sourceLength,MAX_SCHEMA_FIELDS);index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return{isArray:!0,value:Object.freeze(output),exceededLimit:sourceLength>MAX_SCHEMA_FIELDS}}function snapshotSchema(value){if(value==null)return{schema:EMPTY_SCHEMA,shapeError:"",exceededLimits:!1};let isArray=!1;try{isArray=Array.isArray(value)}catch{return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1}}if(typeof value!="object"||isArray)return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1};let rootDescriptors;try{rootDescriptors=Object.getOwnPropertyDescriptors(value)}catch{return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1}}const typeDescriptor=rootDescriptors.type;if(!typeDescriptor||!("value"in typeDescriptor)||typeDescriptor.value!=="object")return{schema:EMPTY_SCHEMA,shapeError:"object",exceededLimits:!1};const propertiesDescriptor=rootDescriptors.properties,propertiesValue=propertiesDescriptor&&"value"in propertiesDescriptor?propertiesDescriptor.value:void 0;if(propertiesValue===null||typeof propertiesValue!="object"||!isPlainRecord(propertiesValue))return{schema:EMPTY_SCHEMA,shapeError:"properties",exceededLimits:!1};const properties=Object.create(null);let shapeError="",exceededLimits=!1,seenFields=0,propertyDescriptors;try{propertyDescriptors=Object.getOwnPropertyDescriptors(propertiesValue)}catch{return{schema:EMPTY_SCHEMA,shapeError:"properties",exceededLimits:!1}}for(const key of Reflect.ownKeys(propertyDescriptors)){const descriptor=propertyDescriptors[key];if(typeof key!="string"||!descriptor?.enumerable)continue;if(seenFields+=1,seenFields>MAX_SCHEMA_FIELDS){exceededLimits=!0;break}if(!("value"in descriptor)||descriptor.value===null||typeof descriptor.value!="object"||!isPlainRecord(descriptor.value)){shapeError="properties";continue}const propertySnapshot=snapshotFormValue(descriptor.value);if(propertySnapshot.invalid||propertySnapshot.truncated){shapeError="properties";continue}const property=propertySnapshot.value;let choices=property.enum;Array.isArray(choices)&&choices.length>MAX_ENUM_OPTIONS&&(exceededLimits=!0,choices=Object.freeze(choices.slice(0,MAX_ENUM_OPTIONS))),properties[key]=Object.freeze({...property,...choices===void 0?{}:{enum:choices}})}const requiredDescriptor=rootDescriptors.required;let required;if(requiredDescriptor&&"value"in requiredDescriptor){const requiredSnapshot=snapshotSchemaStringArray(requiredDescriptor.value);requiredSnapshot.isArray?(required=requiredSnapshot.value,requiredSnapshot.exceededLimit&&(exceededLimits=!0)):requiredDescriptor.enumerable&&(shapeError="properties")}else requiredDescriptor?.enumerable&&(shapeError="properties");return{schema:Object.freeze({type:"object",properties:Object.freeze(properties),...required===void 0?{}:{required}}),shapeError,exceededLimits}}function cloneFormValue(value,_ownerWindow){return snapshotFormValue(value).value}class LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamBooleanFalse:LYRA_DEFAULT_toolParamBooleanFalse,toolParamBooleanTrue:LYRA_DEFAULT_toolParamBooleanTrue,toolParamBooleanUnset:LYRA_DEFAULT_toolParamBooleanUnset,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,toolParamSchemaLimit:LYRA_DEFAULT_toolParamSchemaLimit,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change","lr-input"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},schema:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this._errors={},this._formError="",this.showFormError=!1,this.touchedFields=new Set,this.baseId=nextId("tool-param-form"),this._fieldsetDisabled=!1,this._name="",this._schema=EMPTY_SCHEMA,this.schemaInputShapeError="",this.schemaInputExceededLimits=!1,this._value=Object.freeze({}),this.valueInputInvalid=!1,this.valueInputTruncated=!1,this.defaultValueSnapshot=Object.freeze({}),this.defaultValueCaptured=!1,this._effectiveValue=Object.freeze({}),this._validityFlags={},this._disabled=!1,this.hasInteracted=!1,this.visibleErrorSnapshot=new Map,this.suppressNextErrorAnnouncement=!0,this.stopNestedControlEvent=e=>{e.stopPropagation()},this.onFieldFocus=()=>{this.emit("focus")},this.onFieldBlur=()=>{this.emit("blur")},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.syncFormState()}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](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset.key===key);if(field)return field}}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&!!this._errors[key])}firstMissingPropertyError(){if(!this.renderRoot)return;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset.key===key);if(error)return error}}focusFirstControl(){if(!this.renderRoot)return;const controls=this.renderRoot.querySelectorAll("input.control, lr-select");for(const control of controls)if(!(control.disabled||control.getAttribute("aria-disabled")==="true")){control.focus();return}}click(){this.effectiveDisabled||this.focusFirstControl()}connectedCallback(){this.defaultValueCaptured||(this.defaultValueSnapshot=cloneFormValue(this._value,this.ownerDocument.defaultView),this.defaultValueCaptured=!0),super.connectedCallback(),this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.hasUpdated&&(this.suppressNextErrorAnnouncement=!0,this.requestUpdate()),this.syncFormState()}disconnectedCallback(){super.disconnectedCallback(),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.suppressNextErrorAnnouncement=!0}get effectiveValue(){return snapshotFormValue(this._effectiveValue).value}get schemaProperties(){return this._schema.properties}get requiredKeys(){return this._schema.required??Object.freeze([])}resolveEffectiveValue(){const props=this.schemaProperties,out={...this.value};for(const[key,prop]of Object.entries(props))!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0&&Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:prop.default});return snapshotFormValue(out).value}get schema(){return this._schema}set schema(next){const old=this._schema,snapshot=snapshotSchema(next);this._schema=snapshot.schema,this.schemaInputShapeError=snapshot.shapeError,this.schemaInputExceededLimits=snapshot.exceededLimits,this.syncFormState(),this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value,snapshot=snapshotFormValue(next);this._value=snapshot.value,this.valueInputInvalid=snapshot.invalid,this.valueInputTruncated=snapshot.truncated,this.syncFormState(),this.requestUpdate("value",old)}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.applyValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&(this.validityController.customValidityMessage||this._formError)&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties,required=new Set(this.requiredKeys),out={},flags={},addError=(key,message)=>{Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)})),flags.customError=!0;continue}if(!(Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0)){required.has(key)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);continue}const v=effective[key];if(type==="string"&&typeof v!="string"){addError(key,this.localize("fieldMustBeString")),flags.typeMismatch=!0;continue}if(type==="number"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber")),flags.typeMismatch=!0;continue}if(type==="integer"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger")),flags.typeMismatch=!0;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger")),flags.stepMismatch=!0;continue}if(type==="boolean"&&typeof v!="boolean"){addError(key,this.localize("fieldMustBeBoolean")),flags.typeMismatch=!0;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)})),flags.customError=!0;continue}prop.const!==void 0&&v!==prop.const&&(addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)})),flags.customError=!0)}for(const key of required)Object.prototype.hasOwnProperty.call(props,key)||(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);return{errors:out,flags}}checkValidity(){return this.syncFormState(),this.internals.checkValidity()}reportValidity(){this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this._formError&&(this.showFormError=!0);const valid=this.internals.reportValidity();return!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0&&this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor(),error?.focus()}),valid}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot()}formResetCallback(){this.hasInteracted=!1,this.value=cloneFormValue(this.defaultValueSnapshot,this.ownerDocument.defaultView),this.touchedFields=new Set,this.showFormError=!1}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.applyValidity(),this.requestUpdate()}schemaShapeError(){return this.schemaInputShapeError==="object"?this.localize("schemaMustBeObject"):this.schemaInputShapeError==="properties"?this.localize("schemaPropertiesMustBeFlat"):this.schemaInputExceededLimits?this.localize("toolParamSchemaLimit",void 0,{fields:getNumberFormat(this.effectiveLocale).format(MAX_SCHEMA_FIELDS),options:getNumberFormat(this.effectiveLocale).format(MAX_ENUM_OPTIONS)}):""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value=="number"&&!Number.isFinite(value))throw new TypeError("Non-finite numbers are not JSON values.");return value});if(typeof serialized!="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue),this.applyValidity()}applyValidity(){if(this.validityController){if(this.barredFromValidation||Object.keys(this._validityFlags).length===0)this.validityController.setValidity({});else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective=Object.freeze({}),errors={},flags={},formError="",formValue=null;try{if(formError=this.schemaShapeError(),this.valueInputInvalid||this.valueInputTruncated)throw new TypeError("The value could not be retained within the public snapshot boundary.");effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors,flags=validation.flags,formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable"),formValue=null}formError&&(flags.customError=!0,formValue=null),this._effectiveValue=effective,JSON.stringify(this._errors)!==JSON.stringify(errors)&&(this._errors=errors),this._formError=formError,this._validityFlags=flags,this.syncInternals(formValue)}updated(changed){if(super.updated(changed),this.publishValiditySnapshot(),changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]=="function").map(element=>element.updateComplete).filter(update=>update!==void 0);nestedUpdates.length>0&&Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset.key,key=node.dataset.key??fieldKey??"form",text=node.textContent?.trim()??"";text&&currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors)this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)&&freshMessages.push(text);freshMessages.length>0&&this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors,this.suppressNextErrorAnnouncement=!1}setFieldValue(key,val){this.effectiveDisabled||(this.hasInteracted=!0,this.value={...this.value,[key]:val},this.emit("lr-input",{value:this.effectiveValue}))}markTouched(key){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(key)&&(this.touchedFields=new Set(this.touchedFields).add(key))}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const n=e.target.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value)}onBooleanSelectChange(key,e){e.stopPropagation();const value=e.target.value;if(value===""){if(this.effectiveDisabled)return;this.hasInteracted=!0;const next={...this.value};Reflect.deleteProperty(next,key),this.value=next,this.emit("lr-input",{value:this.effectiveValue});return}this.setFieldValue(key,value==="true")}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0)return html`<lr-select
2
2
  id=${fieldId}
3
3
  .label=${label}
4
4
  .hint=${prop.description??""}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{closeIcon,expandIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{styles}from"./tool-result-dialog.styles.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_maximize,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_toolCall}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){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,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{closeIcon,expandIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{styles}from"./tool-result-dialog.styles.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_maximize,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_toolCall}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -20,7 +20,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
20
20
  <circle cx="12" cy="12" r="9"></circle>
21
21
  <line x1="9" y1="9" x2="15" y2="15"></line>
22
22
  <line x1="15" y1="9" x2="9" y2="15"></line>
23
- `)}function deniedIcon(){return icon(svg`<circle cx="12" cy="12" r="9"></circle><line x1="6" y1="18" x2="18" y2="6"></line>`)}const STATUS_ICON={pending:pendingIcon,running:runningIcon,success:successIcon,error:errorIcon,denied:deniedIcon},STATUS_LABEL={pending:"Pending",running:"Running",success:"Success",error:"Error",denied:"Denied"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied"},STATUS_VALUES=new Set(Object.keys(STATUS_LABEL)),statusConverter={fromAttribute(value){return value!==null&&STATUS_VALUES.has(value)?value:"pending"},toAttribute(value){return value}};class LyraToolResultDialog extends LyraElement{constructor(){super(...arguments),this.open=!1,this.accessibleLabel=null,this.toolName="",this.status="pending",this.maximized=!1,this.hasFooterSlot=!1,this.titleId=nextId("tool-result-dialog-title"),this.onFooterSlotChange=e=>{this.hasFooterSlot=e.target.assignedElements({flatten:!0}).length>0},this.onBackdropClick=()=>{this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{this.close("close-button")},this.toggleMaximized=()=>{this.maximized=!this.maximized,this.emit("lr-maximize-change",Object.freeze({maximized:this.maximized}))}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,maximize:LYRA_DEFAULT_maximize,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,toolCall:LYRA_DEFAULT_toolCall}}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")),changed.has("open")&&(this.open?this.activateOverlay():this.deactivateOverlay())}updated(changed){super.updated(changed),changed.has("open")&&this.open&&this.overlay?.focusInitial()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueMicrotask(()=>this.overlay?.focusInitial()))}disconnectedCallback(){super.disconnectedCallback(),this.overlay?.suspend()}close(reason="api"){this.open&&(this.open=!1,this.emit("lr-close",reason))}show(){this.open||(this.open=!0)}hide(reason="api"){this.close(reason)}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.overlay?.deactivate(),this.overlay=void 0}localizedDuration(ms){const duration=durationMessageValue(ms);return this.localize(duration.key,void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationSeconds"?1:0}).format(duration.value)})}get safeDurationMs(){return this.durationMs!=null&&Number.isFinite(this.durationMs)?finiteRange(this.durationMs,0,0):null}render(){const durationMs=this.safeDurationMs,panelLabel=hostAriaLabel(this)===null&&this.accessibleLabel?this.accessibleLabel:null;return html`
23
+ `)}function deniedIcon(){return icon(svg`<circle cx="12" cy="12" r="9"></circle><line x1="6" y1="18" x2="18" y2="6"></line>`)}const STATUS_ICON={pending:pendingIcon,running:runningIcon,success:successIcon,error:errorIcon,denied:deniedIcon},STATUS_LABEL={pending:"Pending",running:"Running",success:"Success",error:"Error",denied:"Denied"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied"},STATUS_VALUES=new Set(Object.keys(STATUS_LABEL)),statusConverter={fromAttribute(value){return value!==null&&STATUS_VALUES.has(value)?value:"pending"},toAttribute(value){return value}};class LyraToolResultDialog extends LyraElement{constructor(){super(...arguments),this.open=!1,this.accessibleLabel=null,this.toolName="",this.status="pending",this.maximized=!1,this.hasFooterSlot=!1,this.titleId=nextId("tool-result-dialog-title"),this.onFooterSlotChange=e=>{this.hasFooterSlot=e.target.assignedElements({flatten:!0}).length>0},this.onBackdropClick=()=>{this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{this.close("close-button")},this.toggleMaximized=()=>{this.maximized=!this.maximized,this.emit("lr-maximize-change",Object.freeze({maximized:this.maximized}))}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,maximize:LYRA_DEFAULT_maximize,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,toolCall:LYRA_DEFAULT_toolCall}}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")),changed.has("open")&&(this.open?this.activateOverlay():this.deactivateOverlay())}updated(changed){super.updated(changed),changed.has("open")&&this.open&&this.overlay?.focusInitial()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueMicrotask(()=>this.overlay?.focusInitial()))}disconnectedCallback(){super.disconnectedCallback(),this.overlay?.suspend()}close(reason="api"){this.open&&(this.open=!1,this.emit("lr-close",reason))}show(){this.open||(this.open=!0)}hide(reason="api"){this.close(reason)}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.overlay?.deactivate(),this.overlay=void 0}localizedDuration(ms){const duration=durationMessageValue(ms);return this.localize(duration.key,void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationSeconds"?1:0}).format(duration.value)})}get safeDurationMs(){return this.durationMs!=null&&Number.isFinite(this.durationMs)?finiteRange(this.durationMs,0,0):null}render(){const durationMs=this.safeDurationMs,panelLabel=hostAriaLabel(this)===null&&this.accessibleLabel?this.accessibleLabel:null;return html`
24
24
  <div part="backdrop" @click=${this.onBackdropClick}></div>
25
25
  <div
26
26
  part="panel"
@@ -1,8 +1,8 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isRtl}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{chevronIcon}from"../../../internal/icons.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./trace-tree.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"./span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_collapse,LYRA_DEFAULT_cost,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_traceTree,LYRA_DEFAULT_traceTreeMetricLabel,LYRA_DEFAULT_traceTreeSpanStatus}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function glyph(paths){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,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isRtl}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{chevronIcon}from"../../../internal/icons.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./trace-tree.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"./span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_collapse,LYRA_DEFAULT_cost,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_traceTree,LYRA_DEFAULT_traceTreeMetricLabel,LYRA_DEFAULT_traceTreeSpanStatus}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function glyph(paths){return svg`
2
2
  <svg width="1em" height="1em" viewBox=${ICON_VIEW_BOX} fill="none" stroke="currentColor"
3
3
  stroke-width=${ICON_STROKE_WIDTH} stroke-linecap="round" stroke-linejoin="round"
4
4
  aria-hidden="true" focusable="false">${paths}</svg>
5
- `}function agentIcon(){return glyph(svg`<rect x="5" y="8" width="14" height="10" rx="2"></rect><circle cx="9.5" cy="13" r="1"></circle><circle cx="14.5" cy="13" r="1"></circle><path d="M12 8V5"></path><circle cx="12" cy="4" r="1"></circle>`)}function llmIcon(){return glyph(svg`<path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6z"></path><path d="M18.5 15l.7 1.9 1.9.7-1.9.7-.7 1.9-.7-1.9-1.9-.7 1.9-.7z"></path>`)}function toolIcon(){return glyph(svg`<path d="M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17l3 3 5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-2-2z"></path>`)}function retrieverIcon(){return glyph(svg`<circle cx="10.5" cy="10.5" r="6.5"></circle><line x1="15.5" y1="15.5" x2="20" y2="20"></line>`)}function embeddingIcon(){return glyph(svg`<circle cx="6" cy="6" r="1.6"></circle><circle cx="18" cy="6" r="1.6"></circle><circle cx="6" cy="18" r="1.6"></circle><circle cx="18" cy="18" r="1.6"></circle><circle cx="12" cy="12" r="1.6"></circle><line x1="7.3" y1="7.3" x2="10.8" y2="10.8"></line><line x1="16.7" y1="7.3" x2="13.2" y2="10.8"></line><line x1="7.3" y1="16.7" x2="10.8" y2="13.2"></line><line x1="16.7" y1="16.7" x2="13.2" y2="13.2"></line>`)}function otherIcon(){return glyph(svg`<circle cx="12" cy="12" r="8"></circle>`)}const KIND_ICON={agent:agentIcon,llm:llmIcon,tool:toolIcon,retriever:retrieverIcon,embedding:embeddingIcon,other:otherIcon},KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied"};class LyraTraceTree extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.showTokens=!1,this.showCost=!1,this.hideBars=!1,this.collapsedIds=new Set,this.focusedId=null,this.previousStatuses=new Map,this.pendingAnnouncements=[],this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.renderedProjectionTruncated=!1,this.onKeyDown=e=>{const rows=this.buildRows();if(rows.length===0)return;const currentIndex=rows.findIndex(r=>r.span.id===this.focusedId),current=currentIndex>=0?rows[currentIndex]:rows[0];if(!current)return;const rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else{const child=rows[currentIndex+1];child&&child.depth>current.depth&&this.focusRow(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&!this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else for(let i=currentIndex-1;i>=0;i--){const row=rows[i];if(row&&row.depth<current.depth){this.focusRow(row);break}}break;case"Enter":case" ":e.preventDefault(),this.selectRow(current.span.id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,cost:LYRA_DEFAULT_cost,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,traceTree:LYRA_DEFAULT_traceTree,traceTreeMetricLabel:LYRA_DEFAULT_traceTreeMetricLabel,traceTreeSpanStatus:LYRA_DEFAULT_traceTreeSpanStatus}}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.syncLimitAnnouncementSink(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.renderedProjectionTruncated}disconnectedCallback(){this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=void 0,this.syncLimitAnnouncementSink()}syncLimitAnnouncementSink(){!this.isConnected||this.limitAnnouncementSink?.element.ownerDocument===this.ownerDocument||(this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}buildHierarchy(){const{spans,byId,truncated}=normalizeLyraSpans(this.spans,this.activeSpanId),childrenOf=new Map,parentOf=new Map,roots=[],hasCyclicParentChain=span=>{const visited=new Set([span.id]);let parentId=span.parentId;for(;parentId!=null;){if(visited.has(parentId))return!0;visited.add(parentId),parentId=byId.get(parentId)?.parentId}return!1};for(const span of spans){const parent=span.parentId!=null&&!hasCyclicParentChain(span)?byId.get(span.parentId):void 0;if(parent&&parent.id!==span.id){const list=childrenOf.get(parent.id)??[];list.push(span),childrenOf.set(parent.id,list),parentOf.set(span.id,parent.id)}else roots.push(span)}const byStart=(a,b)=>a.startMs-b.startMs;roots.sort(byStart);for(const list of childrenOf.values())list.sort(byStart);return{spans,byId,childrenOf,parentOf,roots,truncated}}buildRows(hierarchy=this.buildHierarchy()){const rows=[],stack=[...hierarchy.roots].reverse().map((span,reverseIndex)=>({span,depth:0,posInSet:hierarchy.roots.length-reverseIndex,setSize:hierarchy.roots.length})),visited=new Set;for(;stack.length>0&&rows.length<MAX_RENDERED_LYRA_SPANS;){const current=stack.pop();if(!current||visited.has(current.span.id))continue;visited.add(current.span.id);const children=hierarchy.childrenOf.get(current.span.id)??[];if(rows.push({...current,hasChildren:children.length>0}),!(children.length===0||this.collapsedIds.has(current.span.id)))for(let index=children.length-1;index>=0;index--){const child=children[index];child&&stack.push({span:child,depth:current.depth+1,posInSet:index+1,setSize:children.length})}}return rows}traceExtent(spans=this.buildHierarchy().spans){let max=0;for(const s of spans)max=Math.max(max,s.endMs??s.startMs,s.startMs);return max||1}formatDuration(ms){if(ms==null)return"";const number=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:ms<1e3?0:1});return ms<1e3?this.localize("durationMilliseconds",void 0,{value:number.format(ms)}):this.localize("durationSeconds",void 0,{value:number.format(ms/1e3)})}formatNumber(n){return getNumberFormat(this.effectiveLocale).format(finiteCount(n))}validTokenMetric(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0}toggleSpan(id){const collapsed=this.collapsedIds.has(id);collapsed||this.renderedRowById(id)?.focus();const next=new Set(this.collapsedIds);collapsed?next.delete(id):next.add(id),this.collapsedIds=next,this.focusedId=id,this.emit("lr-span-toggle",{spanId:id,expanded:collapsed})}async expandAll(){this.collapsedIds=new Set,await this.updateComplete}collapseAll(){const next=new Set,hierarchy=this.buildHierarchy(),{byId,parentOf}=hierarchy,hasChild=new Set(hierarchy.childrenOf.keys());for(const id of hasChild)next.add(id);if(this.collapsedIds=next,this.focusedId!=null){let current=byId.get(this.focusedId);for(;current&&parentOf.has(current.id);)current=byId.get(parentOf.get(current.id));this.focusedId=current?.id??null,current&&this.renderedRowById(current.id)?.focus()}}focusRow(row){row&&(this.focusedId=row.span.id,this.updateComplete.then(()=>{this.renderedRowById(row.span.id)?.focus()}))}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),changed.has("spans")||changed.has("activeSpanId")||changed.has("collapsedIds")){const hierarchy=this.buildHierarchy(),ids=new Set(hierarchy.byId.keys());let pruned=null;for(const id of this.collapsedIds)ids.has(id)||(pruned??=new Set(this.collapsedIds),pruned.delete(id));if(pruned&&(this.collapsedIds=pruned),(changed.has("spans")||changed.has("activeSpanId"))&&this.activeSpanId&&hierarchy.byId.has(this.activeSpanId)){const revealed=new Set(this.collapsedIds);let currentId=this.activeSpanId,changedCollapse=!1;for(;hierarchy.parentOf.has(currentId);)currentId=hierarchy.parentOf.get(currentId),revealed.delete(currentId)&&(changedCollapse=!0);changedCollapse&&(this.collapsedIds=revealed)}const rows=this.buildRows(hierarchy),visibleIds=new Set(rows.map(row=>row.span.id));if((this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&visibleIds.has(this.activeSpanId)?this.activeSpanId:rows[0]?.span.id??null),changed.has("spans")){for(const row of rows){const{span}=row,prev=this.previousStatuses.get(span.id);prev!==void 0&&prev!==span.status&&this.pendingAnnouncements.push(this.localize("traceTreeSpanStatus",void 0,{name:span.name,status:this.localize(STATUS_LABEL_KEY[span.status])}))}this.previousStatuses=new Map(hierarchy.spans.map(span=>[span.id,span.status]))}const visibleAncestor=id=>{let current=id?hierarchy.byId.get(id):void 0;for(;current;){if(visibleIds.has(current.id))return current.id;current=hierarchy.parentOf.has(current.id)?hierarchy.byId.get(hierarchy.parentOf.get(current.id)):void 0}return null};this.focusedId=visibleAncestor(this.activeSpanId)??visibleAncestor(this.focusedId)??rows[0]?.span.id??null}}renderedRowById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),(changed.has("activeSpanId")||changed.has("spans")||changed.has("collapsedIds"))&&this.activeSpanId){const row=this.renderedRowById(this.activeSpanId);if(row){const ownerWindow=row.ownerDocument.defaultView,reducedMotion=!ownerWindow||prefersReducedMotion(ownerWindow);row.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}if(this.pendingAnnouncements.length>0){const texts=this.pendingAnnouncements;this.pendingAnnouncements=[];for(const text of texts)this.liveRegion?.announce(text)}this.limitAnnouncementInitialized&&this.renderedProjectionTruncated&&!this.previouslyTruncated&&this.limitAnnouncementSink?.announce(this.localize("spanProjectionLimit",void 0,{count:MAX_RENDERED_LYRA_SPANS})),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.renderedProjectionTruncated}renderHeader(){return html`
5
+ `}function agentIcon(){return glyph(svg`<rect x="5" y="8" width="14" height="10" rx="2"></rect><circle cx="9.5" cy="13" r="1"></circle><circle cx="14.5" cy="13" r="1"></circle><path d="M12 8V5"></path><circle cx="12" cy="4" r="1"></circle>`)}function llmIcon(){return glyph(svg`<path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6z"></path><path d="M18.5 15l.7 1.9 1.9.7-1.9.7-.7 1.9-.7-1.9-1.9-.7 1.9-.7z"></path>`)}function toolIcon(){return glyph(svg`<path d="M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17l3 3 5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-2-2z"></path>`)}function retrieverIcon(){return glyph(svg`<circle cx="10.5" cy="10.5" r="6.5"></circle><line x1="15.5" y1="15.5" x2="20" y2="20"></line>`)}function embeddingIcon(){return glyph(svg`<circle cx="6" cy="6" r="1.6"></circle><circle cx="18" cy="6" r="1.6"></circle><circle cx="6" cy="18" r="1.6"></circle><circle cx="18" cy="18" r="1.6"></circle><circle cx="12" cy="12" r="1.6"></circle><line x1="7.3" y1="7.3" x2="10.8" y2="10.8"></line><line x1="16.7" y1="7.3" x2="13.2" y2="10.8"></line><line x1="7.3" y1="16.7" x2="10.8" y2="13.2"></line><line x1="16.7" y1="16.7" x2="13.2" y2="13.2"></line>`)}function otherIcon(){return glyph(svg`<circle cx="12" cy="12" r="8"></circle>`)}const KIND_ICON={agent:agentIcon,llm:llmIcon,tool:toolIcon,retriever:retrieverIcon,embedding:embeddingIcon,other:otherIcon},KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied"};class LyraTraceTree extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.showTokens=!1,this.showCost=!1,this.hideBars=!1,this.collapsedIds=new Set,this.focusedId=null,this.previousStatuses=new Map,this.pendingAnnouncements=[],this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.renderedProjectionTruncated=!1,this.onKeyDown=e=>{const rows=this.buildRows();if(rows.length===0)return;const currentIndex=rows.findIndex(r=>r.span.id===this.focusedId),current=currentIndex>=0?rows[currentIndex]:rows[0];if(!current)return;const rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else{const child=rows[currentIndex+1];child&&child.depth>current.depth&&this.focusRow(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&!this.collapsedIds.has(current.span.id))this.toggleSpan(current.span.id);else for(let i=currentIndex-1;i>=0;i--){const row=rows[i];if(row&&row.depth<current.depth){this.focusRow(row);break}}break;case"Enter":case" ":e.preventDefault(),this.selectRow(current.span.id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,cost:LYRA_DEFAULT_cost,details:LYRA_DEFAULT_details,duration:LYRA_DEFAULT_duration,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,traceTree:LYRA_DEFAULT_traceTree,traceTreeMetricLabel:LYRA_DEFAULT_traceTreeMetricLabel,traceTreeSpanStatus:LYRA_DEFAULT_traceTreeSpanStatus}}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.syncLimitAnnouncementSink(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.renderedProjectionTruncated}disconnectedCallback(){this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=void 0,this.syncLimitAnnouncementSink()}syncLimitAnnouncementSink(){!this.isConnected||this.limitAnnouncementSink?.element.ownerDocument===this.ownerDocument||(this.limitAnnouncementSink?.release(),this.limitAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}buildHierarchy(){const{spans,byId,truncated}=normalizeLyraSpans(this.spans,this.activeSpanId),childrenOf=new Map,parentOf=new Map,roots=[],hasCyclicParentChain=span=>{const visited=new Set([span.id]);let parentId=span.parentId;for(;parentId!=null;){if(visited.has(parentId))return!0;visited.add(parentId),parentId=byId.get(parentId)?.parentId}return!1};for(const span of spans){const parent=span.parentId!=null&&!hasCyclicParentChain(span)?byId.get(span.parentId):void 0;if(parent&&parent.id!==span.id){const list=childrenOf.get(parent.id)??[];list.push(span),childrenOf.set(parent.id,list),parentOf.set(span.id,parent.id)}else roots.push(span)}const byStart=(a,b)=>a.startMs-b.startMs;roots.sort(byStart);for(const list of childrenOf.values())list.sort(byStart);return{spans,byId,childrenOf,parentOf,roots,truncated}}buildRows(hierarchy=this.buildHierarchy()){const rows=[],stack=[...hierarchy.roots].reverse().map((span,reverseIndex)=>({span,depth:0,posInSet:hierarchy.roots.length-reverseIndex,setSize:hierarchy.roots.length})),visited=new Set;for(;stack.length>0&&rows.length<MAX_RENDERED_LYRA_SPANS;){const current=stack.pop();if(!current||visited.has(current.span.id))continue;visited.add(current.span.id);const children=hierarchy.childrenOf.get(current.span.id)??[];if(rows.push({...current,hasChildren:children.length>0}),!(children.length===0||this.collapsedIds.has(current.span.id)))for(let index=children.length-1;index>=0;index--){const child=children[index];child&&stack.push({span:child,depth:current.depth+1,posInSet:index+1,setSize:children.length})}}return rows}traceExtent(spans=this.buildHierarchy().spans){let max=0;for(const s of spans)max=Math.max(max,s.endMs??s.startMs,s.startMs);return max||1}formatDuration(ms){if(ms==null)return"";const number=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:ms<1e3?0:1});return ms<1e3?this.localize("durationMilliseconds",void 0,{value:number.format(ms)}):this.localize("durationSeconds",void 0,{value:number.format(ms/1e3)})}formatNumber(n){return getNumberFormat(this.effectiveLocale).format(finiteCount(n))}validTokenMetric(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0}toggleSpan(id){const collapsed=this.collapsedIds.has(id);collapsed||this.renderedRowById(id)?.focus();const next=new Set(this.collapsedIds);collapsed?next.delete(id):next.add(id),this.collapsedIds=next,this.focusedId=id,this.emit("lr-span-toggle",{spanId:id,expanded:collapsed})}async expandAll(){this.collapsedIds=new Set,await this.updateComplete}collapseAll(){const next=new Set,hierarchy=this.buildHierarchy(),{byId,parentOf}=hierarchy,hasChild=new Set(hierarchy.childrenOf.keys());for(const id of hasChild)next.add(id);if(this.collapsedIds=next,this.focusedId!=null){let current=byId.get(this.focusedId);for(;current&&parentOf.has(current.id);)current=byId.get(parentOf.get(current.id));this.focusedId=current?.id??null,current&&this.renderedRowById(current.id)?.focus()}}focusRow(row){row&&(this.focusedId=row.span.id,this.updateComplete.then(()=>{this.renderedRowById(row.span.id)?.focus()}))}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),changed.has("spans")||changed.has("activeSpanId")||changed.has("collapsedIds")){const hierarchy=this.buildHierarchy(),ids=new Set(hierarchy.byId.keys());let pruned=null;for(const id of this.collapsedIds)ids.has(id)||(pruned??=new Set(this.collapsedIds),pruned.delete(id));if(pruned&&(this.collapsedIds=pruned),(changed.has("spans")||changed.has("activeSpanId"))&&this.activeSpanId&&hierarchy.byId.has(this.activeSpanId)){const revealed=new Set(this.collapsedIds);let currentId=this.activeSpanId,changedCollapse=!1;for(;hierarchy.parentOf.has(currentId);)currentId=hierarchy.parentOf.get(currentId),revealed.delete(currentId)&&(changedCollapse=!0);changedCollapse&&(this.collapsedIds=revealed)}const rows=this.buildRows(hierarchy),visibleIds=new Set(rows.map(row=>row.span.id));if((this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&visibleIds.has(this.activeSpanId)?this.activeSpanId:rows[0]?.span.id??null),changed.has("spans")){for(const row of rows){const{span}=row,prev=this.previousStatuses.get(span.id);prev!==void 0&&prev!==span.status&&this.pendingAnnouncements.push(this.localize("traceTreeSpanStatus",void 0,{name:span.name,status:this.localize(STATUS_LABEL_KEY[span.status])}))}this.previousStatuses=new Map(hierarchy.spans.map(span=>[span.id,span.status]))}const visibleAncestor=id=>{let current=id?hierarchy.byId.get(id):void 0;for(;current;){if(visibleIds.has(current.id))return current.id;current=hierarchy.parentOf.has(current.id)?hierarchy.byId.get(hierarchy.parentOf.get(current.id)):void 0}return null};this.focusedId=visibleAncestor(this.activeSpanId)??visibleAncestor(this.focusedId)??rows[0]?.span.id??null}}renderedRowById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),(changed.has("activeSpanId")||changed.has("spans")||changed.has("collapsedIds"))&&this.activeSpanId){const row=this.renderedRowById(this.activeSpanId);if(row){const ownerWindow=row.ownerDocument.defaultView,reducedMotion=!ownerWindow||prefersReducedMotion(ownerWindow);row.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}if(this.pendingAnnouncements.length>0){const texts=this.pendingAnnouncements;this.pendingAnnouncements=[];for(const text of texts)this.liveRegion?.announce(text)}this.limitAnnouncementInitialized&&this.renderedProjectionTruncated&&!this.previouslyTruncated&&this.limitAnnouncementSink?.announce(this.localize("spanProjectionLimit",void 0,{count:MAX_RENDERED_LYRA_SPANS})),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.renderedProjectionTruncated}renderHeader(){return html`
6
6
  <div part="header">
7
7
  <span class="col-toggle" aria-hidden="true"></span>
8
8
  <span class="col-icon" aria-hidden="true"></span>
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraBarChart extends LyraChart{constructor(){super(...arguments),this.type="bar"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraBarChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraBarChart extends LyraChart{constructor(){super(...arguments),this.type="bar"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraBarChart};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraBubbleChart extends LyraChart{constructor(){super(...arguments),this.type="bubble"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraBubbleChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraBubbleChart extends LyraChart{constructor(){super(...arguments),this.type="bubble"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraBubbleChart};
@@ -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{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{loadChartJs}from"./chart-core-loader.js";import{loadChartJsWithZoom,loadChartJsWithZoomResult,loadChartJsWithDataLabelsResult,loadChartJsWithAnnotationResult}from"./chart-feature-loader.js";import{styles}from"./chart.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{finiteAdd,finiteNumber}from"../../../internal/numbers.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveCanvasColor,resolveCanvasColors,seriesPalette,translucentAreaColor}from"./chart-colors.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartAxisTotal,LYRA_DEFAULT_chartBubblePointCoordinates,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataLabelsUnavailable,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartLabeledPoint,LYRA_DEFAULT_chartMissingLibrary,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartPrimaryAxis,LYRA_DEFAULT_chartSecondaryAxis,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartStackTotalsUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummaryEmpty,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartSummaryWithData,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_chartTypeBar,LYRA_DEFAULT_chartTypeBubble,LYRA_DEFAULT_chartTypeDoughnut,LYRA_DEFAULT_chartTypeLine,LYRA_DEFAULT_chartTypePie,LYRA_DEFAULT_chartTypePolarArea,LYRA_DEFAULT_chartTypeRadar,LYRA_DEFAULT_chartTypeScatter,LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_chartZoomUnavailable,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_liteChartMarkSummary,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_resetZoom,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{seriesPalette as seriesPalette2}from"./chart-colors.js";const CHART_TYPES=new Set(["line","bar","scatter","pie","doughnut","radar","polarArea","bubble"]),CHART_TYPE_MESSAGE_KEYS={line:"chartTypeLine",bar:"chartTypeBar",scatter:"chartTypeScatter",pie:"chartTypePie",doughnut:"chartTypeDoughnut",radar:"chartTypeRadar",polarArea:"chartTypePolarArea",bubble:"chartTypeBubble"};function normalizeChartType(value){return typeof value=="string"&&CHART_TYPES.has(value)?value:"bar"}function normalizeChartGrid(value){return value==="x"||value==="y"||value==="none"||value==="both"?value:"both"}function normalizeLegendPosition(value){return value==="left"||value==="top"||value==="right"||value==="bottom"||value==="center"||value==="chartArea"||value==="start"||value==="end"||value==="auto"||isPlainObject(value)&&Object.values(value).every(candidate=>typeof candidate=="number"&&Number.isFinite(candidate))?value:"top"}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}const UNSAFE_KEYS=new Set(["__proto__","constructor","prototype"]),FALLBACK_GRID_COLOR="#8a8a90",FALLBACK_TICK_COLOR="#6b7280",FALLBACK_LEGEND_COLOR="#1a1a1a",FALLBACK_TOOLTIP_BG="#fff",FALLBACK_TOOLTIP_TEXT="#1a1a1a";function deepMerge(base,override,seen=new WeakMap){if(typeof override=="object"&&override!==null){const previous=seen.get(override);if(previous!==void 0)return previous}if(!isPlainObject(base)||!isPlainObject(override))return override===void 0?base:override;const result={...base};seen.set(override,result);try{for(const key of Object.keys(override))UNSAFE_KEYS.has(key)||(result[key]=deepMerge(base[key],override[key],seen))}finally{seen.delete(override)}return result}function isChartPoint(value){return isPlainObject(value)?Number.isFinite(value.x)&&Number.isFinite(value.y):!1}function normalizedChartPoint(value){if(!isChartPoint(value))return null;const radius=value.r;return{x:value.x,y:value.y,...typeof radius=="number"&&Number.isFinite(radius)&&radius>=0?{r:radius}:{},...typeof value.label=="string"?{label:value.label}:{}}}function nonNegativeFinite(value,fallback){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:fallback}function labelText(value){return value==null?"":Array.isArray(value)?value.map(labelText).join(" "):String(value)}class LyraChart extends LyraElement{static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartAxisTotal:LYRA_DEFAULT_chartAxisTotal,chartBubblePointCoordinates:LYRA_DEFAULT_chartBubblePointCoordinates,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataLabelsUnavailable:LYRA_DEFAULT_chartDataLabelsUnavailable,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartLabeledPoint:LYRA_DEFAULT_chartLabeledPoint,chartMissingLibrary:LYRA_DEFAULT_chartMissingLibrary,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartPrimaryAxis:LYRA_DEFAULT_chartPrimaryAxis,chartSecondaryAxis:LYRA_DEFAULT_chartSecondaryAxis,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartStackTotalsUnavailable:LYRA_DEFAULT_chartStackTotalsUnavailable,chartSummary:LYRA_DEFAULT_chartSummary,chartSummaryEmpty:LYRA_DEFAULT_chartSummaryEmpty,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartSummaryWithData:LYRA_DEFAULT_chartSummaryWithData,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartTypeBar:LYRA_DEFAULT_chartTypeBar,chartTypeBubble:LYRA_DEFAULT_chartTypeBubble,chartTypeDoughnut:LYRA_DEFAULT_chartTypeDoughnut,chartTypeLine:LYRA_DEFAULT_chartTypeLine,chartTypePie:LYRA_DEFAULT_chartTypePie,chartTypePolarArea:LYRA_DEFAULT_chartTypePolarArea,chartTypeRadar:LYRA_DEFAULT_chartTypeRadar,chartTypeScatter:LYRA_DEFAULT_chartTypeScatter,chartValueLabel:LYRA_DEFAULT_chartValueLabel,chartZoomUnavailable:LYRA_DEFAULT_chartZoomUnavailable,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,resetZoom:LYRA_DEFAULT_resetZoom,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.immutableEventDetails=Object.freeze(["lr-before-legend-visibility-change","lr-legend-visibility-change"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}constructor(){super(),this.type="bar",this.labels=[],this.datasets=[],this.description=null,this.grid="both",this.indexAxis="x",this.label=null,this.legendPosition="top",this.scaleType="linear",this.annotations=[],this.max=null,this.min=null,this.plugins=[],this.area=!1,this.zoom=!1,this.height="280px",this.xLabel=null,this.yLabel=null,this.y2Label="",this.beginAtZero=!0,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("chart-data-table"),this.stacked=!1,this.withoutAnimation=!1,this.withoutLegend=!1,this.withoutTooltip=!1,this.dataLabels=!1,this.stackTotals=!1,this.loading=!0,this.loadFailed=!1,this.loadLibrary=withZoom=>withZoom?loadChartJsWithZoom():loadChartJs(),this.loadZoomFeature=()=>loadChartJsWithZoomResult(),this.loadDataLabelsFeature=()=>loadChartJsWithDataLabelsResult(),this.loadAnnotationFeature=()=>loadChartJsWithAnnotationResult(),this.loadGeneration=0,this.zoomLoadGeneration=0,this.dataLabelsLoadGeneration=0,this.annotationLoadGeneration=0,this.zoomFeatureState="idle",this.dataLabelsFeatureState="idle",this.zoomed=!1,this.visible=!0,this.intersectionGeneration=0,this.autoLegendPosition="right",this.chartAreaUpdateQueued=!1,this.builtPlugins=[],this.suppressZoomComplete=!1,this.descriptionId=nextId("chart-description"),this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.announcedFeatureWarnings=new Set,this.onReducedMotionChange=()=>{!this.isConnected||this.ownerWindow!==this.reducedMotionWindow||this.drawIfVisible()},new ThemeWatcher(this,()=>{this.chart&&this.refreshTheme()})}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}normalizeEffectiveConfig(config){return config}effectiveConfig(){return this.normalizeEffectiveConfig(this.config??this.slottedConfig)}onConfigSlotChange(event){const script=event.currentTarget.assignedElements({flatten:!0}).find(element=>element.localName==="script"&&element.type.trim().toLowerCase()==="application/json");let next;if(script)try{const parsed=JSON.parse(script.textContent??"");isPlainObject(parsed)&&(next=parsed)}catch{next=void 0}this.slottedConfig=next}effectiveData(){const generated={labels:this.labels,datasets:this.datasets.map(series=>({...series,data:[...series.points??series.data??[]],yAxisID:series.axis==="y2"?"y2":"y"}))},override=this.effectiveConfig()?.data,merged=isPlainObject(override)?deepMerge(generated,override):generated;return{labels:Array.isArray(merged.labels)?merged.labels:[],datasets:Array.isArray(merged.datasets)?merged.datasets.filter(isPlainObject):[]}}effectiveHiddenDatasetIndexes(){const effective=this.effectiveData(),controlled=normalizeHiddenDatasets(this.hiddenDatasets,effective.datasets.length);return controlled!==void 0?controlled:effective.datasets.flatMap((dataset,index)=>dataset.hidden===!0?[index]:[])}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceDatasetCount=this.effectiveData().datasets.length,controlled=normalizeHiddenDatasets(this.hiddenDatasets,sourceDatasetCount);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++){const sourceIndex=this.visualDatasetSourceIndexes?.[index]??index;this.chart.setDatasetVisibility(index,!hidden.has(sourceIndex))}return datasetCount>0}hasExplicitConfigData(){const config=this.effectiveConfig();return isPlainObject(config)&&Object.prototype.hasOwnProperty.call(config,"data")}datasetLabel(dataset,index){return labelText(dataset.label)||this.localize("chartPointLabel",void 0,{n:getNumberFormat(this.effectiveLocale).format(index+1)})}datasetValues(dataset){return Array.isArray(dataset.data)?dataset.data:[]}isPointDataset(dataset){const values=this.datasetValues(dataset);return this.effectiveType()==="scatter"||this.effectiveType()==="bubble"||values.some(isChartPoint)}appendData(label,values,maxPoints=0){const limit=Number.isFinite(maxPoints)?Math.max(0,Math.floor(maxPoints)):0;if(this.hasExplicitConfigData()){const effective=this.effectiveData();let domainLength2=effective.labels.length;for(const dataset of effective.datasets)this.isPointDataset(dataset)||(domainLength2=Math.max(domainLength2,this.datasetValues(dataset).length));const labels2=[...effective.labels,...Array.from({length:Math.max(0,domainLength2-effective.labels.length)},()=>""),label],effectiveConfig=this.effectiveConfig(),currentData=isPlainObject(effectiveConfig?.data)?effectiveConfig.data:{},explicitLabels=Array.isArray(currentData.labels),explicitDatasets=Array.isArray(currentData.datasets),nextLabels=limit>0?labels2.slice(-limit):labels2;if(explicitLabels||(this.labels=nextLabels.map(labelText)),!explicitDatasets){const datasets2=this.datasets.map((series,index)=>{if(series.points)return series;const current=series.data??[],data=[...current,...Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),values[index]??null];return{...series,data:limit>0?data.slice(-limit):data}});this.datasets=datasets2}if(explicitLabels||explicitDatasets){const nextData={...currentData};explicitLabels&&(nextData.labels=nextLabels),explicitDatasets&&(nextData.datasets=effective.datasets.map((dataset,index)=>{if(this.isPointDataset(dataset))return dataset;const current=this.datasetValues(dataset),data=[...current,...Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),values[index]??null];return{...dataset,data:limit>0?data.slice(-limit):data}})),this.config={...effectiveConfig,data:nextData}}return}let domainLength=this.labels.length;for(const series of this.datasets)series.points||(domainLength=Math.max(domainLength,series.data?.length??0));const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>series.points?series:{...series,data:[...series.data??[],...Array.from({length:Math.max(0,domainLength-(series.data?.length??0))},()=>null),values[index]??null]});this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>series.points?series:{...series,data:series.data?.slice(-limit)}):datasets}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const effective=this.effectiveData(),columns=effective.datasets.map((dataset,datasetIndex)=>{const values=this.datasetValues(dataset),label=this.datasetLabel(dataset,datasetIndex),points=values.filter(isChartPoint);return{dataset,label,point:this.isPointDataset(dataset),radius:points.some(point=>point.r!=null),pointLabel:points.some(point=>point.label!=null)}}),header=["label",...columns.flatMap(column=>column.point?[`${column.label} x`,`${column.label} y`,...column.radius?[`${column.label} r`]:[],...column.pointLabel?[`${column.label} label`]:[]]:[column.label])].map(escapeCsvField).join(",");let rowCount=effective.labels.length;for(const dataset of effective.datasets)rowCount=Math.max(rowCount,this.datasetValues(dataset).length);const exportCell=value=>typeof value!="number"||!Number.isFinite(value)?value??"":this.formatExportValue(value)??value,rows=Array.from({length:rowCount},(_,index)=>{const firstPoint=effective.datasets.map(dataset=>this.datasetValues(dataset)[index]).find(isChartPoint);return[labelText(effective.labels[index])||firstPoint?.label||"",...columns.flatMap(column=>{const value=this.datasetValues(column.dataset)[index];return column.point?isChartPoint(value)?[exportCell(value.x),exportCell(value.y),...column.radius?[value.r==null?"":exportCell(value.r)]:[],...column.pointLabel?[value.label??""]:[]]:["","",...column.radius?[""]:[],...column.pointLabel?[""]:[]]:[exportCell(value)]})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,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{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{loadChartJs}from"./chart-core-loader.js";import{loadChartJsWithZoom,loadChartJsWithZoomResult,loadChartJsWithDataLabelsResult,loadChartJsWithAnnotationResult}from"./chart-feature-loader.js";import{styles}from"./chart.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{finiteAdd,finiteNumber}from"../../../internal/numbers.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveCanvasColor,resolveCanvasColors,seriesPalette,translucentAreaColor}from"./chart-colors.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartAxisTotal,LYRA_DEFAULT_chartBubblePointCoordinates,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataLabelsUnavailable,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartLabeledPoint,LYRA_DEFAULT_chartMissingLibrary,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartPrimaryAxis,LYRA_DEFAULT_chartSecondaryAxis,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartStackTotalsUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummaryEmpty,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartSummaryWithData,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_chartTypeBar,LYRA_DEFAULT_chartTypeBubble,LYRA_DEFAULT_chartTypeDoughnut,LYRA_DEFAULT_chartTypeLine,LYRA_DEFAULT_chartTypePie,LYRA_DEFAULT_chartTypePolarArea,LYRA_DEFAULT_chartTypeRadar,LYRA_DEFAULT_chartTypeScatter,LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_chartZoomUnavailable,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_liteChartMarkSummary,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_resetZoom,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{seriesPalette as seriesPalette2}from"./chart-colors.js";const CHART_TYPES=new Set(["line","bar","scatter","pie","doughnut","radar","polarArea","bubble"]),CHART_TYPE_MESSAGE_KEYS={line:"chartTypeLine",bar:"chartTypeBar",scatter:"chartTypeScatter",pie:"chartTypePie",doughnut:"chartTypeDoughnut",radar:"chartTypeRadar",polarArea:"chartTypePolarArea",bubble:"chartTypeBubble"};function normalizeChartType(value){return typeof value=="string"&&CHART_TYPES.has(value)?value:"bar"}function normalizeChartGrid(value){return value==="x"||value==="y"||value==="none"||value==="both"?value:"both"}function normalizeLegendPosition(value){return value==="left"||value==="top"||value==="right"||value==="bottom"||value==="center"||value==="chartArea"||value==="start"||value==="end"||value==="auto"||isPlainObject(value)&&Object.values(value).every(candidate=>typeof candidate=="number"&&Number.isFinite(candidate))?value:"top"}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}const UNSAFE_KEYS=new Set(["__proto__","constructor","prototype"]),FALLBACK_GRID_COLOR="#8a8a90",FALLBACK_TICK_COLOR="#6b7280",FALLBACK_LEGEND_COLOR="#1a1a1a",FALLBACK_TOOLTIP_BG="#fff",FALLBACK_TOOLTIP_TEXT="#1a1a1a";function deepMerge(base,override,seen=new WeakMap){if(typeof override=="object"&&override!==null){const previous=seen.get(override);if(previous!==void 0)return previous}if(!isPlainObject(base)||!isPlainObject(override))return override===void 0?base:override;const result={...base};seen.set(override,result);try{for(const key of Object.keys(override))UNSAFE_KEYS.has(key)||(result[key]=deepMerge(base[key],override[key],seen))}finally{seen.delete(override)}return result}function isChartPoint(value){return isPlainObject(value)?Number.isFinite(value.x)&&Number.isFinite(value.y):!1}function normalizedChartPoint(value){if(!isChartPoint(value))return null;const radius=value.r;return{x:value.x,y:value.y,...typeof radius=="number"&&Number.isFinite(radius)&&radius>=0?{r:radius}:{},...typeof value.label=="string"?{label:value.label}:{}}}function nonNegativeFinite(value,fallback){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:fallback}function labelText(value){return value==null?"":Array.isArray(value)?value.map(labelText).join(" "):String(value)}class LyraChart extends LyraElement{static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartAxisTotal:LYRA_DEFAULT_chartAxisTotal,chartBubblePointCoordinates:LYRA_DEFAULT_chartBubblePointCoordinates,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataLabelsUnavailable:LYRA_DEFAULT_chartDataLabelsUnavailable,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartLabeledPoint:LYRA_DEFAULT_chartLabeledPoint,chartMissingLibrary:LYRA_DEFAULT_chartMissingLibrary,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartPrimaryAxis:LYRA_DEFAULT_chartPrimaryAxis,chartSecondaryAxis:LYRA_DEFAULT_chartSecondaryAxis,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartStackTotalsUnavailable:LYRA_DEFAULT_chartStackTotalsUnavailable,chartSummary:LYRA_DEFAULT_chartSummary,chartSummaryEmpty:LYRA_DEFAULT_chartSummaryEmpty,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartSummaryWithData:LYRA_DEFAULT_chartSummaryWithData,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartTypeBar:LYRA_DEFAULT_chartTypeBar,chartTypeBubble:LYRA_DEFAULT_chartTypeBubble,chartTypeDoughnut:LYRA_DEFAULT_chartTypeDoughnut,chartTypeLine:LYRA_DEFAULT_chartTypeLine,chartTypePie:LYRA_DEFAULT_chartTypePie,chartTypePolarArea:LYRA_DEFAULT_chartTypePolarArea,chartTypeRadar:LYRA_DEFAULT_chartTypeRadar,chartTypeScatter:LYRA_DEFAULT_chartTypeScatter,chartValueLabel:LYRA_DEFAULT_chartValueLabel,chartZoomUnavailable:LYRA_DEFAULT_chartZoomUnavailable,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,resetZoom:LYRA_DEFAULT_resetZoom,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.immutableEventDetails=Object.freeze(["lr-before-legend-visibility-change","lr-legend-visibility-change"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}constructor(){super(),this.type="bar",this.labels=[],this.datasets=[],this.description=null,this.grid="both",this.indexAxis="x",this.label=null,this.legendPosition="top",this.scaleType="linear",this.annotations=[],this.max=null,this.min=null,this.plugins=[],this.area=!1,this.zoom=!1,this.height="280px",this.xLabel=null,this.yLabel=null,this.y2Label="",this.beginAtZero=!0,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("chart-data-table"),this.stacked=!1,this.withoutAnimation=!1,this.withoutLegend=!1,this.withoutTooltip=!1,this.dataLabels=!1,this.stackTotals=!1,this.loading=!0,this.loadFailed=!1,this.loadLibrary=withZoom=>withZoom?loadChartJsWithZoom():loadChartJs(),this.loadZoomFeature=()=>loadChartJsWithZoomResult(),this.loadDataLabelsFeature=()=>loadChartJsWithDataLabelsResult(),this.loadAnnotationFeature=()=>loadChartJsWithAnnotationResult(),this.loadGeneration=0,this.zoomLoadGeneration=0,this.dataLabelsLoadGeneration=0,this.annotationLoadGeneration=0,this.zoomFeatureState="idle",this.dataLabelsFeatureState="idle",this.zoomed=!1,this.visible=!0,this.intersectionGeneration=0,this.autoLegendPosition="right",this.chartAreaUpdateQueued=!1,this.builtPlugins=[],this.suppressZoomComplete=!1,this.descriptionId=nextId("chart-description"),this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.announcedFeatureWarnings=new Set,this.onReducedMotionChange=()=>{!this.isConnected||this.ownerWindow!==this.reducedMotionWindow||this.drawIfVisible()},new ThemeWatcher(this,()=>{this.chart&&this.refreshTheme()})}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}normalizeEffectiveConfig(config){return config}effectiveConfig(){return this.normalizeEffectiveConfig(this.config??this.slottedConfig)}onConfigSlotChange(event){const script=event.currentTarget.assignedElements({flatten:!0}).find(element=>element.localName==="script"&&element.type.trim().toLowerCase()==="application/json");let next;if(script)try{const parsed=JSON.parse(script.textContent??"");isPlainObject(parsed)&&(next=parsed)}catch{next=void 0}this.slottedConfig=next}effectiveData(){const generated={labels:this.labels,datasets:this.datasets.map(series=>({...series,data:[...series.points??series.data??[]],yAxisID:series.axis==="y2"?"y2":"y"}))},override=this.effectiveConfig()?.data,merged=isPlainObject(override)?deepMerge(generated,override):generated;return{labels:Array.isArray(merged.labels)?merged.labels:[],datasets:Array.isArray(merged.datasets)?merged.datasets.filter(isPlainObject):[]}}effectiveHiddenDatasetIndexes(){const effective=this.effectiveData(),controlled=normalizeHiddenDatasets(this.hiddenDatasets,effective.datasets.length);return controlled!==void 0?controlled:effective.datasets.flatMap((dataset,index)=>dataset.hidden===!0?[index]:[])}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceDatasetCount=this.effectiveData().datasets.length,controlled=normalizeHiddenDatasets(this.hiddenDatasets,sourceDatasetCount);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++){const sourceIndex=this.visualDatasetSourceIndexes?.[index]??index;this.chart.setDatasetVisibility(index,!hidden.has(sourceIndex))}return datasetCount>0}hasExplicitConfigData(){const config=this.effectiveConfig();return isPlainObject(config)&&Object.prototype.hasOwnProperty.call(config,"data")}datasetLabel(dataset,index){return labelText(dataset.label)||this.localize("chartPointLabel",void 0,{n:getNumberFormat(this.effectiveLocale).format(index+1)})}datasetValues(dataset){return Array.isArray(dataset.data)?dataset.data:[]}isPointDataset(dataset){const values=this.datasetValues(dataset);return this.effectiveType()==="scatter"||this.effectiveType()==="bubble"||values.some(isChartPoint)}appendData(label,values,maxPoints=0){const limit=Number.isFinite(maxPoints)?Math.max(0,Math.floor(maxPoints)):0;if(this.hasExplicitConfigData()){const effective=this.effectiveData();let domainLength2=effective.labels.length;for(const dataset of effective.datasets)this.isPointDataset(dataset)||(domainLength2=Math.max(domainLength2,this.datasetValues(dataset).length));const labels2=[...effective.labels,...Array.from({length:Math.max(0,domainLength2-effective.labels.length)},()=>""),label],effectiveConfig=this.effectiveConfig(),currentData=isPlainObject(effectiveConfig?.data)?effectiveConfig.data:{},explicitLabels=Array.isArray(currentData.labels),explicitDatasets=Array.isArray(currentData.datasets),nextLabels=limit>0?labels2.slice(-limit):labels2;if(explicitLabels||(this.labels=nextLabels.map(labelText)),!explicitDatasets){const datasets2=this.datasets.map((series,index)=>{if(series.points)return series;const current=series.data??[],data=[...current,...Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),values[index]??null];return{...series,data:limit>0?data.slice(-limit):data}});this.datasets=datasets2}if(explicitLabels||explicitDatasets){const nextData={...currentData};explicitLabels&&(nextData.labels=nextLabels),explicitDatasets&&(nextData.datasets=effective.datasets.map((dataset,index)=>{if(this.isPointDataset(dataset))return dataset;const current=this.datasetValues(dataset),data=[...current,...Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),values[index]??null];return{...dataset,data:limit>0?data.slice(-limit):data}})),this.config={...effectiveConfig,data:nextData}}return}let domainLength=this.labels.length;for(const series of this.datasets)series.points||(domainLength=Math.max(domainLength,series.data?.length??0));const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>series.points?series:{...series,data:[...series.data??[],...Array.from({length:Math.max(0,domainLength-(series.data?.length??0))},()=>null),values[index]??null]});this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>series.points?series:{...series,data:series.data?.slice(-limit)}):datasets}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const effective=this.effectiveData(),columns=effective.datasets.map((dataset,datasetIndex)=>{const values=this.datasetValues(dataset),label=this.datasetLabel(dataset,datasetIndex),points=values.filter(isChartPoint);return{dataset,label,point:this.isPointDataset(dataset),radius:points.some(point=>point.r!=null),pointLabel:points.some(point=>point.label!=null)}}),header=["label",...columns.flatMap(column=>column.point?[`${column.label} x`,`${column.label} y`,...column.radius?[`${column.label} r`]:[],...column.pointLabel?[`${column.label} label`]:[]]:[column.label])].map(escapeCsvField).join(",");let rowCount=effective.labels.length;for(const dataset of effective.datasets)rowCount=Math.max(rowCount,this.datasetValues(dataset).length);const exportCell=value=>typeof value!="number"||!Number.isFinite(value)?value??"":this.formatExportValue(value)??value,rows=Array.from({length:rowCount},(_,index)=>{const firstPoint=effective.datasets.map(dataset=>this.datasetValues(dataset)[index]).find(isChartPoint);return[labelText(effective.labels[index])||firstPoint?.label||"",...columns.flatMap(column=>{const value=this.datasetValues(column.dataset)[index];return column.point?isChartPoint(value)?[exportCell(value.x),exportCell(value.y),...column.radius?[value.r==null?"":exportCell(value.r)]:[],...column.pointLabel?[value.label??""]:[]]:["","",...column.radius?[""]:[],...column.pointLabel?[""]:[]]:[exportCell(value)]})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
2
2
  `)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSinks(),this.visible=!0,this.armReducedMotionWatcher();const ownerWindow=this.ownerWindow,ResizeObserverCtor=ownerWindow?.ResizeObserver;ResizeObserverCtor&&(this.resizeObserver=new ResizeObserverCtor(entries=>{const width=entries[0]?.contentRect.width??this.getBoundingClientRect().width;if(Number.isFinite(width)&&this.lastObservedInlineSize!==void 0&&Math.abs(width-this.lastObservedInlineSize)<.5||(this.lastObservedInlineSize=width,this.resizeDrawFrame!==void 0))return;const frameOwner=this.ownerWindow;frameOwner&&(this.resizeDrawFrameOwner=frameOwner,this.resizeDrawFrame=frameOwner.requestAnimationFrame(()=>{this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,!(!this.isConnected||this.ownerWindow!==frameOwner)&&(this.updateAutoLegendPosition()||this.drawIfVisible())}))}),this.resizeObserver.observe(this)),this.updateAutoLegendPosition();const generation=++this.loadGeneration;this.zoom&&this.requestZoomFeature(),this.loadLibrary(this.zoom).then(async mod=>{try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mod){this.loadFailed=!0;return}this.loadFailed=!1,this.chartJsModule=mod,this.drawIfVisible()}}),this.needsDataLabels&&this.requestDataLabelsFeature(),this.needsAnnotations&&this.requestAnnotationFeature();const IntersectionObserverCtor=ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSinks(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.announcedFeatureWarnings.clear(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeDrawFrame!==void 0&&this.resizeDrawFrameOwner?.cancelAnimationFrame(this.resizeDrawFrame),this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,this.lastObservedInlineSize=void 0,this.loadGeneration+=1,this.zoomLoadGeneration+=1,this.dataLabelsLoadGeneration+=1,this.discardChart(!1),this.builtPlugins=[],this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSinks(),this.syncAnnouncementSinks(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){const ownerWindow=this.ownerWindow;ownerWindow?.matchMedia&&(this.reducedMotionWindow===ownerWindow&&this.reducedMotionQuery||(this.disarmReducedMotionWatcher(),this.reducedMotionWindow=ownerWindow,this.reducedMotionQuery=ownerWindow.matchMedia("(prefers-reduced-motion: reduce)"),this.reducedMotionQuery.addEventListener("change",this.onReducedMotionChange)))}disarmReducedMotionWatcher(){this.reducedMotionQuery?.removeEventListener("change",this.onReducedMotionChange),this.reducedMotionQuery=void 0,this.reducedMotionWindow=void 0}syncAnnouncementSinks(){!this.isConnected||this.politeAnnouncementSink?.element.ownerDocument===this.ownerDocument&&this.assertiveAnnouncementSink?.element.ownerDocument===this.ownerDocument||(this.releaseAnnouncementSinks(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSinks(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0,this.assertiveAnnouncementSink?.release(),this.assertiveAnnouncementSink=void 0}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}computedStyle(element=this){const view=this.ownerWindow;return view?view.getComputedStyle(element):"style"in element?element.style:this.style}applyDataLabelsPlugin(plugin){this.dataLabelsPlugin=plugin;let rebuilt=!1;plugin&&this.needsDataLabels&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[],rebuilt=!0),this.drawIfVisible(),rebuilt&&this.showsLegend&&this.requestUpdate()}get zoomFeatureAvailable(){return this.zoom&&this.zoomFeatureState==="available"}featureWarningMessages(){if(this.loading||this.loadFailed)return[];const messages=[];return this.zoom&&this.zoomFeatureState==="unavailable"&&messages.push(this.localize("chartZoomUnavailable")),this.dataLabelsFeatureState==="unavailable"&&(this.dataLabels&&messages.push(this.localize("chartDataLabelsUnavailable")),this.stackTotals&&messages.push(this.localize("chartStackTotalsUnavailable"))),messages}requestZoomFeature(){const generation=++this.zoomLoadGeneration;if(!this.zoom){this.zoomFeatureState="idle";return}this.zoomFeatureState="loading",this.loadZoomFeature().then(result=>{generation!==this.zoomLoadGeneration||!this.isConnected||!this.zoom||(this.zoomFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.drawIfVisible(),this.requestUpdate())})}requestAnnotationFeature(){const generation=++this.annotationLoadGeneration;this.needsAnnotations&&this.loadAnnotationFeature().then(result=>{generation!==this.annotationLoadGeneration||!this.isConnected||!this.needsAnnotations||(result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.applyAnnotationPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate())})}applyAnnotationPlugin(plugin){this.annotationPlugin=plugin,plugin&&this.needsAnnotations&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[]),this.drawIfVisible()}requestDataLabelsFeature(){const generation=++this.dataLabelsLoadGeneration;if(!this.needsDataLabels){this.dataLabelsFeatureState="idle";return}this.dataLabelsFeatureState="loading",this.loadDataLabelsFeature().then(result=>{generation!==this.dataLabelsLoadGeneration||!this.isConnected||!this.needsDataLabels||(this.dataLabelsFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.applyDataLabelsPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate())})}willUpdate(changed){super.willUpdate(changed),this.zoomed&&this.effectiveType()!==this.builtType&&(this.zoomed=!1,this.emit("lr-zoom",{zoomed:!1}))}updated(changed){if(super.updated(changed),!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.politeAnnouncementSink?.announce(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.assertiveAnnouncementSink?.announce(this.localize("chartMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed){const featureWarnings=this.featureWarningMessages();for(const warning of featureWarnings)this.announcedFeatureWarnings.has(warning)||this.assertiveAnnouncementSink?.announce(warning);this.announcedFeatureWarnings=new Set(featureWarnings),!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation))}if(this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;changed.has("zoom")&&this.requestZoomFeature(),(changed.has("dataLabels")||changed.has("stackTotals"))&&this.requestDataLabelsFeature(),changed.has("annotations")&&this.requestAnnotationFeature();const contentChanged=this.chartContentChanged(changed),effectiveDirection=this.effectiveDirection,effectiveLocale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==effectiveDirection||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==effectiveLocale;this.lastDrawnDirection=effectiveDirection,this.lastDrawnLocale=effectiveLocale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}chartContentChanged(changed){return["type","labels","datasets","hiddenDatasets","description","grid","indexAxis","label","legendPosition","min","max","plugins","autoLegendPosition","valueFormatter","formatter","area","height","xLabel","yLabel","y2Label","beginAtZero","stacked","withoutAnimation","withoutLegend","withoutTooltip","dataLabels","stackTotals","config","slottedConfig","zoom","locale","strings","loading"].some(name=>changed.has(name))}seriesToDataset(s,index,palette,effectiveType,chartStyle=this.chartStyleOptions(palette),rowIndexes){const fullNormalizedData=s.points?s.points.map(normalizedChartPoint):(s.data??[]).map(value=>typeof value=="number"&&Number.isFinite(value)?value:null),normalizedData=rowIndexes?rowIndexes.map(rowIndex=>fullNormalizedData[rowIndex]??null):fullNormalizedData,borderFallback=chartStyle.borderColors[index%chartStyle.borderColors.length]??palette[index%palette.length],fillFallback=chartStyle.fillColors[index%chartStyle.fillColors.length]??palette[index%palette.length],authoredColors=Array.isArray(s.color)&&rowIndexes?rowIndexes.map(rowIndex=>s.color[rowIndex]??""):s.color,colors=typeof authoredColors=="string"?[resolveCanvasColor(this,authoredColors,borderFallback??"transparent")]:authoredColors?resolveCanvasColors(this,authoredColors,borderFallback??"transparent"):void 0,sliceChart=effectiveType==="pie"||effectiveType==="doughnut"||effectiveType==="polarArea",sliceFillColors=sliceChart&&chartStyle.fillColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.fillColors[sourceIndex%chartStyle.fillColors.length]}):void 0,sliceBorderColors=sliceChart&&chartStyle.borderColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.borderColors[sourceIndex%chartStyle.borderColors.length]}):void 0,fill=s.fill??this.area,backgroundColor=colors??sliceFillColors??fillFallback,datasetType=s.type??effectiveType,authoredSegmentColors=s.segmentColors&&rowIndexes?rowIndexes.map(rowIndex=>s.segmentColors[rowIndex]??""):s.segmentColors,segmentColors=authoredSegmentColors?resolveCanvasColors(this,authoredSegmentColors,colors?.[0]??borderFallback??"transparent"):void 0,authoredPointColors=s.pointColors&&rowIndexes?rowIndexes.map(rowIndex=>s.pointColors[rowIndex]??""):s.pointColors,resolvedBackgroundColor=datasetType==="line"&&fill&&(colors||!chartStyle.authoredFillColors[index%chartStyle.authoredFillColors.length])?Array.isArray(backgroundColor)?backgroundColor.map(color=>translucentAreaColor(this,color)):backgroundColor&&translucentAreaColor(this,backgroundColor):backgroundColor,encoding=forcedColorEncoding(index),encodedBackgroundColor=chartStyle.forcedColors?Array.isArray(resolvedBackgroundColor)?resolvedBackgroundColor.map((color,itemIndex)=>this.forcedColorPattern(sliceChart?itemIndex:index,color)):resolvedBackgroundColor&&this.forcedColorPattern(index,resolvedBackgroundColor):resolvedBackgroundColor,pointRadii=Array.isArray(s.pointRadius)?s.pointRadius:void 0;return{label:s.label,data:normalizedData,type:s.type,fill,borderRadius:chartStyle.borderRadius,borderWidth:nonNegativeFinite(s.width,datasetType==="line"?chartStyle.lineBorderWidth:chartStyle.borderWidth),borderDash:s.dash?[4,4]:chartStyle.forcedColors?[...encoding.dash]:void 0,pointStyle:chartStyle.forcedColors?encoding.pointStyle:void 0,backgroundColor:encodedBackgroundColor,borderColor:colors?.[0]??sliceBorderColors??borderFallback,pointBackgroundColor:authoredPointColors?resolveCanvasColors(this,authoredPointColors,colors?.[0]??borderFallback??"transparent"):void 0,pointRadius:pointRadii?(rowIndexes?rowIndexes.map(rowIndex=>pointRadii[rowIndex]):pointRadii).map(radius=>nonNegativeFinite(radius,chartStyle.pointRadius)):nonNegativeFinite(s.pointRadius,chartStyle.pointRadius),...segmentColors?.length?{segment:{borderColor:ctx=>segmentColors[ctx.p0DataIndex%segmentColors.length]}}:{},yAxisID:s.axis==="y2"?"y2":"y"}}themeColors(){const cs=this.computedStyle(),grid=cs.getPropertyValue("--grid-color").trim()||cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),tick=cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),legend=cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),tooltipBg=cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),tooltipText=cs.getPropertyValue("--lr-chart-tooltip-text").trim()||cs.getPropertyValue("--_lr-chart-tooltip-text").trim();return{grid:resolveCanvasColor(this,grid,FALLBACK_GRID_COLOR),tick:resolveCanvasColor(this,tick,FALLBACK_TICK_COLOR),legend:resolveCanvasColor(this,legend,FALLBACK_LEGEND_COLOR),tooltipBg:resolveCanvasColor(this,tooltipBg,FALLBACK_TOOLTIP_BG),tooltipText:resolveCanvasColor(this,tooltipText,FALLBACK_TOOLTIP_TEXT)}}styleColor(name,fallback){const value=this.computedStyle().getPropertyValue(name).trim();return value?resolveCanvasColor(this,value,fallback):fallback}styleNumber(name,fallbackToken,fallback){const computed=this.computedStyle(),value=computed.getPropertyValue(name).trim()||computed.getPropertyValue(fallbackToken).trim(),direct=/^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(?:px)?$/i.exec(value);if(direct){const resolved=Number.parseFloat(direct[1]);if(Number.isFinite(resolved)&&resolved>=0)return resolved}if(!value||!this.ownerWindow)return fallback;const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{const resolved=Number.parseFloat(this.computedStyle(probe).inlineSize);return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}finally{probe.remove()}}forcedColorPattern(index,background){return this.ownerWindow?createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG)):background}chartStyleOptions(palette){const computed=this.computedStyle(),authoredFillColors=palette.map((_,index)=>index<6&&!!computed.getPropertyValue(`--fill-color-${index+1}`).trim()),borderColors=palette.map((fallback,index)=>index<6?this.styleColor(`--border-color-${index+1}`,fallback):fallback),fillColors=palette.map((fallback,index)=>index<6?this.styleColor(`--fill-color-${index+1}`,fallback):fallback);return{borderColors,fillColors,authoredFillColors,borderRadius:this.styleNumber("--border-radius","--lr-radius",6),borderWidth:this.styleNumber("--border-width","--lr-border-width-thin",1),gridBorderWidth:this.styleNumber("--grid-border-width","--lr-border-width-thin",1),lineBorderWidth:this.styleNumber("--line-border-width","--lr-border-width-medium",2),pointRadius:this.styleNumber("--point-radius","--lr-space-2xs",4),forcedColors:forcedColorsActive(this.ownerWindow)}}get needsDataLabels(){return this.dataLabels||this.stackTotals}get needsAnnotations(){return this.normalizedAnnotations().length>0}normalizedAnnotations(){const source=Array.isArray(this.annotations)?this.annotations:[],usable=[];for(const entry of source){if(!entry||typeof entry!="object")continue;const{value,from,to}=entry;if(typeof value=="number"&&Number.isFinite(value)){usable.push(entry);continue}typeof from=="number"&&Number.isFinite(from)&&typeof to=="number"&&Number.isFinite(to)&&usable.push(from<=to?entry:{...entry,from:to,to:from})}return usable}annotationColor(tone){const token=`--lr-color-${tone??"neutral"}`,raw=this.computedStyle().getPropertyValue(token).trim();return resolveCanvasColor(this,raw,FALLBACK_TICK_COLOR)}annotationOptions(){const entries={};return this.normalizedAnnotations().forEach((entry,index)=>{const axis=entry.axis==="x"?"x":"y",color=this.annotationColor(entry.tone),label=entry.label?{content:entry.label,display:!0,color:this.themeColors().tick}:void 0;if(typeof entry.value=="number"){entries[`lr-annotation-${index}`]={type:"line",scaleID:axis,value:entry.value,borderColor:color,borderWidth:2,...label?{label}:{}};return}const bounds=axis==="y"?{yMin:entry.from,yMax:entry.to}:{xMin:entry.from,xMax:entry.to};entries[`lr-annotation-${index}`]={type:"box",...bounds,backgroundColor:translucentAreaColor(this,color),borderColor:color,borderWidth:0,...label?{label}:{}}}),entries}datalabelsOptions(theme,effectiveType){if(!this.needsDataLabels)return{display:!1};const datasets=this.effectiveData().datasets,stackTotalsActive=this.stackTotals&&this.stacked&&(effectiveType==="bar"||effectiveType==="line"),topDatasetIndexByAxis=new Map;stackTotalsActive&&datasets.forEach((dataset,index)=>topDatasetIndexByAxis.set(dataset.yAxisID==="y2"||dataset.axis==="y2"?"y2":"y",index));const totalsByAxis=stackTotalsActive?{y:this.computeStackTotals("y"),y2:this.computeStackTotals("y2")}:void 0;return{color:theme.tick,align:stackTotalsActive?"end":"center",anchor:stackTotalsActive?"end":"center",display:context=>{const datasetIndex=context.datasetIndex,dataset=datasets[datasetIndex],axis=dataset?.yAxisID==="y2"||dataset?.axis==="y2"?"y2":"y";return stackTotalsActive?topDatasetIndexByAxis.get(axis)!==datasetIndex?this.dataLabels:totalsByAxis?.[axis][context.dataIndex]==null?this.dataLabels:!0:this.dataLabels},formatter:(value,context)=>{const datasetIndex=context.datasetIndex,dataset=datasets[datasetIndex],axis=dataset?.yAxisID==="y2"||dataset?.axis==="y2"?"y2":"y";if(stackTotalsActive&&topDatasetIndexByAxis.get(axis)===datasetIndex){const total=totalsByAxis?.[axis][context.dataIndex];if(total!=null)return this.formatDataLabel(total)}const numeric=typeof value=="number"?value:Number(value?.y??value);return numeric==null||!Number.isFinite(numeric)?"":this.formatDataLabel(numeric)}}}formatDataLabel(value){if(this.formatter||this.valueFormatter){const formatted=this.formatter?.({value,surface:"visual"})??this.valueFormatter?.(value,"tooltip");if(formatted!=null)return String(formatted)}return value.toLocaleString(this.effectiveLocale)}computeStackTotals(axisId="y"){const effective=this.effectiveData(),members=effective.datasets.filter(dataset=>(dataset.yAxisID==="y2"||dataset.axis==="y2"?"y2":"y")===axisId),categoryCount=members.reduce((max,dataset)=>Math.max(max,this.datasetValues(dataset).length),effective.labels.length),totals=[];for(let i=0;i<categoryCount;i++){let sum=0,any=!1;for(const dataset of members){const value=this.datasetValues(dataset)[i],numeric=isChartPoint(value)?value.y:value;numeric==null||!Number.isFinite(numeric)||(sum=finiteAdd(sum,numeric),any=!0)}totals.push(any?sum:null)}return totals}seriesPalette(){return seriesPalette(this)}tickOptions(theme,kind="value"){return{color:theme.tick,...(this.formatter||this.valueFormatter)&&kind==="value"?{callback:value=>this.formatValue(value,"tick")}:{}}}effectiveIndexAxis(){return this.indexAxis==="y"?"y":"x"}valueScaleType(){return this.scaleType==="logarithmic"?"logarithmic":"linear"}valueBeginAtZero(){return this.valueScaleType()==="logarithmic"?void 0:this.beginAtZero}scaleBounds(){const min=this.min!==null&&Number.isFinite(this.min)?finiteNumber(this.min,0):void 0,max=this.max!==null&&Number.isFinite(this.max)?finiteNumber(this.max,0):void 0;return{...min!==void 0?{min}:{},...max!==void 0?{max}:{}}}gridAxisVisible(axis){const grid=normalizeChartGrid(this.grid);return grid==="both"||grid===axis}buildScales(effectiveType,theme,chartStyle){if(effectiveType==="pie"||effectiveType==="doughnut")return{};if(effectiveType==="radar"||effectiveType==="polarArea")return{r:{beginAtZero:this.beginAtZero,...this.scaleBounds(),ticks:{...this.tickOptions(theme),showLabelBackdrop:!1,z:1},grid:{color:theme.grid,display:this.gridAxisVisible("y"),lineWidth:chartStyle.gridBorderWidth},border:{width:chartStyle.gridBorderWidth},angleLines:{color:theme.grid,display:this.gridAxisVisible("x"),lineWidth:chartStyle.gridBorderWidth},pointLabels:{color:theme.tick}}};const hasY2=this.effectiveData().datasets.some(dataset=>dataset.yAxisID==="y2"||dataset.axis==="y2"),rtl=this.effectiveDirection==="rtl",stacked=this.stacked&&(effectiveType==="bar"||effectiveType==="line"),horizontalCategorical=(effectiveType==="bar"||effectiveType==="line")&&this.effectiveIndexAxis()==="y",xKind=effectiveType==="scatter"||effectiveType==="bubble"||horizontalCategorical?"value":"category",yKind=horizontalCategorical?"category":"value",valueAxis=horizontalCategorical?"x":"y",bounds=this.scaleBounds();return{x:{type:xKind==="value"?this.valueScaleType():"category",beginAtZero:xKind==="value"?this.valueBeginAtZero():void 0,...valueAxis==="x"?bounds:{},title:{display:!!this.xLabel,text:this.xLabel,color:theme.tick},ticks:this.tickOptions(theme,xKind),grid:{color:theme.grid,display:this.gridAxisVisible("x"),lineWidth:chartStyle.gridBorderWidth},border:{width:chartStyle.gridBorderWidth},stacked},y:{type:yKind==="value"?this.valueScaleType():"category",position:rtl?"right":"left",beginAtZero:yKind==="value"?this.valueBeginAtZero():void 0,...valueAxis==="y"?bounds:{},title:{display:!!this.yLabel,text:this.yLabel,color:theme.tick},ticks:this.tickOptions(theme,yKind),grid:{color:theme.grid,display:this.gridAxisVisible("y"),lineWidth:chartStyle.gridBorderWidth},border:{width:chartStyle.gridBorderWidth},stacked},...hasY2?{y2:{type:this.valueScaleType(),position:rtl?"left":"right",...valueAxis==="y"?bounds:{},grid:{drawOnChartArea:!1,color:theme.grid,display:this.gridAxisVisible("y"),lineWidth:chartStyle.gridBorderWidth},border:{width:chartStyle.gridBorderWidth},title:{display:!!this.y2Label,text:this.y2Label,color:theme.tick},ticks:this.tickOptions(theme),stacked}}:{}}}handlePointClick(event,chart){const hit=chart.getElementsAtEventForMode(event,"nearest",{intersect:!0},!0)[0];if(!hit)return;const datasetIndex=this.visualDatasetSourceIndexes?.[hit.datasetIndex]??hit.datasetIndex,index=this.visualRowSourceIndexes?.[hit.index]??hit.index,effective=this.effectiveData(),value=this.datasetValues(effective.datasets[datasetIndex])[index]??null,label=isChartPoint(value)&&value.label!==void 0?value.label:labelText(effective.labels[index])||void 0;this.activateDatum({datasetIndex,index,label,value})}chartDatums(){const chartData=this.chart?.data,labels=chartData?.labels??this.labels,datasets=chartData?.datasets??this.datasets.map(series=>({data:series.points??series.data??[]}));let rowCount=labels.length;for(const dataset of datasets)rowCount=Math.max(rowCount,dataset.data?.length??0);const sample=sampleChartTableIndexes(rowCount,datasets.length),datums=[];return sample.seriesIndexes.forEach(datasetIndex=>{const dataset=datasets[datasetIndex];if(!dataset)return;const values=dataset.data??[];sample.rowIndexes.forEach(index=>{const value=values[index];value!=null&&(typeof value=="number"&&!Number.isFinite(value)||datums.push({datasetIndex:this.visualDatasetSourceIndexes?.[datasetIndex]??datasetIndex,index:this.visualRowSourceIndexes?.[index]??index,label:isChartPoint(value)&&value.label!==void 0?value.label:labelText(labels[index])||void 0,value}))})}),datums}datumDisplayValue(value){if(isChartPoint(value)){const numberFormat=getNumberFormat(this.effectiveLocale),x=numberFormat.format(value.x),y=numberFormat.format(value.y),coordinates=value.r==null?this.localize("chartPointCoordinates",void 0,{x,y}):this.localize("chartBubblePointCoordinates",void 0,{x,y,radius:numberFormat.format(value.r)});return typeof value.label=="string"?this.localize("chartLabeledPoint",void 0,{label:value.label,coordinates}):coordinates}const numeric=typeof value=="number"?value:Number(typeof value=="object"&&value!==null?value.y??value.r??value.x:value);return Number.isFinite(numeric)?this.formatSpokenValue(numeric):String(value)}datumAnnouncement(datum,position,total){const series=String(this.effectiveData().datasets[datum.datasetIndex]?.label??"")||this.localize("chartSeriesLabel");return this.localize("liteChartMarkSummary",void 0,{series,label:datum.label??this.localize("chartPointLabel",void 0,{n:getNumberFormat(this.effectiveLocale).format(datum.index+1)}),value:this.datumDisplayValue(datum.value),index:getNumberFormat(this.effectiveLocale).format(position+1),total:getNumberFormat(this.effectiveLocale).format(total)})}activateDatum(datum){const datums=this.chartDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.datumAnnouncement(datum,position,datums.length));const type=this.effectiveType(),kind=type==="bar"?"bar":type==="pie"||type==="doughnut"||type==="polarArea"?"slice":type==="line"?"segment":"point";this.emit("lr-datum-activate",{...datum,kind}),this.emit("lr-point-click",datum)}onCanvasFocus(){const datums=this.chartDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),this.keyboardDatumAnnouncement=this.datumAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.chartDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateDatum(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.keyboardDatumAnnouncement=this.datumAnnouncement(datums[next],next,datums.length)}effectiveType(){return this.effectiveConfig()?.type??normalizeChartType(this.type)}localizedChartType(){const type=this.effectiveType(),key=CHART_TYPE_MESSAGE_KEYS[type];return key?this.localize(key):String(type)}formatValue(value,context){const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)?this.formatter?.({value:numeric,surface:context})??this.valueFormatter?.(numeric,context)??value:value}legendValue(item,chart){const datasetIndex=item.datasetIndex;if(datasetIndex===void 0)return;const data=chart.data.datasets?.[datasetIndex]?.data;if(!data)return;const indexed=typeof item.index=="number"&&Number.isInteger(item.index)?Number(data[item.index]):NaN;if(Number.isFinite(indexed))return indexed;let sum=0,hasValue=!1;for(const datum of data){const value=Number(datum);Number.isFinite(value)&&(sum=finiteAdd(sum,value),hasValue=!0)}return hasValue?sum:void 0}legendLabels(chart){const generateLabels=this.chartJsModule?.defaults?.plugins?.legend?.labels?.generateLabels;return((generateLabels&&chart.legend&&chart.options?generateLabels(chart):void 0)??(chart.data.datasets??[]).map((dataset,index)=>({text:labelText(dataset.label)||String(index+1),datasetIndex:index}))).map(item=>{const value=this.legendValue(item,chart),formatted=this.formatValue(value,"legend");return formatted===value||formatted===void 0?item:{...item,text:this.localize("chartValueLabel",void 0,{label:String(item.text),value:String(formatted)})}})}tooltipLabel(context){const parsed=context.parsed,rawValue=isPlainObject(parsed)?parsed.y??parsed.r??parsed.x:parsed??context.raw,formatted=this.formatValue(rawValue,"tooltip");if(!(formatted===rawValue||formatted===void 0))return context.dataset?.label?this.localize("chartValueLabel",void 0,{label:String(context.dataset.label),value:String(formatted)}):String(formatted)}updateAutoLegendPosition(){const width=this.getBoundingClientRect().width||this.clientWidth,next=width>0&&width<480?"bottom":"right";return next===this.autoLegendPosition?!1:(this.autoLegendPosition=next,!0)}legendPositionForConfig(){const position=normalizeLegendPosition(this.legendPosition);return position==="auto"?this.autoLegendPosition:position==="start"?this.effectiveDirection==="rtl"?"right":"left":position==="end"?this.effectiveDirection==="rtl"?"left":"right":position}legendPositionForLayout(){const position=this.legendPositionForConfig();return position==="top"||position==="right"||position==="left"?position:"bottom"}legendGridPlacement(){const position=normalizeLegendPosition(this.legendPosition);if(position==="auto")return this.autoLegendPosition==="right"?"inline-end":"bottom";if(position==="start")return"inline-start";if(position==="end")return"inline-end";if(position==="top")return"top";const rtl=this.effectiveDirection==="rtl";return position==="left"?rtl?"inline-end":"inline-start":position==="right"?rtl?"inline-start":"inline-end":"bottom"}updateChartArea(chart=this.chart){const area=chart?.chartArea;if(!area)return;const next={top:Number(area.top),left:Number(area.left),right:Number(area.right),bottom:Number(area.bottom),width:Number(area.width),height:Number(area.height)};if(Object.values(next).some(value=>!Number.isFinite(value)))return;const previous=this.resolvedChartArea;previous&&Object.keys(next).every(key=>previous[key]===next[key])||(this.resolvedChartArea=next,this.chartAreaUpdateQueued||(this.chartAreaUpdateQueued=!0,queueMicrotask(()=>{this.chartAreaUpdateQueued=!1,this.isConnected&&this.requestUpdate()})))}get chartArea(){return this.resolvedChartArea}buildConfig(){const theme=this.themeColors(),effectiveType=this.effectiveType(),palette=this.seriesPalette(),chartStyle=this.chartStyleOptions(palette),rawDataEscapeHatch=this.hasExplicitConfigData();let visualRows,visualSeries;if(rawDataEscapeHatch)this.visualRowSourceIndexes=void 0,this.visualDatasetSourceIndexes=void 0;else{let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,(series.points??series.data??[]).length);const sample=sampleChartTableIndexes(rowCount,this.datasets.length);visualRows=sample.rowIndexes.length<rowCount?sample.rowIndexes:void 0,visualSeries=sample.seriesIndexes.length<this.datasets.length?sample.seriesIndexes:void 0,this.visualRowSourceIndexes=visualRows,this.visualDatasetSourceIndexes=visualSeries}const generated={type:effectiveType,data:{labels:visualRows?visualRows.map(index=>this.labels[index]??""):this.labels,datasets:visualSeries?visualSeries.map(sourceIndex=>this.seriesToDataset(this.datasets[sourceIndex],sourceIndex,palette,effectiveType,chartStyle,visualRows)):this.datasets.map((s,i)=>this.seriesToDataset(s,i,palette,effectiveType,chartStyle,visualRows))},...this.plugins.length||this.needsDataLabels&&this.dataLabelsPlugin?{plugins:[...this.plugins,...this.needsDataLabels&&this.dataLabelsPlugin?[this.dataLabelsPlugin]:[]]}:{},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,indexAxis:this.effectiveIndexAxis(),animation:this.withoutAnimation||prefersReducedMotion(this.ownerWindow)?!1:void 0,interaction:{intersect:!1,mode:effectiveType==="scatter"?"nearest":"index"},onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),plugins:{...this.needsAnnotations&&this.annotationPlugin?{annotation:{annotations:this.annotationOptions()}}:{},legend:{display:!1,position:this.legendPositionForConfig(),labels:{color:theme.legend,...this.formatter||this.valueFormatter?{generateLabels:chart=>this.legendLabels(chart)}:{}}},tooltip:{enabled:!this.withoutTooltip,backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>this.tooltipLabel(context)}}:{},filter:item=>!this.effectiveData().datasets[item.datasetIndex]?.noTooltip},zoom:this.zoom&&this.zoomFeatureState!=="unavailable"?{pan:{enabled:!1},zoom:{wheel:{enabled:!0},drag:{enabled:!0},pinch:{enabled:!0},mode:"x",onZoomComplete:()=>{this.suppressZoomComplete||(this.zoomed=!0,this.emit("lr-zoom",{zoomed:!0}))}},limits:{x:{min:"original",max:"original"}}}:void 0,datalabels:this.datalabelsOptions(theme,effectiveType)},onResize:chart=>this.updateChartArea(chart),scales:this.buildScales(effectiveType,theme,chartStyle)}},effectiveConfig=this.effectiveConfig();if(!effectiveConfig)return generated;const merged=deepMerge(generated,effectiveConfig),requiredPlugins=[...this.plugins,...this.needsDataLabels&&this.dataLabelsPlugin?[this.dataLabelsPlugin]:[]];if(requiredPlugins.length){const mergedPlugins=Array.isArray(merged.plugins)?merged.plugins:[];merged.plugins=[...mergedPlugins,...requiredPlugins.filter(plugin=>!mergedPlugins.includes(plugin))]}return merged}draw(){if(!this.chartJsModule||!this.canvasEl)return;const config=this.buildConfig(),effectiveType=config.type,nextPlugins=Array.isArray(config.plugins)?config.plugins:[],samePlugins=nextPlugins.length===this.builtPlugins.length&&nextPlugins.every((plugin,index)=>plugin===this.builtPlugins[index]);if(this.chart&&this.builtType===effectiveType&&samePlugins){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.updateChartArea(this.chart);return}this.discardChart(!0),this.chart=new this.chartJsModule.Chart(this.canvasEl,config),this.builtType=effectiveType,this.builtPlugins=[...nextPlugins],this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.updateChartArea(this.chart)}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}discardChart(announceZoomReset){this.chart?.destroy(),this.chart=void 0,this.resolvedChartArea=void 0,this.zoomed&&(this.zoomed=!1,announceZoomReset&&this.emit("lr-zoom",{zoomed:!1}))}renderChart(){this.drawIfVisible()}resetZoom(){this.suppressZoomComplete=!0;try{this.chart?.resetZoom?.()}finally{this.suppressZoomComplete=!1}this.zoomed=!1,this.emit("lr-zoom",{zoomed:!1})}refreshTheme(){this.drawIfVisible(),this.showsLegend&&this.requestUpdate()}summarizeSeries(dataset){let count=0,first=0,last=0,min=0,max=0;for(const datum of this.datasetValues(dataset)){const value=isChartPoint(datum)?datum.y:datum;typeof value!="number"||!Number.isFinite(value)||(count===0&&(first=value,min=value,max=value),last=value,min=Math.min(min,value),max=Math.max(max,value),count++)}return count?{count,first,last,min,max}:void 0}formatSummaryValue(value){return getNumberFormat(this.effectiveLocale).format(value)}formatTableValue(value){return this.formatter?.({value,surface:"table"})??this.valueFormatter?.(value,"table")??this.formatSummaryValue(value)}formatExportValue(value){return this.formatter?.({value,surface:"export"})??this.valueFormatter?.(value,"table")}formatSpokenValue(value){return this.formatter?.({value,surface:"spoken"})??this.formatSummaryValue(value)}tableStackAxes(){const type=this.effectiveType();if(!this.stackTotals||!this.stacked||type!=="bar"&&type!=="line")return[];const present=new Set;for(const dataset of this.effectiveData().datasets)present.add(dataset.yAxisID==="y2"||dataset.axis==="y2"?"y2":"y");return["y","y2"].filter(axis=>present.has(axis))}tableStackTotalLabel(axis,axisCount){if(axisCount===1)return this.localize("chartTotal");const axisLabel=axis==="y2"?this.y2Label||this.localize("chartSecondaryAxis"):this.yLabel||this.localize("chartPrimaryAxis");return this.localize("chartAxisTotal",void 0,{axis:axisLabel})}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}chartDescription(){if(this.description)return this.description;const effective=this.effectiveData(),sample=this.dataTableSample(effective),includePointDetails=!this.hasCustomDataTable(),summaries=sample.seriesIndexes.map(index=>{const dataset=effective.datasets[index],seriesLabel=this.datasetLabel(dataset,index),values=this.summarizeSeries(dataset);if(!values)return this.localize("chartSeriesNoData",void 0,{label:seriesLabel});const trend=values.last>values.first?this.localize("chartTrendIncreasing"):values.last<values.first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat"),summary=this.localize("chartSummary",void 0,{label:seriesLabel,count:this.formatSummaryValue(values.count),min:this.formatSummaryValue(values.min),max:this.formatSummaryValue(values.max),trend}),rawValues=this.datasetValues(dataset),pointDetails=includePointDetails?sample.rowIndexes.flatMap(rowIndex=>{const point=rawValues[rowIndex];return isChartPoint(point)?[this.datumDisplayValue(point)]:[]}):[];return pointDetails.length?[summary,...pointDetails].join(this.localize("chartSummarySeparator")):summary}),base=summaries.length?this.localize("chartSummaryWithData",void 0,{type:this.localizedChartType(),summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("chartSummaryEmpty",void 0,{type:this.localizedChartType()}),annotationLabels=this.normalizedAnnotations().map(entry=>entry.label?.trim()).filter(label=>!!label);return annotationLabels.length?[base,...annotationLabels].join(this.localize("chartSummarySeparator")):base}dataTableSample(effective=this.effectiveData()){let rowCount=effective.labels.length;for(const dataset of effective.datasets)rowCount=Math.max(rowCount,this.datasetValues(dataset).length);const indexes=sampleChartTableIndexes(rowCount,effective.datasets.length);return{rowCount,seriesCount:effective.datasets.length,...indexes}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}renderDataTable(){const effective=this.effectiveData(),sample=this.dataTableSample(effective),stackAxes=this.tableStackAxes(),stackTotals=new Map(stackAxes.map(axis=>[axis,this.computeStackTotals(axis)]));return html`
3
3
  <table class=${this.dataTableVisible?nothing:"sr-only"}>
4
4
  <caption>${this.accessibleName(this.localize("chartData"))}</caption>
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraDoughnutChart extends LyraChart{constructor(){super(...arguments),this.type="doughnut"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraDoughnutChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraDoughnutChart extends LyraChart{constructor(){super(...arguments),this.type="doughnut"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraDoughnutChart};
@@ -1 +1 @@
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{property}from"lit/decorators.js";import{LyraChart}from"./chart.class.js";import{lockChartType}from"./chart-type-lock.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{binValues,normalizeHistogramBinCount}from"./histogram-bin.js";import{styles}from"./histogram.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_histogramFrequency,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraHistogram extends LyraChart{constructor(){super(...arguments),this.type="bar",this.bins=10,this.values=[],this.seriesLabel=""}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,histogramFrequency:LYRA_DEFAULT_histogramFrequency,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}}static{this.ownedCollectionProperties=Object.freeze(["values"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}appendSamples(values,maxSamples=0){const appended=values.filter(value=>typeof value=="number"&&Number.isFinite(value)),combined=[...this.values,...appended],limit=Number.isFinite(maxSamples)?Math.max(0,Math.floor(maxSamples)):0;this.values=limit>0?combined.slice(-limit):combined}normalizeEffectiveConfig(config){if(!config)return;const normalized={...config};return delete normalized.type,delete normalized.data,normalized}appendData(_label,values,maxPoints=0){this.appendSamples(values,maxPoints)}chartContentChanged(changed){return super.chartContentChanged(changed)||["values","bins","seriesLabel"].some(name=>changed.has(name))}}__decorate([property({converter:{fromAttribute:value=>normalizeHistogramBinCount(value)}})],LyraHistogram.prototype,"bins",void 0),__decorate([property({attribute:!1})],LyraHistogram.prototype,"values",void 0),__decorate([property({attribute:"series-label"})],LyraHistogram.prototype,"seriesLabel",void 0);const bucketCache=new WeakMap;function binnedBuckets(el){const bins=normalizeHistogramBinCount(el.bins),locale=el.effectiveLocale,cached=bucketCache.get(el);if(cached&&cached.values===el.values&&cached.bins===bins&&cached.locale===locale)return cached.buckets;const buckets=binValues(el.values,bins,locale);return bucketCache.set(el,{values:el.values,bins,locale,buckets}),buckets}Object.defineProperty(LyraHistogram.prototype,"labels",{configurable:!0,enumerable:!0,get(){return binnedBuckets(this).map(b=>b.label)},set(_v){}}),Object.defineProperty(LyraHistogram.prototype,"datasets",{configurable:!0,enumerable:!0,get(){return[{label:this.seriesLabel||this.localize("histogramFrequency"),data:binnedBuckets(this).map(b=>b.count)}]},set(_v){}}),lockChartType(LyraHistogram,"bar");export{LyraHistogram,binnedBuckets};
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{property}from"lit/decorators.js";import{LyraChart}from"./chart.class.js";import{lockChartType}from"./chart-type-lock.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{binValues,normalizeHistogramBinCount}from"./histogram-bin.js";import{styles}from"./histogram.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_histogramFrequency,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraHistogram extends LyraChart{constructor(){super(...arguments),this.type="bar",this.bins=10,this.values=[],this.seriesLabel=""}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,histogramFrequency:LYRA_DEFAULT_histogramFrequency,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["values"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}appendSamples(values,maxSamples=0){const appended=values.filter(value=>typeof value=="number"&&Number.isFinite(value)),combined=[...this.values,...appended],limit=Number.isFinite(maxSamples)?Math.max(0,Math.floor(maxSamples)):0;this.values=limit>0?combined.slice(-limit):combined}normalizeEffectiveConfig(config){if(!config)return;const normalized={...config};return delete normalized.type,delete normalized.data,normalized}appendData(_label,values,maxPoints=0){this.appendSamples(values,maxPoints)}chartContentChanged(changed){return super.chartContentChanged(changed)||["values","bins","seriesLabel"].some(name=>changed.has(name))}}__decorate([property({converter:{fromAttribute:value=>normalizeHistogramBinCount(value)}})],LyraHistogram.prototype,"bins",void 0),__decorate([property({attribute:!1})],LyraHistogram.prototype,"values",void 0),__decorate([property({attribute:"series-label"})],LyraHistogram.prototype,"seriesLabel",void 0);const bucketCache=new WeakMap;function binnedBuckets(el){const bins=normalizeHistogramBinCount(el.bins),locale=el.effectiveLocale,cached=bucketCache.get(el);if(cached&&cached.values===el.values&&cached.bins===bins&&cached.locale===locale)return cached.buckets;const buckets=binValues(el.values,bins,locale);return bucketCache.set(el,{values:el.values,bins,locale,buckets}),buckets}Object.defineProperty(LyraHistogram.prototype,"labels",{configurable:!0,enumerable:!0,get(){return binnedBuckets(this).map(b=>b.label)},set(_v){}}),Object.defineProperty(LyraHistogram.prototype,"datasets",{configurable:!0,enumerable:!0,get(){return[{label:this.seriesLabel||this.localize("histogramFrequency"),data:binnedBuckets(this).map(b=>b.count)}]},set(_v){}}),lockChartType(LyraHistogram,"bar");export{LyraHistogram,binnedBuckets};
@@ -1 +1 @@
1
- import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraLineChart extends LyraChart{constructor(){super(...arguments),this.type="line"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraLineChart};
1
+ import{LyraChart}from"./chart.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraLineChart extends LyraChart{constructor(){super(...arguments),this.type="line"}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}}export{LyraLineChart};
@@ -126,6 +126,12 @@ export interface LyraLiteChartEventMap {
126
126
  * @csspart legend-text - Extra per-item text after the series label, rendered only when `legendText` is set.
127
127
  * @csspart live-region - The current mark announcement for keyboard users.
128
128
  * @csspart data-list - A visually hidden sampled list of plotted data points (single-series only).
129
+ * @csspart data-table-toggle - The disclosure button rendered by `dataTableToggle`.
130
+ * @cssprop [--lr-lite-chart-data-table-toggle-hover-bg=var(--lr-color-brand-quiet)] - Hover
131
+ * background of the `dataTableToggle` disclosure button.
132
+ * @cssprop --lr-lite-chart-data-table-toggle-active-bg - Pressed background of the
133
+ * `dataTableToggle` disclosure button; defaults to a mix of the hover background with the shared
134
+ * active mix partner.
129
135
  * @csspart data-table - A visually hidden sampled category×series data table, rendered instead of
130
136
  * `data-list` when there is more than one dataset so a screen-reader user hears series grouping
131
137
  * rather than one flattened N×M sequence.
@@ -186,6 +192,32 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
186
192
  /** Adds a localized total column to the built-in multi-series accessible table for a stacked
187
193
  * bar chart. Ignored for grouped bars and line charts. */
188
194
  tableTotals: boolean;
195
+ /**
196
+ * Makes the generated data table visible; it stays screen-reader available when false. Same
197
+ * meaning as `<lr-chart>`'s property of the same name.
198
+ * @default false
199
+ */
200
+ showDataTable: boolean;
201
+ /**
202
+ * Render a disclosure button above the accessible data table so a sighted reader can reveal the
203
+ * numbers on demand, turning `showDataTable` into the disclosure's INITIAL state rather than its
204
+ * whole behavior. The table stays in the DOM in both states, so assistive technology never loses
205
+ * it.
206
+ *
207
+ * Matters more here than on `<lr-chart>`: this component exists to avoid the Chart.js peers, so
208
+ * without it an app that chose it for that reason had to either hand-roll a `<details>` around a
209
+ * duplicated table or adopt `<lr-chart>` and pull in Chart.js for a button — the cheap component
210
+ * stuck with the expensive workaround.
211
+ * @default false
212
+ */
213
+ dataTableToggle: boolean;
214
+ /** Live disclosure state; null until toggled, so an untouched control follows `showDataTable`. */
215
+ private dataTableExpandedOverride;
216
+ private readonly dataTableId;
217
+ /** Identical to `showDataTable` whenever `dataTableToggle` is off, keeping the unset path
218
+ * byte-identical to before. */
219
+ private get dataTableVisible();
220
+ private toggleDataTable;
189
221
  /** `'fit'` (default) squeezes the plot into the measured host width, unchanged from before this
190
222
  * property existed. `'scroll'` gives every bar a fixed `barWidth` instead, letting the plot's
191
223
  * content width exceed the host's — the host becomes horizontally scrollable