@aceshooting/lyra-ui 12.0.0 → 12.1.1

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 (174) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/autoloader.js +1 -1
  4. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
  5. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  6. package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
  7. package/dist/components/charts/chart/histogram-bin.js +1 -1
  8. package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
  9. package/dist/components/charts/chart/lite-chart.class.js +6 -6
  10. package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
  11. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  12. package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
  13. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  14. package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
  15. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  16. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  17. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
  18. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  19. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  20. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
  21. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  22. package/dist/components/data/heatmap/heatmap.class.d.ts +4 -1
  23. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  24. package/dist/components/data/table/table.class.d.ts +18 -4
  25. package/dist/components/data/table/table.class.js +2 -2
  26. package/dist/components/data/table/table.styles.js +2 -1
  27. package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
  28. package/dist/components/data/timeline/timeline-cluster.js +1 -0
  29. package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
  30. package/dist/components/data/timeline/timeline-item.class.js +13 -2
  31. package/dist/components/data/timeline/timeline-item.styles.js +65 -0
  32. package/dist/components/data/timeline/timeline.class.d.ts +83 -27
  33. package/dist/components/data/timeline/timeline.class.js +3 -3
  34. package/dist/components/data/timeline/timeline.d.ts +1 -0
  35. package/dist/components/data/timeline/timeline.js +1 -1
  36. package/dist/components/data/timeline/timeline.styles.js +14 -0
  37. package/dist/components/forms/button/button.class.js +1 -1
  38. package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
  39. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  40. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
  41. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  42. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  43. package/dist/components/forms/color-picker/color-picker.class.js +1 -1
  44. package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
  45. package/dist/components/forms/combobox/combobox.class.js +3 -2
  46. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  47. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  48. package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
  49. package/dist/components/forms/input/native-time-input.class.js +1 -1
  50. package/dist/components/forms/input/time-input-shared.d.ts +2 -1
  51. package/dist/components/forms/input/time-input.class.js +1 -1
  52. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
  53. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  54. package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
  55. package/dist/components/forms/radio/radio-button.styles.js +1 -1
  56. package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
  57. package/dist/components/forms/radio/radio-group.class.js +1 -1
  58. package/dist/components/forms/radio/radio.class.d.ts +0 -1
  59. package/dist/components/forms/radio/radio.class.js +1 -1
  60. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
  61. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  62. package/dist/components/forms/select/select.class.d.ts +0 -1
  63. package/dist/components/forms/select/select.class.js +1 -1
  64. package/dist/components/forms/slider/slider.class.d.ts +0 -1
  65. package/dist/components/forms/slider/slider.class.js +1 -1
  66. package/dist/components/forms/switch/switch.class.d.ts +0 -1
  67. package/dist/components/forms/switch/switch.class.js +1 -1
  68. package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
  69. package/dist/components/forms/time-range/time-range.class.js +1 -1
  70. package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
  71. package/dist/components/forms/token-input/token-input.class.js +1 -1
  72. package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
  73. package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
  74. package/dist/components/layout/details/accordion-owner.d.ts +1 -1
  75. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  76. package/dist/components/layout/menu/menu-item.class.js +1 -1
  77. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  78. package/dist/components/media/av-player/av-metadata.d.ts +0 -2
  79. package/dist/components/media/av-player/av-metadata.js +1 -1
  80. package/dist/components/media/file-input/file-input.class.d.ts +0 -1
  81. package/dist/components/media/file-input/file-input.class.js +1 -1
  82. package/dist/components/media/map/map-loader.d.ts +4 -1
  83. package/dist/components/media/map/map.class.d.ts +50 -12
  84. package/dist/components/media/map/map.class.js +2 -2
  85. package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
  86. package/dist/components/overlays/overlay/popover.class.js +1 -1
  87. package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
  88. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  89. package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
  90. package/dist/components/overlays/progress/progress-shared.js +1 -1
  91. package/dist/components/overlays/rating/rating.class.js +1 -1
  92. package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
  93. package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
  94. package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
  95. package/dist/components/utility/format/format-options.d.ts +0 -2
  96. package/dist/components/utility/format/format-options.js +1 -1
  97. package/dist/components/utility/icon/icon-resource.d.ts +0 -2
  98. package/dist/components/utility/icon/icon-resource.js +1 -1
  99. package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
  100. package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
  101. package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
  102. package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
  103. package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
  104. package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
  105. package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
  106. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  107. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
  108. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
  109. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
  110. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
  111. package/dist/custom-elements-jsx.d.ts +4 -4
  112. package/dist/events.d.ts +15 -0
  113. package/dist/internal/accessibility-visibility.d.ts +1 -1
  114. package/dist/internal/anchor-target.d.ts +1 -3
  115. package/dist/internal/anchor-target.js +2 -2
  116. package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
  117. package/dist/internal/anchored-overlay-runtime.js +1 -0
  118. package/dist/internal/announcement-text.d.ts +1 -1
  119. package/dist/internal/ansi.d.ts +0 -4
  120. package/dist/internal/ansi.js +1 -1
  121. package/dist/internal/aria-ownership.d.ts +2 -1
  122. package/dist/internal/default-strings.generated.d.ts +1 -0
  123. package/dist/internal/default-strings.generated.js +1 -1
  124. package/dist/internal/focus-navigation.d.ts +3 -2
  125. package/dist/internal/form-associated.d.ts +0 -1
  126. package/dist/internal/form-associated.js +1 -1
  127. package/dist/internal/form-control-labels.d.ts +0 -3
  128. package/dist/internal/form-control-labels.js +1 -1
  129. package/dist/internal/localization-runtime.js +1 -1
  130. package/dist/internal/localization-types.d.ts +1 -1
  131. package/dist/internal/localization.js +1 -1
  132. package/dist/internal/lyra-element.d.ts +0 -13
  133. package/dist/internal/lyra-element.js +1 -1
  134. package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
  135. package/dist/internal/nonmodal-overlay-manager.js +1 -0
  136. package/dist/internal/overlay-manager.d.ts +4 -20
  137. package/dist/internal/overlay-manager.js +1 -1
  138. package/dist/internal/overlay-stack.d.ts +66 -0
  139. package/dist/internal/overlay-stack.js +1 -0
  140. package/dist/internal/package-metadata.d.ts +1 -1
  141. package/dist/internal/package-metadata.js +1 -1
  142. package/dist/internal/positioner.js +1 -1
  143. package/dist/internal/text-quote.d.ts +1 -1
  144. package/dist/lyra.d.ts +2 -3
  145. package/dist/svelte.d.ts +4 -4
  146. package/dist/translations/ar.js +1 -1
  147. package/dist/translations/de.js +1 -1
  148. package/dist/translations/es.js +1 -1
  149. package/dist/translations/fa.js +1 -1
  150. package/dist/translations/fr.js +1 -1
  151. package/dist/translations/he.js +1 -1
  152. package/dist/translations/ja.js +1 -1
  153. package/dist/translations/pt-BR.js +1 -1
  154. package/dist/translations/ru.js +1 -1
  155. package/dist/translations/zh-CN.js +1 -1
  156. package/dist/utilities/localization.js +1 -1
  157. package/dist/vue.d.ts +4 -4
  158. package/llms/components/lr-combobox.md +42 -0
  159. package/llms/components/lr-date-input.md +1 -1
  160. package/llms/components/lr-date-picker.md +1 -1
  161. package/llms/components/lr-filter-bar.md +2 -2
  162. package/llms/components/lr-heatmap.md +4 -1
  163. package/llms/components/lr-lite-chart.md +20 -8
  164. package/llms/components/lr-map.md +52 -22
  165. package/llms/components/lr-option.md +42 -0
  166. package/llms/components/lr-popover.md +39 -0
  167. package/llms/components/lr-table.md +7 -3
  168. package/llms/components/lr-timeline-item.md +49 -24
  169. package/llms/components/lr-timeline.md +49 -24
  170. package/llms-full.txt +224 -60
  171. package/package.json +3 -4
  172. package/vscode-css-data.json +21 -0
  173. package/vscode-html-data.json +12 -6
  174. package/web-types.json +47 -16
