@aceshooting/lyra-ui 28.0.0 → 28.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 (85) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
  3. package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
  4. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  5. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  6. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
  7. package/dist/components/charts/chart/box-plot.class.d.ts +5 -3
  8. package/dist/components/charts/chart/box-plot.class.js +18 -17
  9. package/dist/components/charts/chart/chart.class.d.ts +6 -4
  10. package/dist/components/charts/chart/chart.class.js +19 -18
  11. package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
  12. package/dist/components/charts/chart/lite-chart.class.js +8 -8
  13. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  14. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  15. package/dist/components/data/data-grid/data-grid-processing.js +1 -1
  16. package/dist/components/data/gauge/gauge.class.js +1 -1
  17. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
  18. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  19. package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
  20. package/dist/components/data/heatmap/heatmap.class.d.ts +3 -2
  21. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  22. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  23. package/dist/components/data/stat/stat.class.d.ts +11 -9
  24. package/dist/components/data/stat/stat.class.js +4 -2
  25. package/dist/components/data/tree/tree.class.js +1 -1
  26. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  27. package/dist/components/forms/color-picker/color-picker.class.js +3 -3
  28. package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
  29. package/dist/components/forms/combobox/combobox.class.js +1 -1
  30. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  31. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  32. package/dist/components/forms/select/select.class.js +4 -3
  33. package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
  34. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  35. package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
  36. package/dist/components/layout/menu/menu.class.js +1 -1
  37. package/dist/components/layout/menubar/menubar.class.js +1 -1
  38. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
  39. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  40. package/dist/components/layout/page/page.class.js +1 -1
  41. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  42. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
  43. package/dist/components/media/file-input/file-input.class.js +1 -1
  44. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  45. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
  46. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
  47. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  48. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  49. package/dist/components/retrieval/graph/graph-canvas.js +1 -1
  50. package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
  51. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  52. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  53. package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
  54. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
  55. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
  56. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  57. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  58. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  59. package/dist/framework-types.d.ts +1 -1
  60. package/dist/internal/default-strings/charts.generated.js +1 -1
  61. package/dist/internal/localization-types.d.ts +1 -1
  62. package/dist/internal/localization.js +1 -1
  63. package/dist/internal/native-modal-carrier.js +2 -2
  64. package/dist/internal/nonmodal-overlay-manager.js +1 -1
  65. package/dist/internal/open-overlay-ancestors.js +1 -0
  66. package/dist/internal/open-overlay-raise.styles.js +1 -1
  67. package/dist/internal/overlay-manager.d.ts +2 -0
  68. package/dist/internal/overlay-manager.js +1 -1
  69. package/dist/internal/package-metadata.js +1 -1
  70. package/dist/testing/happy-dom-shims.d.ts +3 -1
  71. package/dist/testing/happy-dom-shims.js +1 -1
  72. package/llms/components/lr-box-plot.md +5 -0
  73. package/llms/components/lr-chart.md +6 -0
  74. package/llms/components/lr-color-picker.md +2 -0
  75. package/llms/components/lr-commit-card.md +3 -2
  76. package/llms/components/lr-heatmap.md +10 -2
  77. package/llms/components/lr-select.md +2 -0
  78. package/llms/components/lr-stat.md +4 -0
  79. package/llms/peers.md +1 -1
  80. package/llms/shared/ai-and-peers.md +44 -0
  81. package/llms/shared/testing-and-utilities.md +14 -1
  82. package/llms/shared.md +58 -1
  83. package/locales.json +138 -138
  84. package/package.json +7 -6
  85. package/registrations.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import{__decorate}from"tslib";import{LazyChartSyncController}from"./chart-sync-lazy.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues,chartSeriesValueLimit}from"./chart-series-bounds.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";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-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{decimalPlaces,finiteAdd,finiteCount,finiteNumber,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{bidiStyles,isolateHtml,isolatedMessage}from"./chart-bidi.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{categoryLabelGrowth,hasCategoryLabelText,sparseCategoryLabelExtent,visibleCategoryLabelIndexes,widestEstimatedCategoryLabel}from"./lite-chart-axis-layout.js";import{LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chart}from"../../../internal/default-strings/shared.generated.js";function isLiteChartSeries(value){return hasArraySeriesData(value)}function normalizeLiteChartSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isLiteChartSeries):[])}catch{return Object.freeze([])}}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,CATEGORY_LABEL_SELECTION_BOUNDS=Object.freeze({characterWidth:APPROX_LABEL_CHARACTER_WIDTH,laneInset:AUTO_CATEGORY_LABEL_INSET,maxContentWidth:MAX_SCROLL_CONTENT_WIDTH,maxRenderedRecords:MAX_RENDERED_CHART_RECORDS});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 snapToStep(value,step){return Number.isFinite(step)&&step>0?Number(value.toFixed(Math.min(decimalPlaces(step),100))):value}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 Number((lo*(1-ratio)+hi*ratio).toPrecision(15))}).filter(Number.isFinite)}function logarithmicTicks(lo,hi,count){if(!(lo>0&&hi>lo)||!Number.isFinite(lo)||!Number.isFinite(hi))return;const start=Math.log10(lo),end=Math.log10(hi),span=end-start;if(!(span>0))return;const decades=span>=1,step=decades?Math.ceil(span/count):niceStep(hi-lo,count);if(!Number.isFinite(step)||step<=0)return[...new Set(safeDomainTicks(lo,hi,count))];const ticks=[lo],minimumGap=decades?step/2:span/(count*2),first=Math.ceil((decades?start:lo)/step);for(let index=0;index<=count+1;index++){const value=decades?10**((first+index)*step):snapToStep((first+index)*step,step);if(!Number.isFinite(value)||value>=hi)break;if(value<=ticks.at(-1))continue;const logarithm=Math.log10(value);logarithm-Math.log10(ticks.at(-1))>=minimumGap&&end-logarithm>=minimumGap&&ticks.push(value)}return ticks.push(hi),ticks}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 snap=value=>snapToStep(value,step),roundedLo=snap(Math.floor(lo/step)*step),roundedHi=snap(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=snap(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=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.stacked=!1,this.tableTotals=!1,this.withDataTable=!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.hostAccessibleLabel=null,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.syncPlot={y:0,height:0},this.syncCategoryPositions=new Map,this.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.categoryLabelFits=new WeakMap,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.syncGroup="",this.chartSync=new LazyChartSyncController(this,(label,index)=>this.syncPresentation(label,index),void 0,target=>target.nodeType===1&&target.hasAttribute("data-mark-index"),()=>this.requestUpdate()),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,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}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=normalizeLiteChartSeries(snapshotPublicCollection(boundChartSeriesValues(value)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}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 bound=chartSeriesValueLimit(this.datasets.length),requested=Math.max(0,finiteCount(maxPoints,0)),limit=requested>0?Math.min(requested,bound):bound;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];this.labels=labels.slice(-limit),this.datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null].slice(-limit)}))}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,axis:"y"})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
