@aceshooting/lyra-ui 28.1.1 → 28.1.2
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.
- package/CHANGELOG.md +26 -0
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +3 -3
- package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/utility/tour/tour.class.js +4 -4
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-push-to-talk.md +3 -0
- package/llms/peers.md +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 28.1.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- The release version stamp changes compressed bundle measurements by 1–3 bytes. Two direct-entry and five initial-marginal ceilings advance to those exact measurements without added allowance; bundle inputs and all passing ceilings remain unchanged.
|
|
8
|
+
|
|
9
|
+
- ea2a845: Avoid a redundant Chart.js update after accepted dataset legend actions in charts and box plots. Visibility still updates synchronously before the committed event; coalesced data changes, controlled resets, inherited context, accessible tables, and synchronization continue to reconcile normally.
|
|
10
|
+
|
|
11
|
+
Six aggregate bundle ceilings increase by 69–359 gzip bytes to their exact measured sizes, with no added headroom, for the peer and visibility checks that prevent duplicate updates. Individual-component and initial-route ceilings remain unchanged.
|
|
12
|
+
- 4ceefc4: Keep slotted accessible names current when responsive panels and widgets move between connected documents, and restore inherited locale updates for responsive panels. Owner-realm subscriptions now finish teardown before overlay teardown, allowing the connected destination to bind its own observations.
|
|
13
|
+
|
|
14
|
+
The connection cleanup ordering adds 28–33 gzip bytes to five aggregate entry bundles and 3 bytes to the component percentile. Their reviewed ceilings advance to those exact measurements without extra allowance; other bundle ceilings and measurement options are unchanged.
|
|
15
|
+
- 7a119cc: Keep textarea auto sizing, page allocation frames, and initial menu, popover, dropdown, and accordion ownership inactive while disconnected. Restore current content and geometry on reconnect, and ignore callbacks retired by reconnection or document adoption.
|
|
16
|
+
|
|
17
|
+
The lifecycle guards add 81 gzip bytes to the complete registration bundle and 30 bytes to the menu's initial route. Only breached bundle ceilings advance to their exact measured sizes, with no added allowance.
|
|
18
|
+
- b3cc650: Keep heatmap PNG export empty while detached, including when a pending update flushes after removal, and repaint current data on reconnect. Defer graph simulation and force updates until reconnect, then rebind the current renderer and its interaction targets. Six aggregate bundle ceilings rise only to their measured gzip bytes for these lifecycle guards; component, CSS, and initial-route ceilings remain unchanged.
|
|
19
|
+
- 829c00d: Keep image-viewer geometry observers, span-waterfall axis observers, and flow-canvas companion notifications inactive while detached, including pending updates that finish after removal. Restore current geometry and companion snapshots on reconnect, and ignore stale callbacks from a previous document or observation. Eight aggregate bundle ceilings increase only to the measured gzip bytes required by these lifecycle guards, without added headroom; passing component, CSS, and initial-route ceilings remain unchanged.
|
|
20
|
+
- e607435: Avoid development warnings for the standard `form` owner attribute on form-associated custom elements.
|
|
21
|
+
- bfd071f: Keep push-to-talk recording active when its optional audio-level analysis cannot initialize, including when level events are enabled during capture. Close partially initialized audio contexts without reporting a recorder failure or rejecting the component update; microphone capture and normal stop behavior remain available.
|
|
22
|
+
|
|
23
|
+
The optional-analysis guard adds 7–10 gzip bytes to five complete or conversation entry bundles. Their previously exact ceilings advance only to the reviewed measurements, with no extra allowance; passing ceilings and optional-peer exclusions remain unchanged.
|
|
24
|
+
- e449f0b: Restore the tour backdrop and spotlight cutout by rendering their shapes in the SVG namespace. Keep the spotlight aligned when its target resizes, and fill the backdrop when the target is missing.
|
|
25
|
+
|
|
26
|
+
Reuse one scrim, formatted progress text and scoped geometry lookups to reduce repeated rendering work. The corrected SVG rendering requires three additional gzip bytes in the complete registration bundle and four in the tour initial marginal bundle after these reductions. Their reviewed ceilings advance to exactly 1,269,107 and 18,769 bytes, with no additional allowance; other budgets and measurement inputs are unchanged.
|
|
27
|
+
- @aceshooting/lyra-translations@28.1.2
|
|
28
|
+
|
|
3
29
|
## 28.1.1
|
|
4
30
|
|
|
5
31
|
### Patch Changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"../trace-tree/span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut}from"../../../internal/default-strings/shared.generated.js";const KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;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 axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=normalizeLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache}viewWindow(){this.sortedSpans();const fallbackEnd=Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1),start=this.viewStartMs==null?0:finiteRange(this.viewStartMs,0,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){return this.localize("spanProjectionLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(MAX_RENDERED_LYRA_SPANS)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),(changed.has("spans")||changed.has("activeSpanId"))&&(this.sortedSource=void 0),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId")){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated&&this.announcements.announcePolite(this.projectionLimitText()),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;!axis||!ResizeObserverCtor||(this.axisObserver??=new ResizeObserverCtor(()=>this.fitAxisLabels()),this.axisObserver.observe(axis))}fitAxisLabels(){const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"../trace-tree/span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut}from"../../../internal/default-strings/shared.generated.js";const KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;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 axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=normalizeLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache}viewWindow(){this.sortedSpans();const fallbackEnd=Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1),start=this.viewStartMs==null?0:finiteRange(this.viewStartMs,0,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){return this.localize("spanProjectionLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(MAX_RENDERED_LYRA_SPANS)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),(changed.has("spans")||changed.has("activeSpanId"))&&(this.sortedSource=void 0),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId")){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated&&this.announcements.announcePolite(this.projectionLimitText()),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(!axis||!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.axisObserver!==observer||this.fitAxisLabels()});this.axisObserver=observer,observer.observe(axis)}fitAxisLabels(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
2
2
|
<div part="axis" aria-hidden="true">
|
|
3
3
|
${ticks.map(t=>{const pct=finiteRatio(t,view.start,view.end)*100;return pct<0||pct>100?nothing:html`<span
|
|
4
4
|
part="tick"
|
|
@@ -103,7 +103,7 @@ export interface LyraBoxPlotPointDetail{datasetIndex:number;index:number;label:s
|
|
|
103
103
|
* @status stable
|
|
104
104
|
* @since 4.0.0
|
|
105
105
|
*/
|
|
106
|
-
export declare class LyraBoxPlot extends LyraElement<LyraBoxPlotEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];protected static readonly immutableEventDetails:readonly string[];constructor();private readonly canvasTokens;labels:readonly string[];private _datasets;private datasetsSource;
|
|
106
|
+
export declare class LyraBoxPlot extends LyraElement<LyraBoxPlotEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];protected static readonly immutableEventDetails:readonly string[];constructor();private readonly canvasTokens;private appliedLegendVisibility?;labels:readonly string[];private _datasets;private datasetsSource;
|
|
107
107
|
/**
|
|
108
108
|
* Series with an array `data` payload. Malformed entries are dropped without hiding siblings.
|
|
109
109
|
* A bounded, clone-owned readonly snapshot: each series keeps at most its first
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){if(super.updated(changed),!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??formatChartValue(value,this.effectiveLocale)}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const visibilityAlreadyApplied=appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.hiddenDatasets,contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)&&(name!=="hiddenDatasets"||!visibilityAlreadyApplied)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.appliedLegendVisibility=void 0,this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??formatChartValue(value,this.effectiveLocale)}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
2
2
|
`)}boxPlotDescription(){if(this.description)return this.description;const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample(),datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){const hit=chart.getElementsAtEventForMode?.(event,"nearest",{intersect:!0},!0)?.[0];if(!hit)return;const sample=this.dataTableSample(),datasetIndex=sample.seriesIndexes[hit.datasetIndex],index=sample.rowIndexes[hit.index];if(datasetIndex===void 0||index===void 0)return;const point=this.datasets[datasetIndex]?.data[index];this.activateBox({datasetIndex,index,label:this.labels[index]||void 0,value:this.validPoint(point)?summaryOf(point):null})}showKeyboardBox(datum){if(!this.chart||!datum&&!this.keyboardBoxShown)return;const sample=this.dataTableSample();this.keyboardBoxShown=showChartActiveDatum(this.chart,datum&&{datasetIndex:sample.seriesIndexes.indexOf(datum.datasetIndex),index:sample.rowIndexes.indexOf(datum.index)})}onCanvasFocus(event){const datums=this.boxDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),isKeyboardFocusEvent(event)&&this.showKeyboardBox(datums[this.keyboardDatumIndex]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.boxDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateBox(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.showKeyboardBox(datums[next]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[next],next,datums.length)}validPoint(point){return!!point&&[point.min,point.q1,point.median,point.q3,point.max].every(Number.isFinite)&&point.min<=point.q1&&point.q1<=point.median&&point.median<=point.q3&&point.q3<=point.max}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}dataTableSample(){let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,series.data.length);const indexes=sampleChartTableIndexes(rowCount,this.datasets.length);return{rowCount,seriesCount:this.datasets.length,...indexes}}generatedDataIsSampled(){const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}requestUpdate(...args){args[0]!=="keyboardDatumAnnouncement"&&(this.dataTableRows=void 0),super.requestUpdate(...args)}renderDataTableRows(){if(this.dataTableRows)return this.dataTableRows;const numberFormat=getNumberFormat(this.effectiveLocale),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",sample=this.dataTableSample();return this.dataTableRows=sample.seriesIndexes.flatMap(seriesIndex=>{const series=this.datasets[seriesIndex];return sample.rowIndexes.map(index=>{const point=series.data[index],metadata={datasetIndex:seriesIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};return this.validPoint(point)?html`
|
|
3
3
|
<tr>
|
|
4
4
|
<th scope="row">${isolateHtml(this.labels[index]||this.localize("chartPointLabel",void 0,{n:numberFormat.format(index+1)}),direction)}</th>
|
|
@@ -27,7 +27,7 @@ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}
|
|
|
27
27
|
${this.renderDataTableRows()}
|
|
28
28
|
</tbody>
|
|
29
29
|
</table>
|
|
30
|
-
`}hasCustomDataTable(){return hasSlottedChartDataTable(this)}toggleDataset(index){if(!this.chart||index<0||index>=this.datasets.length)return;const hidden=this.effectiveHiddenDatasetIndexes(),wasHidden=hidden.includes(index),nextHidden=wasHidden?hidden.filter(candidate=>candidate!==index):[...hidden,index].sort((left,right)=>left-right),visible=wasHidden;this.emit("lr-legend-visibility-change-request",legendVisibilityDetail(index,visible,nextHidden),{cancelable:!0}).defaultPrevented
|
|
30
|
+
`}hasCustomDataTable(){return hasSlottedChartDataTable(this)}toggleDataset(index){if(!this.chart||index<0||index>=this.datasets.length)return;const hidden=this.effectiveHiddenDatasetIndexes(),wasHidden=hidden.includes(index),nextHidden=wasHidden?hidden.filter(candidate=>candidate!==index):[...hidden,index].sort((left,right)=>left-right),visible=wasHidden;if(this.emit("lr-legend-visibility-change-request",legendVisibilityDetail(index,visible,nextHidden),{cancelable:!0}).defaultPrevented)return;this.hiddenDatasets=nextHidden;const appliedVisibility={chart:this.chart,hidden:this.hiddenDatasets};this.applyDatasetVisibility(),this.chart.update("none"),this.appliedLegendVisibility=appliedVisibility,this.requestUpdate(),this.emit("lr-legend-visibility-change",legendVisibilityDetail(index,visible,nextHidden))}renderLegend(){if(!this.withLegend)return nothing;const palette=this.canvasTokens.palette(),forced=forcedColorsActive(this.ownerWindow),controlledHidden=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length),controlledHiddenSet=controlledHidden===void 0?void 0:new Set(controlledHidden),sample=this.dataTableSample();return html`
|
|
31
31
|
<div part="legend" role="group" aria-label=${this.accessibleName(this.localize("boxPlot"))}>
|
|
32
32
|
${sample.seriesIndexes.map(index=>{const series=this.datasets[index],color=this.seriesFillColor(index,palette),visible=controlledHiddenSet===void 0||!controlledHiddenSet.has(index),encoding=forced?forcedColorEncoding(index).name:void 0;return html`
|
|
33
33
|
<button
|
|
@@ -281,7 +281,7 @@ export interface LyraChartDatumActivateDetail<TKind extends LyraChartDatumKind=L
|
|
|
281
281
|
* @status stable
|
|
282
282
|
* @since 4.0.0
|
|
283
283
|
*/
|
|
284
|
-
export declare class LyraChart extends LyraElement<LyraChartEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];constructor();private readonly canvasTokens;type:LyraChartType;labels:string[];private labelsSnapshot?;private annotationsSnapshot?;private hiddenDatasetsSnapshot?;private canonicalLabels;private canonicalAnnotations;private canonicalHiddenDatasets;private _datasets;private datasetsSource;
|
|
284
|
+
export declare class LyraChart extends LyraElement<LyraChartEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly immutableEventDetails:readonly string[];protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];constructor();private readonly canvasTokens;type:LyraChartType;labels:string[];private labelsSnapshot?;private annotationsSnapshot?;private appliedLegendVisibility?;private hiddenDatasetsSnapshot?;private canonicalLabels;private canonicalAnnotations;private canonicalHiddenDatasets;private _datasets;private datasetsSource;
|
|
285
285
|
/** Simplified chart series. Non-record entries are dropped while valid sibling series remain. */
|
|
286
286
|
get datasets():readonly LyraChartSeries[];set datasets(value:readonly LyraChartSeries[]);
|
|
287
287
|
/**
|