@@ -1 +1 @@
1
- import{AUTOLOADER_MANIFEST}from"./internal/autoloader-manifest.js";import{loadAutoloaderConstructor}from"./internal/autoloader-loaders.js";import{AUTOLOADER_TAG_SET}from"./internal/autoloader-tags.js";import{registryForRoot}from"./internal/definition-registry.js";import{collectRenderedTree,nativeElementLocalName,renderedTreeTraversalLimits,RenderedTreeTraversalError}from"./internal/rendered-tree-traversal.js";const AUTOLOADER_PENDING_ATTRIBUTE="data-lr-autoload-pending",markerOwners=new Map;let activeContext;function defaultRoot(){return typeof document>"u"?void 0:document}function isReadonlySet(value){if(!value||typeof value!="object")return!1;const candidate=value;return typeof candidate.has=="function"&&typeof candidate[Symbol.iterator]=="function"}function normalizeConcurrency(value){const resolved=value??16;if(!Number.isFinite(resolved)||!Number.isInteger(resolved)||resolved<1)throw new RangeError("Autoloader maxConcurrency must be an integer >= 1");return resolved}function normalizeOptions(options){const traversal=renderedTreeTraversalLimits(options??{},"Autoloader"),maxConcurrency=normalizeConcurrency(options?.maxConcurrency),common={events:options?.events===!0,traversal,maxConcurrency},policy=options?.optionalPeers;if(policy===void 0)return{optionalPeers:new Set,...common};if(policy==="all")return{optionalPeers:"all",...common};if(!Array.isArray(policy)&&!isReadonlySet(policy))throw new TypeError("optionalPeers must be 'all', an array, or a ReadonlySet of package names");const peers=[...policy];if(peers.some(peer=>typeof peer!="string"||peer.length===0||peer!==peer.trim()))throw new TypeError("optionalPeers must contain non-empty package names");return{optionalPeers:new Set(peers),...common}}function isEligible(entry,options){const allowedPeers=options.optionalPeers;return entry.optionalPeers.length===0||allowedPeers==="all"?!0:entry.optionalPeers.every(peer=>allowedPeers.has(peer))}function nativeNodeType(node){try{const NodeConstructor=typeof Node>"u"?void 0:Node;return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"nodeType")?.get)?.call(node)??node.nodeType}catch{return}}function ownerDocumentForNode(node){if(nativeNodeType(node)===9)return node;try{const NodeConstructor=typeof Node>"u"?void 0:Node;return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"ownerDocument")?.get)?.call(node)??void 0}catch{return}}function eventConstructor(root){const fromWindow=ownerDocumentForNode(root)?.defaultView?.CustomEvent;return fromWindow||(typeof CustomEvent>"u"?void 0:CustomEvent)}function emit(context,name,detail){if(!context.options.events||!context.active)return;const EventConstructor=eventConstructor(context.root);EventConstructor&&context.root.dispatchEvent(new EventConstructor(name,{bubbles:!0,composed:!0,detail}))}function markPending(context,element){let owners=markerOwners.get(element);if(!owners){if(element.hasAttribute(AUTOLOADER_PENDING_ATTRIBUTE))return;owners=new Set,markerOwners.set(element,owners)}const claim={context,element};return owners.add(claim),context.markerClaims.add(claim),element.hasAttribute(AUTOLOADER_PENDING_ATTRIBUTE)||element.setAttribute(AUTOLOADER_PENDING_ATTRIBUTE,""),claim}function clearPending(claim){if(!claim.context.markerClaims.delete(claim))return;const owners=markerOwners.get(claim.element);owners?.delete(claim)&&(owners.size>0||(claim.element.removeAttribute(AUTOLOADER_PENDING_ATTRIBUTE),markerOwners.delete(claim.element)))}function clearAllPending(context){for(const claim of[...context.markerClaims])clearPending(claim)}function definitionMap(context,registry){let definitions=context.definitionLoads.get(registry);return definitions||(definitions=new Map,context.definitionLoads.set(registry,definitions)),definitions}async function waitForUpdate(element){try{const updateComplete=element.updateComplete;updateComplete&&typeof updateComplete.then=="function"&&await updateComplete}catch{}}async function runBounded(items,concurrency,task){let next=0,failed=!1,failure;const worker=async()=>{for(;!failed;){const index=next;if(index>=items.length)return;next+=1;try{await task(items[index])}catch(error){failed||(failed=!0,failure=error)}}},workers=Array.from({length:Math.min(concurrency,items.length)},()=>worker());if(await Promise.all(workers),failed)throw failure}async function withWorkSlot(context,task){if(context.active&&(context.activeWork>=context.options.maxConcurrency&&await new Promise(resolve=>context.workWaiters.push(resolve)),!!context.active)){context.activeWork+=1;try{return await task()}finally{context.activeWork-=1,context.workWaiters.shift()?.()}}}async function defineTag(context,registry,tag){if(registry.get(tag))return;const definitions=definitionMap(context,registry),existing=definitions.get(tag);if(existing)return existing;const entry=AUTOLOADER_MANIFEST[tag],pending=(async()=>{emit(context,"lr-autoload-preload",{tag,optionalPeers:entry.optionalPeers});try{const constructor=await loadAutoloaderConstructor(tag);if(!context.active||(registry.get(tag)||registry.define(tag,constructor),await registry.whenDefined(tag),!context.active))return;context.loadedTags.add(tag),emit(context,"lr-autoload-loaded",{tag,optionalPeers:entry.optionalPeers})}catch(error){throw emit(context,"lr-autoload-error",{tag,optionalPeers:entry.optionalPeers,error}),error}})();definitions.set(tag,pending);const clearDefinition=()=>{definitions.get(tag)===pending&&definitions.delete(tag)};return pending.then(clearDefinition,clearDefinition),pending}function newDiscoveryState(){return{work:0,elements:new Set,roots:new Set}}function collectDiscoveryBatch(context,requestedRoots,state){const batchRoots=[],batchElements=[],rootDepths=new Map,elementDepths=new Map,seenRequests=new Set;for(const request of requestedRoots){if(seenRequests.has(request.root))continue;seenRequests.add(request.root);const result=collectRenderedTree(request.root,context.options.traversal,state,"Autoloader discovery",request.depth);for(const discoveredRoot of result.roots)batchRoots.push(discoveredRoot),rootDepths.set(discoveredRoot,result.rootDepths.get(discoveredRoot)??request.depth);for(const element of result.elements)batchElements.push(element),elementDepths.set(element,result.elementDepths.get(element)??request.depth)}return{roots:batchRoots,elements:batchElements,rootDepths,elementDepths}}function isElement(node){return nativeNodeType(node)===1}function observerConstructor(root){const fromWindow=ownerDocumentForNode(root)?.defaultView?.MutationObserver;return fromWindow||(typeof MutationObserver>"u"?void 0:MutationObserver)}function nativeParentNode(node){try{const NodeConstructor=ownerDocumentForNode(node)?.defaultView?.Node??(typeof Node>"u"?void 0:Node);return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"parentNode")?.get)?.call(node)??null}catch{return null}}function parentAcrossOpenShadowBoundary(node){const parent=nativeParentNode(node);if(parent)return parent;if(nativeNodeType(node)!==11||!("host"in node))return null;try{const ShadowRootConstructor=ownerDocumentForNode(node)?.defaultView?.ShadowRoot??(typeof ShadowRoot>"u"?void 0:ShadowRoot),host=(ShadowRootConstructor&&Object.getOwnPropertyDescriptor(ShadowRootConstructor.prototype,"host")?.get)?.call(node)??void 0;return host&&isElement(host)?host:null}catch{return null}}function spendAncestryWork(state,maximum){if(state.work>=maximum)throw new RenderedTreeTraversalError("Autoloader discovery","maxWork",maximum);state.work+=1}function renderedDepthFromRoot(root,node,state,maximumWork){let current=node,depth=0;const seen=new Set;for(;current&&!seen.has(current);){if(spendAncestryWork(state,maximumWork),current===root)return depth;if(seen.add(current),nativeNodeType(current)===11&&"host"in current){const host=parentAcrossOpenShadowBoundary(current);if(!host)return;depth+=1,current=host;continue}const parent=parentAcrossOpenShadowBoundary(current);if(!parent)return;isElement(parent)&&(depth+=1),current=parent}}function isReachableFromRoot(root,node,state,maximumWork){let current=node;const seen=new Set;for(;current&&!seen.has(current);){if(spendAncestryWork(state,maximumWork),current===root)return!0;seen.add(current),current=parentAcrossOpenShadowBoundary(current)}return!1}function observeRoot(context,root){!context.observer||context.observedRoots.has(root)||(context.observer.observe(root,{childList:!0,subtree:!0}),context.observedRoots.add(root))}function pruneDetachedObservedRoots(context,state){const observer=context.observer;if(!observer)return;const reachableRoots=[...context.observedRoots].filter(root=>isReachableFromRoot(context.root,root,state,context.options.traversal.maxWork));if(reachableRoots.length!==context.observedRoots.size){observer.disconnect(),context.observedRoots.clear();for(const root of reachableRoots)observeRoot(context,root)}}function openShadowRootFor(element){try{const ElementConstructor=element.ownerDocument?.defaultView?.Element??(typeof Element>"u"?void 0:Element);return(ElementConstructor&&Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"shadowRoot")?.get)?.call(element)??void 0}catch{return}}async function finishDiscoveredElement(context,element){if(await waitForUpdate(element),!!context.active)return openShadowRootFor(element)}function prepareDiscoveryBatch(context,requestedRoots,state){if(!context.active||requestedRoots.length===0)return;const{roots,elements,elementDepths}=collectDiscoveryBatch(context,requestedRoots,state);for(const discoveredRoot of roots)observeRoot(context,discoveredRoot);const grouped=new Map,definedElements=[],markerClaims=new Map;for(const element of elements){const tag=nativeElementLocalName(element);if(!tag||!AUTOLOADER_TAG_SET.has(tag))continue;const typedTag=tag,entry=AUTOLOADER_MANIFEST[typedTag],registry=registryForRoot(element);if(!registry)continue;let alreadyDefined=!1;try{alreadyDefined=typeof registry.get=="function"&&registry.get(typedTag)!==void 0}catch{continue}if(alreadyDefined){const markerClaim=markPending(context,element);definedElements.push({element,depth:elementDepths.get(element)??0,markerClaim});continue}if(!isEligible(entry,context.options))continue;markerClaims.set(element,markPending(context,element));let tags=grouped.get(registry);tags||(tags=new Map,grouped.set(registry,tags));const matches=tags.get(typedTag)??[];matches.push(element),tags.set(typedTag,matches)}const definitions=[],elementsToFinish=[...definedElements];for(const[registry,tags]of grouped)for(const[tag,matches]of tags){const definition={registry,tag};definitions.push(definition),elementsToFinish.push(...matches.map(element=>({element,depth:elementDepths.get(element)??0,markerClaim:markerClaims.get(element),definition})))}return{definitions,elementsToFinish,state}}async function executeDiscoveryBatch(context,prepared){const{definitions,elementsToFinish,state}=prepared;try{let hasDefinitionFailure=!1,firstDefinitionFailure;const failedDefinitions=new Set;if(await runBounded(definitions,context.options.maxConcurrency,async definition=>{try{await withWorkSlot(context,()=>defineTag(context,definition.registry,definition.tag))}catch(error){failedDefinitions.add(definition),hasDefinitionFailure||(hasDefinitionFailure=!0,firstDefinitionFailure=error)}}),!context.active)return;const postUpdateRoots=new Map;if(await runBounded(elementsToFinish,context.options.maxConcurrency,async work=>{try{if(work.definition&&failedDefinitions.has(work.definition))return;const shadowRoot=await withWorkSlot(context,()=>finishDiscoveredElement(context,work.element));shadowRoot&&postUpdateRoots.set(shadowRoot,work.depth+1)}finally{work.markerClaim&&clearPending(work.markerClaim)}}),context.active&&postUpdateRoots.size>0&&await processDiscoveryBatch(context,[...postUpdateRoots].map(([root,depth])=>({root,depth})),state),hasDefinitionFailure)throw firstDefinitionFailure}finally{for(const{markerClaim}of elementsToFinish)markerClaim&&clearPending(markerClaim)}}async function processDiscoveryBatch(context,requestedRoots,state,queuedClaims=[]){const prepared=prepareDiscoveryBatch(context,requestedRoots,state);for(const claim of queuedClaims)clearPending(claim);prepared&&await executeDiscoveryBatch(context,prepared)}async function discoverRootsWithContext(context,roots){if(!context.active)return[];const before=new Set(context.loadedTags);return await processDiscoveryBatch(context,roots.map(root=>({root,depth:0})),newDiscoveryState()),[...context.loadedTags].filter(tag=>!before.has(tag))}function queueObservedDiscovery(context,roots,state){const queuedClaims=[];for(const{root}of roots){if(!isElement(root))continue;const localName=nativeElementLocalName(root);if(!localName||!AUTOLOADER_TAG_SET.has(localName))continue;const tag=localName,registry=registryForRoot(root);if(!registry)continue;let alreadyDefined=!1;try{alreadyDefined=typeof registry.get=="function"&&registry.get(tag)!==void 0}catch{continue}if(!alreadyDefined&&!isEligible(AUTOLOADER_MANIFEST[tag],context.options))continue;const claim=markPending(context,root);claim&&queuedClaims.push(claim)}const queued=context.discoveryTail.then(()=>processDiscoveryBatch(context,roots,state,queuedClaims));return context.discoveryTail=queued.then(()=>{},()=>{}),queued.finally(()=>{for(const claim of queuedClaims)clearPending(claim)})}function createContext(root,options){return{active:!0,root,options:normalizeOptions(options),markerClaims:new Set,definitionLoads:new WeakMap,loadedTags:new Set,observedRoots:new Set,discoveryTail:Promise.resolve(),activeWork:0,workWaiters:[]}}async function discover(root=defaultRoot(),options){if(!root||typeof root.querySelectorAll!="function")return[];const context=createContext(root,options);try{return await discoverRootsWithContext(context,[root])}finally{context.active=!1,clearAllPending(context)}}async function start(root=defaultRoot(),options){if(stop(),!root||typeof root.querySelectorAll!="function")return[];const context=createContext(root,options);activeContext=context;const Observer=observerConstructor(root);Observer&&(context.observer=new Observer(records=>{if(!context.active)return;const state=newDiscoveryState(),addedRoots=new Map;try{records.some(record=>record.removedNodes.length>0)&&pruneDetachedObservedRoots(context,state);for(const record of records)if(isReachableFromRoot(context.root,record.target,state,context.options.traversal.maxWork))for(const node of record.addedNodes){const nodeType=nativeNodeType(node);if(nodeType!==1&&nodeType!==11)continue;const depth=renderedDepthFromRoot(context.root,node,state,context.options.traversal.maxWork);depth!==void 0&&addedRoots.set(node,depth)}}catch(error){error instanceof RenderedTreeTraversalError&&emit(context,"lr-autoload-traversal-error",{limit:error.limit,maximum:error.maximum,error});return}addedRoots.size!==0&&queueObservedDiscovery(context,[...addedRoots].map(([discoveredRoot,depth])=>({root:discoveredRoot,depth})),state).catch(error=>{error instanceof RenderedTreeTraversalError&&emit(context,"lr-autoload-traversal-error",{limit:error.limit,maximum:error.maximum,error})})}));try{const initialDiscovery=discoverRootsWithContext(context,[root]);return context.discoveryTail=initialDiscovery.then(()=>{},()=>{}),await initialDiscovery}catch(error){throw activeContext===context&&stop(),error}}function stop(){const context=activeContext;if(context){activeContext=void 0,context.active=!1,context.observer?.disconnect(),context.observedRoots.clear();for(const resolve of context.workWaiters.splice(0))resolve();clearAllPending(context)}}export{AUTOLOADER_PENDING_ATTRIBUTE,discover,start,stop};
1
+ import{AUTOLOADER_MANIFEST}from"./internal/autoloader-manifest.js";import{loadAutoloaderConstructor}from"./internal/autoloader-loaders.js";import{AUTOLOADER_TAG_SET}from"./internal/autoloader-tags.js";import{registryForRoot}from"./internal/definition-registry.js";import{collectRenderedTree,nativeElementLocalName,renderedTreeTraversalLimits,RenderedTreeTraversalError}from"./internal/rendered-tree-traversal.js";const AUTOLOADER_PENDING_ATTRIBUTE="data-lr-autoload-pending",markerOwners=new Map;let activeContext;function defaultRoot(){return typeof document>"u"?void 0:document}function isReadonlySet(value){if(!value||typeof value!="object")return!1;const candidate=value;return typeof candidate.has=="function"&&typeof candidate[Symbol.iterator]=="function"}function normalizeConcurrency(value){const resolved=value??16;if(!Number.isFinite(resolved)||!Number.isInteger(resolved)||resolved<1)throw new RangeError("Autoloader maxConcurrency must be an integer >= 1");return resolved}function normalizeOptions(options){const traversal=renderedTreeTraversalLimits(options??{},"Autoloader"),maxConcurrency=normalizeConcurrency(options?.maxConcurrency),common={events:options?.events===!0,traversal,maxConcurrency},policy=options?.optionalPeers;if(policy===void 0)return{optionalPeers:new Set,...common};if(policy==="all")return{optionalPeers:"all",...common};if(!Array.isArray(policy)&&!isReadonlySet(policy))throw new TypeError("optionalPeers must be 'all', an array, or a ReadonlySet of package names");const peers=[...policy];if(peers.some(peer=>typeof peer!="string"||peer.length===0||peer!==peer.trim()))throw new TypeError("optionalPeers must contain non-empty package names");return{optionalPeers:new Set(peers),...common}}function isEligible(entry,options){const allowedPeers=options.optionalPeers;return entry.optionalPeers.length===0||allowedPeers==="all"?!0:entry.optionalPeers.every(peer=>allowedPeers.has(peer))}function nativeNodeType(node){try{const NodeConstructor=typeof Node>"u"?void 0:Node;return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"nodeType")?.get)?.call(node)??node.nodeType}catch{return}}function ownerDocumentForNode(node){if(nativeNodeType(node)===9)return node;try{const NodeConstructor=typeof Node>"u"?void 0:Node;return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"ownerDocument")?.get)?.call(node)??void 0}catch{return}}function eventConstructor(root){const fromWindow=ownerDocumentForNode(root)?.defaultView?.CustomEvent;return fromWindow||(typeof CustomEvent>"u"?void 0:CustomEvent)}function emit(context,name,detail){if(!context.options.events||!context.active)return;const EventConstructor=eventConstructor(context.root);EventConstructor&&context.root.dispatchEvent(new EventConstructor(name,{bubbles:!0,composed:!0,detail}))}function markPending(context,element){let owners=markerOwners.get(element);if(!owners){if(element.hasAttribute(AUTOLOADER_PENDING_ATTRIBUTE))return;owners=new Set,markerOwners.set(element,owners)}const claim={context,element};return owners.add(claim),context.markerClaims.add(claim),element.hasAttribute(AUTOLOADER_PENDING_ATTRIBUTE)||element.setAttribute(AUTOLOADER_PENDING_ATTRIBUTE,""),claim}function clearPending(claim){if(!claim.context.markerClaims.delete(claim))return;const owners=markerOwners.get(claim.element);owners?.delete(claim)&&(owners.size>0||(claim.element.removeAttribute(AUTOLOADER_PENDING_ATTRIBUTE),markerOwners.delete(claim.element)))}function clearAllPending(context){for(const claim of[...context.markerClaims])clearPending(claim)}function definitionMap(context,registry){let definitions=context.definitionLoads.get(registry);return definitions||(definitions=new Map,context.definitionLoads.set(registry,definitions)),definitions}async function waitForUpdate(element){try{const updateComplete=element.updateComplete;updateComplete&&typeof updateComplete.then=="function"&&await updateComplete}catch{}}async function runBounded(items,concurrency,task){let next=0,failed=!1,failure;const worker=async()=>{for(;!failed;){const index=next;if(index>=items.length)return;next+=1;try{await task(items[index])}catch(error){failed||(failed=!0,failure=error)}}},workers=Array.from({length:Math.min(concurrency,items.length)},()=>worker());if(await Promise.all(workers),failed)throw failure}async function withWorkSlot(context,task){if(context.active)return task()}async function defineTag(context,registry,tag){if(registry.get(tag))return;const definitions=definitionMap(context,registry),existing=definitions.get(tag);if(existing)return existing;const entry=AUTOLOADER_MANIFEST[tag],pending=(async()=>{emit(context,"lr-autoload-preload",{tag,optionalPeers:entry.optionalPeers});try{const constructor=await loadAutoloaderConstructor(tag);if(!context.active||(registry.get(tag)||registry.define(tag,constructor),await registry.whenDefined(tag),!context.active))return;context.loadedTags.add(tag),emit(context,"lr-autoload-loaded",{tag,optionalPeers:entry.optionalPeers})}catch(error){throw emit(context,"lr-autoload-error",{tag,optionalPeers:entry.optionalPeers,error}),error}})();definitions.set(tag,pending);const clearDefinition=()=>{definitions.get(tag)===pending&&definitions.delete(tag)};return pending.then(clearDefinition,clearDefinition),pending}function newDiscoveryState(){return{work:0,elements:new Set,roots:new Set}}function collectDiscoveryBatch(context,requestedRoots,state){const batchRoots=[],batchElements=[],rootDepths=new Map,elementDepths=new Map,seenRequests=new Set;for(const request of requestedRoots){if(seenRequests.has(request.root))continue;seenRequests.add(request.root);const result=collectRenderedTree(request.root,context.options.traversal,state,"Autoloader discovery",request.depth);for(const discoveredRoot of result.roots)batchRoots.push(discoveredRoot),rootDepths.set(discoveredRoot,result.rootDepths.get(discoveredRoot)??request.depth);for(const element of result.elements)batchElements.push(element),elementDepths.set(element,result.elementDepths.get(element)??request.depth)}return{roots:batchRoots,elements:batchElements,rootDepths,elementDepths}}function isElement(node){return nativeNodeType(node)===1}function observerConstructor(root){const fromWindow=ownerDocumentForNode(root)?.defaultView?.MutationObserver;return fromWindow||(typeof MutationObserver>"u"?void 0:MutationObserver)}function nativeParentNode(node){try{const NodeConstructor=ownerDocumentForNode(node)?.defaultView?.Node??(typeof Node>"u"?void 0:Node);return(NodeConstructor&&Object.getOwnPropertyDescriptor(NodeConstructor.prototype,"parentNode")?.get)?.call(node)??null}catch{return null}}function parentAcrossOpenShadowBoundary(node){const parent=nativeParentNode(node);if(parent)return parent;if(nativeNodeType(node)!==11||!("host"in node))return null;try{const ShadowRootConstructor=ownerDocumentForNode(node)?.defaultView?.ShadowRoot??(typeof ShadowRoot>"u"?void 0:ShadowRoot),host=(ShadowRootConstructor&&Object.getOwnPropertyDescriptor(ShadowRootConstructor.prototype,"host")?.get)?.call(node)??void 0;return host&&isElement(host)?host:null}catch{return null}}function spendAncestryWork(state,maximum){if(state.work>=maximum)throw new RenderedTreeTraversalError("Autoloader discovery","maxWork",maximum);state.work+=1}function renderedDepthFromRoot(root,node,state,maximumWork){let current=node,depth=0;const seen=new Set;for(;current&&!seen.has(current);){if(spendAncestryWork(state,maximumWork),current===root)return depth;if(seen.add(current),nativeNodeType(current)===11&&"host"in current){const host=parentAcrossOpenShadowBoundary(current);if(!host)return;depth+=1,current=host;continue}const parent=parentAcrossOpenShadowBoundary(current);if(!parent)return;isElement(parent)&&(depth+=1),current=parent}}function isReachableFromRoot(root,node,state,maximumWork){let current=node;const seen=new Set;for(;current&&!seen.has(current);){if(spendAncestryWork(state,maximumWork),current===root)return!0;seen.add(current),current=parentAcrossOpenShadowBoundary(current)}return!1}function observeRoot(context,root){!context.observer||context.observedRoots.has(root)||(context.observer.observe(root,{childList:!0,subtree:!0}),context.observedRoots.add(root))}function pruneDetachedObservedRoots(context,state){const observer=context.observer;if(!observer)return;const reachableRoots=[...context.observedRoots].filter(root=>isReachableFromRoot(context.root,root,state,context.options.traversal.maxWork));if(reachableRoots.length!==context.observedRoots.size){observer.disconnect(),context.observedRoots.clear();for(const root of reachableRoots)observeRoot(context,root)}}function openShadowRootFor(element){try{const ElementConstructor=element.ownerDocument?.defaultView?.Element??(typeof Element>"u"?void 0:Element);return(ElementConstructor&&Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"shadowRoot")?.get)?.call(element)??void 0}catch{return}}async function finishDiscoveredElement(context,element){if(await waitForUpdate(element),!!context.active)return openShadowRootFor(element)}function prepareDiscoveryBatch(context,requestedRoots,state){if(!context.active||requestedRoots.length===0)return;const{roots,elements,elementDepths}=collectDiscoveryBatch(context,requestedRoots,state);for(const discoveredRoot of roots)observeRoot(context,discoveredRoot);const grouped=new Map,definedElements=[],markerClaims=new Map;for(const element of elements){const tag=nativeElementLocalName(element);if(!tag||!AUTOLOADER_TAG_SET.has(tag))continue;const typedTag=tag,entry=AUTOLOADER_MANIFEST[typedTag],registry=registryForRoot(element);if(!registry)continue;let alreadyDefined=!1;try{alreadyDefined=typeof registry.get=="function"&&registry.get(typedTag)!==void 0}catch{continue}if(alreadyDefined){const markerClaim=markPending(context,element);definedElements.push({element,depth:elementDepths.get(element)??0,markerClaim});continue}if(!isEligible(entry,context.options))continue;markerClaims.set(element,markPending(context,element));let tags=grouped.get(registry);tags||(tags=new Map,grouped.set(registry,tags));const matches=tags.get(typedTag)??[];matches.push(element),tags.set(typedTag,matches)}const definitions=[],elementsToFinish=[...definedElements];for(const[registry,tags]of grouped)for(const[tag,matches]of tags){const definition={registry,tag};definitions.push(definition),elementsToFinish.push(...matches.map(element=>({element,depth:elementDepths.get(element)??0,markerClaim:markerClaims.get(element),definition})))}return{definitions,elementsToFinish,state}}async function executeDiscoveryBatch(context,prepared){const{definitions,elementsToFinish,state}=prepared;try{let hasDefinitionFailure=!1,firstDefinitionFailure;const failedDefinitions=new Set;if(await runBounded(definitions,context.options.maxConcurrency,async definition=>{try{await withWorkSlot(context,()=>defineTag(context,definition.registry,definition.tag))}catch(error){failedDefinitions.add(definition),hasDefinitionFailure||(hasDefinitionFailure=!0,firstDefinitionFailure=error)}}),!context.active)return;const postUpdateRoots=new Map;if(await runBounded(elementsToFinish,context.options.maxConcurrency,async work=>{try{if(work.definition&&failedDefinitions.has(work.definition))return;const shadowRoot=await withWorkSlot(context,()=>finishDiscoveredElement(context,work.element));shadowRoot&&postUpdateRoots.set(shadowRoot,work.depth+1)}finally{work.markerClaim&&clearPending(work.markerClaim)}}),context.active&&postUpdateRoots.size>0&&await processDiscoveryBatch(context,[...postUpdateRoots].map(([root,depth])=>({root,depth})),state),hasDefinitionFailure)throw firstDefinitionFailure}finally{for(const{markerClaim}of elementsToFinish)markerClaim&&clearPending(markerClaim)}}async function processDiscoveryBatch(context,requestedRoots,state,queuedClaims=[]){const prepared=prepareDiscoveryBatch(context,requestedRoots,state);for(const claim of queuedClaims)clearPending(claim);prepared&&await executeDiscoveryBatch(context,prepared)}async function discoverRootsWithContext(context,roots){if(!context.active)return[];const before=new Set(context.loadedTags);return await processDiscoveryBatch(context,roots.map(root=>({root,depth:0})),newDiscoveryState()),[...context.loadedTags].filter(tag=>!before.has(tag))}function queueObservedDiscovery(context,roots,state){const queuedClaims=[];for(const{root}of roots){if(!isElement(root))continue;const localName=nativeElementLocalName(root);if(!localName||!AUTOLOADER_TAG_SET.has(localName))continue;const tag=localName,registry=registryForRoot(root);if(!registry)continue;let alreadyDefined=!1;try{alreadyDefined=typeof registry.get=="function"&&registry.get(tag)!==void 0}catch{continue}if(!alreadyDefined&&!isEligible(AUTOLOADER_MANIFEST[tag],context.options))continue;const claim=markPending(context,root);claim&&queuedClaims.push(claim)}const queued=context.discoveryTail.then(()=>processDiscoveryBatch(context,roots,state,queuedClaims));return context.discoveryTail=queued.then(()=>{},()=>{}),queued.finally(()=>{for(const claim of queuedClaims)clearPending(claim)})}function createContext(root,options){return{active:!0,root,options:normalizeOptions(options),markerClaims:new Set,definitionLoads:new WeakMap,loadedTags:new Set,observedRoots:new Set,discoveryTail:Promise.resolve()}}async function discover(root=defaultRoot(),options){if(!root||typeof root.querySelectorAll!="function")return[];const context=createContext(root,options);try{return await discoverRootsWithContext(context,[root])}finally{context.active=!1,clearAllPending(context)}}async function start(root=defaultRoot(),options){if(stop(),!root||typeof root.querySelectorAll!="function")return[];const context=createContext(root,options);activeContext=context;const Observer=observerConstructor(root);Observer&&(context.observer=new Observer(records=>{if(!context.active)return;const state=newDiscoveryState(),addedRoots=new Map;try{records.some(record=>record.removedNodes.length>0)&&pruneDetachedObservedRoots(context,state);for(const record of records)if(isReachableFromRoot(context.root,record.target,state,context.options.traversal.maxWork))for(const node of record.addedNodes){const nodeType=nativeNodeType(node);if(nodeType!==1&&nodeType!==11)continue;const depth=renderedDepthFromRoot(context.root,node,state,context.options.traversal.maxWork);depth!==void 0&&addedRoots.set(node,depth)}}catch(error){error instanceof RenderedTreeTraversalError&&emit(context,"lr-autoload-traversal-error",{limit:error.limit,maximum:error.maximum,error});return}addedRoots.size!==0&&queueObservedDiscovery(context,[...addedRoots].map(([discoveredRoot,depth])=>({root:discoveredRoot,depth})),state).catch(error=>{error instanceof RenderedTreeTraversalError&&emit(context,"lr-autoload-traversal-error",{limit:error.limit,maximum:error.maximum,error})})}));try{const initialDiscovery=discoverRootsWithContext(context,[root]);return context.discoveryTail=initialDiscovery.then(()=>{},()=>{}),await initialDiscovery}catch(error){throw activeContext===context&&stop(),error}}function stop(){const context=activeContext;context&&(activeContext=void 0,context.active=!1,context.observer?.disconnect(),context.observedRoots.clear(),clearAllPending(context))}export{AUTOLOADER_PENDING_ATTRIBUTE,discover,start,stop};
@@ -1,6 +1,5 @@
1
1
  import { type TemplateResult, type PropertyValues } from 'lit';