2
- `)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.requestUpdate(),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 svgEntry=entries.find(entry=>entry.target===target);if(svgEntry){const box=svgEntry.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=target.getBoundingClientRect();this.plotWidth=rect.width,this.plotHeight=rect.height}}entries.some(entry=>this.axisTitleTargets.has(entry.target))&&this.queueAxisTitleFit()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target),this.syncAxisTitleTargets()}disconnectedCallback(){this.chartSync.disconnect(),super.disconnectedCallback(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){this.chartSync.disconnect(),super.adoptedCallback(),this.requestUpdate(),this.resetResizeObserver(),this.announcements.adopted(),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}resetResizeObserver(){this.axisTitleFrame!==void 0&&(this.resizeObserverDocument?.defaultView?.cancelAnimationFrame(this.axisTitleFrame),this.axisTitleFrame=void 0),this.axisTitleTargets.clear(),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){super.willUpdate(changed);for(const name of changed.keys())name!=="activeMarkIndex"&&(this.dataListMemo=void 0);const shouldSync=this.isConnected&&typeof this.syncGroup=="string"&&this.syncGroup.trim()!=="";if(this.chartSync.enabled!==shouldSync&&this.chartSync.update(this.syncGroup,!0),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=shadowFocusTarget(this)??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.announcements.announcePolite(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),[...changed.keys()].some(name=>name!=="activeMarkIndex")&&(this.fitAxisTitles(),this.fitCategoryLabels()),this.syncAxisTitleTargets();const dataChanged=["datasets","labels","type","skipZero","layout","maxRecords","maxSeries"].some(name=>changed.has(name));this.chartSync.update(this.syncGroup,!0,dataChanged)}fitAxisTitles(){if(!(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length))for(const title of this.svgEl.querySelectorAll('[part="axis-title"]')){const text=Array.from(title.childNodes).find(node=>node.nodeType===3);if(!text)continue;const source=title.getAttribute("aria-label")??"",extent=finiteRange(Number(title.getAttribute("data-title-extent")),0,0,MAX_SCROLL_CONTENT_WIDTH),previous=this.axisTitleFits.get(title);if(!(previous?.source===source&&previous.extent===extent&&previous.display===text.data&&previous.width===title.getComputedTextLength())){if(title.style.removeProperty("opacity"),text.data=source,title.getComputedTextLength()>extent)if(text.data="…",title.getComputedTextLength()>extent)title.style.opacity="0";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=`${source.slice(0,middle)}…`,title.getComputedTextLength()<=extent?lower=middle:upper=middle-1}const last=source.charCodeAt(lower-1);last>=55296&&last<=56319&&(lower-=1),text.data=`${source.slice(0,lower)}…`}this.axisTitleFits.set(title,{source,extent,display:text.data,width:title.getComputedTextLength()})}}}fitOneCategoryLabel(tick,x,anchor,extent){const bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);tick.setAttribute("data-label-extent",String(bounded));const text=Array.from(tick.childNodes).find(node=>node.nodeType===3);if(!text)return x;const source=tick.getAttribute("data-full-label")??"",previous=this.categoryLabelFits.get(tick);if(previous?.source===source&&previous.extent===bounded&&previous.display===text.data&&previous.width===tick.getComputedTextLength())return anchor==="start"?x+previous.width:anchor==="end"?x-previous.width:x;if(text.data=source,tick.getComputedTextLength()>bounded)if(source.length<=1)text.data=source.length===0?source:"…";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=middle===0?"…":`${source.slice(0,middle)}…`,tick.getComputedTextLength()<=bounded?lower=middle:upper=middle-1}const lastCode=source.charCodeAt(lower-1);lastCode>=55296&&lastCode<=56319&&(lower-=1),text.data=lower===0?"…":`${source.slice(0,lower)}…`}text.data===source?tick.removeAttribute("aria-label"):tick.setAttribute("aria-label",source);const width=tick.getComputedTextLength();return this.categoryLabelFits.set(tick,{source,extent:bounded,display:text.data,width}),anchor==="start"?x+width:anchor==="end"?x-width:x}fitCategoryLabels(){if(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length)return;const ticks=[...this.svgEl.querySelectorAll('[part="axis-label"][data-full-label]')].filter(tick=>hasCategoryLabelText(tick.getAttribute("data-full-label"))).sort((a,b)=>Number(a.getAttribute("x"))-Number(b.getAttribute("x"))),count=ticks.length;if(count===0)return;const MARGIN=BAR_CORNER_RADIUS,positionOf=tick=>Number(tick.getAttribute("x"))||0,anchorOf=tick=>tick.getAttribute("text-anchor")??"middle",first=ticks[0],last=ticks[count-1],firstIsBoundary=count>1&&anchorOf(first)!=="middle",lastIsBoundary=count>1&&anchorOf(last)!=="middle";let firstRightEdge=positionOf(first),lastLeftEdge=positionOf(last);if(firstIsBoundary&&lastIsBoundary&&count===2){const half=Math.max(0,(positionOf(last)-positionOf(first))/2-MARGIN);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),half),lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),half)}else{if(firstIsBoundary){const gap=positionOf(ticks[1])-positionOf(first);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),gap-MARGIN)}if(lastIsBoundary){const gap=positionOf(last)-positionOf(ticks[count-2]);lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),gap-MARGIN)}}for(let index=0;index<count;index++){if(index===0&&firstIsBoundary||index===count-1&&lastIsBoundary)continue;const tick=ticks[index],x=positionOf(tick),leftAvailable=index===0?MAX_SCROLL_CONTENT_WIDTH:index===1&&firstIsBoundary?x-firstRightEdge:(x-positionOf(ticks[index-1]))/2,rightAvailable=index===count-1?MAX_SCROLL_CONTENT_WIDTH:index===count-2&&lastIsBoundary?lastLeftEdge-x:(positionOf(ticks[index+1])-x)/2,extent=2*Math.min(leftAvailable,rightAvailable)-MARGIN;this.fitOneCategoryLabel(tick,x,anchorOf(tick),extent)}}syncAxisTitleTargets(){if(!this.resizeObserver||!this.svgEl)return;const current=new Set(this.svgEl.querySelectorAll('[part="axis-title"]'));for(const title of this.axisTitleTargets)current.has(title)||this.resizeObserver.unobserve(title);for(const title of current)this.axisTitleTargets.has(title)||this.resizeObserver.observe(title);this.axisTitleTargets=current}queueAxisTitleFit(){const document=this.resizeObserverDocument,window=document?.defaultView;if(!window||this.axisTitleFrame!==void 0)return;const generation=this.resizeObserverGeneration,frame=window.requestAnimationFrame(()=>{this.axisTitleFrame!==frame||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==document||(this.axisTitleFrame=void 0,this.fitAxisTitles())});this.axisTitleFrame=frame}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>
2
+ `)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.requestUpdate(),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 svgEntry=entries.find(entry=>entry.target===target);if(svgEntry){const box=svgEntry.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=target.getBoundingClientRect();this.plotWidth=rect.width,this.plotHeight=rect.height}}entries.some(entry=>this.axisTitleTargets.has(entry.target))&&this.queueAxisTitleFit()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target),this.syncAxisTitleTargets()}disconnectedCallback(){this.chartSync.disconnect(),super.disconnectedCallback(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){this.chartSync.disconnect(),super.adoptedCallback(),this.requestUpdate(),this.resetResizeObserver(),this.announcements.adopted(),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}resetResizeObserver(){this.axisTitleFrame!==void 0&&(this.resizeObserverDocument?.defaultView?.cancelAnimationFrame(this.axisTitleFrame),this.axisTitleFrame=void 0),this.axisTitleTargets.clear(),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){super.willUpdate(changed);const shouldSync=this.isConnected&&typeof this.syncGroup=="string"&&this.syncGroup.trim()!=="";if(this.chartSync.enabled!==shouldSync&&this.chartSync.update(this.syncGroup,!0),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=shadowFocusTarget(this)??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.announcements.announcePolite(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),[...changed.keys()].some(name=>name!=="activeMarkIndex")&&(this.fitAxisTitles(),this.fitCategoryLabels()),this.syncAxisTitleTargets();const dataChanged=["datasets","labels","type","skipZero","layout","maxRecords","maxSeries"].some(name=>changed.has(name));this.chartSync.update(this.syncGroup,!0,dataChanged)}fitAxisTitles(){if(!(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length))for(const title of this.svgEl.querySelectorAll('[part="axis-title"]')){const text=Array.from(title.childNodes).find(node=>node.nodeType===3);if(!text)continue;const source=title.getAttribute("aria-label")??"",extent=finiteRange(Number(title.getAttribute("data-title-extent")),0,0,MAX_SCROLL_CONTENT_WIDTH),previous=this.axisTitleFits.get(title);if(!(previous?.source===source&&previous.extent===extent&&previous.display===text.data&&previous.width===title.getComputedTextLength())){if(title.style.removeProperty("opacity"),text.data=source,title.getComputedTextLength()>extent)if(text.data="…",title.getComputedTextLength()>extent)title.style.opacity="0";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=`${source.slice(0,middle)}…`,title.getComputedTextLength()<=extent?lower=middle:upper=middle-1}const last=source.charCodeAt(lower-1);last>=55296&&last<=56319&&(lower-=1),text.data=`${source.slice(0,lower)}…`}this.axisTitleFits.set(title,{source,extent,display:text.data,width:title.getComputedTextLength()})}}}fitOneCategoryLabel(tick,x,anchor,extent){const bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);tick.setAttribute("data-label-extent",String(bounded));const text=Array.from(tick.childNodes).find(node=>node.nodeType===3);if(!text)return x;const source=tick.getAttribute("data-full-label")??"",previous=this.categoryLabelFits.get(tick);if(previous?.source===source&&previous.extent===bounded&&previous.display===text.data&&previous.width===tick.getComputedTextLength())return anchor==="start"?x+previous.width:anchor==="end"?x-previous.width:x;if(text.data=source,tick.getComputedTextLength()>bounded)if(source.length<=1)text.data=source.length===0?source:"…";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=middle===0?"…":`${source.slice(0,middle)}…`,tick.getComputedTextLength()<=bounded?lower=middle:upper=middle-1}const lastCode=source.charCodeAt(lower-1);lastCode>=55296&&lastCode<=56319&&(lower-=1),text.data=lower===0?"…":`${source.slice(0,lower)}…`}text.data===source?tick.removeAttribute("aria-label"):tick.setAttribute("aria-label",source);const width=tick.getComputedTextLength();return this.categoryLabelFits.set(tick,{source,extent:bounded,display:text.data,width}),anchor==="start"?x+width:anchor==="end"?x-width:x}fitCategoryLabels(){if(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length)return;const ticks=[...this.svgEl.querySelectorAll('[part="axis-label"][data-full-label]')].filter(tick=>hasCategoryLabelText(tick.getAttribute("data-full-label"))).sort((a,b)=>Number(a.getAttribute("x"))-Number(b.getAttribute("x"))),count=ticks.length;if(count===0)return;const MARGIN=BAR_CORNER_RADIUS,positionOf=tick=>Number(tick.getAttribute("x"))||0,anchorOf=tick=>tick.getAttribute("text-anchor")??"middle",first=ticks[0],last=ticks[count-1],firstIsBoundary=count>1&&anchorOf(first)!=="middle",lastIsBoundary=count>1&&anchorOf(last)!=="middle";let firstRightEdge=positionOf(first),lastLeftEdge=positionOf(last);if(firstIsBoundary&&lastIsBoundary&&count===2){const half=Math.max(0,(positionOf(last)-positionOf(first))/2-MARGIN);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),half),lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),half)}else{if(firstIsBoundary){const gap=positionOf(ticks[1])-positionOf(first);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),gap-MARGIN)}if(lastIsBoundary){const gap=positionOf(last)-positionOf(ticks[count-2]);lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),gap-MARGIN)}}for(let index=0;index<count;index++){if(index===0&&firstIsBoundary||index===count-1&&lastIsBoundary)continue;const tick=ticks[index],x=positionOf(tick),leftAvailable=index===0?MAX_SCROLL_CONTENT_WIDTH:index===1&&firstIsBoundary?x-firstRightEdge:(x-positionOf(ticks[index-1]))/2,rightAvailable=index===count-1?MAX_SCROLL_CONTENT_WIDTH:index===count-2&&lastIsBoundary?lastLeftEdge-x:(positionOf(ticks[index+1])-x)/2,extent=2*Math.min(leftAvailable,rightAvailable)-MARGIN;this.fitOneCategoryLabel(tick,x,anchorOf(tick),extent)}}syncAxisTitleTargets(){if(!this.resizeObserver||!this.svgEl)return;const current=new Set(this.svgEl.querySelectorAll('[part="axis-title"]'));for(const title of this.axisTitleTargets)current.has(title)||this.resizeObserver.unobserve(title);for(const title of current)this.axisTitleTargets.has(title)||this.resizeObserver.observe(title);this.axisTitleTargets=current}queueAxisTitleFit(){const document=this.resizeObserverDocument,window=document?.defaultView;if(!window||this.axisTitleFrame!==void 0)return;const generation=this.resizeObserverGeneration,frame=window.requestAnimationFrame(()=>{this.axisTitleFrame!==frame||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==document||(this.axisTitleFrame=void 0,this.fitAxisTitles())});this.axisTitleFrame=frame}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`}
5
5
  stroke=${texture}
@@ -19,7 +19,11 @@ import{__decorate}from"tslib";import{LazyChartSyncController}from"./chart-sync-l
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,index){return this.formatter?.({value,surface:"visual",datasetIndex,...index===void 0?{}:{index},label,seriesLabel:this.datasets[datasetIndex]?.label,axis:"y"})??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,axis:"y",...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??formatChartValue(value,this.effectiveLocale,numberFormat)}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 memo=this.recordSampleMemo;if(memo?.labels===this.labels&&memo.datasets===this.datasets)return memo.value;const rowCount=this.recordCount(),seriesCount=this.datasets.length,value={rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)};return this.recordSampleMemo={labels:this.labels,datasets:this.datasets,value},value}generatedDataIsSampled(){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.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}hasCustomDataTable(){return hasSlottedChartDataTable(this)}interactiveMarks(){const sample=this.recordSample(),memo=this.marksMemo;if(memo?.sample===sample&&memo.type===this.effectiveType&&memo.skipZero===this.skipZero)return memo.value;const marks=[];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 this.marksMemo={sample,type:this.effectiveType,skipZero:this.skipZero,value:marks},marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){const marks=this.interactiveMarks(),memo=this.marksMemo;return memo.indexes??=new Map(marks.map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index])),memo.indexes}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markSummary(index,marks){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,axis:"y"})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex,mark.index);return custom?{format:values=>this.localize("liteChartCustomMarkSummary",void 0,values),values:{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["content"]}:{format:values=>this.localize("liteChartMarkSummary",void 0,values),values:{series,label:mark.label,value:formatChartValue(mark.value,this.effectiveLocale),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["series","label","value"]}}dataListItems(marks){const visible=this.dataTableVisible,memo=this.dataListMemo;if(memo?.marks===marks&&memo.visible===visible)return memo.value;const value=marks.map((_mark,index)=>html`<li>${visible?this.markListItem(index,marks):this.markAnnouncement(index,marks)}</li>`);return this.dataListMemo={marks,visible,value},value}markAnnouncement(index,marks=this.interactiveMarks()){const summary=this.markSummary(index,marks);return summary?summary.format(summary.values):""}markListItem(index,marks){const summary=this.markSummary(index,marks);return summary?isolatedMessage(summary.format,summary.values,summary.isolated):""}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.publishSyncMark(marks[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&&(shadowFocusTarget(this)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const zeroY=plotY+plotH-domainFraction(0,lo,hi)*plotH;if(value>=0){const domainMax2=hi>0?hi:1,fraction2=Math.sqrt(Math.min(domainMax2,value)/domainMax2);return zeroY-fraction2*(zeroY-plotY)}const domainMax=lo<0?-lo:1,fraction=Math.sqrt(Math.min(domainMax,-value)/domainMax);return zeroY+fraction*(plotY+plotH-zeroY)}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;if(this.smallestPositive?.datasets!==this.datasets){let smallest2=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest2&&(smallest2=value);this.smallestPositive={datasets:this.datasets,value:smallest2}}const smallest=this.smallestPositive.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));(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1);const domain=niceDomain(lo,hi,!this.withoutZeroBaseline,TICK_COUNT);if(this.scale==="logarithmic"){const ticks=logarithmicTicks(this.logDomainFloor(domain.lo,domain.hi),domain.hi,TICK_COUNT);if(ticks)return{...domain,ticks}}return domain}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-activate",{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)}publishSyncMark(mark){this.chartSync.publish(mark.label,mark.index)}syncPresentation(label,sourceIndex){const marks=this.interactiveMarks(),index=sourceIndex??marks.filter(mark=>mark.label===label).sort((a,b)=>a.index-b.index)[0]?.index;if(index===void 0||this.labels[index]!==label)return;const matched=marks.filter(mark=>mark.index===index);if(!matched.length||!this.svgEl)return;const target=this.svgEl.querySelector(`[data-dataset-index="${matched[0].datasetIndex}"][data-index="${index}"]`),container=this.renderRoot.querySelector('[part="base"]');if(!target||!container||!target.getClientRects().length)return;const bounds=container.getBoundingClientRect(),matrix=this.svgEl.getScreenCTM();if(!matrix)return;const rows=matched.map(mark=>{const series=this.datasets[mark.datasetIndex]?.label??"";return this.resolvePointText(mark.label,mark.value,mark.datasetIndex,mark.index)??this.localize("liteChartBarLabel",void 0,{series,label:mark.label,value:formatChartValue(mark.value,this.effectiveLocale)})});return{container,x:matrix.a*(this.syncCategoryPositions.get(index)??0)+matrix.e-bounds.left+container.scrollLeft,top:matrix.d*this.syncPlot.y+matrix.f-bounds.top+container.scrollTop,height:Math.abs(matrix.d*this.syncPlot.height),tooltip:{title:label,rows}}}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",axis:"y"})??(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`
22
+ </defs>`}resolvePointText(label,value,datasetIndex,index){return this.formatter?.({value,surface:"visual",datasetIndex,...index===void 0?{}:{index},label,seriesLabel:this.datasets[datasetIndex]?.label,axis:"y"})??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,axis:"y",...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??formatChartValue(value,this.effectiveLocale,numberFormat)}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 memo=this.recordSampleMemo;if(memo?.labels===this.labels&&memo.datasets===this.datasets)return memo.value;const rowCount=this.recordCount(),seriesCount=this.datasets.length,value={rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)};return this.recordSampleMemo={labels:this.labels,datasets:this.datasets,value},value}generatedDataIsSampled(){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.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}hasCustomDataTable(){return hasSlottedChartDataTable(this)}interactiveMarks(){const sample=this.recordSample(),memo=this.marksMemo;if(memo?.sample===sample&&memo.type===this.effectiveType&&memo.skipZero===this.skipZero)return memo.value;const marks=[];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 this.marksMemo={sample,type:this.effectiveType,skipZero:this.skipZero,value:marks},marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){const marks=this.interactiveMarks(),memo=this.marksMemo;return memo.indexes??=new Map(marks.map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index])),memo.indexes}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markSummary(index,marks){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,axis:"y"})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex,mark.index);return custom?{format:values=>this.localize("liteChartCustomMarkSummary",void 0,values),values:{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["content"]}:{format:values=>this.localize("liteChartMarkSummary",void 0,values),values:{series,label:mark.label,value:formatChartValue(mark.value,this.effectiveLocale),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["series","label","value"]}}requestUpdate(...args){args[0]!=="activeMarkIndex"&&(this.dataTableRows=void 0,this.dataListMemo=void 0),super.requestUpdate(...args)}renderDataTableRows(){if(this.dataTableRows)return this.dataTableRows;const recordSample=this.recordSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",tableNumberFormat=getNumberFormat(this.effectiveLocale),showTableTotals=this.effectiveType==="bar"&&this.stacked&&this.tableTotals;return this.dataTableRows=recordSample.rowIndexes.map(index=>{const label=this.labels[index]??"";return html`<tr>
23
+ <th scope="row">${isolateHtml(label||getNumberFormat(this.effectiveLocale).format(index+1),direction)}</th>
24
+ ${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex],value=series.data[index];return html`<td>${isolateHtml(value==null||!Number.isFinite(value)?"":this.formatTableCell(value,{kind:"value",datasetIndex,index,label,seriesLabel:series.label},tableNumberFormat),direction)}</td>`})}
25
+ ${showTableTotals?(()=>{const total=this.tableTotalAt(index,recordSample.seriesIndexes);return html`<td>${isolateHtml(total==null?"":this.formatTableCell(total,{kind:"total",datasetIndex:null,index,label,seriesLabel:null},tableNumberFormat),direction)}</td>`})():nothing}
26
+ </tr>`})}dataListItems(marks){const visible=this.dataTableVisible,memo=this.dataListMemo;if(memo?.marks===marks&&memo.visible===visible)return memo.value;const value=marks.map((_mark,index)=>html`<li>${visible?this.markListItem(index,marks):this.markAnnouncement(index,marks)}</li>`);return this.dataListMemo={marks,visible,value},value}markAnnouncement(index,marks=this.interactiveMarks()){const summary=this.markSummary(index,marks);return summary?summary.format(summary.values):""}markListItem(index,marks){const summary=this.markSummary(index,marks);return summary?isolatedMessage(summary.format,summary.values,summary.isolated):""}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.publishSyncMark(marks[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&&(shadowFocusTarget(this)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const zeroY=plotY+plotH-domainFraction(0,lo,hi)*plotH;if(value>=0){const domainMax2=hi>0?hi:1,fraction2=Math.sqrt(Math.min(domainMax2,value)/domainMax2);return zeroY-fraction2*(zeroY-plotY)}const domainMax=lo<0?-lo:1,fraction=Math.sqrt(Math.min(domainMax,-value)/domainMax);return zeroY+fraction*(plotY+plotH-zeroY)}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;if(this.smallestPositive?.datasets!==this.datasets){let smallest2=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest2&&(smallest2=value);this.smallestPositive={datasets:this.datasets,value:smallest2}}const smallest=this.smallestPositive.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));(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1);const domain=niceDomain(lo,hi,!this.withoutZeroBaseline,TICK_COUNT);if(this.scale==="logarithmic"){const ticks=logarithmicTicks(this.logDomainFloor(domain.lo,domain.hi),domain.hi,TICK_COUNT);if(ticks)return{...domain,ticks}}return domain}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-activate",{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)}publishSyncMark(mark){this.chartSync.publish(mark.label,mark.index)}syncPresentation(label,sourceIndex){const marks=this.interactiveMarks();let index=sourceIndex??void 0;if(index===void 0)for(const mark of marks)mark.label===label&&(index===void 0||mark.index<index)&&(index=mark.index);if(index===void 0||this.labels[index]!==label)return;const matched=marks.filter(mark=>mark.index===index);if(!matched.length||!this.svgEl)return;const target=this.svgEl.querySelector(`[data-dataset-index="${matched[0].datasetIndex}"][data-index="${index}"]`),container=this.renderRoot.querySelector('[part="base"]');if(!target||!container||!target.getClientRects().length)return;const bounds=container.getBoundingClientRect(),matrix=this.svgEl.getScreenCTM();if(!matrix)return;const rows=matched.map(mark=>{const series=this.datasets[mark.datasetIndex]?.label??"";return this.resolvePointText(mark.label,mark.value,mark.datasetIndex,mark.index)??this.localize("liteChartBarLabel",void 0,{series,label:mark.label,value:formatChartValue(mark.value,this.effectiveLocale)})});return{container,x:matrix.a*(this.syncCategoryPositions.get(index)??0)+matrix.e-bounds.left+container.scrollLeft,top:matrix.d*this.syncPlot.y+matrix.f-bounds.top+container.scrollTop,height:Math.abs(matrix.d*this.syncPlot.height),tooltip:{title:label,rows}}}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",axis:"y"})??(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
27
  <line part="grid-line" x1=${plotX} y1=${y} x2=${plotX+plotW} y2=${y}></line>
24
28
  <text
25
29
  part="axis-label"
@@ -128,7 +132,7 @@ import{__decorate}from"tslib";import{LazyChartSyncController}from"./chart-sync-l
128
132
  data-label-extent=${labelExtent}
129
133
  data-full-label=${fullLabel}
130
134
  aria-label=${displayLabel===fullLabel?nothing:fullLabel}
131
- >${displayLabel}</text>`}),datasetLabels=recordSample.seriesIndexes.map(datasetIndex=>this.datasets[datasetIndex].label).filter(Boolean),chartLabel=this.hostAccessibleLabel??(this.label||(datasetLabels.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(datasetLabels):"")||this.localize("chart")),marksForA11y=this.interactiveMarks(),tableNumberFormat=getNumberFormat(this.effectiveLocale),showTableTotals=this.effectiveType==="bar"&&this.stacked&&this.tableTotals,dataTruncation=this.dataTruncationMessage(),hasCustomDataTable=this.hasCustomDataTable();return html`
135
+ >${displayLabel}</text>`}),datasetLabels=recordSample.seriesIndexes.map(datasetIndex=>this.datasets[datasetIndex].label).filter(Boolean),chartLabel=this.hostAccessibleLabel??(this.label||(datasetLabels.length?getListFormat(this.effectiveLocale,{type:"conjunction"}).format(datasetLabels):"")||this.localize("chart")),marksForA11y=this.interactiveMarks(),showTableTotals=this.effectiveType==="bar"&&this.stacked&&this.tableTotals,dataTruncation=this.dataTruncationMessage(),hasCustomDataTable=this.hasCustomDataTable();return html`
132
136
  <div
133
137
  part="base"
134
138
  data-legend-position=${this.withLegend?chartChromeLegendPlacement(this.legendPosition):nothing}
@@ -185,11 +189,7 @@ import{__decorate}from"tslib";import{LazyChartSyncController}from"./chart-sync-l
185
189
  </tr>
186
190
  </thead>
187
191
  <tbody>
188
- ${recordSample.rowIndexes.map(index=>{const label=this.labels[index]??"";return html`<tr>
189
- <th scope="row">${isolateHtml(label||getNumberFormat(this.effectiveLocale).format(index+1),direction)}</th>
190
- ${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex],value=series.data[index];return html`<td>${isolateHtml(value==null||!Number.isFinite(value)?"":this.formatTableCell(value,{kind:"value",datasetIndex,index,label,seriesLabel:series.label},tableNumberFormat),direction)}</td>`})}
191
- ${showTableTotals?(()=>{const total=this.tableTotalAt(index,recordSample.seriesIndexes);return html`<td>${isolateHtml(total==null?"":this.formatTableCell(total,{kind:"total",datasetIndex:null,index,label,seriesLabel:null},tableNumberFormat),direction)}</td>`})():nothing}
192
- </tr>`})}
192
+ ${this.renderDataTableRows()}
193
193
  </tbody>
194
194
  </table>`:html`<ul
195
195
  part="data-list"
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
11
11
  >
12
12
  ${thumbIcon(direction,pressed)}
13
13
  </button>
14
- `}render(){return html`
14
+ `}render(){const selectedReasons=new Set(this.selectedReasonIds);return html`
15
15
  <div part="base">
16
16
  <div part="thumbs">${this.renderThumb("up")}${this.renderThumb("down")}</div>
17
17
  ${this.hasDetailContent?html`
@@ -30,7 +30,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
30
30
  ${this.detailReasons.map(reason=>html`
31
31
  <lr-chip
32
32
  toggleable
33
- ?selected=${this.selectedReasonIds.includes(reason.id)}
33
+ ?selected=${selectedReasons.has(reason.id)}
34
34
  .disabled=${this.disabled||this.pending}
35
35
  @lr-chip-toggle-request=${event=>{event.stopPropagation(),this.toggleReason(reason.id)}}
36
36
  @lr-chip-select=${this.stopChipAliasEvent}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{isEditableKeyEventTarget}from"../../../internal/hotkey.js";import{RovingToolbarController,leaseTabIndex,observeStopChanges}from"../../../internal/roving-toolbar.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{finiteAdd,finiteMidpoint,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./selection-toolbar.styles.js";import{isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"../../../internal/top-layer-escape.js";import{LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const COMPOSITE_ROLES=new Set(["menu","menubar","listbox","tree","treegrid","grid","tablist","radiogroup"]);function insideComposite(element,root){for(let node=composedParentElement(element);node&&node!==root;node=composedParentElement(node))if(COMPOSITE_ROLES.has(node.getAttribute("role")??""))return!0;return!1}const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="toolbar"][role="toolbar"]')),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.actionTabIndexLeases=new WeakMap,this.rovingToolbar=new RovingToolbarController,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{if(event.defaultPrevented||isEditableKeyEventTarget(event))return;const buttons=this.actionButtons();if(buttons.length===0)return;const path=event.composedPath(),originIndex=buttons.findIndex(button=>path.includes(button));if(originIndex<0&&path[0]!==event.currentTarget)return;const currentIndex=originIndex>=0?originIndex:this.activeActionIndex,next=this.rovingToolbar.move(event,buttons.length,currentIndex,this.effectiveDirection);if(next===null)return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const viewport=this.viewportBounds(view),maxEdge=finiteMidpoint(0,Math.min(viewport.width,viewport.height)),gap=finiteRange(this.placementGapPx(),DEFAULT_PLACEMENT_GAP_PX,0,maxEdge),edge=gap,fallbackInline=finiteMidpoint(viewport.left,viewport.right),rect=this.rect?this.safeRect(this.rect):{left:fallbackInline,top:viewport.top,width:0,height:0,right:fallbackInline,bottom:viewport.top,inlineCenter:fallbackInline},doubleEdge=finiteAdd(edge,edge),maxInlineSize=finiteRange(finiteAdd(viewport.width,-doubleEdge),0,0,Number.MAX_VALUE),maxBlockSize=finiteRange(finiteAdd(viewport.height,-doubleEdge),0,0,Number.MAX_VALUE);toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",this.px(maxInlineSize)),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",this.px(maxBlockSize));const width=finiteRange(toolbar.offsetWidth,0,0,Number.MAX_VALUE),height=finiteRange(toolbar.offsetHeight,0,0,Number.MAX_VALUE),desiredInline=finiteRange(rect.inlineCenter,viewport.left,viewport.left,viewport.right),anchorBlock=finiteRange(rect.top,viewport.top,viewport.top,viewport.bottom),desiredLeft=finiteAdd(desiredInline,-finiteMidpoint(0,width)),minLeft=finiteAdd(viewport.left,edge),maxLeft=Math.max(minLeft,finiteAdd(finiteAdd(viewport.right,-width),-edge)),left=finiteRange(desiredLeft,minLeft,minLeft,maxLeft),above=finiteAdd(finiteAdd(rect.top,-height),-gap),below=finiteAdd(rect.bottom,gap),minTop=finiteAdd(viewport.top,edge),desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,finiteAdd(finiteAdd(viewport.bottom,-height),-edge)),top=finiteRange(desiredTop,minTop,minTop,maxTop),logicalInline=this.effectiveDirection==="rtl"?finiteAdd(viewport.layoutWidth,-desiredInline):desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",this.px(logicalInline)),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",this.px(anchorBlock)),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",this.px(finiteAdd(left,-desiredLeft))),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",this.px(finiteAdd(top,-finiteAdd(anchorBlock,-height)))),toolbar.toggleAttribute("data-positioned",!0)},new GlassScrollLayer(this,'[part="toolbar"]')}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),this.copyFailed&&(changed.has("text")||changed.has("open")&&this.open)&&(this.copyFailed=!1),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),this.open&&this.text&&this.escapeTrappingAncestor(),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss()}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.sink?.announce(this.localize("copyFailed")),this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>(!!isSemanticActionElement(button)||this.hasAuthoredActionTabIndex(button))&&!insideComposite(button,toolbar)):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}hasAuthoredActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);return lease?lease.hasAuthored(button):button.hasAttribute("tabindex")}writeActionTabIndex(button,tabIndex){let lease=this.actionTabIndexLeases.get(button);lease||this.actionTabIndexLeases.set(button,lease=leaseTabIndex()),lease.set(button,tabIndex)}releaseActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);lease&&(lease.release(),this.actionTabIndexLeases.delete(button))}releaseManagedActionStops(){for(const button of this.managedActionStops)this.releaseActionTabIndex(button);this.managedActionStops.clear()}setRovingStops(buttons,index){this.actionObserver?.disconnect();for(const previous of this.managedActionStops)buttons.includes(previous)||this.releaseActionTabIndex(previous);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{this.writeActionTabIndex(button,buttonIndex===this.activeActionIndex?0:-1)}),this.managedActionStops=new Set(buttons),this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&&current!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options=observeStopChanges();for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){const left=finiteRange(rect.left,0,-Number.MAX_VALUE,Number.MAX_VALUE),top=finiteRange(rect.top,0,-Number.MAX_VALUE,Number.MAX_VALUE),width=finiteRange(rect.width,0,0,Number.MAX_VALUE),height=finiteRange(rect.height,0,0,Number.MAX_VALUE),right=finiteAdd(left,width),bottom=finiteAdd(top,height);return{left,top,width,height,right,bottom,inlineCenter:finiteMidpoint(left,right)}}viewportBounds(view){const layoutWidth=finiteRange(view.innerWidth,0,0,Number.MAX_VALUE),layoutHeight=finiteRange(view.innerHeight,0,0,Number.MAX_VALUE),viewport=view.visualViewport,left=finiteRange(viewport?.offsetLeft??0,0,0,Number.MAX_VALUE),top=finiteRange(viewport?.offsetTop??0,0,0,Number.MAX_VALUE),width=finiteRange(viewport?.width??layoutWidth,layoutWidth,0,Number.MAX_VALUE),height=finiteRange(viewport?.height??layoutHeight,layoutHeight,0,Number.MAX_VALUE);return{left,top,width,height,right:finiteAdd(left,width),bottom:finiteAdd(top,height),layoutWidth}}px(value){return`${finiteRange(value,0,-Number.MAX_VALUE,Number.MAX_VALUE)}px`}placementGapPx(){const computed=this.ownerDocument.defaultView?.getComputedStyle(this),publicValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"",{host:this});if(publicValue!==void 0)return finiteRange(publicValue,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE);const tokenValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-space-s").trim()??"",{host:this});return finiteRange(tokenValue??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}escapeTrappingAncestor(){const toolbar=this.toolbar;!toolbar||isLibraryPromotedAndShowing(toolbar)||(needsTopLayerEscape(toolbar)?promoteToTopLayer(toolbar):stripStaleTopLayer(toolbar))}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label==null?this.localize("selectionToolbarLabel"):this.label);return html`<div
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{isEditableKeyEventTarget}from"../../../internal/hotkey.js";import{RovingToolbarController,leaseTabIndex,observeStopChanges}from"../../../internal/roving-toolbar.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{finiteAdd,finiteMidpoint,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./selection-toolbar.styles.js";import{isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"../../../internal/top-layer-escape.js";import{LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const COMPOSITE_ROLES=new Set(["menu","menubar","listbox","tree","treegrid","grid","tablist","radiogroup"]);function insideComposite(element,root){for(let node=composedParentElement(element);node&&node!==root;node=composedParentElement(node))if(COMPOSITE_ROLES.has(node.getAttribute("role")??""))return!0;return!1}const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="toolbar"][role="toolbar"]')),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.actionTabIndexLeases=new WeakMap,this.rovingToolbar=new RovingToolbarController,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{if(event.defaultPrevented||isEditableKeyEventTarget(event))return;const buttons=this.actionButtons();if(buttons.length===0)return;const path=event.composedPath(),originIndex=buttons.findIndex(button=>path.includes(button));if(originIndex<0&&path[0]!==event.currentTarget)return;const currentIndex=originIndex>=0?originIndex:this.activeActionIndex,next=this.rovingToolbar.move(event,buttons.length,currentIndex,this.effectiveDirection);if(next===null)return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const viewport=this.viewportBounds(view),maxEdge=finiteMidpoint(0,Math.min(viewport.width,viewport.height)),gap=finiteRange(this.placementGapPx(),DEFAULT_PLACEMENT_GAP_PX,0,maxEdge),edge=gap,fallbackInline=finiteMidpoint(viewport.left,viewport.right),rect=this.rect?this.safeRect(this.rect):{left:fallbackInline,top:viewport.top,width:0,height:0,right:fallbackInline,bottom:viewport.top,inlineCenter:fallbackInline},doubleEdge=finiteAdd(edge,edge),maxInlineSize=finiteRange(finiteAdd(viewport.width,-doubleEdge),0,0,Number.MAX_VALUE),maxBlockSize=finiteRange(finiteAdd(viewport.height,-doubleEdge),0,0,Number.MAX_VALUE);toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",this.px(maxInlineSize)),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",this.px(maxBlockSize));const width=finiteRange(toolbar.offsetWidth,0,0,Number.MAX_VALUE),height=finiteRange(toolbar.offsetHeight,0,0,Number.MAX_VALUE),desiredInline=finiteRange(rect.inlineCenter,viewport.left,viewport.left,viewport.right),anchorBlock=finiteRange(rect.top,viewport.top,viewport.top,viewport.bottom),desiredLeft=finiteAdd(desiredInline,-finiteMidpoint(0,width)),minLeft=finiteAdd(viewport.left,edge),maxLeft=Math.max(minLeft,finiteAdd(finiteAdd(viewport.right,-width),-edge)),left=finiteRange(desiredLeft,minLeft,minLeft,maxLeft),above=finiteAdd(finiteAdd(rect.top,-height),-gap),below=finiteAdd(rect.bottom,gap),minTop=finiteAdd(viewport.top,edge),desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,finiteAdd(finiteAdd(viewport.bottom,-height),-edge)),top=finiteRange(desiredTop,minTop,minTop,maxTop),logicalInline=this.effectiveDirection==="rtl"?finiteAdd(viewport.layoutWidth,-desiredInline):desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",this.px(logicalInline)),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",this.px(anchorBlock)),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",this.px(finiteAdd(left,-desiredLeft))),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",this.px(finiteAdd(top,-finiteAdd(anchorBlock,-height)))),toolbar.toggleAttribute("data-positioned",!0)},new GlassScrollLayer(this,'[part="toolbar"]')}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),this.copyFailed&&(changed.has("text")||changed.has("open")&&this.open)&&(this.copyFailed=!1),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),this.open&&this.text&&this.escapeTrappingAncestor(),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss()}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.sink?.announce(this.localize("copyFailed")),this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>(!!isSemanticActionElement(button)||this.hasAuthoredActionTabIndex(button))&&!insideComposite(button,toolbar)):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}hasAuthoredActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);return lease?lease.hasAuthored(button):button.hasAttribute("tabindex")}writeActionTabIndex(button,tabIndex){let lease=this.actionTabIndexLeases.get(button);lease||this.actionTabIndexLeases.set(button,lease=leaseTabIndex()),lease.set(button,tabIndex)}releaseActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);lease&&(lease.release(),this.actionTabIndexLeases.delete(button))}releaseManagedActionStops(){for(const button of this.managedActionStops)this.releaseActionTabIndex(button);this.managedActionStops.clear()}setRovingStops(buttons,index){this.actionObserver?.disconnect();const nextStops=new Set(buttons);for(const previous of this.managedActionStops)nextStops.has(previous)||this.releaseActionTabIndex(previous);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{this.writeActionTabIndex(button,buttonIndex===this.activeActionIndex?0:-1)}),this.managedActionStops=nextStops,this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&&current!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options=observeStopChanges();for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){const left=finiteRange(rect.left,0,-Number.MAX_VALUE,Number.MAX_VALUE),top=finiteRange(rect.top,0,-Number.MAX_VALUE,Number.MAX_VALUE),width=finiteRange(rect.width,0,0,Number.MAX_VALUE),height=finiteRange(rect.height,0,0,Number.MAX_VALUE),right=finiteAdd(left,width),bottom=finiteAdd(top,height);return{left,top,width,height,right,bottom,inlineCenter:finiteMidpoint(left,right)}}viewportBounds(view){const layoutWidth=finiteRange(view.innerWidth,0,0,Number.MAX_VALUE),layoutHeight=finiteRange(view.innerHeight,0,0,Number.MAX_VALUE),viewport=view.visualViewport,left=finiteRange(viewport?.offsetLeft??0,0,0,Number.MAX_VALUE),top=finiteRange(viewport?.offsetTop??0,0,0,Number.MAX_VALUE),width=finiteRange(viewport?.width??layoutWidth,layoutWidth,0,Number.MAX_VALUE),height=finiteRange(viewport?.height??layoutHeight,layoutHeight,0,Number.MAX_VALUE);return{left,top,width,height,right:finiteAdd(left,width),bottom:finiteAdd(top,height),layoutWidth}}px(value){return`${finiteRange(value,0,-Number.MAX_VALUE,Number.MAX_VALUE)}px`}placementGapPx(){const computed=this.ownerDocument.defaultView?.getComputedStyle(this),publicValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"",{host:this});if(publicValue!==void 0)return finiteRange(publicValue,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE);const tokenValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-space-s").trim()??"",{host:this});return finiteRange(tokenValue??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}escapeTrappingAncestor(){const toolbar=this.toolbar;!toolbar||isLibraryPromotedAndShowing(toolbar)||(needsTopLayerEscape(toolbar)?promoteToTopLayer(toolbar):stripStaleTopLayer(toolbar))}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label==null?this.localize("selectionToolbarLabel"):this.label);return html`<div
2
2
  part="toolbar"
3
3
  role="toolbar"
4
4
  aria-label=${label}
@@ -1,2 +1,2 @@
1
- import{getCollator,resolveIntlLocale}from"../../../internal/intl-cache.js";import{UNSAFE_LEADING}from"../../utility/export-button/csv.js";function columnId(column,_index){return typeof column.id=="string"&&column.id.trim()!==""?column.id:typeof column.field=="string"&&column.field.trim()!==""?column.field:""}function pathValue(value,path){if(!path)return;let current=value;for(const segment of path.split(".")){if(typeof current!="object"||current===null)return;current=current[segment]}return current}function columnValue(column,row){return column.value?column.value(row):column.field?pathValue(row,column.field):void 0}function comparableText(value){if(value==null)return"";if(value instanceof Date)return Number.isFinite(value.getTime())?value.toISOString():"";if(Array.isArray(value))return value.map(comparableText).join(" ");if(typeof value=="object")try{return JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)??""}catch{return""}return String(value)}function numericDate(value){if(value instanceof Date)return Number.isFinite(value.getTime())?value.getTime():void 0;if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value=="string"){const parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:void 0}}function finiteValue(value){if(typeof value=="string"&&value.trim()==="")return;const number=typeof value=="number"?value:Number(value);return Number.isFinite(number)?number:void 0}function valuesFromFilter(value){return Array.isArray(value)?value:value instanceof Set?[...value]:value==null||value===""?[]:[value]}function valuesFromCell(value){return Array.isArray(value)?value:value instanceof Set?[...value]:[value]}function sameValue(left,right,locale){return Object.is(left,right)?!0:getCollator(locale,{sensitivity:"base",numeric:!0}).compare(comparableText(left),comparableText(right))===0}const DATE_ONLY=/^(\d{4})-(\d{2})-(\d{2})$/;function localCalendarDay(value){if(typeof value!="string")return;const match=DATE_ONLY.exec(value.trim());if(!match)return;const year=Number(match[1]),month=Number(match[2])-1,day=Number(match[3]),date=new Date(0);return date.setFullYear(year,month,day),date.setHours(0,0,0,0),date.getFullYear()===year&&date.getMonth()===month&&date.getDate()===day?date.getTime():void 0}function matchesRange(value,filter,date){if(!Array.isArray(filter))return!0;const[rawStart,rawEnd]=filter,read=date?candidate=>localCalendarDay(candidate)??numericDate(candidate):finiteValue,current=read(value);if(current===void 0)return!1;const start=read(rawStart),end=read(rawEnd);if(start!==void 0&&current<start)return!1;if(end!==void 0){if(date){const inclusiveEnd=new Date(end);if(inclusiveEnd.setHours(23,59,59,999),current>inclusiveEnd.getTime())return!1}else if(current>end)return!1}return!0}function matchesFilter(row,column,filter,locale){const intlLocale=resolveIntlLocale(locale),value=columnValue(column,row);if(column.filterFn)return!!column.filterFn(value,filter,row);const type=column.filterType??"text",collator=getCollator(intlLocale,{sensitivity:"base",numeric:!0});if(type==="number-range")return matchesRange(value,filter,!1);if(type==="date-range")return matchesRange(value,filter,!0);if(type==="equals")return collator.compare(comparableText(value),comparableText(filter))===0;const needles=valuesFromFilter(filter);if(needles.length===0)return!0;const values=valuesFromCell(value);return type==="set"||type==="includes-any"?needles.some(needle=>values.some(candidate=>sameValue(candidate,needle,locale))):type==="includes-all"?needles.every(needle=>values.some(candidate=>sameValue(candidate,needle,locale))):comparableText(value).toLocaleLowerCase(intlLocale).includes(comparableText(filter).toLocaleLowerCase(intlLocale))}function filterRows(rows,columns,filters,locale){if(filters.length===0)return[...rows];const byId=new Map(columns.map((column,index)=>[columnId(column,index),column]));return rows.filter(row=>filters.every(filter=>{const column=byId.get(filter.id);return!column||matchesFilter(row,column,filter.value,locale)}))}function searchRows(rows,columns,term,locale,searchFn){const intlLocale=resolveIntlLocale(locale),needle=term.trim();if(!needle)return[...rows];const searchable=columns.filter(column=>(column.field||column.value)&&column.searchable!==!1);return rows.filter(row=>searchable.some(column=>{const value=columnValue(column,row);return searchFn?!!searchFn(value,needle,row):comparableText(value).toLocaleLowerCase(intlLocale).includes(needle.toLocaleLowerCase(intlLocale))}))}function undefinedRank(column,left,right){const leftMissing=left==null||typeof left=="number"&&!Number.isFinite(left),rightMissing=right==null||typeof right=="number"&&!Number.isFinite(right);if(leftMissing===rightMissing)return;const policy=column.sortUndefined??"last";return leftMissing===(policy==="first"||policy===-1)?-1:1}function cellText(cell){return cell.text??=comparableText(cell.value)}function cellTime(cell){return cell.time===void 0&&(cell.time=numericDate(cell.value)??null),cell.time??void 0}function cellComparator(column,locale){const comparator=column.comparator;if(comparator)return(left,right,leftRow,rightRow)=>comparator(left.value,right.value,leftRow,rightRow);const algorithm=column.sortFn??"alphanumeric",caseSensitive=algorithm==="alphanumericCaseSensitive"||algorithm==="textCaseSensitive",numeric=algorithm==="alphanumeric"||algorithm==="alphanumericCaseSensitive";let collator;return(left,right)=>{if(algorithm==="datetime"){const leftTime=cellTime(left),rightTime=cellTime(right);if(leftTime!==void 0&&rightTime!==void 0)return leftTime-rightTime}return algorithm==="basic"&&typeof left.value=="number"&&typeof right.value=="number"?left.value-right.value:(collator??=getCollator(locale,{sensitivity:caseSensitive?"variant":"base",numeric}),collator.compare(cellText(left),cellText(right)))}}function sortRows(rows,columns,sorting,locale){if(sorting.length===0)return[...rows];const byId=new Map(columns.map((column,index)=>[columnId(column,index),column])),active=[];for(const sort of sorting){const column=byId.get(sort.id);column&&active.push({desc:sort.desc,column,compare:cellComparator(column,locale)})}return rows.map((row,index)=>({row,index,cells:active.map(({column})=>({value:columnValue(column,row)}))})).sort((left,right)=>{for(let position=0;position<active.length;position+=1){const{desc,column,compare}=active[position],leftCell=left.cells[position],rightCell=right.cells[position],missing=undefinedRank(column,leftCell.value,rightCell.value);if(missing!==void 0)return typeof(column.sortUndefined??"last")=="string"?missing:desc?-missing:missing;const compared=compare(leftCell,rightCell,left.row,right.row);if(compared!==0)return desc?-compared:compared}return left.index-right.index}).map(({row})=>row)}function aggregateValues(aggregation,rows,values){if(typeof aggregation=="function")return aggregation(rows,values);if(aggregation==="count")return rows.length;const defined=values.filter(value=>value!=null);if(aggregation==="unique")return[...new Set(defined)];if(aggregation==="uniqueCount")return new Set(defined).size;const numeric=defined.map(finiteValue).filter(value=>value!==void 0);if(numeric.length===0)return aggregation==="extent"?[]:void 0;const sorted=[...numeric].sort((left,right)=>left-right);let scale=0;for(const value of numeric)scale=Math.max(scale,Math.abs(value));let scaledTotal=0;if(scale>0)for(const value of numeric)scaledTotal+=value/scale;if(aggregation==="sum"){const sum=scale===0?0:scaledTotal*scale;return Number.isFinite(sum)?sum:void 0}if(aggregation==="min")return sorted[0];if(aggregation==="max")return sorted.at(-1);if(aggregation==="mean"){const mean=scale===0?0:scaledTotal/numeric.length*scale;return Number.isFinite(mean)?mean:void 0}if(aggregation==="median"){const middle=Math.floor(sorted.length/2);if(sorted.length%2!==0)return sorted[middle];const left=sorted[middle-1]??0,right=sorted[middle]??0,median=Math.sign(left)===Math.sign(right)?left+(right-left)/2:left/2+right/2;return Number.isFinite(median)?median:void 0}return[sorted[0],sorted.at(-1)]}function csvCell(value,delimiter,escapeFormulas){let text=comparableText(value);return escapeFormulas&&typeof value!="number"&&UNSAFE_LEADING.test(text)&&(text=`'${text}`),(text.includes(delimiter)||/[\x22\r\n]/u.test(text))&&(text=`"${text.replaceAll('"','""')}"`),text}function rowsAsDelimited(rows,columns,options={}){const delimiter=options.delimiter??",",includeHeaders=options.includeHeaders??!0,escapeFormulas=options.escapeFormulas??!0,requested=options.columnIds?new Set(options.columnIds):void 0,visible=columns.filter((column,index)=>column.hidden!==!0&&(!requested||requested.has(columnId(column,index)))),lines=[];includeHeaders&&lines.push(visible.map((column,index)=>csvCell(column.label??columnId(column,index),delimiter,!1)).join(delimiter));for(const row of rows)lines.push(visible.map(column=>csvCell(columnValue(column,row),delimiter,escapeFormulas)).join(delimiter));return lines.join(`\r
1
+ import{getCollator,resolveIntlLocale}from"../../../internal/intl-cache.js";import{UNSAFE_LEADING}from"../../utility/export-button/csv.js";function columnId(column,_index){return typeof column.id=="string"&&column.id.trim()!==""?column.id:typeof column.field=="string"&&column.field.trim()!==""?column.field:""}function pathValue(value,path){if(!path)return;let current=value;for(const segment of path.split(".")){if(typeof current!="object"||current===null)return;current=current[segment]}return current}function columnValue(column,row){return column.value?column.value(row):column.field?pathValue(row,column.field):void 0}function comparableText(value){if(value==null)return"";if(value instanceof Date)return Number.isFinite(value.getTime())?value.toISOString():"";if(Array.isArray(value))return value.map(comparableText).join(" ");if(typeof value=="object")try{return JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)??""}catch{return""}return String(value)}function numericDate(value){if(value instanceof Date)return Number.isFinite(value.getTime())?value.getTime():void 0;if(typeof value=="number")return Number.isFinite(value)?value:void 0;if(typeof value=="string"){const parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:void 0}}function finiteValue(value){if(typeof value=="string"&&value.trim()==="")return;const number=typeof value=="number"?value:Number(value);return Number.isFinite(number)?number:void 0}function valuesFromFilter(value){return Array.isArray(value)?value:value instanceof Set?[...value]:value==null||value===""?[]:[value]}function valuesFromCell(value){return Array.isArray(value)?value:value instanceof Set?[...value]:[value]}function sameValue(left,right,collator){return Object.is(left,right)?!0:collator().compare(comparableText(left),comparableText(right))===0}const DATE_ONLY=/^(\d{4})-(\d{2})-(\d{2})$/;function localCalendarDay(value){if(typeof value!="string")return;const match=DATE_ONLY.exec(value.trim());if(!match)return;const year=Number(match[1]),month=Number(match[2])-1,day=Number(match[3]),date=new Date(0);return date.setFullYear(year,month,day),date.setHours(0,0,0,0),date.getFullYear()===year&&date.getMonth()===month&&date.getDate()===day?date.getTime():void 0}function matchesRange(value,filter,date){if(!Array.isArray(filter))return!0;const[rawStart,rawEnd]=filter,read=date?candidate=>localCalendarDay(candidate)??numericDate(candidate):finiteValue,current=read(value);if(current===void 0)return!1;const start=read(rawStart),end=read(rawEnd);if(start!==void 0&&current<start)return!1;if(end!==void 0){if(date){const inclusiveEnd=new Date(end);if(inclusiveEnd.setHours(23,59,59,999),current>inclusiveEnd.getTime())return!1}else if(current>end)return!1}return!0}function matchesFilter(row,column,filter,locale){const intlLocale=resolveIntlLocale(locale),value=columnValue(column,row);if(column.filterFn)return!!column.filterFn(value,filter,row);const type=column.filterType??"text";if(type==="number-range")return matchesRange(value,filter,!1);if(type==="date-range")return matchesRange(value,filter,!0);let collator;const comparison=()=>collator??=getCollator(intlLocale,{sensitivity:"base",numeric:!0});if(type==="equals")return comparison().compare(comparableText(value),comparableText(filter))===0;const needles=valuesFromFilter(filter);if(needles.length===0)return!0;const values=valuesFromCell(value);return type==="set"||type==="includes-any"?needles.some(needle=>values.some(candidate=>sameValue(candidate,needle,comparison))):type==="includes-all"?needles.every(needle=>values.some(candidate=>sameValue(candidate,needle,comparison))):comparableText(value).toLocaleLowerCase(intlLocale).includes(comparableText(filter).toLocaleLowerCase(intlLocale))}function filterRows(rows,columns,filters,locale){if(filters.length===0)return[...rows];const byId=new Map(columns.map((column,index)=>[columnId(column,index),column]));return rows.filter(row=>filters.every(filter=>{const column=byId.get(filter.id);return!column||matchesFilter(row,column,filter.value,locale)}))}function searchRows(rows,columns,term,locale,searchFn){const intlLocale=resolveIntlLocale(locale),needle=term.trim();if(!needle)return[...rows];const searchable=columns.filter(column=>(column.field||column.value)&&column.searchable!==!1),normalizedNeedle=searchFn?"":needle.toLocaleLowerCase(intlLocale);return rows.filter(row=>searchable.some(column=>{const value=columnValue(column,row);return searchFn?!!searchFn(value,needle,row):comparableText(value).toLocaleLowerCase(intlLocale).includes(normalizedNeedle)}))}function undefinedRank(column,left,right){const leftMissing=left==null||typeof left=="number"&&!Number.isFinite(left),rightMissing=right==null||typeof right=="number"&&!Number.isFinite(right);if(leftMissing===rightMissing)return;const policy=column.sortUndefined??"last";return leftMissing===(policy==="first"||policy===-1)?-1:1}function cellText(cell){return cell.text??=comparableText(cell.value)}function cellTime(cell){return cell.time===void 0&&(cell.time=numericDate(cell.value)??null),cell.time??void 0}function cellComparator(column,locale){const comparator=column.comparator;if(comparator)return(left,right,leftRow,rightRow)=>comparator(left.value,right.value,leftRow,rightRow);const algorithm=column.sortFn??"alphanumeric",caseSensitive=algorithm==="alphanumericCaseSensitive"||algorithm==="textCaseSensitive",numeric=algorithm==="alphanumeric"||algorithm==="alphanumericCaseSensitive";let collator;return(left,right)=>{if(algorithm==="datetime"){const leftTime=cellTime(left),rightTime=cellTime(right);if(leftTime!==void 0&&rightTime!==void 0)return leftTime-rightTime}return algorithm==="basic"&&typeof left.value=="number"&&typeof right.value=="number"?left.value-right.value:(collator??=getCollator(locale,{sensitivity:caseSensitive?"variant":"base",numeric}),collator.compare(cellText(left),cellText(right)))}}function sortRows(rows,columns,sorting,locale){if(sorting.length===0)return[...rows];const byId=new Map(columns.map((column,index)=>[columnId(column,index),column])),active=[];for(const sort of sorting){const column=byId.get(sort.id);column&&active.push({desc:sort.desc,column,compare:cellComparator(column,locale)})}return rows.map((row,index)=>({row,index,cells:active.map(({column})=>({value:columnValue(column,row)}))})).sort((left,right)=>{for(let position=0;position<active.length;position+=1){const{desc,column,compare}=active[position],leftCell=left.cells[position],rightCell=right.cells[position],missing=undefinedRank(column,leftCell.value,rightCell.value);if(missing!==void 0)return typeof(column.sortUndefined??"last")=="string"?missing:desc?-missing:missing;const compared=compare(leftCell,rightCell,left.row,right.row);if(compared!==0)return desc?-compared:compared}return left.index-right.index}).map(({row})=>row)}function aggregateValues(aggregation,rows,values){if(typeof aggregation=="function")return aggregation(rows,values);if(aggregation==="count")return rows.length;const defined=values.filter(value=>value!=null);if(aggregation==="unique")return[...new Set(defined)];if(aggregation==="uniqueCount")return new Set(defined).size;const numeric=defined.map(finiteValue).filter(value=>value!==void 0);if(numeric.length===0)return aggregation==="extent"?[]:void 0;if(aggregation==="sum"||aggregation==="mean"){let scale=0;for(const value of numeric)scale=Math.max(scale,Math.abs(value));let scaledTotal=0;if(scale>0)for(const value of numeric)scaledTotal+=value/scale;const result=scale===0?0:aggregation==="sum"?scaledTotal*scale:scaledTotal/numeric.length*scale;return Number.isFinite(result)?result:void 0}if(aggregation==="median"){const sorted=[...numeric].sort((left2,right2)=>left2-right2),middle=Math.floor(sorted.length/2);if(sorted.length%2!==0)return sorted[middle];const left=sorted[middle-1]??0,right=sorted[middle]??0,median=Math.sign(left)===Math.sign(right)?left+(right-left)/2:left/2+right/2;return Number.isFinite(median)?median:void 0}let minimum=numeric[0],maximum=minimum;for(const value of numeric)value<minimum&&(minimum=value),value>=maximum&&(maximum=value);return aggregation==="min"?minimum:aggregation==="max"?maximum:[minimum,maximum]}function csvCell(value,delimiter,escapeFormulas){let text=comparableText(value);return escapeFormulas&&typeof value!="number"&&UNSAFE_LEADING.test(text)&&(text=`'${text}`),(text.includes(delimiter)||/[\x22\r\n]/u.test(text))&&(text=`"${text.replaceAll('"','""')}"`),text}function rowsAsDelimited(rows,columns,options={}){const delimiter=options.delimiter??",",includeHeaders=options.includeHeaders??!0,escapeFormulas=options.escapeFormulas??!0,requested=options.columnIds?new Set(options.columnIds):void 0,visible=columns.filter((column,index)=>column.hidden!==!0&&(!requested||requested.has(columnId(column,index)))),lines=[];includeHeaders&&lines.push(visible.map((column,index)=>csvCell(column.label??columnId(column,index),delimiter,!1)).join(delimiter));for(const row of rows)lines.push(visible.map(column=>csvCell(columnValue(column,row),delimiter,escapeFormulas)).join(delimiter));return lines.join(`\r
2
2
  `)}export{aggregateValues,columnId,columnValue,filterRows,matchesFilter,pathValue,rowsAsDelimited,searchRows,sortRows};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chartValueFractionDigits}from"../../charts/chart/chart-number-format.js";import{finiteNumber,finiteRatio}from"../../../internal/numbers.js";import{styles}from"./gauge.styles.js";import{LYRA_DEFAULT_gaugeLabel,LYRA_DEFAULT_gaugeValueLabel}from"../../../internal/default-strings/data.generated.js";const SWEEP_DEG=270,START_DEG=135,RADIUS=40,CENTER=50,STROKE=10,LINEAR_STROKE=6,LINEAR_BAR_Y=15,LINEAR_TEXT_Y=8,LINEAR_LENGTH=100,RADIAL_VALUE_CHARACTERS=9,RADIAL_LABEL_CHARACTERS=12,LINEAR_VALUE_CHARACTERS=10,LINEAR_LABEL_CHARACTERS=10;function abbreviateSvgText(value,maxCharacters){const characters=Array.from(value);return characters.length<=maxCharacters?value:`${characters.slice(0,maxCharacters-1).join("")}…`}function polarToCartesian(angleDeg){const rad=angleDeg*Math.PI/180;return[CENTER+RADIUS*Math.cos(rad),CENTER+RADIUS*Math.sin(rad)]}function arcPath(startDeg,endDeg){const[sx,sy]=polarToCartesian(startDeg),[ex,ey]=polarToCartesian(endDeg),largeArc=endDeg-startDeg>180?1:0;return`M ${sx} ${sy} A ${RADIUS} ${RADIUS} 0 ${largeArc} 1 ${ex} ${ey}`}const RADIAL_ARC_D=arcPath(START_DEG,START_DEG+SWEEP_DEG),RADIAL_ARC_LENGTH=SWEEP_DEG/360*2*Math.PI*RADIUS,RING_CIRCUMFERENCE=2*Math.PI*RADIUS;class LyraGauge extends LyraElement{constructor(){super(...arguments),this.value=0,this.min=0,this.max=100,this.shape="radial",this.label="",this.withoutValue=!1,this.variant="brand",this.thresholds=[],this.appliedAriaLabel=null,this.explicitAriaLabel=null,this.authorRole=null,this.syncingGeneratedRole=!1,this.serverRendered=!1}static{this.defaultStrings={...super.defaultStrings,gaugeLabel:LYRA_DEFAULT_gaugeLabel,gaugeValueLabel:LYRA_DEFAULT_gaugeValueLabel}}static{this.styles=[LyraElement.styles,contextualSizes,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}connectedCallback(){this.serverRendered||=!this.hasUpdated&&this.shadowRoot!==null,super.connectedCallback()}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(name!=="role"||oldValue===value||this.syncingGeneratedRole)&&(!this.hasUpdated&&this.shadowRoot&&(value==="meter"||value==="img")||(this.authorRole=value,this.requestUpdate()))}get domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}get ratio(){if(!Number.isFinite(this.value))return 0;const{lo,hi}=this.domain;return finiteRatio(this.value,lo,hi)}get effectiveVariant(){if(Number.isFinite(this.value)&&this.thresholds.length>0){const sorted=[...this.thresholds.filter(threshold=>Number.isFinite(threshold.at))].sort((a,b)=>finiteNumber(a.at,0)-finiteNumber(b.at,0));let matched;for(const threshold of sorted)finiteNumber(threshold.at,0)<=this.value&&(matched=threshold.variant);if(matched)return matched}return this.variant}get displayText(){return this.valueText||(Number.isFinite(this.value)?getNumberFormat(this.effectiveLocale,{maximumFractionDigits:chartValueFractionDigits(this.value)}).format(this.value):"")}truncatedTooltip(fullText,renderedText,renderedLabel){return renderedText===fullText&&renderedLabel===(this.label??"")?"":this.label&&fullText?this.localize("gaugeValueLabel",void 0,{label:this.label,value:fullText}):this.label||fullText}willUpdate(changed){super.willUpdate(changed),this.setAttribute("data-effective-variant",this.effectiveVariant);const{lo,hi}=this.domain,finiteTrio=Number.isFinite(this.value)&&Number.isFinite(lo)&&Number.isFinite(hi)&&lo!==hi;if(this.authorRole===null){this.syncingGeneratedRole=!0;try{this.setAttribute("role",finiteTrio?"meter":"img")}finally{this.syncingGeneratedRole=!1}}if(finiteTrio){const clamped=Math.min(hi,Math.max(lo,this.value));this.setAttribute("aria-valuenow",String(clamped)),this.setAttribute("aria-valuemin",String(lo)),this.setAttribute("aria-valuemax",String(hi))}else this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemin"),this.removeAttribute("aria-valuemax");const defaultName=this.label||this.localize("gaugeLabel"),fallbackValueLabel=this.displayText&&(!Number.isFinite(this.value)||lo===hi)?this.localize("gaugeValueLabel",void 0,{label:defaultName,value:this.displayText}):defaultName,currentAriaLabel=this.getAttribute("aria-label");!this.hasUpdated&&this.serverRendered&&currentAriaLabel===(finiteTrio?defaultName:fallbackValueLabel)&&(this.appliedAriaLabel=currentAriaLabel),currentAriaLabel!==this.appliedAriaLabel&&(this.explicitAriaLabel=currentAriaLabel);const nextAriaLabel=this.explicitAriaLabel||(finiteTrio?defaultName:fallbackValueLabel);this.setAttribute("aria-label",nextAriaLabel),this.appliedAriaLabel=nextAriaLabel,finiteTrio&&this.valueText?this.setAttribute("aria-valuetext",this.valueText):this.removeAttribute("aria-valuetext")}renderRadial(){const fullText=this.displayText,text=abbreviateSvgText(fullText,RADIAL_VALUE_CHARACTERS),label=abbreviateSvgText(this.label??"",RADIAL_LABEL_CHARACTERS),tooltip=this.truncatedTooltip(fullText,text,label),dashoffset=RADIAL_ARC_LENGTH*(1-this.ratio);return html`<svg
1
+ import{__decorate}from"tslib";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chartValueFractionDigits}from"../../charts/chart/chart-number-format.js";import{finiteNumber,finiteRatio}from"../../../internal/numbers.js";import{styles}from"./gauge.styles.js";import{LYRA_DEFAULT_gaugeLabel,LYRA_DEFAULT_gaugeValueLabel}from"../../../internal/default-strings/data.generated.js";const SWEEP_DEG=270,START_DEG=135,RADIUS=40,CENTER=50,STROKE=10,LINEAR_STROKE=6,LINEAR_BAR_Y=15,LINEAR_TEXT_Y=8,LINEAR_LENGTH=100,RADIAL_VALUE_CHARACTERS=9,RADIAL_LABEL_CHARACTERS=12,LINEAR_VALUE_CHARACTERS=10,LINEAR_LABEL_CHARACTERS=10;function abbreviateSvgText(value,maxCharacters){const characters=Array.from(value);return characters.length<=maxCharacters?value:`${characters.slice(0,maxCharacters-1).join("")}…`}function polarToCartesian(angleDeg){const rad=angleDeg*Math.PI/180;return[CENTER+RADIUS*Math.cos(rad),CENTER+RADIUS*Math.sin(rad)]}function arcPath(startDeg,endDeg){const[sx,sy]=polarToCartesian(startDeg),[ex,ey]=polarToCartesian(endDeg),largeArc=endDeg-startDeg>180?1:0;return`M ${sx} ${sy} A ${RADIUS} ${RADIUS} 0 ${largeArc} 1 ${ex} ${ey}`}const RADIAL_ARC_D=arcPath(START_DEG,START_DEG+SWEEP_DEG),RADIAL_ARC_LENGTH=SWEEP_DEG/360*2*Math.PI*RADIUS,RING_CIRCUMFERENCE=2*Math.PI*RADIUS;class LyraGauge extends LyraElement{constructor(){super(...arguments),this.value=0,this.min=0,this.max=100,this.shape="radial",this.label="",this.withoutValue=!1,this.variant="brand",this.thresholds=[],this.appliedAriaLabel=null,this.explicitAriaLabel=null,this.authorRole=null,this.syncingGeneratedRole=!1,this.serverRendered=!1}static{this.defaultStrings={...super.defaultStrings,gaugeLabel:LYRA_DEFAULT_gaugeLabel,gaugeValueLabel:LYRA_DEFAULT_gaugeValueLabel}}static{this.styles=[LyraElement.styles,contextualSizes,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}connectedCallback(){this.serverRendered||=!this.hasUpdated&&this.shadowRoot!==null,super.connectedCallback()}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(name!=="role"||oldValue===value||this.syncingGeneratedRole)&&(!this.hasUpdated&&this.shadowRoot&&(value==="meter"||value==="img")||(this.authorRole=value,this.requestUpdate()))}get domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}get ratio(){if(!Number.isFinite(this.value))return 0;const{lo,hi}=this.domain;return finiteRatio(this.value,lo,hi)}get effectiveVariant(){if(Number.isFinite(this.value)&&this.thresholds.length>0){let matchedAt=Number.NEGATIVE_INFINITY,matched;if(this.thresholds.forEach(threshold=>{const rawAt=threshold.at;if(!Number.isFinite(rawAt))return;const at=finiteNumber(rawAt,0);at<=this.value&&at>=matchedAt&&(matchedAt=at,matched=threshold.variant)}),matched)return matched}return this.variant}get displayText(){return this.valueText||(Number.isFinite(this.value)?getNumberFormat(this.effectiveLocale,{maximumFractionDigits:chartValueFractionDigits(this.value)}).format(this.value):"")}truncatedTooltip(fullText,renderedText,renderedLabel){return renderedText===fullText&&renderedLabel===(this.label??"")?"":this.label&&fullText?this.localize("gaugeValueLabel",void 0,{label:this.label,value:fullText}):this.label||fullText}willUpdate(changed){super.willUpdate(changed),this.setAttribute("data-effective-variant",this.effectiveVariant);const{lo,hi}=this.domain,finiteTrio=Number.isFinite(this.value)&&Number.isFinite(lo)&&Number.isFinite(hi)&&lo!==hi;if(this.authorRole===null){this.syncingGeneratedRole=!0;try{this.setAttribute("role",finiteTrio?"meter":"img")}finally{this.syncingGeneratedRole=!1}}if(finiteTrio){const clamped=Math.min(hi,Math.max(lo,this.value));this.setAttribute("aria-valuenow",String(clamped)),this.setAttribute("aria-valuemin",String(lo)),this.setAttribute("aria-valuemax",String(hi))}else this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemin"),this.removeAttribute("aria-valuemax");const defaultName=this.label||this.localize("gaugeLabel"),fallbackValueLabel=this.displayText&&(!Number.isFinite(this.value)||lo===hi)?this.localize("gaugeValueLabel",void 0,{label:defaultName,value:this.displayText}):defaultName,currentAriaLabel=this.getAttribute("aria-label");!this.hasUpdated&&this.serverRendered&&currentAriaLabel===(finiteTrio?defaultName:fallbackValueLabel)&&(this.appliedAriaLabel=currentAriaLabel),currentAriaLabel!==this.appliedAriaLabel&&(this.explicitAriaLabel=currentAriaLabel);const nextAriaLabel=this.explicitAriaLabel||(finiteTrio?defaultName:fallbackValueLabel);this.setAttribute("aria-label",nextAriaLabel),this.appliedAriaLabel=nextAriaLabel,finiteTrio&&this.valueText?this.setAttribute("aria-valuetext",this.valueText):this.removeAttribute("aria-valuetext")}renderRadial(){const fullText=this.displayText,text=abbreviateSvgText(fullText,RADIAL_VALUE_CHARACTERS),label=abbreviateSvgText(this.label??"",RADIAL_LABEL_CHARACTERS),tooltip=this.truncatedTooltip(fullText,text,label),dashoffset=RADIAL_ARC_LENGTH*(1-this.ratio);return html`<svg
2
2
  part="base"
3
3
  viewBox="0 0 100 100"
4
4
  aria-hidden="true"
@@ -265,4 +265,4 @@ focus(options?:FocusOptions):void;
265
265
  blur():void;
266
266
  /** Forwards host clicks to the first rendered control so callers can interact with this wrapper
267
267
  * as if it exposed a single root control. */
268
- click():void;private setValue;private onValueCommit;private addRelationshipType;private removeRelationshipType;private addNodeType;private removeNodeType;private captureChipRemovalFocus;private markTouched;private runQuery;private saveQuery;private loadQuery;private deleteQuery;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hopOptions;private labelForType;protected createRenderRoot():HTMLElement|DocumentFragment;private renderTypeFilter;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-graph-query-builder':LyraGraphQueryBuilder;}}
268
+ click():void;private setValue;private onValueCommit;private addRelationshipType;private removeRelationshipType;private addNodeType;private removeNodeType;private captureChipRemovalFocus;private markTouched;private runQuery;private saveQuery;private loadQuery;private deleteQuery;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private hopOptions;protected createRenderRoot():HTMLElement|DocumentFragment;private renderTypeFilter;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-graph-query-builder':LyraGraphQueryBuilder;}}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{BUILDER_CHILD_EVENTS,containShadowChildEvent}from"../../../internal/child-event-containment.js";import{boundedRecordString,normalizeLabeledOptions}from"../../../internal/record-normalize.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{styles}from"./graph-query-builder.styles.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_TYPES=500,MAX_SAVED_QUERIES=200,MAX_TEXT=256,EMPTY_STRINGS=Object.freeze([]),EMPTY_VALUE=Object.freeze({startId:"",endId:"",relationshipTypes:EMPTY_STRINGS,nodeTypes:EMPTY_STRINGS,direction:"both",minHops:1,maxHops:1}),EMPTY_OPTIONS=Object.freeze([]),EMPTY_SAVED=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value){return boundedRecordString(value,MAX_TEXT)}function stringArray(value){return Array.isArray(value)?Object.freeze([...new Set(value.slice(0,MAX_TYPES).filter(entry=>typeof entry=="string").map(entry=>boundedString(entry)).filter(Boolean))]):EMPTY_STRINGS}function normalizeGraphQuery(value){const record=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,direction=ownValue(record,"direction");return Object.freeze({startId:boundedString(ownValue(record,"startId")),endId:boundedString(ownValue(record,"endId")),relationshipTypes:stringArray(ownValue(record,"relationshipTypes")),nodeTypes:stringArray(ownValue(record,"nodeTypes")),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof ownValue(record,"minHops")=="number"?ownValue(record,"minHops"):EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof ownValue(record,"maxHops")=="number"?ownValue(record,"maxHops"):EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)})}function normalizeTypeOptions(value){return Array.isArray(value)?normalizeLabeledOptions(value,MAX_TYPES,MAX_TEXT):EMPTY_OPTIONS}function normalizeSavedQueries(value){if(!Array.isArray(value))return EMPTY_SAVED;const ids=new Set,result=[];for(const candidate of value.slice(0,MAX_SAVED_QUERIES)){if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const id=boundedString(ownValue(candidate,"id"));id.trim().length===0||ids.has(id)||(ids.add(id),result.push(Object.freeze({id,name:boundedString(ownValue(candidate,"name")),query:normalizeGraphQuery(ownValue(candidate,"query"))})))}return Object.freeze(result)}class LyraGraphQueryBuilder extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,select:LYRA_DEFAULT_select}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-query-run-request","lr-query-run","lr-query-save-request","lr-query-save","lr-query-load-request","lr-query-load"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get relationshipTypeOptions(){return this._relationshipTypeOptions}set relationshipTypeOptions(value){if(value===this.relationshipOptionsSource||value===this._relationshipTypeOptions)return;this.relationshipOptionsSource=value;const previous=this._relationshipTypeOptions;this._relationshipTypeOptions=normalizeTypeOptions(value),this.requestUpdate("relationshipTypeOptions",previous)}get nodeTypeOptions(){return this._nodeTypeOptions}set nodeTypeOptions(value){if(value===this.nodeOptionsSource||value===this._nodeTypeOptions)return;this.nodeOptionsSource=value;const previous=this._nodeTypeOptions;this._nodeTypeOptions=normalizeTypeOptions(value),this.requestUpdate("nodeTypeOptions",previous)}get savedQueries(){return this._savedQueries}set savedQueries(value){if(value===this.savedQueriesSource||value===this._savedQueries)return;this.savedQueriesSource=value;const previous=this._savedQueries;this._savedQueries=normalizeSavedQueries(value),this.requestUpdate("savedQueries",previous)}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this._relationshipTypeOptions=EMPTY_OPTIONS,this._nodeTypeOptions=EMPTY_OPTIONS,this._savedQueries=EMPTY_SAVED,this.hopLimit=6,this.label="",this.hint="",this.errorText="",this._errors={},this.touchedFields=new Set,this.saveName="",this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("graph-query-builder-label"),this.hintId=nextId("graph-query-builder-hint"),this.errorId=nextId("graph-query-builder-error"),this._fieldsetDisabled=!1,this._name="",this._value=EMPTY_VALUE,this.defaultValue=normalizeGraphQuery(EMPTY_VALUE),this.defaultValueCaptured=!1,this._disabled=!1,this.hasInteracted=!1,this.removalFocusGeneration=0,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.syncValidityCustomStates())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",Object.freeze({value:this._value}),detail=>this.emit("lr-change",detail))},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.syncFormState()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.removalFocusGeneration++,this.pendingRemovalFocus=void 0,this.releaseExternalDescription(),super.disconnectedCallback()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"]')??null:null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get value(){return this._value}set value(next){if(next===this.valueSource||next===this._value)return;this.valueSource=next;const old=this._value;this._value=normalizeGraphQuery(next),this.syncFormState(),this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._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._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.validityController&&this.syncFormState(),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.validity.customError&&(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})))}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!(!firstInvalidPart||!this.renderRoot))return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={},flags={};return this._value.startId.trim()||(errors["start-input"]=this.localize("fieldRequired"),flags.valueMissing=!0),this._value.minHops>this._value.maxHops&&(errors["max-hops"]=this.localize("graphQueryHopRangeInvalid"),flags.rangeUnderflow=!0),{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:!0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.hasInteracted=!1,this.captureDefaultValue(),this.value=this.defaultValue,this.touchedFields=new Set,this.saveName=""}captureDefaultValue(){this.defaultValueCaptured||(this.defaultValue=normalizeGraphQuery(this._value),this.defaultValueCaptured=!0)}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=normalizeGraphQuery(parsed))}catch{}this.value=restored}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncFormState(),this.requestUpdate())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focusFirstControl(options){if(!this.renderRoot||this.liveDisabled)return;(this.renderRoot.querySelector('[part="start-input"]')||this.renderRoot.querySelector('[part="end-input"]')||this.renderRoot.querySelector('[part="min-hops"]')||this.renderRoot.querySelector('[part="max-hops"]')||this.renderRoot.querySelector('[part="direction"]')||this.renderRoot.querySelector('[part="save-name-input"]'))?.focus(options)}focus(options){this.focusFirstControl(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}click(){this.focusFirstControl()}setValue(next,committed=!0){if(this.effectiveDisabled)return;this.hasInteracted=!0,this.value=next;const detail=Object.freeze({value:this._value});emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}addRelationshipType(type){!type||this._value.relationshipTypes.includes(type)||this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.captureChipRemovalFocus("relationship",type,this._value.relationshipTypes),this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){!type||this._value.nodeTypes.includes(type)||this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.captureChipRemovalFocus("node-type",type,this._value.nodeTypes),this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}captureChipRemovalFocus(group,value,selected){const active=shadowFocusTarget(this),expectedPart=group==="relationship"?"relationship-chips":"node-type-chips";if(active?.localName!==tag("chip")||active.getAttribute("value")!==value||active.closest(tag("chip-group"))?.getAttribute("part")!==expectedPart)return;const index=selected.indexOf(value),survivors=selected.filter(candidate=>candidate!==value),targetValue=survivors[Math.min(Math.max(index,0),survivors.length-1)];this.pendingRemovalFocus={kind:"chip",group,targetValue},this.removalFocusGeneration++}markTouched(part){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(part)&&(this.touchedFields=new Set(this.touchedFields).add(part))}runQuery(){if(this.effectiveDisabled||!this.reportValidity())return;const detail=()=>Object.freeze({query:normalizeGraphQuery(this._value)});this.emit("lr-query-run-request",detail(),{cancelable:!0}).defaultPrevented||this.emit("lr-query-run",detail())}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;const detail=()=>Object.freeze({name,query:normalizeGraphQuery(this._value)});this.emit("lr-query-save-request",detail(),{cancelable:!0}).defaultPrevented||(this.saveName="",this.emit("lr-query-save",detail()))}loadQuery(item){if(this.effectiveDisabled)return;const detail=()=>Object.freeze({queryId:item.id,query:normalizeGraphQuery(item.query)});this.emit("lr-query-load-request",detail(),{cancelable:!0}).defaultPrevented||(this.setValue({...EMPTY_VALUE,...item.query}),this.emit("lr-query-load",detail()))}deleteQuery(item){if(this.effectiveDisabled)return;const detail=()=>Object.freeze({queryId:item.id});this.emit("lr-query-delete-request",detail(),{cancelable:!0}).defaultPrevented||this.emit("lr-query-delete",detail())}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated||this.captureDefaultValue(),!changed.has("savedQueries"))return;const active=shadowFocusTarget(this);if(active?.getAttribute("part")!=="saved-delete-button")return;const focusedId=active.closest("[data-query-id]")?.dataset.queryId;if(!focusedId||this.savedQueries.some(item=>item.id===focusedId))return;const index=(changed.get("savedQueries")??[]).findIndex(item=>item.id===focusedId),target=this.savedQueries[Math.min(Math.max(index,0),this.savedQueries.length-1)];this.pendingRemovalFocus={kind:"saved",targetId:target?.id},this.removalFocusGeneration++}updated(changed){super.updated(changed),this.publishValiditySnapshot(),this.syncExternalDescription();const pending=this.pendingRemovalFocus;if(!pending)return;this.pendingRemovalFocus=void 0;const generation=this.removalFocusGeneration;this.scheduleAfterUpdate(()=>{if(!(generation!==this.removalFocusGeneration||!this.isConnected)){if(pending.kind==="chip"){if(pending.targetValue){const part=pending.group==="relationship"?"relationship-chips":"node-type-chips",chip=[...this.shadowRoot?.querySelectorAll(`[part="${part}"] ${tag("chip")}`)??[]].find(candidate=>candidate.getAttribute("value")===pending.targetValue);if(chip){chip.focus();return}}const pickerPart=pending.group==="relationship"?"relationship-picker":"node-type-picker";this.shadowRoot?.querySelector(`[part="${pickerPart}"]`)?.focus();return}if(pending.targetId){const action=[...this.shadowRoot?.querySelectorAll("[data-query-id]")??[]].find(candidate=>candidate.dataset.queryId===pending.targetId)?.querySelector('[part="saved-delete-button"]');if(action){action.focus();return}}this.shadowRoot?.querySelector('[part="save-name-input"]')?.focus()}},"graph-query-removal-focus")}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20),options=new Set(Array.from({length:limit},(_,i)=>i+1));return options.add(this._value.minHops),options.add(this._value.maxHops),[...options].sort((a,b)=>a-b)}labelForType(options,value){return options.find(o=>o.value===value)?.label??value}createRenderRoot(){const root=super.createRenderRoot();for(const type of BUILDER_CHILD_EVENTS)root.addEventListener(type,containShadowChildEvent);return root}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker",chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips",pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel"),available=options.filter(o=>!selected.includes(o.value));return html`
1
+ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{BUILDER_CHILD_EVENTS,containShadowChildEvent}from"../../../internal/child-event-containment.js";import{boundedRecordString,normalizeLabeledOptions}from"../../../internal/record-normalize.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{styles}from"./graph-query-builder.styles.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_TYPES=500,MAX_SAVED_QUERIES=200,MAX_TEXT=256,EMPTY_STRINGS=Object.freeze([]),EMPTY_VALUE=Object.freeze({startId:"",endId:"",relationshipTypes:EMPTY_STRINGS,nodeTypes:EMPTY_STRINGS,direction:"both",minHops:1,maxHops:1}),EMPTY_OPTIONS=Object.freeze([]),EMPTY_SAVED=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value){return boundedRecordString(value,MAX_TEXT)}function stringArray(value){return Array.isArray(value)?Object.freeze([...new Set(value.slice(0,MAX_TYPES).filter(entry=>typeof entry=="string").map(entry=>boundedString(entry)).filter(Boolean))]):EMPTY_STRINGS}function normalizeGraphQuery(value){const record=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,direction=ownValue(record,"direction");return Object.freeze({startId:boundedString(ownValue(record,"startId")),endId:boundedString(ownValue(record,"endId")),relationshipTypes:stringArray(ownValue(record,"relationshipTypes")),nodeTypes:stringArray(ownValue(record,"nodeTypes")),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof ownValue(record,"minHops")=="number"?ownValue(record,"minHops"):EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof ownValue(record,"maxHops")=="number"?ownValue(record,"maxHops"):EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)})}function normalizeTypeOptions(value){return Array.isArray(value)?normalizeLabeledOptions(value,MAX_TYPES,MAX_TEXT):EMPTY_OPTIONS}function normalizeSavedQueries(value){if(!Array.isArray(value))return EMPTY_SAVED;const ids=new Set,result=[];for(const candidate of value.slice(0,MAX_SAVED_QUERIES)){if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const id=boundedString(ownValue(candidate,"id"));id.trim().length===0||ids.has(id)||(ids.add(id),result.push(Object.freeze({id,name:boundedString(ownValue(candidate,"name")),query:normalizeGraphQuery(ownValue(candidate,"query"))})))}return Object.freeze(result)}class LyraGraphQueryBuilder extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,select:LYRA_DEFAULT_select}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-query-run-request","lr-query-run","lr-query-save-request","lr-query-save","lr-query-load-request","lr-query-load"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get relationshipTypeOptions(){return this._relationshipTypeOptions}set relationshipTypeOptions(value){if(value===this.relationshipOptionsSource||value===this._relationshipTypeOptions)return;this.relationshipOptionsSource=value;const previous=this._relationshipTypeOptions;this._relationshipTypeOptions=normalizeTypeOptions(value),this.requestUpdate("relationshipTypeOptions",previous)}get nodeTypeOptions(){return this._nodeTypeOptions}set nodeTypeOptions(value){if(value===this.nodeOptionsSource||value===this._nodeTypeOptions)return;this.nodeOptionsSource=value;const previous=this._nodeTypeOptions;this._nodeTypeOptions=normalizeTypeOptions(value),this.requestUpdate("nodeTypeOptions",previous)}get savedQueries(){return this._savedQueries}set savedQueries(value){if(value===this.savedQueriesSource||value===this._savedQueries)return;this.savedQueriesSource=value;const previous=this._savedQueries;this._savedQueries=normalizeSavedQueries(value),this.requestUpdate("savedQueries",previous)}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this._relationshipTypeOptions=EMPTY_OPTIONS,this._nodeTypeOptions=EMPTY_OPTIONS,this._savedQueries=EMPTY_SAVED,this.hopLimit=6,this.label="",this.hint="",this.errorText="",this._errors={},this.touchedFields=new Set,this.saveName="",this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("graph-query-builder-label"),this.hintId=nextId("graph-query-builder-hint"),this.errorId=nextId("graph-query-builder-error"),this._fieldsetDisabled=!1,this._name="",this._value=EMPTY_VALUE,this.defaultValue=normalizeGraphQuery(EMPTY_VALUE),this.defaultValueCaptured=!1,this._disabled=!1,this.hasInteracted=!1,this.removalFocusGeneration=0,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.syncValidityCustomStates())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",Object.freeze({value:this._value}),detail=>this.emit("lr-change",detail))},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.syncFormState()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.removalFocusGeneration++,this.pendingRemovalFocus=void 0,this.releaseExternalDescription(),super.disconnectedCallback()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"]')??null:null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get value(){return this._value}set value(next){if(next===this.valueSource||next===this._value)return;this.valueSource=next;const old=this._value;this._value=normalizeGraphQuery(next),this.syncFormState(),this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._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._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.validityController&&this.syncFormState(),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.validity.customError&&(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})))}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!(!firstInvalidPart||!this.renderRoot))return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={},flags={};return this._value.startId.trim()||(errors["start-input"]=this.localize("fieldRequired"),flags.valueMissing=!0),this._value.minHops>this._value.maxHops&&(errors["max-hops"]=this.localize("graphQueryHopRangeInvalid"),flags.rangeUnderflow=!0),{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:!0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.hasInteracted=!1,this.captureDefaultValue(),this.value=this.defaultValue,this.touchedFields=new Set,this.saveName=""}captureDefaultValue(){this.defaultValueCaptured||(this.defaultValue=normalizeGraphQuery(this._value),this.defaultValueCaptured=!0)}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=normalizeGraphQuery(parsed))}catch{}this.value=restored}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncFormState(),this.requestUpdate())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focusFirstControl(options){if(!this.renderRoot||this.liveDisabled)return;(this.renderRoot.querySelector('[part="start-input"]')||this.renderRoot.querySelector('[part="end-input"]')||this.renderRoot.querySelector('[part="min-hops"]')||this.renderRoot.querySelector('[part="max-hops"]')||this.renderRoot.querySelector('[part="direction"]')||this.renderRoot.querySelector('[part="save-name-input"]'))?.focus(options)}focus(options){this.focusFirstControl(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}click(){this.focusFirstControl()}setValue(next,committed=!0){if(this.effectiveDisabled)return;this.hasInteracted=!0,this.value=next;const detail=Object.freeze({value:this._value});emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}addRelationshipType(type){!type||this._value.relationshipTypes.includes(type)||this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.captureChipRemovalFocus("relationship",type,this._value.relationshipTypes),this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){!type||this._value.nodeTypes.includes(type)||this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.captureChipRemovalFocus("node-type",type,this._value.nodeTypes),this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}captureChipRemovalFocus(group,value,selected){const active=shadowFocusTarget(this),expectedPart=group==="relationship"?"relationship-chips":"node-type-chips";if(active?.localName!==tag("chip")||active.getAttribute("value")!==value||active.closest(tag("chip-group"))?.getAttribute("part")!==expectedPart)return;const index=selected.indexOf(value),survivors=selected.filter(candidate=>candidate!==value),targetValue=survivors[Math.min(Math.max(index,0),survivors.length-1)];this.pendingRemovalFocus={kind:"chip",group,targetValue},this.removalFocusGeneration++}markTouched(part){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(part)&&(this.touchedFields=new Set(this.touchedFields).add(part))}runQuery(){if(this.effectiveDisabled||!this.reportValidity())return;const detail=()=>Object.freeze({query:normalizeGraphQuery(this._value)});this.emit("lr-query-run-request",detail(),{cancelable:!0}).defaultPrevented||this.emit("lr-query-run",detail())}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;const detail=()=>Object.freeze({name,query:normalizeGraphQuery(this._value)});this.emit("lr-query-save-request",detail(),{cancelable:!0}).defaultPrevented||(this.saveName="",this.emit("lr-query-save",detail()))}loadQuery(item){if(this.effectiveDisabled)return;const detail=()=>Object.freeze({queryId:item.id,query:normalizeGraphQuery(item.query)});this.emit("lr-query-load-request",detail(),{cancelable:!0}).defaultPrevented||(this.setValue({...EMPTY_VALUE,...item.query}),this.emit("lr-query-load",detail()))}deleteQuery(item){if(this.effectiveDisabled)return;const detail=()=>Object.freeze({queryId:item.id});this.emit("lr-query-delete-request",detail(),{cancelable:!0}).defaultPrevented||this.emit("lr-query-delete",detail())}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated||this.captureDefaultValue(),!changed.has("savedQueries"))return;const active=shadowFocusTarget(this);if(active?.getAttribute("part")!=="saved-delete-button")return;const focusedId=active.closest("[data-query-id]")?.dataset.queryId;if(!focusedId||this.savedQueries.some(item=>item.id===focusedId))return;const index=(changed.get("savedQueries")??[]).findIndex(item=>item.id===focusedId),target=this.savedQueries[Math.min(Math.max(index,0),this.savedQueries.length-1)];this.pendingRemovalFocus={kind:"saved",targetId:target?.id},this.removalFocusGeneration++}updated(changed){super.updated(changed),this.publishValiditySnapshot(),this.syncExternalDescription();const pending=this.pendingRemovalFocus;if(!pending)return;this.pendingRemovalFocus=void 0;const generation=this.removalFocusGeneration;this.scheduleAfterUpdate(()=>{if(!(generation!==this.removalFocusGeneration||!this.isConnected)){if(pending.kind==="chip"){if(pending.targetValue){const part=pending.group==="relationship"?"relationship-chips":"node-type-chips",chip=[...this.shadowRoot?.querySelectorAll(`[part="${part}"] ${tag("chip")}`)??[]].find(candidate=>candidate.getAttribute("value")===pending.targetValue);if(chip){chip.focus();return}}const pickerPart=pending.group==="relationship"?"relationship-picker":"node-type-picker";this.shadowRoot?.querySelector(`[part="${pickerPart}"]`)?.focus();return}if(pending.targetId){const action=[...this.shadowRoot?.querySelectorAll("[data-query-id]")??[]].find(candidate=>candidate.dataset.queryId===pending.targetId)?.querySelector('[part="saved-delete-button"]');if(action){action.focus();return}}this.shadowRoot?.querySelector('[part="save-name-input"]')?.focus()}},"graph-query-removal-focus")}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20),options=new Set(Array.from({length:limit},(_,i)=>i+1));return options.add(this._value.minHops),options.add(this._value.maxHops),[...options].sort((a,b)=>a-b)}createRenderRoot(){const root=super.createRenderRoot();for(const type of BUILDER_CHILD_EVENTS)root.addEventListener(type,containShadowChildEvent);return root}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker",chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips",pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel"),selectedValues=new Set(selected),selectedLabels=new Map,available=options.filter(option=>{const value=option.value;return selectedValues.has(value)?(selectedLabels.has(value)||selectedLabels.set(value,option.label),!1):!0});return html`
2
2
  <div part="filter-group" data-kind=${kind}>
3
3
  <lr-select
4
4
  part=${pickerPart}
@@ -15,7 +15,7 @@ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/valu
15
15
  ?removable=${!disabled}
16
16
  value=${t}
17
17
  @lr-remove=${event=>{event.stopPropagation(),remove(t)}}
18
- >${this.labelForType(options,t)}</lr-chip
18
+ >${selectedLabels.get(t)??t}</lr-chip
19
19
  >`)}
