@aceshooting/lyra-ui 28.1.0 → 28.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
- package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
- package/dist/components/charts/chart/box-plot.class.d.ts +2 -2
- package/dist/components/charts/chart/box-plot.class.js +14 -14
- package/dist/components/charts/chart/chart.class.d.ts +2 -2
- package/dist/components/charts/chart/chart.class.js +14 -14
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +8 -8
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +2 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/stat/stat.class.d.ts +11 -9
- package/dist/components/data/stat/stat.class.js +4 -2
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/select/select.class.js +4 -3
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/utility/tour/tour.class.js +4 -4
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- package/dist/internal/overlay-manager.d.ts +2 -0
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-push-to-talk.md +3 -0
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-stat.md +4 -0
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +44 -0
- package/llms/shared.md +44 -0
- package/package.json +5 -5
- 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(),
|
|
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
|
-
${
|
|
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=${
|
|
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}
|
|
@@ -61,7 +61,8 @@ timesliceMs:number;mimeType:string;deviceId:string;
|
|
|
61
61
|
/** Additional audio constraints (`echoCancellation`, …). `deviceId` has one authority: the
|
|
62
62
|
* top-level `deviceId` property. */
|
|
63
63
|
audioConstraints?:PushToTalkAudioConstraints;
|
|
64
|
-
/** Enables `lr-level` sampling. Changes take effect immediately during an active recording.
|
|
64
|
+
/** Enables `lr-level` sampling. Changes take effect immediately during an active recording.
|
|
65
|
+
* If audio analysis cannot initialize, recording continues without level events. */
|
|
65
66
|
levelEvents:boolean;
|
|
66
67
|
/** `> 0` auto-stops the take at this many milliseconds (a stuck-key guard); `0` (the default)
|
|
67
68
|
* never auto-stops. Clamped to `[1, MAX_TIMEOUT_MS]` at the point it's handed to `setTimeout()`
|
|
@@ -7,7 +7,7 @@ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,
|
|
|
7
7
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
8
8
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
9
9
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
10
|
-
`)}function pulseGlyph(){return icon(svg`<circle cx="12" cy="12" r="6"></circle>`)}class LyraPushToTalk extends LyraElement{constructor(){super(...arguments),this._mode="hold",this.timesliceMs=0,this.mimeType="",this.deviceId="",this.levelEvents=!1,this.maxDurationMs=0,this.withoutTimer=!1,this.disabled=!1,this.elapsedMs=0,this.captureSupported=!1,this._state="idle",this._stream=null,this.describedByReflected=!1,this.chunks=[],this.recordingStartedAt=0,this.lifecycleGeneration=0,this.captureSequence=0,this.intentSequence=0,this.cancelRequested=!1,this.recorderStopRequested=!1,this.recorderFailed=!1,this.tickTimer=new OwnedInterval(this),this.maxDurationTimer=new OwnedTimeout(this),this.levelFrame=new OwnedFrame(this),this.onPointerDown=e=>{if(this.mode!=="hold"||this.disabled)return;e.preventDefault();try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}if(this.holdGesture)return;const intent=this.createIntent("hold",{source:"pointer",pointerId:e.pointerId});intent&&(this.holdGesture=intent,this.startForIntent(intent))},this.onPointerUp=event=>{this.holdGesture?.source!=="pointer"||this.holdGesture.pointerId!==event.pointerId||this.releaseHoldGesture()},this.onPointerCancel=event=>{this.holdGesture?.source!=="pointer"||this.holdGesture.pointerId!==event.pointerId||this.releaseHoldGesture()},this.onKeyDown=e=>{if(this.disabled)return;if(e.key==="Escape"){if(this._state!=="requesting"&&this._state!=="recording")return;e.preventDefault(),this.cancel();return}if(e.key!=="Enter"&&e.key!==" "||this.mode!=="hold"||e.repeat||(e.preventDefault(),this.holdGesture))return;const intent=this.createIntent("hold",{source:"keyboard",key:e.key});intent&&(this.holdGesture=intent,this.startForIntent(intent))},this.onKeyUp=e=>{e.key!=="Enter"&&e.key!==" "||this.holdGesture?.source!=="keyboard"||this.holdGesture.key!==e.key||this.releaseHoldGesture()},this.onBlur=()=>{this.releaseHoldGesture()},this.onClick=()=>{this.mode!=="toggle"||this.disabled||(this._state==="recording"?this.stop():this.start())}}static{this.defaultStrings={...super.defaultStrings,pushToTalkCancelled:LYRA_DEFAULT_pushToTalkCancelled,pushToTalkDenied:LYRA_DEFAULT_pushToTalkDenied,pushToTalkError:LYRA_DEFAULT_pushToTalkError,pushToTalkHold:LYRA_DEFAULT_pushToTalkHold,pushToTalkRequesting:LYRA_DEFAULT_pushToTalkRequesting,pushToTalkStart:LYRA_DEFAULT_pushToTalkStart,pushToTalkStarted:LYRA_DEFAULT_pushToTalkStarted,pushToTalkStop:LYRA_DEFAULT_pushToTalkStop,pushToTalkStopped:LYRA_DEFAULT_pushToTalkStopped,pushToTalkUnsupported:LYRA_DEFAULT_pushToTalkUnsupported}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=PUSH_TO_TALK_MODE.normalize(next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get state(){return this._state}get stream(){return this._stream}get ownerWindow(){return this.ownerDocument?.defaultView??null}get captureOwner(){const owner=this.ownerWindow;if(isPushToTalkSupported(owner))return{document:this.ownerDocument,window:owner,generation:this.lifecycleGeneration}}ownsCurrentLifecycle(owner){return this.isConnected&&this.isCurrentRealm(owner)&&this.lifecycleGeneration===owner.generation}isCurrentRealm(owner){return this.ownerDocument===owner.document&&this.ownerWindow===owner.window}rebaseCurrentRealmOwner(owner){this.isCurrentRealm(owner)&&(owner.generation=this.lifecycleGeneration)}createIntent(kind,details={}){const owner=this.captureOwner;if(!owner)return;const intent={id:++this.intentSequence,owner,kind,...details};return this.captureIntent=intent,intent}isLiveIntent(intent){return this.captureIntent===intent&&!this.disabled&&this.ownsCurrentLifecycle(intent.owner)&&(intent.kind!=="hold"||this.holdGesture===intent)}clearIntent(intent){this.captureIntent===intent&&(this.captureIntent=void 0),this.holdGesture===intent&&(this.holdGesture=void 0),this.queuedIntent===intent&&(this.queuedIntent=void 0)}retirePendingRequest(request,notifyCancellation){request.invalidated=!0,request.notifyCancellation||=notifyCancellation,request.retiredAtIntentId=this.intentSequence,request.retiredAtGeneration=this.lifecycleGeneration,this.pendingRequest===request&&(this.pendingRequest=void 0),this.clearIntent(request.intent),this._state==="requesting"&&!this.activeCapture&&this.setState("idle")}invalidateLifecycle(notifyCancellation,retainCurrentRealmIntents=!1){this.lifecycleGeneration+=1,this.captureIntent&&retainCurrentRealmIntents&&this.isCurrentRealm(this.captureIntent.owner)?this.rebaseCurrentRealmOwner(this.captureIntent.owner):this.captureIntent=void 0,this.holdGesture&&retainCurrentRealmIntents&&this.isCurrentRealm(this.holdGesture.owner)?this.rebaseCurrentRealmOwner(this.holdGesture.owner):this.holdGesture=void 0,this.queuedIntent&&retainCurrentRealmIntents&&this.isCurrentRealm(this.queuedIntent.owner)?this.rebaseCurrentRealmOwner(this.queuedIntent.owner):this.queuedIntent=void 0;const request=this.pendingRequest;request&&(retainCurrentRealmIntents&&this.isCurrentRealm(request.owner)?this.rebaseCurrentRealmOwner(request.owner):this.retirePendingRequest(request,notifyCancellation));const active=this.activeCapture;active&&(active.notifyCancellation&&=notifyCancellation,this.requestRecorderStop(!0))}canAdoptRequest(request,intent){return this.pendingRequest===request&&!request.invalidated&&this._state==="requesting"&&this.ownsCurrentLifecycle(request.owner)&&this.isLiveIntent(intent)&&request.owner.document===intent.owner.document&&request.owner.window===intent.owner.window&&request.owner.generation===intent.owner.generation}canStartRequest(request){return this.canAdoptRequest(request,request.intent)}notifyCancellation(){this.emit("lr-record-cancel",null),this.isConnected&&this.announce(this.localize("pushToTalkCancelled"))}resumeQueuedIntent(){const intent=this.queuedIntent;this.queuedIntent=void 0,!(!intent||!this.isLiveIntent(intent))&&this.startForIntent(intent)}finishRetiredRequest(request){request.notifyCancellation&&!request.cancellationNotified&&request.retiredAtIntentId===this.intentSequence&&request.retiredAtGeneration===this.lifecycleGeneration&&!this.pendingRequest&&!this.activeCapture&&!this.captureIntent&&(request.cancellationNotified=!0,this.notifyCancellation())}finishUnusableRequest(request){if(request.invalidated){this.finishRetiredRequest(request);return}this.pendingRequest===request&&(this.pendingRequest=void 0),this.clearIntent(request.intent),this._state==="requesting"&&!this.activeCapture&&this.setState("idle"),this.notifyCancellation()}syncCaptureSupport(){this.captureSupported=isPushToTalkSupported(this.ownerWindow)}connectedCallback(){super.connectedCallback(),this.requestUpdate("mode",void 0),this.hasAttribute("data-state")||this.setAttribute("data-state",this._state)}disconnectedCallback(){const previousOwner=this.activeCapture?.owner??this.pendingRequest?.owner;this.invalidateLifecycle(!1,!!previousOwner&&!this.isCurrentRealm(previousOwner)),super.disconnectedCallback()}adoptedCallback(){this.invalidateLifecycle(!1,!0),super.adoptedCallback(),this.syncCaptureSupport()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?this.syncCaptureSupport():this.seedFirstRenderState(()=>this.syncCaptureSupport()),changed.has("mode")&&changed.get("mode")!==void 0&&this.holdGesture&&this.releaseHoldGesture(!0),changed.has("disabled")&&this.disabled&&this.invalidateLifecycle(!0);const owner=this.captureWindow;this._state!=="recording"||!owner||(changed.has("withoutTimer")&&this.syncElapsedTimer(owner),changed.has("maxDurationMs")&&this.syncMaxDurationTimer(owner),changed.has("levelEvents")&&this.syncLevelMeter(owner))}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");(describedBy||this.describedByReflected)&&(this.describedByReflected=syncAriaDescribedByElements(this,this.trigger,describedBy))}focus(options){this.trigger?.focus(options)}blur(){this.trigger?.blur()}click(){this.disabled||!isPushToTalkSupported(this.ownerWindow)||(this.mode==="toggle"?this.trigger?.click():this._state==="recording"?this.stop():this.start())}resolveMimeType(owner){if(this.mimeType)return this.mimeType;for(const candidate of CANDIDATE_MIME_TYPES)if(owner.MediaRecorder.isTypeSupported?.(candidate))return candidate;return""}setState(next){if(this._state===next)return;const old=this._state;this._state=next,this.setAttribute("data-state",next),this.requestUpdate("state",old),this.emit("lr-record-state-change",{state:next})}announce(text){const region=this.liveRegion;region&&(region.mode="polite",region.announce(text,{force:!0}))}async start(){if(this.disabled||this._state==="recording")return!1;const intent=this.createIntent("programmatic");return intent?this.startForIntent(intent):!1}startForIntent(intent){const pending=this.pendingRequest;if(pending)return this.canAdoptRequest(pending,intent)?(pending.intent=intent,pending.completion??Promise.resolve(!1)):(this.clearIntent(intent),Promise.resolve(!1));if(this._state==="recording")return intent.kind==="hold"&&this.activeCapture&&this.recorderStopRequested&&this.isLiveIntent(intent)?(this.queuedIntent=intent,Promise.resolve(!1)):(this.clearIntent(intent),Promise.resolve(!1));if(!this.isLiveIntent(intent))return this.clearIntent(intent),Promise.resolve(!1);const request={id:++this.captureSequence,owner:intent.owner,intent,invalidated:!1,notifyCancellation:!1,cancellationNotified:!1};this.pendingRequest=request,this.setState("requesting");const completion=this.requestPermission(request);return request.completion=completion,completion}captureConstraints(){const additionalConstraints={...this.audioConstraints??{}};return delete additionalConstraints.deviceId,{audio:{...additionalConstraints,...this.deviceId?{deviceId:{exact:this.deviceId}}:{}}}}async requestPermission(request){try{const stream=await request.owner.window.navigator.mediaDevices.getUserMedia(this.captureConstraints());if(!this.canStartRequest(request)){for(const track of stream.getTracks())track.stop();return this.finishUnusableRequest(request),!1}return this.pendingRequest=void 0,this.startRecorder(request,stream)}catch(error){if(!this.canStartRequest(request))return this.finishUnusableRequest(request),!1;this.pendingRequest=void 0,this.clearIntent(request.intent);const denied=typeof error=="object"&&error!==null&&"name"in error&&error.name==="NotAllowedError";return this.setState(denied?"denied":"error"),this.emit("lr-record-error",{error}),this.announce(this.localize(denied?"pushToTalkDenied":"pushToTalkError")),!1}}startRecorder(request,stream){const owner=request.owner.window,active={id:request.id,owner:request.owner,intent:request.intent,notifyCancellation:!0};this.activeCapture=active,this.captureWindow=owner,this._stream=stream,this.cancelRequested=!1,this.recorderStopRequested=!1,this.recorderFailed=!1,this.chunks=[];try{const mimeType=this.resolveMimeType(owner),recorder=new owner.MediaRecorder(stream,mimeType?{mimeType}:void 0);this.recorder=recorder;const timeslice=this.timesliceMs>0?finiteDuration(this.timesliceMs,MAX_TIMEOUT_MS,1,MAX_TIMEOUT_MS):void 0,emitChunksForTake=timeslice!==void 0;return recorder.ondataavailable=event=>{this.recorder!==recorder||this.activeCapture!==active||!event.data||event.data.size===0||(this.chunks.push(event.data),emitChunksForTake&&this.emit("lr-record-chunk",{blob:event.data}))},recorder.onstop=()=>this.finalizeStop(recorder,active),recorder.onerror=event=>this.failRecorder(recorder,active,event.error??new Error("MediaRecorder failed")),recorder.start(timeslice),this.recordingStartedAt=owner.performance.now(),this.elapsedMs=0,this.setState("recording"),this.emit("lr-record-start",{stream}),this.announce(this.localize("pushToTalkStarted")),this.syncLevelMeter(owner),this.syncMaxDurationTimer(owner,!0),this.syncElapsedTimer(owner,!0),!0}catch(error){if(this.activeCapture!==active){for(const track of stream.getTracks())track.stop();return!1}return this.teardownStream(active),this.clearIntent(active.intent),this.setState("error"),this.emit("lr-record-error",{error}),this.announce(this.localize("pushToTalkError")),!1}}stop(){this.requestRecorderStop(!1)}cancel(){const pending=this.pendingRequest;if(pending&&this._state==="requesting"){this.retirePendingRequest(pending,!0);return}this._state==="recording"&&this.requestRecorderStop(!0)}requestRecorderStop(cancelled){const active=this.activeCapture;if(this._state!=="recording"||!active||(cancelled&&(this.cancelRequested=!0),this.recorderStopRequested))return;this.recorderStopRequested=!0,this.stopRuntimeLoops();const recorder=this.recorder;recorder&&recorder.state!=="inactive"&&recorder.stop()}finalizeStop(recorder,active){if(this.recorder!==recorder||this.activeCapture!==active||this.recorderFailed)return;const owner=active.owner.window,cancelled=this.cancelRequested,durationMs=Math.round(owner.performance.now()-this.recordingStartedAt),mimeType=recorder.mimeType||this.resolveMimeType(owner)||"audio/webm",blob=new owner.Blob(this.chunks,{type:mimeType});this.teardownStream(active),this.clearIntent(active.intent),this.setState("idle"),cancelled?active.notifyCancellation&&this.notifyCancellation():(this.emit("lr-record-stop",{blob,durationMs}),this.announce(this.localize("pushToTalkStopped"))),this.cancelRequested=!1,this.resumeQueuedIntent()}failRecorder(recorder,active,error){this.recorder!==recorder||this.activeCapture!==active||this.recorderFailed||this.cancelRequested||(this.recorderFailed=!0,this.cancelRequested=!1,this.teardownStream(active),this.clearIntent(active.intent),this.setState("error"),this.emit("lr-record-error",{error}),this.announce(this.localize("pushToTalkError")),this.resumeQueuedIntent())}teardownStream(active=this.activeCapture){if(!(!active||this.activeCapture!==active)){for(const track of this._stream?.getTracks()??[])track.stop();this._stream=null,this.recorder&&(this.recorder.ondataavailable=null,this.recorder.onstop=null,this.recorder.onerror=null),this.recorder=void 0,this.recorderStopRequested=!1,this.chunks=[],this.stopRuntimeLoops(),this.captureWindow=void 0,this.activeCapture=void 0}}stopRuntimeLoops(){this.tickTimer.cancel(),this.maxDurationTimer.cancel(),this.stopLevelMeter()}syncElapsedTimer(owner,initial=!1){this.tickTimer.cancel();const active=this.activeCapture;this.withoutTimer||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner)||(initial||(this.elapsedMs=owner.performance.now()-this.recordingStartedAt),this.tickTimer.schedule(1e3,()=>{this.activeCapture!==active||this._state!=="recording"||!this.ownsCurrentLifecycle(active.owner)||(this.elapsedMs=owner.performance.now()-this.recordingStartedAt)}))}syncMaxDurationTimer(owner,initial=!1){this.maxDurationTimer.cancel();const active=this.activeCapture;if(this.maxDurationMs<=0||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner))return;const duration=finiteDuration(this.maxDurationMs,MAX_TIMEOUT_MS,1,MAX_TIMEOUT_MS),elapsed=initial?0:Math.max(0,owner.performance.now()-this.recordingStartedAt);this.maxDurationTimer.schedule(Math.max(0,duration-elapsed),()=>{this.activeCapture!==active||!this.ownsCurrentLifecycle(active.owner)||this.stop()})}syncLevelMeter(owner){const active=this.activeCapture;if(!this.levelEvents||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner)||!this._stream){this.stopLevelMeter();return}this.audioCtx||this.startLevelMeter(this._stream,owner)}startLevelMeter(stream,owner){const AudioCtxCtor=owner.AudioContext??owner.webkitAudioContext;if(!AudioCtxCtor)return;const audioCtx=new AudioCtxCtor;audioCtx.resume().catch(()=>{}),this.audioCtx=audioCtx;const source=audioCtx.createMediaStreamSource(stream),analyser=audioCtx.createAnalyser();this.analyser=analyser,analyser.fftSize=256,source.connect(analyser),this.levelData=new owner.Uint8Array(analyser.frequencyBinCount),this.sampleLevel(owner)}sampleLevel(owner){const active=this.activeCapture;if(!this.analyser||!this.levelData||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner))return;this.analyser.getByteTimeDomainData(this.levelData);let sumSquares=0;for(const v of this.levelData){const norm=(v-128)/128;sumSquares+=norm*norm}const rms=Math.sqrt(sumSquares/this.levelData.length);this.emit("lr-level",{level:Math.min(1,rms)}),this.levelFrame.schedule(()=>{this.activeCapture===active&&this.ownsCurrentLifecycle(active.owner)&&this.sampleLevel(owner)})}stopLevelMeter(){this.levelFrame.cancel(),this.analyser=void 0,this.levelData=void 0,this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=void 0)}formatElapsed(ms){return formatMediaTime(ms/1e3,this.effectiveLocale)}releaseHoldGesture(retirePending=!1){const intent=this.holdGesture;if(!intent)return;this.holdGesture=void 0,this.captureIntent===intent&&(this.captureIntent=void 0),this.queuedIntent===intent&&(this.queuedIntent=void 0);const pending=this.pendingRequest;if(pending?.intent===intent){retirePending&&this.retirePendingRequest(pending,!0);return}this.activeCapture?.intent===intent&&this.requestRecorderStop(!1)}get triggerLabel(){const override=this.getAttribute("aria-label");return override!==null?override:this.mode==="hold"?this.localize("pushToTalkHold"):this._state==="recording"?this.localize("pushToTalkStop"):this.localize("pushToTalkStart")}get statusText(){if(!this.captureSupported)return this.localize("pushToTalkUnsupported");switch(this._state){case"requesting":return this.localize("pushToTalkRequesting");case"denied":return this.localize("pushToTalkDenied");case"error":return this.localize("pushToTalkError");default:return""}}render(){const supported=this.captureSupported,recording=this._state==="recording",status=this.statusText;return html`
|
|
10
|
+
`)}function pulseGlyph(){return icon(svg`<circle cx="12" cy="12" r="6"></circle>`)}class LyraPushToTalk extends LyraElement{constructor(){super(...arguments),this._mode="hold",this.timesliceMs=0,this.mimeType="",this.deviceId="",this.levelEvents=!1,this.maxDurationMs=0,this.withoutTimer=!1,this.disabled=!1,this.elapsedMs=0,this.captureSupported=!1,this._state="idle",this._stream=null,this.describedByReflected=!1,this.chunks=[],this.recordingStartedAt=0,this.lifecycleGeneration=0,this.captureSequence=0,this.intentSequence=0,this.cancelRequested=!1,this.recorderStopRequested=!1,this.recorderFailed=!1,this.tickTimer=new OwnedInterval(this),this.maxDurationTimer=new OwnedTimeout(this),this.levelFrame=new OwnedFrame(this),this.onPointerDown=e=>{if(this.mode!=="hold"||this.disabled)return;e.preventDefault();try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}if(this.holdGesture)return;const intent=this.createIntent("hold",{source:"pointer",pointerId:e.pointerId});intent&&(this.holdGesture=intent,this.startForIntent(intent))},this.onPointerUp=event=>{this.holdGesture?.source!=="pointer"||this.holdGesture.pointerId!==event.pointerId||this.releaseHoldGesture()},this.onPointerCancel=event=>{this.holdGesture?.source!=="pointer"||this.holdGesture.pointerId!==event.pointerId||this.releaseHoldGesture()},this.onKeyDown=e=>{if(this.disabled)return;if(e.key==="Escape"){if(this._state!=="requesting"&&this._state!=="recording")return;e.preventDefault(),this.cancel();return}if(e.key!=="Enter"&&e.key!==" "||this.mode!=="hold"||e.repeat||(e.preventDefault(),this.holdGesture))return;const intent=this.createIntent("hold",{source:"keyboard",key:e.key});intent&&(this.holdGesture=intent,this.startForIntent(intent))},this.onKeyUp=e=>{e.key!=="Enter"&&e.key!==" "||this.holdGesture?.source!=="keyboard"||this.holdGesture.key!==e.key||this.releaseHoldGesture()},this.onBlur=()=>{this.releaseHoldGesture()},this.onClick=()=>{this.mode!=="toggle"||this.disabled||(this._state==="recording"?this.stop():this.start())}}static{this.defaultStrings={...super.defaultStrings,pushToTalkCancelled:LYRA_DEFAULT_pushToTalkCancelled,pushToTalkDenied:LYRA_DEFAULT_pushToTalkDenied,pushToTalkError:LYRA_DEFAULT_pushToTalkError,pushToTalkHold:LYRA_DEFAULT_pushToTalkHold,pushToTalkRequesting:LYRA_DEFAULT_pushToTalkRequesting,pushToTalkStart:LYRA_DEFAULT_pushToTalkStart,pushToTalkStarted:LYRA_DEFAULT_pushToTalkStarted,pushToTalkStop:LYRA_DEFAULT_pushToTalkStop,pushToTalkStopped:LYRA_DEFAULT_pushToTalkStopped,pushToTalkUnsupported:LYRA_DEFAULT_pushToTalkUnsupported}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=PUSH_TO_TALK_MODE.normalize(next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get state(){return this._state}get stream(){return this._stream}get ownerWindow(){return this.ownerDocument?.defaultView??null}get captureOwner(){const owner=this.ownerWindow;if(isPushToTalkSupported(owner))return{document:this.ownerDocument,window:owner,generation:this.lifecycleGeneration}}ownsCurrentLifecycle(owner){return this.isConnected&&this.isCurrentRealm(owner)&&this.lifecycleGeneration===owner.generation}isCurrentRealm(owner){return this.ownerDocument===owner.document&&this.ownerWindow===owner.window}rebaseCurrentRealmOwner(owner){this.isCurrentRealm(owner)&&(owner.generation=this.lifecycleGeneration)}createIntent(kind,details={}){const owner=this.captureOwner;if(!owner)return;const intent={id:++this.intentSequence,owner,kind,...details};return this.captureIntent=intent,intent}isLiveIntent(intent){return this.captureIntent===intent&&!this.disabled&&this.ownsCurrentLifecycle(intent.owner)&&(intent.kind!=="hold"||this.holdGesture===intent)}clearIntent(intent){this.captureIntent===intent&&(this.captureIntent=void 0),this.holdGesture===intent&&(this.holdGesture=void 0),this.queuedIntent===intent&&(this.queuedIntent=void 0)}retirePendingRequest(request,notifyCancellation){request.invalidated=!0,request.notifyCancellation||=notifyCancellation,request.retiredAtIntentId=this.intentSequence,request.retiredAtGeneration=this.lifecycleGeneration,this.pendingRequest===request&&(this.pendingRequest=void 0),this.clearIntent(request.intent),this._state==="requesting"&&!this.activeCapture&&this.setState("idle")}invalidateLifecycle(notifyCancellation,retainCurrentRealmIntents=!1){this.lifecycleGeneration+=1,this.captureIntent&&retainCurrentRealmIntents&&this.isCurrentRealm(this.captureIntent.owner)?this.rebaseCurrentRealmOwner(this.captureIntent.owner):this.captureIntent=void 0,this.holdGesture&&retainCurrentRealmIntents&&this.isCurrentRealm(this.holdGesture.owner)?this.rebaseCurrentRealmOwner(this.holdGesture.owner):this.holdGesture=void 0,this.queuedIntent&&retainCurrentRealmIntents&&this.isCurrentRealm(this.queuedIntent.owner)?this.rebaseCurrentRealmOwner(this.queuedIntent.owner):this.queuedIntent=void 0;const request=this.pendingRequest;request&&(retainCurrentRealmIntents&&this.isCurrentRealm(request.owner)?this.rebaseCurrentRealmOwner(request.owner):this.retirePendingRequest(request,notifyCancellation));const active=this.activeCapture;active&&(active.notifyCancellation&&=notifyCancellation,this.requestRecorderStop(!0))}canAdoptRequest(request,intent){return this.pendingRequest===request&&!request.invalidated&&this._state==="requesting"&&this.ownsCurrentLifecycle(request.owner)&&this.isLiveIntent(intent)&&request.owner.document===intent.owner.document&&request.owner.window===intent.owner.window&&request.owner.generation===intent.owner.generation}canStartRequest(request){return this.canAdoptRequest(request,request.intent)}notifyCancellation(){this.emit("lr-record-cancel",null),this.isConnected&&this.announce(this.localize("pushToTalkCancelled"))}resumeQueuedIntent(){const intent=this.queuedIntent;this.queuedIntent=void 0,!(!intent||!this.isLiveIntent(intent))&&this.startForIntent(intent)}finishRetiredRequest(request){request.notifyCancellation&&!request.cancellationNotified&&request.retiredAtIntentId===this.intentSequence&&request.retiredAtGeneration===this.lifecycleGeneration&&!this.pendingRequest&&!this.activeCapture&&!this.captureIntent&&(request.cancellationNotified=!0,this.notifyCancellation())}finishUnusableRequest(request){if(request.invalidated){this.finishRetiredRequest(request);return}this.pendingRequest===request&&(this.pendingRequest=void 0),this.clearIntent(request.intent),this._state==="requesting"&&!this.activeCapture&&this.setState("idle"),this.notifyCancellation()}syncCaptureSupport(){this.captureSupported=isPushToTalkSupported(this.ownerWindow)}connectedCallback(){super.connectedCallback(),this.requestUpdate("mode",void 0),this.hasAttribute("data-state")||this.setAttribute("data-state",this._state)}disconnectedCallback(){const previousOwner=this.activeCapture?.owner??this.pendingRequest?.owner;this.invalidateLifecycle(!1,!!previousOwner&&!this.isCurrentRealm(previousOwner)),super.disconnectedCallback()}adoptedCallback(){this.invalidateLifecycle(!1,!0),super.adoptedCallback(),this.syncCaptureSupport()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?this.syncCaptureSupport():this.seedFirstRenderState(()=>this.syncCaptureSupport()),changed.has("mode")&&changed.get("mode")!==void 0&&this.holdGesture&&this.releaseHoldGesture(!0),changed.has("disabled")&&this.disabled&&this.invalidateLifecycle(!0);const owner=this.captureWindow;this._state!=="recording"||!owner||(changed.has("withoutTimer")&&this.syncElapsedTimer(owner),changed.has("maxDurationMs")&&this.syncMaxDurationTimer(owner),changed.has("levelEvents")&&this.syncLevelMeter(owner))}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");(describedBy||this.describedByReflected)&&(this.describedByReflected=syncAriaDescribedByElements(this,this.trigger,describedBy))}focus(options){this.trigger?.focus(options)}blur(){this.trigger?.blur()}click(){this.disabled||!isPushToTalkSupported(this.ownerWindow)||(this.mode==="toggle"?this.trigger?.click():this._state==="recording"?this.stop():this.start())}resolveMimeType(owner){if(this.mimeType)return this.mimeType;for(const candidate of CANDIDATE_MIME_TYPES)if(owner.MediaRecorder.isTypeSupported?.(candidate))return candidate;return""}setState(next){if(this._state===next)return;const old=this._state;this._state=next,this.setAttribute("data-state",next),this.requestUpdate("state",old),this.emit("lr-record-state-change",{state:next})}announce(text){const region=this.liveRegion;region&&(region.mode="polite",region.announce(text,{force:!0}))}async start(){if(this.disabled||this._state==="recording")return!1;const intent=this.createIntent("programmatic");return intent?this.startForIntent(intent):!1}startForIntent(intent){const pending=this.pendingRequest;if(pending)return this.canAdoptRequest(pending,intent)?(pending.intent=intent,pending.completion??Promise.resolve(!1)):(this.clearIntent(intent),Promise.resolve(!1));if(this._state==="recording")return intent.kind==="hold"&&this.activeCapture&&this.recorderStopRequested&&this.isLiveIntent(intent)?(this.queuedIntent=intent,Promise.resolve(!1)):(this.clearIntent(intent),Promise.resolve(!1));if(!this.isLiveIntent(intent))return this.clearIntent(intent),Promise.resolve(!1);const request={id:++this.captureSequence,owner:intent.owner,intent,invalidated:!1,notifyCancellation:!1,cancellationNotified:!1};this.pendingRequest=request,this.setState("requesting");const completion=this.requestPermission(request);return request.completion=completion,completion}captureConstraints(){const additionalConstraints={...this.audioConstraints??{}};return delete additionalConstraints.deviceId,{audio:{...additionalConstraints,...this.deviceId?{deviceId:{exact:this.deviceId}}:{}}}}async requestPermission(request){try{const stream=await request.owner.window.navigator.mediaDevices.getUserMedia(this.captureConstraints());if(!this.canStartRequest(request)){for(const track of stream.getTracks())track.stop();return this.finishUnusableRequest(request),!1}return this.pendingRequest=void 0,this.startRecorder(request,stream)}catch(error){if(!this.canStartRequest(request))return this.finishUnusableRequest(request),!1;this.pendingRequest=void 0,this.clearIntent(request.intent);const denied=typeof error=="object"&&error!==null&&"name"in error&&error.name==="NotAllowedError";return this.setState(denied?"denied":"error"),this.emit("lr-record-error",{error}),this.announce(this.localize(denied?"pushToTalkDenied":"pushToTalkError")),!1}}startRecorder(request,stream){const owner=request.owner.window,active={id:request.id,owner:request.owner,intent:request.intent,notifyCancellation:!0};this.activeCapture=active,this.captureWindow=owner,this._stream=stream,this.cancelRequested=!1,this.recorderStopRequested=!1,this.recorderFailed=!1,this.chunks=[];try{const mimeType=this.resolveMimeType(owner),recorder=new owner.MediaRecorder(stream,mimeType?{mimeType}:void 0);this.recorder=recorder;const timeslice=this.timesliceMs>0?finiteDuration(this.timesliceMs,MAX_TIMEOUT_MS,1,MAX_TIMEOUT_MS):void 0,emitChunksForTake=timeslice!==void 0;return recorder.ondataavailable=event=>{this.recorder!==recorder||this.activeCapture!==active||!event.data||event.data.size===0||(this.chunks.push(event.data),emitChunksForTake&&this.emit("lr-record-chunk",{blob:event.data}))},recorder.onstop=()=>this.finalizeStop(recorder,active),recorder.onerror=event=>this.failRecorder(recorder,active,event.error??new Error("MediaRecorder failed")),recorder.start(timeslice),this.recordingStartedAt=owner.performance.now(),this.elapsedMs=0,this.setState("recording"),this.emit("lr-record-start",{stream}),this.announce(this.localize("pushToTalkStarted")),this.syncLevelMeter(owner),this.syncMaxDurationTimer(owner,!0),this.syncElapsedTimer(owner,!0),!0}catch(error){if(this.activeCapture!==active){for(const track of stream.getTracks())track.stop();return!1}return this.teardownStream(active),this.clearIntent(active.intent),this.setState("error"),this.emit("lr-record-error",{error}),this.announce(this.localize("pushToTalkError")),!1}}stop(){this.requestRecorderStop(!1)}cancel(){const pending=this.pendingRequest;if(pending&&this._state==="requesting"){this.retirePendingRequest(pending,!0);return}this._state==="recording"&&this.requestRecorderStop(!0)}requestRecorderStop(cancelled){const active=this.activeCapture;if(this._state!=="recording"||!active||(cancelled&&(this.cancelRequested=!0),this.recorderStopRequested))return;this.recorderStopRequested=!0,this.stopRuntimeLoops();const recorder=this.recorder;recorder&&recorder.state!=="inactive"&&recorder.stop()}finalizeStop(recorder,active){if(this.recorder!==recorder||this.activeCapture!==active||this.recorderFailed)return;const owner=active.owner.window,cancelled=this.cancelRequested,durationMs=Math.round(owner.performance.now()-this.recordingStartedAt),mimeType=recorder.mimeType||this.resolveMimeType(owner)||"audio/webm",blob=new owner.Blob(this.chunks,{type:mimeType});this.teardownStream(active),this.clearIntent(active.intent),this.setState("idle"),cancelled?active.notifyCancellation&&this.notifyCancellation():(this.emit("lr-record-stop",{blob,durationMs}),this.announce(this.localize("pushToTalkStopped"))),this.cancelRequested=!1,this.resumeQueuedIntent()}failRecorder(recorder,active,error){this.recorder!==recorder||this.activeCapture!==active||this.recorderFailed||this.cancelRequested||(this.recorderFailed=!0,this.cancelRequested=!1,this.teardownStream(active),this.clearIntent(active.intent),this.setState("error"),this.emit("lr-record-error",{error}),this.announce(this.localize("pushToTalkError")),this.resumeQueuedIntent())}teardownStream(active=this.activeCapture){if(!(!active||this.activeCapture!==active)){for(const track of this._stream?.getTracks()??[])track.stop();this._stream=null,this.recorder&&(this.recorder.ondataavailable=null,this.recorder.onstop=null,this.recorder.onerror=null),this.recorder=void 0,this.recorderStopRequested=!1,this.chunks=[],this.stopRuntimeLoops(),this.captureWindow=void 0,this.activeCapture=void 0}}stopRuntimeLoops(){this.tickTimer.cancel(),this.maxDurationTimer.cancel(),this.stopLevelMeter()}syncElapsedTimer(owner,initial=!1){this.tickTimer.cancel();const active=this.activeCapture;this.withoutTimer||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner)||(initial||(this.elapsedMs=owner.performance.now()-this.recordingStartedAt),this.tickTimer.schedule(1e3,()=>{this.activeCapture!==active||this._state!=="recording"||!this.ownsCurrentLifecycle(active.owner)||(this.elapsedMs=owner.performance.now()-this.recordingStartedAt)}))}syncMaxDurationTimer(owner,initial=!1){this.maxDurationTimer.cancel();const active=this.activeCapture;if(this.maxDurationMs<=0||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner))return;const duration=finiteDuration(this.maxDurationMs,MAX_TIMEOUT_MS,1,MAX_TIMEOUT_MS),elapsed=initial?0:Math.max(0,owner.performance.now()-this.recordingStartedAt);this.maxDurationTimer.schedule(Math.max(0,duration-elapsed),()=>{this.activeCapture!==active||!this.ownsCurrentLifecycle(active.owner)||this.stop()})}syncLevelMeter(owner){const active=this.activeCapture;if(!this.levelEvents||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner)||!this._stream){this.stopLevelMeter();return}this.audioCtx||this.startLevelMeter(this._stream,owner)}startLevelMeter(stream,owner){const AudioCtxCtor=owner.AudioContext??owner.webkitAudioContext;if(AudioCtxCtor)try{const audioCtx=new AudioCtxCtor;this.audioCtx=audioCtx,audioCtx.resume().catch(()=>{});const source=audioCtx.createMediaStreamSource(stream),analyser=audioCtx.createAnalyser();this.analyser=analyser,analyser.fftSize=256,source.connect(analyser),this.levelData=new owner.Uint8Array(analyser.frequencyBinCount),this.sampleLevel(owner)}catch{this.stopLevelMeter()}}sampleLevel(owner){const active=this.activeCapture;if(!this.analyser||!this.levelData||this._state!=="recording"||!active||active.owner.window!==owner||!this.ownsCurrentLifecycle(active.owner))return;this.analyser.getByteTimeDomainData(this.levelData);let sumSquares=0;for(const v of this.levelData){const norm=(v-128)/128;sumSquares+=norm*norm}const rms=Math.sqrt(sumSquares/this.levelData.length);this.emit("lr-level",{level:Math.min(1,rms)}),this.levelFrame.schedule(()=>{this.activeCapture===active&&this.ownsCurrentLifecycle(active.owner)&&this.sampleLevel(owner)})}stopLevelMeter(){this.levelFrame.cancel(),this.analyser=void 0,this.levelData=void 0,this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=void 0)}formatElapsed(ms){return formatMediaTime(ms/1e3,this.effectiveLocale)}releaseHoldGesture(retirePending=!1){const intent=this.holdGesture;if(!intent)return;this.holdGesture=void 0,this.captureIntent===intent&&(this.captureIntent=void 0),this.queuedIntent===intent&&(this.queuedIntent=void 0);const pending=this.pendingRequest;if(pending?.intent===intent){retirePending&&this.retirePendingRequest(pending,!0);return}this.activeCapture?.intent===intent&&this.requestRecorderStop(!1)}get triggerLabel(){const override=this.getAttribute("aria-label");return override!==null?override:this.mode==="hold"?this.localize("pushToTalkHold"):this._state==="recording"?this.localize("pushToTalkStop"):this.localize("pushToTalkStart")}get statusText(){if(!this.captureSupported)return this.localize("pushToTalkUnsupported");switch(this._state){case"requesting":return this.localize("pushToTalkRequesting");case"denied":return this.localize("pushToTalkDenied");case"error":return this.localize("pushToTalkError");default:return""}}render(){const supported=this.captureSupported,recording=this._state==="recording",status=this.statusText;return html`
|
|
11
11
|
<button
|
|
12
12
|
part="trigger"
|
|
13
13
|
type="button"
|
|
@@ -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&¤t!==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&¤t!==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,
|
|
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&¤t<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};
|