2
2
  import { LyraElement, type LyraEventDetailSnapshot } from '../../../internal/lyra-element.js';
3
- import '../../../internal/form-control-labels.js';
4
3
  import '../../forms/select/select.class.js';
5
4
  import '../../forms/combobox/option.class.js';
6
5
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{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
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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();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??""}
@@ -2,7 +2,6 @@ export interface HistogramBucket {
2
2
  label: string;
3
3
  count: number;
4
4
  }
5
- export declare const MAX_HISTOGRAM_BINS = 1000;
6
5
  /** Converts an untyped bucket count to a bounded, non-negative integer. */
7
6
  export declare function normalizeHistogramBinCount(binCount: unknown): number;
8
7
  /** Splits `values` into `binCount` equal-width buckets and counts membership.
@@ -1 +1 @@
1
- import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteInterpolate,finiteRatio}from"../../../internal/numbers.js";const MAX_HISTOGRAM_BINS=1e3,LEFT_TO_RIGHT_ISOLATE="\u2066",POP_DIRECTIONAL_ISOLATE="\u2069";function normalizeHistogramBinCount(binCount){const numeric=typeof binCount=="number"?binCount:Number(binCount);return Number.isFinite(numeric)?Math.min(MAX_HISTOGRAM_BINS,Math.max(0,Math.floor(numeric))):0}function binValues(values,binCount,locale){const finite=values.filter(v=>Number.isFinite(v));if(finite.length===0)return[];const bins=normalizeHistogramBinCount(binCount);if(bins<=0)return[];let lo=finite[0],hi=finite[0];for(const v of finite)v<lo&&(lo=v),v>hi&&(hi=v);const constant=hi===lo,numberFormat=getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1});if(constant)return[{label:`${LEFT_TO_RIGHT_ISOLATE}${numberFormat.format(lo)}${POP_DIRECTIONAL_ISOLATE}`,count:finite.length}];const labelHi=hi,formatRange=numberFormat.formatRange?.bind(numberFormat),buckets=Array.from({length:bins},(_,i)=>{const bLo=finiteInterpolate(lo,labelHi,i/bins),bHi=finiteInterpolate(lo,labelHi,(i+1)/bins);return{label:`${LEFT_TO_RIGHT_ISOLATE}${formatRange?formatRange(bLo,bHi):`${numberFormat.format(bLo)}\u2013${numberFormat.format(bHi)}`}${POP_DIRECTIONAL_ISOLATE}`,count:0}});for(const v of finite){const index=Math.floor(finiteRatio(v,lo,hi)*bins);buckets[Math.min(bins-1,Math.max(0,index))].count++}return buckets}export{MAX_HISTOGRAM_BINS,binValues,normalizeHistogramBinCount};
1
+ import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteInterpolate,finiteRatio}from"../../../internal/numbers.js";const MAX_HISTOGRAM_BINS=1e3,LEFT_TO_RIGHT_ISOLATE="\u2066",POP_DIRECTIONAL_ISOLATE="\u2069";function normalizeHistogramBinCount(binCount){const numeric=typeof binCount=="number"?binCount:Number(binCount);return Number.isFinite(numeric)?Math.min(MAX_HISTOGRAM_BINS,Math.max(0,Math.floor(numeric))):0}function binValues(values,binCount,locale){const finite=values.filter(v=>Number.isFinite(v));if(finite.length===0)return[];const bins=normalizeHistogramBinCount(binCount);if(bins<=0)return[];let lo=finite[0],hi=finite[0];for(const v of finite)v<lo&&(lo=v),v>hi&&(hi=v);const constant=hi===lo,numberFormat=getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1});if(constant)return[{label:`${LEFT_TO_RIGHT_ISOLATE}${numberFormat.format(lo)}${POP_DIRECTIONAL_ISOLATE}`,count:finite.length}];const labelHi=hi,formatRange=numberFormat.formatRange?.bind(numberFormat),buckets=Array.from({length:bins},(_,i)=>{const bLo=finiteInterpolate(lo,labelHi,i/bins),bHi=finiteInterpolate(lo,labelHi,(i+1)/bins);return{label:`${LEFT_TO_RIGHT_ISOLATE}${formatRange?formatRange(bLo,bHi):`${numberFormat.format(bLo)}\u2013${numberFormat.format(bHi)}`}${POP_DIRECTIONAL_ISOLATE}`,count:0}});for(const v of finite){const index=Math.floor(finiteRatio(v,lo,hi)*bins);buckets[Math.min(bins-1,Math.max(0,index))].count++}return buckets}export{binValues,normalizeHistogramBinCount};
@@ -66,7 +66,8 @@ export interface LyraLiteChartEventMap {
66
66
  * `layout="scroll"` (+ `barWidth`) gives every bar a fixed pixel width and
67
67
  * lets the plot overflow the host horizontally (scrollable) instead of
68
68
  * squeezing; `maxLabels` decimates which x-axis text labels render (bars
69
- * always still render) once there are more categories than that; and
69
+ * always still render) once there are more categories than that, with
70
+ * `maxLabels="auto"` deriving the cap from the allocated plot width; and
70
71
  * `barX` lets a consumer hand in its own per-category x-coordinate function
71
72
  * — e.g. to pixel-align this chart's bars with a sibling `lr-heatmap`'s
72
73
  * calendar columns — overriding the internal slot math for both bars and
@@ -78,7 +79,8 @@ export interface LyraLiteChartEventMap {
78
79
  * template when unset; `roundedBars` draws bars as a rounded-top path
79
80
  * instead of a square-cornered rect; `skipZero` omits a bar entirely (not
80
81
  * just zero-height) for an exactly-`0` value; `valueAxisGutter`/`barGapRatio`
81
- * override the internal `PAD_LEFT`/`BAR_GROUP_GAP` layout constants; `scale`
82
+ * override the internal `PAD_LEFT`/`BAR_GROUP_GAP` layout constants, while
83
+ * `valueAxisGutter="auto"` sizes the gutter from the rendered tick strings; `scale`
82
84
  * (`type="bar"` only) switches the bar-height mapping from the default
83
85
  * linear `niceDomain` fraction to a `Math.sqrt(value / domainMax)`
84
86
  * compression (mirroring `lr-heatmap`'s matrix-mode `sqrt` scale) so a
@@ -231,10 +233,12 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
231
233
  * so an excessive requested width is reduced as needed to keep SVG and CSS geometry finite. */