20
20
  </lr-chip-group>
21
21
  </div>
@@ -0,0 +1 @@
1
+ const MAX_ENTRIES=1024,MAX_TEXT_UNITS=65536;class HeatmapLabelCache{constructor(){this.widths=new Map,this.clipped=new Map,this.entries=0,this.textUnits=0}key(ctx,text,width){if(typeof text!="string"||text.length>65536)return;const values=[ctx.font,ctx.direction,ctx.fontKerning,ctx.fontStretch,ctx.fontVariantCaps,ctx.letterSpacing,ctx.wordSpacing,ctx.textRendering,text,width];let units=0;for(const value of values)if(typeof value=="string"&&(units+=value.length),units>65536)return;return JSON.stringify(values)}remember(map,key,value,units=key.length){this.entries>=1024||this.textUnits+units>65536||(map.set(key,value),this.entries+=1,this.textUnits+=units)}width(ctx,text){const key=this.key(ctx,text);if(key===void 0)return ctx.measureText(text).width;const cached=this.widths.get(key);if(cached!==void 0)return cached;const width=ctx.measureText(text).width;return this.remember(this.widths,key,width),width}clip(ctx,text,width,compute){const key=this.key(ctx,text,width);if(key===void 0)return compute();const cached=this.clipped.get(key);if(cached!==void 0)return cached;const result=compute();return this.remember(this.clipped,key,result,key.length+result.length),result}}export{HeatmapLabelCache};
@@ -290,6 +290,7 @@ export type LyraHeatmapExportFormat='csv'|'png';
290
290
  * @cssprop [--lr-heatmap-tooltip-bg=var(--lr-color-surface)] - Hover tooltip background.