232
234
  barWidth: number;
233
235
  /** Caps how many x-axis category labels render text once `this.labels.length` exceeds it,
234
- * decimating roughly evenly while always keeping the first and last label. Bars themselves
235
- * always render regardless only the axis text is decimated. Unset (the default) renders every
236
+ * decimating roughly evenly while always keeping the first and last label. `'auto'` derives a
237
+ * deterministic cap from the resolved plot width and widest rendered category label using the
238
+ * same width estimate as label ellipsis. Bars themselves always render regardless — only the
239
+ * axis text is decimated. An explicit number is authoritative. Unset (the default) renders every
236
240
  * label, unchanged from before this property existed. Works in either `layout` mode. */
237
- maxLabels?: number;
241
+ maxLabels?: number | 'auto';
238
242
  /** Overrides the x-origin `renderBars()`/the category labels would otherwise compute internally
239
243
  * for a given category index, for `type="bar"` only (bars and their axis labels stay
240
244
  * consistent with each other either way). Lets a consumer pixel-align this chart's bars with,
@@ -260,9 +264,14 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
260
264
  * is exactly `0` — `null`/non-finite values are always skipped regardless of this flag. Default
261
265
  * `false` preserves today's behavior of a zero-height but focusable/titled bar. */
262
266
  skipZero: boolean;
263
- /** Overrides the internal `PAD_LEFT` (36px) axis-gutter constant. The gutter is on the left in
264
- * LTR and the right in RTL, keeping the y axis at logical start. Unset keeps the 36px default. */
265
- valueAxisGutter?: number;
267
+ /** Overrides the internal `PAD_LEFT` (36px) axis-gutter constant, or accepts `'auto'` to size the
268
+ * gutter from the exact formatted tick strings rendered in the current pass. Automatic sizing
269
+ * never shrinks below 36px. Fit layout bounds it to the smaller of 240px or 40% of the measured
270
+ * SVG width; scroll layout bounds it at 240px without feeding the explicitly-sized SVG's own
271
+ * width back into its gutter. An explicit numeric value is authoritative and retains the
272
+ * established 0..1,000,000px finite guard. The gutter is on the left in LTR and the right in
273
+ * RTL, keeping the y axis at logical start. Unset keeps the 36px default. */
274
+ valueAxisGutter?: number | 'auto';
266
275
  /** Overrides the internal `BAR_GROUP_GAP` (0.2) fraction of a category slot left as a gap between
267
276
  * categories. Unset (the default) keeps today's fixed 0.2. */
268
277
  barGapRatio?: number;
@@ -457,6 +466,7 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
457
466
  private emitPoint;
458
467
  private emitNearestLinePoint;
459
468
  private onPointKeyDown;
469
+ private formatValueAxisTick;
460
470
  private renderGrid;
461
471
  /**
462
472
  * `slot` is the per-category width to lay bars out against — either the
@@ -468,10 +478,13 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
468
478
  private renderBars;
469
479
  private renderLines;
470
480
  render(): TemplateResult;
481
+ private resolvedValueAxisGutter;
482
+ private automaticMaxLabels;
471
483
  /** Indexes retained by `maxLabels`, distributed across the complete domain so the sample
472
484
  * immediately before the forced final endpoint can never bunch against it. The generated mark
473
485
  * sample caps the useful result at 1,000, so this selector must do the same rather than allocate
474
- * an arbitrary consumer-supplied `maxLabels` count. `undefined` means every *sampled* label
486
+ * an arbitrary consumer-supplied `maxLabels` count. In auto mode the resolved plot width and
487
+ * rendered source indexes supply a deterministic cap. `undefined` means every *sampled* label
475
488
  * renders, preserving the default and non-finite-value behavior. */
476
489
  private visibleLabelIndexes;
477
490
  private displayCategoryLabel;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),autoNumberConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();return trimmed.toLowerCase()==="auto"?"auto":Number(trimmed)}},DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,AUTO_CATEGORY_LABEL_INSET=10,VALUE_AXIS_TICK_OFFSET=6,AUTO_VALUE_AXIS_SAFETY_INSET=8,MAX_AUTO_VALUE_AXIS_GUTTER=240,MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION=.4,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
2
2
  `)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.armResizeObserver(),this.armForcedColorsWatcher()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const box=entries[0]?.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=this.svgEl?.getBoundingClientRect();rect&&(this.plotWidth=rect.width,this.plotHeight=rect.height)}});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target)}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver(),this.releaseAnnouncementSink(),this.syncAnnouncementSink(),this.refreshFitMeasurementAvailability(),this.armForcedColorsWatcher()}armForcedColorsWatcher(){const ownerWindow=this.ownerDocument?.defaultView??void 0;ownerWindow?.matchMedia&&(this.forcedColorsWindow===ownerWindow&&this.forcedColorsQuery||(this.disarmForcedColorsWatcher(),this.forcedColorsWindow=ownerWindow,this.forcedColorsQuery=ownerWindow.matchMedia("(forced-colors: active)"),this.forcedColorsQuery.addEventListener("change",this.onForcedColorsChange)))}disarmForcedColorsWatcher(){this.forcedColorsQuery?.removeEventListener("change",this.onForcedColorsChange),this.forcedColorsQuery=void 0,this.forcedColorsWindow=void 0}syncAnnouncementSink(){this.isConnected&&this.politeAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=activeElementIn(this.shadowRoot)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const dataTruncation=this.dataTruncationMessage();wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus())}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
3
3
  ${this.recordSample().seriesIndexes.map(index=>{const series=this.datasets[index],encoding=forcedColorEncoding(index).name,shapes=(()=>{switch(encoding){case"horizontal":return svg`<rect y=${half} width=${size} height="1" fill=${texture}></rect>`;case"vertical":return svg`<rect x=${half} width="1" height=${size} fill=${texture}></rect>`;case"diagonal":return svg`<path
4
4
  d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
@@ -19,15 +19,15 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
19
19
  <rect width=${size} height=${size} fill=${this.colorFor(index,series)}></rect>
20
20
  ${shapes}