291
291
  * @cssprop [--lr-heatmap-tooltip-color=var(--lr-color-text)] - Hover tooltip text color.
292
292
  * @cssprop [--lr-heatmap-focus-ring-color=var(--lr-focus-ring-color)] - Focus ring around a focused cell.
293
+ * @cssprop [--lr-heatmap-hover-ring-color=var(--lr-heatmap-focus-ring-color)] - Pointer hover outline on the canvas and accessible cells; independent of keyboard focus and pressed outlines.
293
294
  * @cssprop [--lr-heatmap-annotation-color=var(--lr-color-danger)] - Border color for an annotated cell.
294
295
  * @cssprop [--lr-heatmap-selected-color=var(--lr-color-success)] - Border color for the selected cell.
295
296
  * @cssprop [--lr-heatmap-sticky-label-bg=var(--lr-color-surface)] - Backdrop painted under a frozen `stickyLabels` band. Must be opaque: it covers the same labels the scrolling canvas painted underneath it.
@@ -440,7 +441,7 @@ set calendarGeometry(_value:Readonly<LyraHeatmapCalendarGeometry> |undefined);pr
440
441
  * omits no-data cells (the `-1`/non-finite sentinel `isNoData()` already honors for painting),
441
442
  * the same way the canvas draw path skips them.
442
443
  */
443
- exportData(format:LyraHeatmapExportFormat):string;private exportCsv;private lastPaintedMatrixGeometry?;private get matrixPadTop();private measureColLabelHeight;private measureRowLabelWidth;private ellipsize;private resolvedCalendarWeekdayLabelWidth;private get calendarPadLeft();private measureCalendarWeekdayLabelWidth;private get matrixRowLabels();private get matrixColLabels();private get matrixValues();private get calendarDays();private get calendarData();private _cellSize?;
444
+ exportData(format:LyraHeatmapExportFormat):string;private exportCsv;private lastPaintedMatrixGeometry?;private get matrixPadTop();private measureColLabelHeight;private measureRowLabelWidth;private labelCache?;private withLabelCache;private labelWidth;private ellipsize;private ellipsizeLabel;private resolvedCalendarWeekdayLabelWidth;private get calendarPadLeft();private measureCalendarWeekdayLabelWidth;private get matrixRowLabels();private get matrixColLabels();private get matrixValues();private get calendarDays();private get calendarData();private _cellSize?;
444
445
  /**
445
446
  * Effective per-cell size (CSS px). Originally matrix-mode only; now also
446
447
  * governs calendar mode's cell size (replacing the previously hardcoded
@@ -663,7 +664,7 @@ cellColor?:(pos:MatrixCellPos|CalendarCellPos,value:number)=>string|undefined;pr
663
664
  * fallback color and prevent the custom legend gradient from being assigned. */
664
665
  colorSteps?:readonly string[];private get calendarColumnX();private get calendarRowY();private canvas?;private resizeObserver?;private intersectionObserver?;private drawFrameRequest?;private dprQuery?;private dprChangeListener?;constructor();private calendarSpacingTrackingArmed?;private explicitCalendarSpacingProperties?;requestUpdate(name?:PropertyKey,oldValue?:unknown,options?:PropertyDeclaration):void;private explicitCalendarSpacing;private cachedValueRange;private cachedMatrixData;private cachedCalendarGrid;private cachedCalendarSortedValues;private cachedCalendarCellsByPos;private cachedCalendarCellsByDate;private cachedAnnotations;private warnOnLegendRampMismatch;private cachedLegendStops;private cachedColorSteps;private cachedCalendarAnnotationDates;private cachedMatrixAnnotationPositions;private decorationProjectionTruncated;private cachedCalendarDateByPos;private cachedColumnGeometry?;private cachedRowGeometry?;private cachedAccessiblePositions;private cachedAccessiblePositionsByKey;private cachedAccessiblePositionIndexByKey;private cachedRamp;private canvasHasContent;private canvasVisible;private drawDirty;private overlayRevision;private hoverCell;private focusedCell;private liveText;private accessibleTargetSizePx;private pendingAccessibleFocus;private pendingAccessibleFocusOrigin;private restoringAccessibleFocus;private accessibleFocusGeneration;private readonly announcements;private authorRole;private authorAriaLabel;private generatedAriaLabel;private syncingGeneratedSemantics;private hasSyncedDescribedByElements;attributeChangedCallback(name:string,oldValue:string|null,value:string|null):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private watchDpr;private clearDprWatcher;private onDprChange;protected willUpdate(changed:PropertyValues):void;private rebuildBoundedDecorations;private get projectionTruncated();private get cellProjectionTruncated();private projectedCellCount;private projectionDescription;private rebuildCanonicalMatrixData;private selectedCellDescription;private computeValueRange;private localizedValueLabel;private formatNumericValue;private syncExternalDescription;protected updated(changed:PropertyValues):void;
665
666
  /** Redraws canvas content after an upstream token or theme change. */
666
- refreshTheme():void;private paintedTheme?;private themeSignature;private onThemeSignal;private refreshAccessibleTargetSize;private scaleEndpoints;private labelColor;private labelFont;private stickyLabelBg;private noDataFill;private focusRingColor;private annotationColor;private selectedColor;private strokeCellState;private isSelectedPos;private draw;private requestDraw;private repaintFocusRing;private scheduleDraw;private cancelDrawFrame;private resolveColorStep;private colorRamp;private calendarCellSize;private calendarSpacing;private clampFitCellSize;private columnXFor;private rowYFor;private calendarColumnPositions;private calendarRowPositions;private weekdayLabels;private paintCalendarAxisLabels;private drawCalendar;private matrixCellSize;private matrixRowHeight;private matrixCellShape;private calendarCellShape;private fillMatrixCell;private paintMatrixCell;private paintMatrixFocusOverlays;private focusRepaintBounds;private repaintMatrixFocusCell;private paintCalendarCell;private fillCalendarCell;private recordCalendarGeometry;private paintCalendarFocusOverlays;private repaintCalendarFocusCell;private drawMatrix;private paintMatrixRowLabels;private paintMatrixColLabels;private paintFrozenLabelBands;private frozenBandCanvas;private sizeCanvas;private paintFrozenBand;private hitTest;private matrixNavigationGeometry;private calendarNavigationGeometry;private hitTestMatrix;private firstInteractiveMatrixCell;private nextInteractiveMatrixCell;private firstInteractiveCalendarCell;private nextInteractiveCalendarCell;private hitTestCalendar;private calendarCellAt;private calendarValueAt;private calendarDateAt;private calendarPos;private cellRect;private accessibleCellRect;private defaultCellText;private matrixCellText;private calendarCellText;private valueAt;private resolveCellText;private isCellInteractive;
667
+ refreshTheme():void;private paintedTheme?;private themeSignature;private onThemeSignal;private refreshAccessibleTargetSize;private scaleEndpoints;private labelColor;private labelFont;private stickyLabelBg;private noDataFill;private focusRingColor;private annotationColor;private selectedColor;private strokeCellState;private isSelectedPos;private draw;private requestDraw;private syncDeferredFitFrame;private repaintFocusRing;private scheduleDraw;private cancelDrawFrame;private resolveColorStep;private colorRamp;private calendarCellSize;private calendarSpacing;private clampFitCellSize;private columnXFor;private rowYFor;private calendarColumnPositions;private calendarRowPositions;private weekdayLabels;private paintCalendarAxisLabels;private drawCalendar;private paintCalendar;private matrixCellSize;private matrixRowHeight;private matrixCellShape;private calendarCellShape;private fillMatrixCell;private paintMatrixCell;private paintMatrixFocusOverlays;private focusRepaintBounds;private repaintMatrixFocusCell;private paintMatrixFocusCell;private paintCalendarCell;private fillCalendarCell;private recordCalendarGeometry;private paintCalendarFocusOverlays;private repaintCalendarFocusCell;private paintCalendarFocusCell;private drawMatrix;private paintMatrix;private paintMatrixRowLabels;private paintMatrixColLabels;private paintFrozenLabelBands;private frozenBandCanvas;private sizeCanvas;private paintFrozenBand;private hitTest;private matrixNavigationGeometry;private calendarNavigationGeometry;private hitTestMatrix;private firstInteractiveMatrixCell;private nextInteractiveMatrixCell;private firstInteractiveCalendarCell;private nextInteractiveCalendarCell;private hitTestCalendar;private calendarCellAt;private calendarValueAt;private calendarDateAt;private calendarPos;private cellRect;private accessibleCellRect;private defaultCellText;private matrixCellText;private calendarCellText;private valueAt;private resolveCellText;private isCellInteractive;
667
668
  /** Refreshes the aria-hidden shadow mirror and shared light-DOM sink for a newly-focused cell.
668
669
  * The selected state goes through the same `heatmapSelectedCellLabel`
669
670
  * template as the host aria-label, so a locale can place the "selected"