21
21
  </pattern>`})}
22
- </defs>`}resolvePointText(label,value,datasetIndex){return this.formatter?.({value,surface:"visual",datasetIndex,label,seriesLabel:this.datasets[datasetIndex]?.label})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markAnnouncement(index,marks=this.interactiveMarks()){const mark=marks[index];if(!mark)return"";const series=this.datasets[mark.datasetIndex]?.label??this.localize("chartSeriesLabel"),custom=this.formatter?.({value:mark.value,surface:"spoken",datasetIndex:mark.datasetIndex,index:mark.index,label:mark.label,seriesLabel:series})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex);return custom?this.localize("liteChartCustomMarkSummary",void 0,{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)}):this.localize("liteChartMarkSummary",void 0,{series,label:mark.label,value:getNumberFormat(this.effectiveLocale).format(mark.value),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)})}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.liveRegion?.announce(this.markAnnouncement(index,marks),{force:!0}))}focusMark(index){this.interactiveMarks()[index]&&(this.activeMarkIndex=index,this.updateComplete.then(()=>{const mark=Array.from(this.renderRoot.querySelectorAll('[part="bar"], [part="point"]'))[index];mark&&(activeElementIn(this.shadowRoot)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const domainMax=hi>0?hi:1,frac=Math.sqrt(Math.min(domainMax,Math.max(0,value))/domainMax);return plotY+plotH-frac*plotH}return plotY+plotH-this.valueFraction(value,lo,hi)*plotH}valueFraction(value,lo,hi){return this.scale==="logarithmic"?logDomainFraction(value,this.logDomainFloor(lo,hi),hi):domainFraction(value,lo,hi)}logDomainFloor(lo,hi){if(lo>0)return lo;let smallest=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest&&(smallest=value);return Number.isFinite(smallest)?smallest:hi>0?hi/10:1}effectiveMinBarHeight(){return this.minBarHeight==null?void 0:finiteRange(this.minBarHeight,0,0,MAX_SCROLL_CONTENT_WIDTH)}roundedBarPath(x,y,w,h){const r=Math.max(0,Math.min(BAR_CORNER_RADIUS,w/2,h));return r<=0?`M${x},${y} h${w} v${h} h${-w} Z`:`M${x},${y+r} Q${x},${y} ${x+r},${y} H${x+w-r} Q${x+w},${y} ${x+w},${y+r} V${y+h} H${x} Z`}domain(){let lo=1/0,hi=-1/0;if(this.effectiveType==="bar"&&this.stacked)for(let i=0;i<this.recordCount();i++){let pos=0,neg=0;for(const s of this.datasets){const v=s.data[i];v==null||!Number.isFinite(v)||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}lo=Math.min(lo,neg),hi=Math.max(hi,pos)}else for(const s of this.datasets)for(const v of s.data)v==null||!Number.isFinite(v)||(lo=Math.min(lo,v),hi=Math.max(hi,v));return(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1),niceDomain(lo,hi,this.beginAtZero,TICK_COUNT)}emitPoint(datasetIndex,index){const label=this.labels[index],value=this.datasets[datasetIndex]?.data[index]??null;this.emit("lr-datum-activate",{kind:this.effectiveType==="bar"?"bar":"point",datasetIndex,index,label,value}),this.emit("lr-point-click",{datasetIndex,index,label,value})}emitNearestLinePoint(event,points,fallbackDatasetIndex,fallbackIndex){let selected=points.find(point=>point.datasetIndex===fallbackDatasetIndex&&point.index===fallbackIndex);const currentTarget=event.currentTarget,svgElement=currentTarget instanceof SVGElement?currentTarget.ownerSVGElement:null,screenMatrix=svgElement?.getScreenCTM();if(event.detail>0&&svgElement&&screenMatrix&&points.length){const renderedPoint=svgElement.createSVGPoint(),squaredDistance=point=>{renderedPoint.x=point.x,renderedPoint.y=point.y;const screenPoint=renderedPoint.matrixTransform(screenMatrix),dx=event.clientX-screenPoint.x,dy=event.clientY-screenPoint.y;return dx*dx+dy*dy};let bestDistance=selected?squaredDistance(selected):Number.POSITIVE_INFINITY;for(const point of points){const distance=squaredDistance(point);distance<bestDistance&&(selected=point,bestDistance=distance)}}this.emitPoint(selected?.datasetIndex??fallbackDatasetIndex,selected?.index??fallbackIndex)}onPointKeyDown(e,datasetIndex,index,markIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onMarkFocus(markIndex),this.emitPoint(datasetIndex,index);return}const marks=this.interactiveMarks();if(!marks.length)return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=markIndex;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(marks.length-1,markIndex+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,markIndex-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=marks.length-1;else return;e.preventDefault(),this.focusMark(next)}renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi){const rtl=this.effectiveDirection==="rtl";return ticks.map(t=>{const y=plotY+plotH-this.valueFraction(t,lo,hi)*plotH;return svg`
22
+ </defs>`}resolvePointText(label,value,datasetIndex){return this.formatter?.({value,surface:"visual",datasetIndex,label,seriesLabel:this.datasets[datasetIndex]?.label})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markAnnouncement(index,marks=this.interactiveMarks()){const mark=marks[index];if(!mark)return"";const series=this.datasets[mark.datasetIndex]?.label??this.localize("chartSeriesLabel"),custom=this.formatter?.({value:mark.value,surface:"spoken",datasetIndex:mark.datasetIndex,index:mark.index,label:mark.label,seriesLabel:series})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex);return custom?this.localize("liteChartCustomMarkSummary",void 0,{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)}):this.localize("liteChartMarkSummary",void 0,{series,label:mark.label,value:getNumberFormat(this.effectiveLocale).format(mark.value),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)})}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.liveRegion?.announce(this.markAnnouncement(index,marks),{force:!0}))}focusMark(index){this.interactiveMarks()[index]&&(this.activeMarkIndex=index,this.updateComplete.then(()=>{const mark=Array.from(this.renderRoot.querySelectorAll('[part="bar"], [part="point"]'))[index];mark&&(activeElementIn(this.shadowRoot)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const domainMax=hi>0?hi:1,frac=Math.sqrt(Math.min(domainMax,Math.max(0,value))/domainMax);return plotY+plotH-frac*plotH}return plotY+plotH-this.valueFraction(value,lo,hi)*plotH}valueFraction(value,lo,hi){return this.scale==="logarithmic"?logDomainFraction(value,this.logDomainFloor(lo,hi),hi):domainFraction(value,lo,hi)}logDomainFloor(lo,hi){if(lo>0)return lo;let smallest=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest&&(smallest=value);return Number.isFinite(smallest)?smallest:hi>0?hi/10:1}effectiveMinBarHeight(){return this.minBarHeight==null?void 0:finiteRange(this.minBarHeight,0,0,MAX_SCROLL_CONTENT_WIDTH)}roundedBarPath(x,y,w,h){const r=Math.max(0,Math.min(BAR_CORNER_RADIUS,w/2,h));return r<=0?`M${x},${y} h${w} v${h} h${-w} Z`:`M${x},${y+r} Q${x},${y} ${x+r},${y} H${x+w-r} Q${x+w},${y} ${x+w},${y+r} V${y+h} H${x} Z`}domain(){let lo=1/0,hi=-1/0;if(this.effectiveType==="bar"&&this.stacked)for(let i=0;i<this.recordCount();i++){let pos=0,neg=0;for(const s of this.datasets){const v=s.data[i];v==null||!Number.isFinite(v)||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}lo=Math.min(lo,neg),hi=Math.max(hi,pos)}else for(const s of this.datasets)for(const v of s.data)v==null||!Number.isFinite(v)||(lo=Math.min(lo,v),hi=Math.max(hi,v));return(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1),niceDomain(lo,hi,this.beginAtZero,TICK_COUNT)}emitPoint(datasetIndex,index){const label=this.labels[index],value=this.datasets[datasetIndex]?.data[index]??null;this.emit("lr-datum-activate",{kind:this.effectiveType==="bar"?"bar":"point",datasetIndex,index,label,value}),this.emit("lr-point-click",{datasetIndex,index,label,value})}emitNearestLinePoint(event,points,fallbackDatasetIndex,fallbackIndex){let selected=points.find(point=>point.datasetIndex===fallbackDatasetIndex&&point.index===fallbackIndex);const currentTarget=event.currentTarget,svgElement=currentTarget instanceof SVGElement?currentTarget.ownerSVGElement:null,screenMatrix=svgElement?.getScreenCTM();if(event.detail>0&&svgElement&&screenMatrix&&points.length){const renderedPoint=svgElement.createSVGPoint(),squaredDistance=point=>{renderedPoint.x=point.x,renderedPoint.y=point.y;const screenPoint=renderedPoint.matrixTransform(screenMatrix),dx=event.clientX-screenPoint.x,dy=event.clientY-screenPoint.y;return dx*dx+dy*dy};let bestDistance=selected?squaredDistance(selected):Number.POSITIVE_INFINITY;for(const point of points){const distance=squaredDistance(point);distance<bestDistance&&(selected=point,bestDistance=distance)}}this.emitPoint(selected?.datasetIndex??fallbackDatasetIndex,selected?.index??fallbackIndex)}onPointKeyDown(e,datasetIndex,index,markIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onMarkFocus(markIndex),this.emitPoint(datasetIndex,index);return}const marks=this.interactiveMarks();if(!marks.length)return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=markIndex;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(marks.length-1,markIndex+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,markIndex-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=marks.length-1;else return;e.preventDefault(),this.focusMark(next)}formatValueAxisTick(value){return this.formatter?.({value,surface:"tick"})??(this.tickFormat?this.tickFormat(value):formatTick(value,this.effectiveLocale))}renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi){const rtl=this.effectiveDirection==="rtl";return ticks.map(({value,label})=>{const y=plotY+plotH-this.valueFraction(value,lo,hi)*plotH;return svg`
23
23
  <line part="grid-line" x1=${plotX} y1=${y} x2=${plotX+plotW} y2=${y}></line>
24
24
  <text
25
25
  part="axis-label"
26
- x=${rtl?plotX+plotW+6:plotX-6}
26
+ x=${rtl?plotX+plotW+VALUE_AXIS_TICK_OFFSET:plotX-VALUE_AXIS_TICK_OFFSET}
27
27
  y=${y}
28
28
  text-anchor="end"
29
29
  dominant-baseline="middle"
30
- >${this.formatter?.({value:t,surface:"tick"})??(this.tickFormat?this.tickFormat(t):formatTick(t,this.effectiveLocale))}</text>
30
+ >${label}</text>
31
31
  `})}renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices){const groupCount=this.stacked?1:Math.max(1,recordSample.seriesIndexes.length),groupGap=finiteRange(this.barGapRatio??BAR_GROUP_GAP,BAR_GROUP_GAP,0,1),groupW=slot*(1-groupGap),barW=(groupW-BAR_GAP*slot*(groupCount-1))/groupCount,markIndexes=this.markIndexMap(),activeMarkIndex=this.normalizedMarkIndex(),numberFormat=getNumberFormat(this.effectiveLocale),minBarHeight=this.effectiveMinBarHeight(),stackedSqrt=this.stacked&&this.scale==="sqrt",domainMax=hi>0?hi:1,negDomainMax=lo<0?-lo:1,zeroY=plotY+plotH-domainFraction(0,lo,hi)*plotH,clampSvgCoordinate=(value,fallback=zeroY)=>finiteRange(value,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH),clampSvgLength=value=>finiteRange(value,0,0,MAX_SCROLL_CONTENT_WIDTH),posAvailH=zeroY-plotY,negAvailH=plotY+plotH-zeroY,posTotals=new Map,negTotals=new Map;if(stackedSqrt)for(const i of recordSample.rowIndexes){let pos=0,neg=0;for(const datasetIndex of recordSample.seriesIndexes){const s=this.datasets[datasetIndex];if(!s)continue;const v=s.data[i];v==null||!Number.isFinite(v)||this.skipZero&&v===0||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}posTotals.set(i,pos),negTotals.set(i,neg)}const bars=[];for(const i of recordSample.rowIndexes){const slotStart=(barOrigins.get(i)??plotX+i*slot)+(slot-groupW)/2;let stackPos=0,stackNeg=0,posPixelTop=zeroY,negPixelBottom=zeroY;const posCompressedH=stackedSqrt?Math.sqrt(Math.min(domainMax,posTotals.get(i)??0)/domainMax)*posAvailH:0,negCompressedH=stackedSqrt?Math.sqrt(Math.min(negDomainMax,-(negTotals.get(i)??0))/negDomainMax)*negAvailH:0;recordSample.seriesIndexes.forEach((di,sampledDatasetIndex)=>{const s=this.datasets[di];if(!s)return;const v=s.data[i];if(v==null||!Number.isFinite(v)||this.skipZero&&v===0)return;const color=this.colorFor(di,s),paint=this.markPaint(di,s);let rectX,y1,y2;if(this.stacked&&stackedSqrt)if(rectX=slotStart,v>=0){const total=posTotals.get(i)??0,shareLo=total>0?stackPos/total:0,nextStackPos=finiteAdd(stackPos,v),shareHi=total>0?nextStackPos/total:0;y1=zeroY-shareHi*posCompressedH,y2=zeroY-shareLo*posCompressedH,stackPos=nextStackPos}else{const total=-(negTotals.get(i)??0),shareLo=-stackNeg/total,nextStackNeg=finiteAdd(stackNeg,v),shareHi=-nextStackNeg/total;y1=zeroY+shareLo*negCompressedH,y2=zeroY+shareHi*negCompressedH,stackNeg=nextStackNeg}else if(this.stacked)if(rectX=slotStart,v>=0){const naturalH=clampSvgLength(Math.max(0,zeroY-this.barValueToY(v,plotY,plotH,lo,hi))),segH=clampSvgLength(minBarHeight!=null&&v!==0&&naturalH<minBarHeight?minBarHeight:naturalH);y2=posPixelTop,y1=clampSvgCoordinate(finiteAdd(posPixelTop,-segH),posPixelTop),posPixelTop=y1}else{const naturalH=clampSvgLength(Math.max(0,this.barValueToY(v,plotY,plotH,lo,hi)-zeroY)),segH=clampSvgLength(minBarHeight!=null&&v!==0&&naturalH<minBarHeight?minBarHeight:naturalH);y1=negPixelBottom,y2=clampSvgCoordinate(finiteAdd(negPixelBottom,segH),negPixelBottom),negPixelBottom=y2}else{rectX=slotStart+sampledDatasetIndex*(barW+BAR_GAP*slot);const zeroClamped=Math.min(hi,Math.max(lo,0)),barValLo=Math.min(zeroClamped,v),barValHi=Math.max(zeroClamped,v);y1=this.barValueToY(barValHi,plotY,plotH,lo,hi),y2=this.barValueToY(barValLo,plotY,plotH,lo,hi)}rectX=clampSvgCoordinate(rectX,plotX),y1=clampSvgCoordinate(y1),y2=clampSvgCoordinate(y2);const label=this.labels[i]??"",titleText=this.resolvePointText(label,v,di)??this.localize("liteChartBarLabel",void 0,{series:s.label,label,value:numberFormat.format(v)}),w=clampSvgLength(Math.max(0,barW));let h=clampSvgLength(Math.max(0,y2-y1));if(!(this.stacked&&!stackedSqrt)&&minBarHeight!=null&&v!==0&&h<minBarHeight){const extra=minBarHeight-h;y1=clampSvgCoordinate(finiteAdd(y1,-extra),y1),h=clampSvgLength(Math.max(0,y2-y1))}const markIndex=markIndexes.get(`${di}:${i}`),selected=selectedIndices.has(i),intraGroupSpacing=barW+BAR_GAP*slot,crossCategorySpacing=slot-Math.max(0,groupCount-1)*intraGroupSpacing,horizontalSpacing=Math.max(0,groupCount>1?Math.min(intraGroupSpacing,crossCategorySpacing):slot),hitWidth=clampSvgLength(Math.max(w,Math.min(24,horizontalSpacing))),hitHeight=this.stacked?h:clampSvgLength(Math.max(24,h)),hitX=clampSvgCoordinate(rectX-(hitWidth-w)/2,rectX),hitY=clampSvgCoordinate(y1-(hitHeight-h)/2,y1),hitTarget=svg`
32
32
  <rect
33
33
  data-mark-hit-target="bar"
@@ -120,7 +120,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
120
120
  d=${d.trim()}
121
121
  stroke=${color}
122
122
  stroke-dasharray=${this.markDash(di)}
123
- ></path>${dots}`})}render(){return this.renderChart()}visibleLabelIndexes(n){if(this.maxLabels==null)return;const max=finiteCount(this.maxLabels,n);if(n<=max)return;const count=Math.min(n,MAX_RENDERED_CHART_RECORDS,Math.max(2,max));return count<=1?new Set(n===1?[0]:[]):new Set(Array.from({length:count},(_,index)=>Math.round(index*(n-1)/(count-1))))}displayCategoryLabel(label,availableWidth){const maxCharacters=Math.max(1,Math.floor(availableWidth/APPROX_LABEL_CHARACTER_WIDTH));return label.length<=maxCharacters?label:maxCharacters===1?"\u2026":`${label.slice(0,maxCharacters-1)}\u2026`}renderChart(){const n=this.recordCount(),awaitingFitMeasurement=this.awaitingFitMeasurement(),h=finiteRange(this.plotHeight||200,200,0,MAX_SCROLL_CONTENT_WIDTH),axisGutter=(this.valueAxisGutter==null?PAD_LEFT:finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH))+(this.yLabel?AXIS_TITLE_SPACE:0),rtl=this.effectiveDirection==="rtl",padBottom=PAD_BOTTOM+(this.xLabel?AXIS_TITLE_SPACE:0),plotX=rtl?PAD_RIGHT:axisGutter,plotY=PAD_TOP,plotH=Math.max(0,h-plotY-padBottom);let w,plotW,slot;if(this.layout==="scroll"){const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;slot=finiteRange(this.barWidth,32,0,maxSlot),plotW=n*slot,w=axisGutter+plotW+PAD_RIGHT}else w=finiteRange(this.plotWidth||400,400,0,MAX_SCROLL_CONTENT_WIDTH),plotW=Math.max(0,w-axisGutter-PAD_RIGHT),slot=n>0?plotW/n:0;const{lo,hi,ticks}=this.domain(),recordSample=this.recordSample(),selectedIndices=new Set,renderedRows=new Set(recordSample.rowIndexes);for(let index=0;index<Math.min(this.selectedIndices.length,MAX_RENDERED_CHART_RECORDS);index++){const candidate=this.selectedIndices[index];typeof candidate=="number"&&Number.isInteger(candidate)&&renderedRows.has(candidate)&&selectedIndices.add(candidate)}const barOrigins=this.effectiveType==="bar"&&!awaitingFitMeasurement?new Map(recordSample.rowIndexes.map(index=>{const fallback=plotX+index*slot,candidate=typeof this.barX=="function"?this.barX(index):fallback;return[index,finiteRange(candidate,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH)]})):new Map,grid=awaitingFitMeasurement||this.withoutValueAxis?[]:this.renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi),marks=awaitingFitMeasurement?[]:this.effectiveType==="bar"?this.renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices):this.renderLines(plotX,plotY,plotW,plotH,lo,hi,recordSample,selectedIndices),visibleLabelIndexes=this.visibleLabelIndexes(n),decimationStride=visibleLabelIndexes?n/visibleLabelIndexes.size:1,categoryLabelWidth=Math.max(0,decimationStride*(this.effectiveType==="bar"?slot:n>1?plotW/(n-1):plotW)-BAR_CORNER_RADIUS),categoryLabels=awaitingFitMeasurement?[]:recordSample.rowIndexes.map(i=>{const label=this.labels[i]??"";if(visibleLabelIndexes&&!visibleLabelIndexes.has(i))return nothing;const fullLabel=label??"",x=this.effectiveType==="bar"&&n>0?(barOrigins.get(i)??plotX+i*slot)+slot/2:plotX+(n>1?i/(n-1)*plotW:plotW/2),displayLabel=this.displayCategoryLabel(fullLabel,categoryLabelWidth);return svg`<text
123
+ ></path>${dots}`})}render(){return this.renderChart()}resolvedValueAxisGutter(ticks,measuredWidth){if(typeof this.valueAxisGutter=="number")return finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH);if(this.valueAxisGutter!=="auto"||ticks.length===0)return PAD_LEFT;let widest=0;for(const tick of ticks)widest=Math.max(widest,tick.label.length*APPROX_LABEL_CHARACTER_WIDTH);const requested=Math.ceil(widest)+VALUE_AXIS_TICK_OFFSET+AUTO_VALUE_AXIS_SAFETY_INSET,maximum=this.layout==="scroll"?MAX_AUTO_VALUE_AXIS_GUTTER:Math.max(PAD_LEFT,Math.min(MAX_AUTO_VALUE_AXIS_GUTTER,measuredWidth*MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION));return finiteRange(requested,PAD_LEFT,PAD_LEFT,maximum)}automaticMaxLabels(n,plotW,renderedIndexes){if(n<=1)return n;let widest=0;for(const index of renderedIndexes){const label=this.labels[index]??"";widest=Math.max(widest,label.length*APPROX_LABEL_CHARACTER_WIDTH)}if(widest===0)return n;const lane=widest+AUTO_CATEGORY_LABEL_INSET,fits=Math.floor(finiteRange(plotW,0,0,MAX_SCROLL_CONTENT_WIDTH)/lane);return Math.min(n,Math.max(2,fits))}visibleLabelIndexes(n,plotW,renderedIndexes){if(this.maxLabels==null)return;const requested=this.maxLabels==="auto"?this.automaticMaxLabels(n,plotW,renderedIndexes):this.maxLabels;if(typeof requested!="number")return;const max=finiteCount(requested,n);if(n<=max)return;const count=Math.min(n,MAX_RENDERED_CHART_RECORDS,Math.max(2,max));return count<=1?new Set(n===1?[0]:[]):new Set(Array.from({length:count},(_,index)=>Math.round(index*(n-1)/(count-1))))}displayCategoryLabel(label,availableWidth){const maxCharacters=Math.max(1,Math.floor(availableWidth/APPROX_LABEL_CHARACTER_WIDTH));return label.length<=maxCharacters?label:maxCharacters===1?"\u2026":`${label.slice(0,maxCharacters-1)}\u2026`}renderChart(){const n=this.recordCount(),awaitingFitMeasurement=this.awaitingFitMeasurement(),h=finiteRange(this.plotHeight||200,200,0,MAX_SCROLL_CONTENT_WIDTH),measuredWidth=finiteRange(this.plotWidth||400,400,0,MAX_SCROLL_CONTENT_WIDTH),{lo,hi,ticks}=this.domain(),formattedTicks=awaitingFitMeasurement||this.withoutValueAxis?[]:ticks.map(value=>({value,label:this.formatValueAxisTick(value)})),axisGutter=this.resolvedValueAxisGutter(formattedTicks,measuredWidth)+(this.yLabel?AXIS_TITLE_SPACE:0),rtl=this.effectiveDirection==="rtl",padBottom=PAD_BOTTOM+(this.xLabel?AXIS_TITLE_SPACE:0),plotX=rtl?PAD_RIGHT:axisGutter,plotY=PAD_TOP,plotH=Math.max(0,h-plotY-padBottom);let w,plotW,slot;if(this.layout==="scroll"){const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;slot=finiteRange(this.barWidth,32,0,maxSlot),plotW=n*slot,w=axisGutter+plotW+PAD_RIGHT}else w=measuredWidth,plotW=Math.max(0,w-axisGutter-PAD_RIGHT),slot=n>0?plotW/n:0;const recordSample=this.recordSample(),selectedIndices=new Set,renderedRows=new Set(recordSample.rowIndexes);for(let index=0;index<Math.min(this.selectedIndices.length,MAX_RENDERED_CHART_RECORDS);index++){const candidate=this.selectedIndices[index];typeof candidate=="number"&&Number.isInteger(candidate)&&renderedRows.has(candidate)&&selectedIndices.add(candidate)}const barOrigins=this.effectiveType==="bar"&&!awaitingFitMeasurement?new Map(recordSample.rowIndexes.map(index=>{const fallback=plotX+index*slot,candidate=typeof this.barX=="function"?this.barX(index):fallback;return[index,finiteRange(candidate,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH)]})):new Map,grid=awaitingFitMeasurement||this.withoutValueAxis?[]:this.renderGrid(plotX,plotY,plotW,plotH,formattedTicks,lo,hi),marks=awaitingFitMeasurement?[]:this.effectiveType==="bar"?this.renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices):this.renderLines(plotX,plotY,plotW,plotH,lo,hi,recordSample,selectedIndices),visibleLabelIndexes=this.visibleLabelIndexes(n,plotW,recordSample.rowIndexes),decimationStride=visibleLabelIndexes?n/visibleLabelIndexes.size:1,categoryLabelWidth=Math.max(0,decimationStride*(this.effectiveType==="bar"?slot:n>1?plotW/(n-1):plotW)-BAR_CORNER_RADIUS),categoryLabels=awaitingFitMeasurement?[]:recordSample.rowIndexes.map(i=>{const label=this.labels[i]??"";if(visibleLabelIndexes&&!visibleLabelIndexes.has(i))return nothing;const fullLabel=label??"",x=this.effectiveType==="bar"&&n>0?(barOrigins.get(i)??plotX+i*slot)+slot/2:plotX+(n>1?i/(n-1)*plotW:plotW/2),displayLabel=this.displayCategoryLabel(fullLabel,categoryLabelWidth);return svg`<text
124
124
  part="axis-label"
125
125
  x=${x}
126
126
  y=${plotY+plotH+CATEGORY_LABEL_OFFSET}
@@ -203,4 +203,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
203
203
  `})}
204
204
  </div>`:nothing}
205
205
  </div>
206
- `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
206
+ `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({converter:autoNumberConverter,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({converter:autoNumberConverter,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
@@ -23,24 +23,7 @@ import type { ShikiTransformer } from './shiki-types.js';
23
23
  import type { LyraAnchor, LyraHighlight, TextSelectRect } from '../../viewers/document-viewer/anchors.js';
24
24
  /** Matches `LyraElement.localize()`'s signature so either component's bound
25
25
  * method can be passed straight through. */
26
- export type LyraLocalizeFn = (key: string, fallback?: string, values?: Record<string, string | number>) => string;
27
- /** The collapse/expand header toggle button's `aria-label`. */
28
- export declare function codeBlockToggleLabel(localize: LyraLocalizeFn, collapsed: boolean): string;
29
- /** The copy-to-clipboard header button's `aria-label`. */
30
- export declare function codeBlockCopyLabel(localize: LyraLocalizeFn, justCopied: boolean, copyFailed: boolean): string;
31
- /** The `[part="body"]` region's `aria-label`: the filename when set, else a
32
- * language-aware "Code" region label. */
33
- export declare function codeBlockBodyLabel(localize: LyraLocalizeFn, filename: string, language: string): string;
34
- /**
35
- * Parses a `highlight-lines` attribute value (e.g. `"3-5,7"`) into the set of one-based line
36
- * numbers it addresses: comma-separated segments, each either a single line number or an
37
- * inclusive range, whitespace around commas/dashes tolerated, a reversed range (`"5-3"`)
38
- * normalized to ascending order. An invalid segment is skipped (with a `console.warn`) rather
39
- * than throwing or discarding the otherwise-valid segments around it.
40
- */
41
- export declare function addBoundedLineRange(lines: Set<number>, start: number, end: number, maxLine: number): void;
42
- /** How long the copy button's confirmation state lasts before reverting. */
43
- export declare const CODE_BLOCK_COPY_CONFIRM_MS = 1500;
26
+ type LyraLocalizeFn = (key: string, fallback?: string, values?: Record<string, string | number>) => string;
44
27
  /** One-based line count of `code`, the upper bound every line-addressing helper below clamps to.
45
28
  * A trailing newline still yields the (empty) line after it, matching the rendered line count. */
46
29
  export declare function codeBlockLineCount(code: string): number;
@@ -80,26 +63,12 @@ export declare function scrollCodeBlockToAnchor(host: CodeBlockAnchorHost, targe
80
63
  /** The one-based gutter line an event originated in, or `null` when it didn't come from a line
81
64
  * button at all. */
82
65
  export declare function codeBlockEventLine(e: Event): number | null;
83
- /** What a keystroke on a gutter line button means. `null` covers both an unhandled key and a
84
- * movement key that would land on the line already focused -- neither of which may
85
- * `preventDefault()`, so the caller must not treat them differently. */
86
- export type CodeBlockLineKeyAction = {
87
- kind: 'activate';
88
- } | {
89
- kind: 'move';
90
- line: number;
91
- } | null;
92
- /** The roving-tabindex keyboard contract for the (`line-numbers`-gated) gutter. */
93
- export declare function codeBlockLineKeyAction(key: string, line: number, total: number): CodeBlockLineKeyAction;
94
66
  /** An `lr-text-select` payload for a selection ending inside `[part="body"]`. */
95
- export interface CodeBlockSelection {
67
+ interface CodeBlockSelection {
96
68
  readonly text: string;
97
69
  readonly anchor: LyraAnchor;
98
70
  readonly rects: readonly TextSelectRect[];
99
71
  }
100
- /** Anchors the current selection to the `line-range` it spans. `null` whenever there's nothing to
101
- * report: no selection, a collapsed/whitespace-only one, or endpoints outside any `[data-line]`. */
102
- export declare function codeBlockSelectionAnchor(shadowRoot: ShadowRoot | null): CodeBlockSelection | null;
103
72
  /** Every property whose change invalidates the cached `highlightedHtml`. */
104
73
  export declare function codeBlockNeedsHighlightResync(changed: PropertyValues): boolean;
105
74
  /**
@@ -182,26 +151,6 @@ export interface CodeBlockPlainCodeOptions {
182
151
  * separate real button, leaving source text selectable in both plain and highlighted output.
183
152
  */
184
153
  export declare function renderCodeBlockPlainCode(options: CodeBlockPlainCodeOptions): TemplateResult;
185
- export interface CodeBlockHeaderOptions {
186
- collapsible: boolean;
187
- collapsed: boolean;
188
- /** `id` of `[part="body"]`, for the toggle's `aria-controls`. */
189
- bodyId: string;
190
- filename: string;
191
- language: string;
192
- copyable: boolean;
193
- justCopied: boolean;
194
- copyFailed: boolean;
195
- localize: LyraLocalizeFn;
196
- onToggle: () => void;
197
- onCopy: () => void;
198
- }
199
- /**
200
- * The header row above the code (filename/language/copy/toggle) shared by `<lr-code-block>` and
201
- * `<lr-code-block-core>`. `aria-expanded` renders both `"true"` and `"false"` rather than being
202
- * conditionally omitted -- the collapse toggle's state is meaningless to assistive tech otherwise.
203
- */
204
- export declare function renderCodeBlockHeader(options: CodeBlockHeaderOptions): TemplateResult;
205
154
  export interface CodeBlockShellOptions {
206
155
  filename: string;
207
156
  language: string;
@@ -244,7 +193,7 @@ export declare function renderCodeBlockShell(options: CodeBlockShellOptions): Te
244
193
  /** The element surface {@linkcode CodeBlockInteractionController} reads. Every member is either
245
194
  * native to `HTMLElement` or already public on both code-block variants, so routing through the
246
195
  * controller widens neither component's own API. */
247
- export interface CodeBlockInteractionHost extends HTMLElement {
196
+ interface CodeBlockInteractionHost extends HTMLElement {
248
197
  readonly renderRoot: HTMLElement | DocumentFragment;
249
198
  readonly updateComplete: Promise<boolean>;
250
199
  readonly code: string;
@@ -306,3 +255,4 @@ export declare class CodeBlockInteractionController {
306
255
  copy: () => Promise<void>;
307
256
  toggleCollapsed: () => void;
308
257
  }
258
+ export {};
@@ -71,4 +71,4 @@ import{html,nothing}from"lit";import{unsafeHTML}from"lit/directives/unsafe-html.
71
71
  ${options.showSkeleton?html`<lr-skeleton shape="rect" .announce=${!1}></lr-skeleton>`:options.highlightedHtml!==null?unsafeHTML(options.highlightedHtml):html`<pre part="pre" class=${options.lineNumbers?"line-numbers":nothing}>${options.renderPlainCode()}</pre>`}
72
72
  </div>
73
73
  </div>
74
- `}class CodeBlockInteractionController{constructor(options){this.options=options,this.copyGeneration=0,this.onLineActivate=line=>{this.setFocusedLine(line),this.options.emitLineActivate(line)},this.onLineKeyDown=(e,line)=>{const{host}=this.options,action=codeBlockLineKeyAction(e.key,line,codeBlockLineCount(host.code));if(action===null)return;if(e.preventDefault(),action.kind==="activate"){this.onLineActivate(line);return}const next=action.line;this.setFocusedLine(next),host.updateComplete.then(()=>{host.renderRoot.querySelector(`[part~="line-button"][data-line="${next}"]`)?.focus()})},this.onBodyClick=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineActivate(line)},this.onBodyKeyDown=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineKeyDown(e,line)},this.onBodyFocusIn=e=>{const line=codeBlockEventLine(e);line!==null&&this.setFocusedLine(line)},this.onBodyMouseUp=()=>{const selection=codeBlockSelectionAnchor(this.options.host.shadowRoot);selection&&this.options.emitTextSelect(selection)},this.copy=async()=>{const{host}=this.options,owner=host.isConnected?host.ownerDocument.defaultView:null,text=host.code,generation=++this.copyGeneration;this.cancelCopyTimer(),this.setCopyStatus("rest");const outcome=await writeClipboardText(owner,text);if(!owner||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration)return;outcome.ok?(this.options.emitCopy(outcome),this.setCopyStatus("success")):(this.setCopyStatus("error"),this.options.emitError(),this.options.emitCopyError(outcome));let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration||(this.copyTimer=void 0,this.setCopyStatus("rest"))},CODE_BLOCK_COPY_CONFIRM_MS),this.copyTimer={owner,handle}},this.toggleCollapsed=()=>{const{host}=this.options,collapsed=!host.collapsed;this.options.requestToggle(collapsed)&&(host.collapsed=collapsed,this.options.emitToggle(host.collapsed))}}refreshTheme(){this.options.setDarkTheme(resolveIsDarkTheme(this.options.host))}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}disconnect(){this.copyGeneration++,this.cancelCopyTimer(),this.options.setJustCopied(!1),this.options.setCopyFailed(!1)}setCopyStatus(status){this.options.setJustCopied(status==="success"),this.options.setCopyFailed(status==="error")}setFocusedLine(line){this.options.setFocusedLine(line);for(const target of this.options.host.renderRoot.querySelectorAll('[data-line][part~="line-button"]'))target.tabIndex=Number(target.dataset.line)===line?0:-1}}export{CODE_BLOCK_COPY_CONFIRM_MS,CodeBlockInteractionController,addBoundedLineRange,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockBodyLabel,codeBlockCopyLabel,codeBlockEventLine,codeBlockLineCount,codeBlockLineHasFocus,codeBlockLineHighlightSet,codeBlockLineKeyAction,codeBlockLineTransformer,codeBlockNeedsHighlightResync,codeBlockPreSuppliedGrammar,codeBlockSelectionAnchor,codeBlockShowsSkeleton,codeBlockToggleLabel,parseHighlightLines,renderCodeBlockHeader,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock};
74
+ `}class CodeBlockInteractionController{constructor(options){this.options=options,this.copyGeneration=0,this.onLineActivate=line=>{this.setFocusedLine(line),this.options.emitLineActivate(line)},this.onLineKeyDown=(e,line)=>{const{host}=this.options,action=codeBlockLineKeyAction(e.key,line,codeBlockLineCount(host.code));if(action===null)return;if(e.preventDefault(),action.kind==="activate"){this.onLineActivate(line);return}const next=action.line;this.setFocusedLine(next),host.updateComplete.then(()=>{host.renderRoot.querySelector(`[part~="line-button"][data-line="${next}"]`)?.focus()})},this.onBodyClick=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineActivate(line)},this.onBodyKeyDown=e=>{if(e.composedPath()[0]?.closest?.("button[data-inline-handler]"))return;const line=codeBlockEventLine(e);line!==null&&this.onLineKeyDown(e,line)},this.onBodyFocusIn=e=>{const line=codeBlockEventLine(e);line!==null&&this.setFocusedLine(line)},this.onBodyMouseUp=()=>{const selection=codeBlockSelectionAnchor(this.options.host.shadowRoot);selection&&this.options.emitTextSelect(selection)},this.copy=async()=>{const{host}=this.options,owner=host.isConnected?host.ownerDocument.defaultView:null,text=host.code,generation=++this.copyGeneration;this.cancelCopyTimer(),this.setCopyStatus("rest");const outcome=await writeClipboardText(owner,text);if(!owner||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration)return;outcome.ok?(this.options.emitCopy(outcome),this.setCopyStatus("success")):(this.setCopyStatus("error"),this.options.emitError(),this.options.emitCopyError(outcome));let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||!host.isConnected||host.ownerDocument.defaultView!==owner||generation!==this.copyGeneration||(this.copyTimer=void 0,this.setCopyStatus("rest"))},CODE_BLOCK_COPY_CONFIRM_MS),this.copyTimer={owner,handle}},this.toggleCollapsed=()=>{const{host}=this.options,collapsed=!host.collapsed;this.options.requestToggle(collapsed)&&(host.collapsed=collapsed,this.options.emitToggle(host.collapsed))}}refreshTheme(){this.options.setDarkTheme(resolveIsDarkTheme(this.options.host))}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}disconnect(){this.copyGeneration++,this.cancelCopyTimer(),this.options.setJustCopied(!1),this.options.setCopyFailed(!1)}setCopyStatus(status){this.options.setJustCopied(status==="success"),this.options.setCopyFailed(status==="error")}setFocusedLine(line){this.options.setFocusedLine(line);for(const target of this.options.host.renderRoot.querySelectorAll('[data-line][part~="line-button"]'))target.tabIndex=Number(target.dataset.line)===line?0:-1}}export{CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockEventLine,codeBlockLineCount,codeBlockLineHasFocus,codeBlockLineHighlightSet,codeBlockLineTransformer,codeBlockNeedsHighlightResync,codeBlockPreSuppliedGrammar,codeBlockShowsSkeleton,parseHighlightLines,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock};