@aceshooting/lyra-ui 29.2.0 → 29.2.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 +19 -0
- package/README.md +2 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +2 -2
- package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
- package/dist/internal/announcer.js +1 -1
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-map.md +9 -0
- package/llms/peers.md +1 -1
- package/llms.txt +2 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 29.2.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e020642: Preserve per-datum border colors across all Chart.js chart types when a series supplies a color array. Keep repeating series and point color palettes aligned with their original data indexes when the chart samples rows for display.
|
|
8
|
+
|
|
9
|
+
The chart-family gzip ceiling and unpacked package ceilings advance only to the next 64-byte boundary where the color correction and release notes exceed their previous limits; other size limits and measurement settings stay unchanged.
|
|
10
|
+
|
|
11
|
+
The matched quick Chromium comparison against 29.2.1 passed all semantic checks. Chart assignment settlement increased from 22.1 to 25.6 ms median, while total chart assignment remained 63.5 to 64.1 ms median. Seven additional timing metrics exceeded the advisory threshold in unchanged document, table, and select workloads, including no-op paint waits; fourteen metrics improved. These seven-sample observations include scheduling variation and do not establish a causal performance change.
|
|
12
|
+
- @aceshooting/lyra-translations@29.2.2
|
|
13
|
+
|
|
14
|
+
## 29.2.1
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- b7262ed: The `lr-map` guide now documents that, on WebKit, a paint change made directly on the `map` engine instance can stay unpresented until another frame is requested (a MapLibre and WebKit behavior, reproducible without `lr-map`), and that calling the engine's `triggerRepaint()` once afterwards presents it.
|
|
19
|
+
- 0ef480e: The README and `llms.txt` now explain why pnpm 12.14 and later list `@aceshooting/lyra-ui` under "Agent skills awaiting approval" after an install: the package ships its agent skills. Nothing runs at install time and `npx lyra-ui init-agents` works either way; `pnpm approve @aceshooting/lyra-ui` (or `pnpm approve '!@aceshooting/lyra-ui'`) records the decision once.
|
|
20
|
+
- @aceshooting/lyra-translations@29.2.1
|
|
21
|
+
|
|
3
22
|
## 29.2.0
|
|
4
23
|
|
|
5
24
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -91,7 +91,8 @@ directory (Claude Code: `.claude/skills/`), as symlinks into `node_modules` so u
|
|
|
91
91
|
(`--copy`, `--dry-run`, `--agents claude,opencode|all`, `--force`), and adds a short marked block to
|
|
92
92
|
`AGENTS.md` (and `CLAUDE.md` if present). Re-running is safe. Prefer a marketplace? `/plugin marketplace add
|
|
93
93
|
aceshooting/lyra-ui` then `/plugin install lyra-ui@aceshooting` (Claude Code), or `codex plugin marketplace
|
|
94
|
-
add aceshooting/lyra-ui` then `codex plugin add lyra-ui@aceshooting` (Codex).
|
|
94
|
+
add aceshooting/lyra-ui` then `codex plugin add lyra-ui@aceshooting` (Codex). pnpm's "Agent skills awaiting
|
|
95
|
+
approval" notice is safe: `pnpm approve @aceshooting/lyra-ui`.
|
|
95
96
|
|
|
96
97
|
## Install
|
|
97
98
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{finiteCount}from"../../../internal/numbers.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{repeat}from"lit/directives/repeat.js";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{chevronIcon}from"../../../internal/icons.js";import{styles}from"./task-list.styles.js";import{LYRA_DEFAULT_taskListCompletedOfTotal,LYRA_DEFAULT_taskListLabel,LYRA_DEFAULT_taskListLimit,LYRA_DEFAULT_taskListStepCompletedAnnounce,LYRA_DEFAULT_taskListStepFailedAnnounce,LYRA_DEFAULT_taskListStepIncompleteAnnounce,LYRA_DEFAULT_taskListStepStartedAnnounce}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";function normalizeTaskStatus(value){return value==="running"||value==="success"||value==="error"||value==="incomplete"?value:"pending"}const DEEP_NESTING_WARNING_KEY="lyra-task-list-nesting-depth",DEEP_NESTING_WARNING="<lr-task-list>: task nesting deeper than one level is ignored.",MAX_RENDERED_TASKS=500,canonicalTaskArrays=new WeakSet;function validTaskItems(value){
|
|
1
|
+
import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hierarchyKey,hierarchyText}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";import{readOwnDataValue}from"../../../internal/data-descriptors.js";import{finiteCount}from"../../../internal/numbers.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,svg,nothing}from"lit";import{repeat}from"lit/directives/repeat.js";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{chevronIcon}from"../../../internal/icons.js";import{styles}from"./task-list.styles.js";import{LYRA_DEFAULT_taskListCompletedOfTotal,LYRA_DEFAULT_taskListLabel,LYRA_DEFAULT_taskListLimit,LYRA_DEFAULT_taskListStepCompletedAnnounce,LYRA_DEFAULT_taskListStepFailedAnnounce,LYRA_DEFAULT_taskListStepIncompleteAnnounce,LYRA_DEFAULT_taskListStepStartedAnnounce}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_treeNodeMoved,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary}from"../../../internal/default-strings/shared.generated.js";function normalizeTaskStatus(value){return value==="running"||value==="success"||value==="error"||value==="incomplete"?value:"pending"}const DEEP_NESTING_WARNING_KEY="lyra-task-list-nesting-depth",DEEP_NESTING_WARNING="<lr-task-list>: task nesting deeper than one level is ignored.",MAX_RENDERED_TASKS=500,canonicalTaskArrays=new WeakSet;function validTaskItems(value){return value&&typeof value=="object"&&canonicalTaskArrays.has(value)?value:[]}function isTaskArray(value){try{return Array.isArray(value)}catch{return!1}}function isTaskRecord(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function taskArrayLength(values){const value=readOwnDataValue(values,"length");return finiteCount(typeof value=="number"?value:0,0)}function projectTaskItems(source){let childBudget=1e4,valid=!0,deep=!1,truncated=!1;const copy=(values,depth)=>{const result=[];try{if(!isTaskArray(values))return result;const length=taskArrayLength(values),count=Math.min(length,depth===0?1e4:childBudget);count<length&&(truncated=!0,valid=!1),depth>0&&(childBudget-=count);for(let index=0;index<count;index++){const value=readOwnDataValue(values,String(index));if(!isTaskRecord(value)){valid=!1;continue}const id=readOwnDataValue(value,"id");if(typeof id!="string"||!id.trim()){valid=!1;continue}const label=readOwnDataValue(value,"label"),detail=readOwnDataValue(value,"detail"),children=readOwnDataValue(value,"children");depth>0&&isTaskArray(children)&&taskArrayLength(children)>0&&(deep=!0);const item={id,label:typeof label=="string"?label:"",status:normalizeTaskStatus(readOwnDataValue(value,"status")),...typeof detail=="string"?{detail}:{},...depth===0&&isTaskArray(children)?{children:copy(children,1)}:{}};result.push(Object.freeze(item))}}catch{valid=!1}return canonicalTaskArrays.add(result),Object.freeze(result),result},items=copy(source,0),flat=[];let completed=0,unique=!0;const ids=new Set;for(const item of items)item.status==="success"&&completed++,flat.push(item,...item.children??[]);for(const item of flat)ids.has(item.id)&&(unique=!1),ids.add(item.id);return{source,items,flat,valid,unique,completed,deep,truncated}}const SOURCE_QUERY=Object.freeze({search:"",hiddenKinds:Object.freeze([])}),ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -5,7 +5,7 @@ import{__decorate}from"tslib";import{SpatialSourceController,spatialContains}fro
|
|
|
5
5
|
${(this.spatial.result?.bins??[]).map((bin,index)=>{const current=this.spatialGuard(()=>this.spatial.result?.bins.includes(bin)===!0);return html`<tr><th scope="row">${this.spatialBinText(bin)}</th><td><button type="button" tabindex=${this.dataTableVisible?"0":"-1"} aria-label=${this.spatialBinText(bin)} data-spatial-bin=${index}
|
|
6
6
|
@click=${event=>{current(event)&&this.activateSpatialBin(bin)}}>${this.formatSummaryValue(bin.count)}</button></td></tr>`})}
|
|
7
7
|
</tbody></table>`}refreshPreparedModel(){if(!this.preparedDirty)return;this.preparedDirty=!1,this.preparedInvalid=!1,this.preparedRequestFailed=!1,this.preparedBaseModel=this.preparedModel=void 0,this.preparedEffective=void 0;const generation=this.preparedGeneration,input=this.preparedDataInput();this.preparedChanged||=this.preparedActive||input!==null,this.spatialActive=!1,this.preparedActive=input!==null;try{if(input!==null){const kind=Object.getOwnPropertyDescriptor(input,"kind");if(generation!==this.preparedGeneration)return;if(kind&&"value"in kind&&kind.value==="spatial"){const type=this.effectiveType();if(type!=="scatter"&&type!=="bubble"||this.scaleType!=="linear")throw new TypeError("Incompatible spatial chart");if(this.spatialActive=!0,this.preparedRequests.setSource(void 0,void 0),this.spatial.bind(input,this.viewport,normalizeChartRecordLimit(this.maxRecords),this.selectedPointId,{type}),generation!==this.preparedGeneration)return;this.preparedInvalid=this.spatial.error;return}const model=prepareChartModel(input,this.effectiveType(),normalizeChartRecordLimit(this.maxRecords));this.preparedBaseModel=this.preparedModel=model,this.preparedRequests.setSource(input,model.revision)}else this.preparedRequests.setSource(void 0,void 0)}catch{this.preparedInvalid=!0,this.preparedRequests.setSource(void 0,void 0)}}async revealSourcePoint(ref){if(typeof ref=="string")return this.revealSpatialPoint(ref);if(!this.isConnected||!ref||typeof ref.seriesId!="string")return!1;ref=Object.freeze({seriesId:ref.seriesId,sourceIndex:ref.sourceIndex}),this.preparedDirty&&await this.updateComplete;const model=this.preparedBaseModel;if(!model||model.kind!=="series")return!1;const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series||!Number.isSafeInteger(ref.sourceIndex)||ref.sourceIndex<0||ref.sourceIndex>=series.counts.sourceCount)return!1;const lease=this.preparedRequests.begin("point",this.effectiveLocale);if(!lease)return!1;this.preparedPending=!0,this.preparedRequestFailed=!1,this.requestUpdate("preparedView",null);const signal=lease.context.signal;try{const source=model.source;if(source.kind!=="series"||source.revision!==model.revision)throw new Error("Prepared source revision changed");const response=source.getPoint(ref,{signal}),point=await preparedResponse(response,signal);if(!lease.isCurrent()||this.preparedBaseModel!==model||source.revision!==model.revision||point===null)return!1;let next=model;const refinement=Object.getOwnPropertyDescriptor(source,"queryRange");if(refinement){if(!("value"in refinement)||typeof refinement.value!="function")throw new TypeError("Invalid indexed refinement");const otherEntries=model.peerCount-series.samples.length,entryBudget=Math.min(model.limit-otherEntries,Math.floor(1e3/model.series.length)),maxPoints=Math.max(1,Math.floor((entryBudget-1)/2)),startIndex=Math.max(0,ref.sourceIndex-maxPoints),endIndex=Math.min(series.counts.sourceCount,ref.sourceIndex+Math.min(maxPoints+1,series.counts.sourceCount-ref.sourceIndex)),request={seriesId:ref.seriesId,startIndex,endIndex,maxPoints,signal},points=await preparedResponse(source.queryRange(request),signal);if(!lease.isCurrent()||this.preparedBaseModel!==model||source.revision!==model.revision)return!1;next=withPreparedRange(model,request,points)}const overlay=withPreparedPoint(next,ref,point);return!lease.isCurrent()||this.preparedBaseModel!==model||source.revision!==model.revision?!1:(this.preparedModel=overlay,this.preparedChanged=!0,this.preparedEffective=void 0,this.descriptionMemo=void 0,this.dataTableRows=void 0,!0)}catch{return lease.isCurrent()&&(this.preparedRequestFailed=!0,this.announcements.announceAssertive(this.localize("chartPreparedUnavailable"))),!1}finally{lease.isCurrent()&&(this.preparedPending=!1,this.requestUpdate("preparedView",null))}}canonicalLabels(){const source=this.labels;if(this.labelsSnapshot&&Object.is(this.labelsSnapshot.source,source))return this.labelsSnapshot.value;const value=projectChartStrings(source)??Object.freeze([]);return this.labelsSnapshot={source,value},value}canonicalAnnotations(){const source=this.annotations;if(this.annotationsSnapshot&&Object.is(this.annotationsSnapshot.source,source))return this.annotationsSnapshot.value;const value=projectChartAnnotations(source);return this.annotationsSnapshot={source,value},value}canonicalHiddenDatasets(){const source=this.hiddenDatasets;if(this.hiddenDatasetsSnapshot&&Object.is(this.hiddenDatasetsSnapshot.source,source))return this.hiddenDatasetsSnapshot.value;const value=source===void 0?void 0:Object.freeze(Array.isArray(source)?source.filter(index=>typeof index=="number"&&Number.isInteger(index)):[]);return this.hiddenDatasetsSnapshot={source,value},value}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._datasets=normalizeChartSeries(value),this.datasetsSource=value,this.requestUpdate("datasets",previous)}get hiddenDatums(){return this._hiddenDatums}set hiddenDatums(value){if(Object.is(value,this.hiddenDatumsSource)||Object.is(value,this._hiddenDatums))return;const previous=this._hiddenDatums;this._hiddenDatums=projectHiddenDatasetIndexes(value)??Object.freeze([]),this.hiddenDatumsSource=value,this.requestUpdate("hiddenDatums",previous)}get compactPlot(){return isDenseChartSize(this.size)}get plugins(){return this._plugins}set plugins(value){if(Object.is(value,this.pluginsSource)||Object.is(value,this._plugins))return;const previous=this._plugins;this._plugins=projectChartPlugins(value),this.pluginsSource=value,this.requestUpdate("plugins",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get config(){return this._config}set config(value){if(Object.is(value,this.configSource)||value!==void 0&&Object.is(value,this._config))return;const previous=this._config;this._config=projectChartConfiguration(value),this.configSource=value,this.requestUpdate("config",previous)}normalizeEffectiveConfig(config){return config}effectiveConfig(){const config=this.normalizeEffectiveConfig(this.config??this.slottedConfig);return this.preparedDataInput()===null||!config?config:{type:config.type,options:config.options,plugins:config.plugins}}onConfigSlotChange(event){const slot=event.currentTarget;slot===this.configSlotEl&&this.collectConfigFromSlot(slot)}collectConfigFromSlot(slot){const script=slot.assignedElements({flatten:!0}).find(element=>element.localName==="script"&&element.type.trim().toLowerCase()==="application/json");let next;if(script)try{const parsed=JSON.parse(script.textContent??"");next=projectChartConfiguration(parsed)}catch{next=void 0}Object.is(this.slottedConfig,next)||(this.slottedConfig=next)}effectiveData(){if(this.spatialActive){const groups=this.spatialSeriesPoints();return{labels:[],datasets:(this.spatial.binding?.chart?.series??[]).map((series,index)=>{const data=groups[index].map(point=>Object.freeze({x:point.x,y:point.y,...point.radius===void 0?{}:{r:point.radius},...point.label===void 0?{}:{label:point.label}})),dataset=Object.freeze({label:series.label,data});return canonicalChartDatasetValues.set(dataset,data),dataset})}}if(this.preparedActive){const model=this.preparedModel;if(!model)return{labels:[],datasets:[]};if(this.preparedEffective?.model===model)return this.preparedEffective.data;const datasets2=model.series.map(series=>{const data2=model.kind==="series"?series.samples.map(point=>point?Object.freeze({x:point.x,y:point.y,label:String(point.sourceIndex)}):null):[...series.values];Object.freeze(data2);const dataset=Object.freeze({label:series.label,data:data2});return canonicalChartDatasetValues.set(dataset,data2),dataset}),data={labels:[...model.labels],datasets:datasets2};return this.preparedEffective={model,data},data}const labels=this.canonicalLabels(),datasets=this.datasets,config=this.config??this.slottedConfig,memo=this.effectiveDataMemo;if(memo?.labels===labels&&memo.datasets===datasets&&memo.config===config)return memo.value;const generated={labels:[...labels],datasets:datasets.map(series=>{const{points:_points,...safeSeries}=series,values=canonicalSeriesPoints(series)??canonicalSeriesData(series),data=[...values];Object.freeze(data);const dataset={...safeSeries,data,yAxisID:series.axis==="y2"?"y2":"y"};return canonicalChartDatasetValues.set(dataset,values),Object.freeze(dataset)})};Object.freeze(generated.labels),Object.freeze(generated.datasets);const override=projectChartDataConfiguration(this.effectiveConfig()?.data);let value=generated;if(override){const projected=projectChartDataConfiguration(deepMerge(generated,override));value={labels:projected?.labels??[],datasets:projected?.datasets??[]}}return this.effectiveDataMemo={labels,datasets,config,value},value}callbackDatasetIndex(value,effective=this.effectiveData()){const datasetIndex=chartCallbackDatasetIndex(value);if(datasetIndex===void 0)return;const visualDatasetCount=this.visualDatasetSourceIndexes?.length??effective.datasets.length;if(datasetIndex>=visualDatasetCount)return;const sourceDatasetIndex=this.visualDatasetSourceIndexes?.[datasetIndex]??datasetIndex;return effective.datasets[sourceDatasetIndex]?datasetIndex:void 0}callbackIndexes(value,effective=this.effectiveData()){const hit=chartCallbackIndexes(value);if(!hit)return;const visualDatasetCount=this.visualDatasetSourceIndexes?.length??effective.datasets.length;if(hit.datasetIndex>=visualDatasetCount)return;const sourceDatasetIndex=this.visualDatasetSourceIndexes?.[hit.datasetIndex]??hit.datasetIndex,dataset=effective.datasets[sourceDatasetIndex];if(!dataset)return;const visualRowCount=this.visualRowSourceIndexes?.length??this.datasetValues(dataset).length;return hit.index<visualRowCount?hit:void 0}effectiveHiddenDatasetIndexes(){const effective=this.effectiveData(),controlled=normalizeHiddenDatasets(this.canonicalHiddenDatasets(),effective.datasets.length);return controlled!==void 0?controlled:effective.datasets.flatMap((dataset,index)=>chartDatasetBoolean(dataset,"hidden")===!0?[index]:[])}applyDatasetVisibility(){if(!this.chart)return!1;const chart=this.chart,sourceDatasetCount=this.effectiveData().datasets.length,datasetCount=this.visualDatasetSourceIndexes?.length??sourceDatasetCount,controlled=normalizeHiddenDatasets(this.canonicalHiddenDatasets(),sourceDatasetCount);if(controlled===void 0){for(let index=0;index<datasetCount;index++)try{const metadata=chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}catch{}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++){const sourceIndex=this.visualDatasetSourceIndexes?.[index]??index;try{chart.setDatasetVisibility(index,!hidden.has(sourceIndex))}catch{}}return datasetCount>0}isSliceChart(){return["pie","doughnut","polarArea"].includes(this.effectiveType())}applyDatumVisibility(){if(!this.chart||!this.isSliceChart())return!1;const sample=this.dataTableSample(),rows=this.visualRowSourceIndexes,hidden=new Set(normalizeHiddenDatasets(this.hiddenDatums,sample.rowCount));let changed=!1;for(let index=0;index<(rows?.length??sample.rowCount);index++){const visible=!hidden.has(rows?.[index]??index);try{this.chart.getDataVisibility?.(index)===!visible&&(this.chart.toggleDataVisibility?.(index),changed=!0)}catch{}}return changed}hasExplicitConfigData(){const config=this.effectiveConfig();if(!isSafeChartConfigurationRecord(config))return!1;const data=chartRecordValue(config,"data");return data!==MISSING_OWN_DATA_DESCRIPTOR&&data!==UNSAFE_OWN_DATA_DESCRIPTOR}datasetLabel(dataset,index){return chartDatasetLabel(dataset)||this.localize("chartPointLabel",void 0,{n:getNumberFormat(this.effectiveLocale).format(index+1)})}datasetValues(dataset){return chartDatasetValues(dataset)}isPointDataset(dataset){const values=this.datasetValues(dataset);return this.effectiveType()==="scatter"||this.effectiveType()==="bubble"||values.some(value=>normalizedChartPoint(value)!==null)}appendData(label,values,maxPoints=0){this.preparedDataInput()===null&&this.withStreamedTableUpdate(()=>{const requested=Number.isFinite(maxPoints)?Math.max(0,Math.floor(maxPoints)):0,limit=requested>0?Math.min(requested,MAX_CHART_INPUT_ENTRIES):MAX_CHART_INPUT_ENTRIES,appendedValues=projectChartNumberData(values)??Object.freeze([]);if(this.hasExplicitConfigData()){const effective=this.effectiveData();let domainLength2=effective.labels.length;for(const dataset of effective.datasets)this.isPointDataset(dataset)||(domainLength2=Math.max(domainLength2,this.datasetValues(dataset).length));const labels2=[...effective.labels,...Array.from({length:Math.max(0,domainLength2-effective.labels.length)},()=>""),label],effectiveConfig=this.effectiveConfig(),currentData=projectChartDataConfiguration(effectiveConfig?.data)??{},explicitLabels=admitChartArray(currentData.labels)!==void 0,explicitDatasets=admitChartArray(currentData.datasets)!==void 0,nextLabels=labels2.slice(-limit);if(explicitLabels||(this.labels=nextLabels.map(labelText)),!explicitDatasets){const datasets2=this.datasets.map((series,index)=>{if(canonicalSeriesPoints(series)!==void 0)return series;const current=canonicalSeriesData(series),data=[...current,...Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),appendedValues[index]??null];return appendChartSeries(series,data.slice(-limit))});this.datasets=datasets2}if(explicitLabels||explicitDatasets){const nextData={...currentData};explicitLabels&&(nextData.labels=Object.freeze(nextLabels)),explicitDatasets&&(nextData.datasets=effective.datasets.map((dataset,index)=>{if(this.isPointDataset(dataset))return dataset;const current=this.datasetValues(dataset),peer=chartDatasetPeerValues(dataset),padding=Array.from({length:Math.max(0,domainLength2-current.length)},()=>null),data=[...peer,...padding,appendedValues[index]??null],canonical=[...current,...padding,appendedValues[index]??null],nextData2=Object.freeze(data.slice(-limit)),nextCanonical=canonical.slice(-limit);canonicalChartDatasetDataValues.set(nextData2,Object.freeze(nextCanonical));const nextDataset=Object.freeze({...dataset,data:nextData2});return canonicalChartDatasetValues.set(nextDataset,Object.freeze(nextCanonical)),nextDataset})),Array.isArray(nextData.datasets)&&Object.freeze(nextData.datasets),canonicalChartDataSnapshots.add(nextData);const previous=this._config;this._config=Object.freeze({...effectiveConfig,data:Object.freeze(nextData)}),this.configSource=this._config,this.requestUpdate("config",previous)}return}const currentLabels=this.canonicalLabels();let domainLength=currentLabels.length;for(const series of this.datasets)canonicalSeriesPoints(series)===void 0&&(domainLength=Math.max(domainLength,canonicalSeriesData(series).length));const labels=[...currentLabels,...Array.from({length:Math.max(0,domainLength-currentLabels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>{if(canonicalSeriesPoints(series)!==void 0)return series;const current=canonicalSeriesData(series),data=[...current,...Array.from({length:Math.max(0,domainLength-current.length)},()=>null),appendedValues[index]??null];return appendChartSeries(series,data.slice(-limit))});this.labels=labels.slice(-limit),this.datasets=datasets})}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";if(this.spatialActive)return spatialCsv(this.spatial.binding?.chart?.series??[],this.spatialPoints(),this.spatial.result?.bins??[],(value,record,column)=>{const datasetIndex="seriesId"in record?this.spatial.binding.chart.series.findIndex(series=>series.id===record.seriesId):void 0;return this.formatExportValue(value,{datasetIndex,..."sourceIndex"in record?{index:record.sourceIndex,label:record.label}:{},...column==="x"||column==="y"||column==="radius"?{statistic:column==="radius"?"r":column}:{}})});const effective=this.effectiveData(),columns=effective.datasets.map((dataset,datasetIndex)=>{const values=this.datasetValues(dataset),label=this.datasetLabel(dataset,datasetIndex),points=values.map(normalizedChartPoint).filter(point=>point!==null);return{dataset,label,point:this.isPointDataset(dataset),radius:points.some(point=>point.r!=null),pointLabel:points.some(point=>point.label!=null)}}),header=["label",...columns.flatMap(column=>column.point?[`${column.label} x`,`${column.label} y`,...column.radius?[`${column.label} r`]:[],...column.pointLabel?[`${column.label} label`]:[]]:[column.label])].map(escapeCsvField).join(",");let rowCount=effective.labels.length;for(const dataset of effective.datasets)rowCount=Math.max(rowCount,this.datasetValues(dataset).length);const exportCell=(value,metadata)=>typeof value!="number"||!Number.isFinite(value)?value??"":this.formatExportValue(value,metadata)??value,rows=Array.from({length:rowCount},(_,index)=>{const firstPoint=effective.datasets.map(dataset=>normalizedChartPoint(this.datasetValues(dataset)[index])).find(point=>point!==null),label=labelText(effective.labels[index])||firstPoint?.label||"";return[label,...columns.flatMap((column,datasetIndex)=>{const value=this.datasetValues(column.dataset)[index],axis=this.datasetValueAxis(column.dataset),metadata={datasetIndex,index,label:label||void 0,seriesLabel:column.label,...axis===void 0?{}:{axis}};if(!column.point)return[exportCell(value,metadata)];const point=normalizedChartPoint(value);return point?[exportCell(point.x,{...metadata,statistic:"x"}),exportCell(point.y,{...metadata,statistic:"y"}),...column.radius?[point.r==null?"":exportCell(point.r,{...metadata,statistic:"r"})]:[],...column.pointLabel?[point.label??""]:[]]:["","",...column.radius?[""]:[],...column.pointLabel?[""]:[]]})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
|
|
8
|
-
`)}connectedCallback(){super.connectedCallback(),this.preparedDirty=!0,this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const ownerWindow=this.ownerWindow,ResizeObserverCtor=ownerWindow?.ResizeObserver;ResizeObserverCtor&&(this.resizeObserver=new ResizeObserverCtor(entries=>{const width=entries[0]?.contentRect.width??this.getBoundingClientRect().width;if(Number.isFinite(width)&&this.lastObservedInlineSize!==void 0&&Math.abs(width-this.lastObservedInlineSize)<.5||(this.lastObservedInlineSize=width,this.resizeDrawFrame!==void 0))return;const frameOwner=this.ownerWindow;frameOwner&&(this.resizeDrawFrameOwner=frameOwner,this.resizeDrawFrame=frameOwner.requestAnimationFrame(()=>{if(this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const samplingWidth=Number.isFinite(this.lastObservedInlineSize)?Math.max(0,Math.floor(this.lastObservedInlineSize)):0;if(samplingWidth!==this.samplingWidth){this.samplingWidth=samplingWidth,this.updateAutoLegendPosition();return}this.updateAutoLegendPosition()||this.drawIfVisible()}))}),this.resizeObserver.observe(this)),this.updateAutoLegendPosition();const generation=++this.loadGeneration;this.zoomable&&this.requestZoomFeature(),this.loadLibrary(this.zoomable).then(async mod=>{try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mod){this.loadFailed=!0;return}this.loadFailed=!1,this.chartJsModule=mod,this.drawIfVisible()}}),this.needsDataLabels&&this.requestDataLabelsFeature(),this.needsAnnotations&&this.requestAnnotationFeature();const IntersectionObserverCtor=ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}disconnectedCallback(){this.spatialRevealToken={},this.spatial.reset(),this.wakeSpatialWaiters(),this.preparedRequests.refresh(),this.preparedModel=this.preparedBaseModel=void 0,this.preparedEffective=void 0,this.preparedDirty=!0,this.chartSync.disconnect(),this.cancelDeferredTable?.(),this.cancelDeferredTable=void 0,this.deferredTableRows=void 0,super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.announcedFeatureWarnings.clear(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeDrawFrame!==void 0&&this.resizeDrawFrameOwner?.cancelAnimationFrame(this.resizeDrawFrame),this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,this.lastObservedInlineSize=void 0,this.loadGeneration+=1,this.zoomLoadGeneration+=1,this.dataLabelsLoadGeneration+=1,this.annotationLoadGeneration+=1,this.discardChart(!1),this.builtPlugins=[],this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.spatial.authority.adopted(),this.spatialRevealToken={},this.wakeSpatialWaiters(),this.preparedRequests.adopted(),this.chartSync.disconnect(),this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.requestUpdate(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}computedStyle(element=this){const view=this.ownerWindow;return view?view.getComputedStyle(element):"style"in element?element.style:this.style}applyDataLabelsPlugin(plugin){this.dataLabelsPlugin=plugin;let rebuilt=!1;plugin&&this.needsDataLabels&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[],rebuilt=!0),this.drawIfVisible(),rebuilt&&this.showsLegend&&this.requestUpdate("canvasPresentation",null)}get zoomFeatureAvailable(){return this.zoomable&&this.zoomFeatureState==="available"}featureWarningMessages(){if(this.loading||this.loadFailed)return[];const messages=[];return this.zoomable&&this.zoomFeatureState==="unavailable"&&messages.push(this.localize("chartZoomUnavailable")),this.dataLabelsFeatureState==="unavailable"&&(this.dataLabels&&messages.push(this.localize("chartDataLabelsUnavailable")),this.stackTotals&&messages.push(this.localize("chartStackTotalsUnavailable"))),this.needsAnnotations&&this.annotationFeatureState==="unavailable"&&messages.push(this.localize("chartAnnotationsUnavailable")),messages}requestZoomFeature(){const generation=++this.zoomLoadGeneration;if(!this.zoomable){this.zoomFeatureState="idle";return}this.zoomFeatureState="loading",this.loadZoomFeature().then(result=>{generation!==this.zoomLoadGeneration||!this.isConnected||!this.zoomable||(this.zoomFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.drawIfVisible(),this.requestUpdate("canvasPresentation",null))})}requestAnnotationFeature(){const generation=++this.annotationLoadGeneration;if(!this.needsAnnotations){this.annotationFeatureState="idle";return}this.annotationFeatureState="loading",this.loadAnnotationFeature().then(result=>{generation!==this.annotationLoadGeneration||!this.isConnected||!this.needsAnnotations||(result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.annotationFeatureState=result.kind==="available"?"available":"unavailable",this.applyAnnotationPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate("canvasPresentation",null))})}applyAnnotationPlugin(plugin){this.annotationPlugin=plugin,plugin&&this.needsAnnotations&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[]),this.drawIfVisible()}rebuildAfterAnnotationRegistration(){!this.chart||this.needsAnnotations||(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[],this.drawIfVisible())}requestDataLabelsFeature(){const generation=++this.dataLabelsLoadGeneration;if(!this.needsDataLabels){this.dataLabelsFeatureState="idle";return}this.dataLabelsFeatureState="loading",this.loadDataLabelsFeature().then(result=>{generation!==this.dataLabelsLoadGeneration||!this.isConnected||!this.needsDataLabels||(this.dataLabelsFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.applyDataLabelsPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate("canvasPresentation",null))})}willUpdate(changed){if(super.willUpdate(changed),this.refreshPreparedModel(),this.spatialActive){this.zoomed=this.viewport!==null;return}this.zoomed&&this.effectiveType()!==this.builtType&&(this.zoomed=!1,this.emit("lr-zoom",{zoomed:!1}))}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{collectInitialSlotAssignment(this.configSlotEl,s=>this.collectConfigFromSlot(s))})}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;let canvasChanges=changed;changed.has("hiddenDatasets")&&appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.canonicalHiddenDatasets()&&(canvasChanges=new Map(changed),canvasChanges.delete("hiddenDatasets"));const contentChanged=this.preparedChanged||this.chartContentChanged(canvasChanges);this.preparedChanged=!1;const syncDataChanged=contentChanged||changed.has("hiddenDatasets")||changed.has("hiddenDatums");this.chartSync.update(this.syncGroup,typeof this.syncGroup=="string"&&this.syncGroup.trim()!==""&&this.syncCompatible(),syncDataChanged);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&this.preparedInvalid&&!this.announcedPreparedInvalid&&this.announcements.announceAssertive(this.localize("chartPreparedUnavailable")),this.announcedPreparedInvalid=this.preparedInvalid,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("chartMissingLibrary"));const dataTruncation=[this.inputLimitMessage(),this.dataTruncationMessage()].filter(Boolean).join(this.localize("chartSummarySeparator"));if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed){const featureWarnings=this.featureWarningMessages();for(const warning of featureWarnings)this.announcedFeatureWarnings.has(warning)||this.announcements.announceAssertive(warning);this.announcedFeatureWarnings=new Set(featureWarnings),!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation))}if(this.setAttribute("aria-busy",String(this.loading||this.preparedPending)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;changed.has("zoomable")&&this.requestZoomFeature(),(changed.has("dataLabels")||changed.has("stackTotals"))&&this.requestDataLabelsFeature(),changed.has("annotations")&&this.requestAnnotationFeature();const effectiveDirection=this.effectiveDirection,effectiveLocale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==effectiveDirection||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==effectiveLocale;if(this.lastDrawnDirection=effectiveDirection,this.lastDrawnLocale=effectiveLocale,!contentChanged&&!contextChanged){changed.has("hiddenDatums")&&this.visible&&this.applyDatumVisibility()&&this.chart?.update("none");return}this.drawIfVisible()}chartContentChanged(changed){return["preparedData","preparedView","spatialView","viewport","selectedPointId","type","maxRecords","samplingWidth","labels","datasets","hiddenDatasets","grid","axes","size","indexAxis","legendPosition","min","max","scaleType","annotations","plugins","autoLegendPosition","valueFormatter","formatter","tooltipTitleFormatter","tooltipFooterFormatter","area","height","xLabel","yLabel","y2Label","withoutZeroBaseline","stacked","stackedAxes","withoutAnimation","withoutLegend","withoutTooltip","syncGroup","dataLabels","stackTotals","config","slottedConfig","zoomable","locale","strings","loading"].some(name=>changed.has(name))}seriesToDataset(s,index,palette,effectiveType,chartStyle=this.chartStyleOptions(palette),rowIndexes){const series=canonicalChartSeries(s);if(!series)return{label:"",data:[]};const points=canonicalSeriesPoints(series),values=points??canonicalSeriesData(series),normalize=points?normalizedChartPoint:value=>typeof value=="number"&&Number.isFinite(value)?value:null,normalizedData=rowIndexes?rowIndexes.map(rowIndex=>normalize(values[rowIndex])):values.map(normalize),borderFallback=chartStyle.borderColors[index%chartStyle.borderColors.length]??palette[index%palette.length],fillFallback=chartStyle.fillColors[index%chartStyle.fillColors.length]??palette[index%palette.length],sourceColors=projectChartStrings(series.color),authoredColors=sourceColors&&rowIndexes?rowIndexes.map(rowIndex=>sourceColors[rowIndex]??""):typeof series.color=="string"?series.color:sourceColors,colors=typeof authoredColors=="string"?[this.canvasTokens.resolve(authoredColors,borderFallback??"transparent")]:authoredColors?this.canvasTokens.resolveMany(authoredColors,borderFallback??"transparent"):void 0,sliceChart=effectiveType==="pie"||effectiveType==="doughnut"||effectiveType==="polarArea",sliceFillColors=sliceChart&&chartStyle.fillColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.fillColors[sourceIndex%chartStyle.fillColors.length]}):void 0,sliceBorderColors=sliceChart&&chartStyle.borderColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.borderColors[sourceIndex%chartStyle.borderColors.length]}):void 0,fill=series.fill??this.area,backgroundColor=colors??sliceFillColors??fillFallback,datasetType=series.type??effectiveType,authoredSegmentColors=series.segmentColors?.length&&rowIndexes?rowIndexes.map(rowIndex=>series.segmentColors[rowIndex%series.segmentColors.length]):series.segmentColors,segmentColors=authoredSegmentColors?this.canvasTokens.resolveMany(authoredSegmentColors,colors?.[0]??borderFallback??"transparent"):void 0,authoredPointColors=series.pointColors&&rowIndexes?rowIndexes.map(rowIndex=>series.pointColors[rowIndex]??""):series.pointColors,backgroundColors=projectChartStrings(backgroundColor),backgroundColorValue=typeof backgroundColor=="string"?backgroundColor:void 0,resolvedBackgroundColor=datasetType==="line"&&fill&&(colors||!chartStyle.authoredFillColors[index%chartStyle.authoredFillColors.length])?backgroundColors?backgroundColors.map(color=>this.canvasTokens.translucent(color)):backgroundColorValue&&this.canvasTokens.translucent(backgroundColorValue):backgroundColor,encoding=forcedColorEncoding(index),resolvedBackgroundColors=projectChartStrings(resolvedBackgroundColor),resolvedBackgroundColorValue=typeof resolvedBackgroundColor=="string"?resolvedBackgroundColor:void 0,encodedBackgroundColor=chartStyle.forcedColors?resolvedBackgroundColors?resolvedBackgroundColors.map((color,itemIndex)=>this.forcedColorPattern(sliceChart?itemIndex:index,color)):resolvedBackgroundColorValue&&this.forcedColorPattern(index,resolvedBackgroundColorValue):resolvedBackgroundColor,pointRadii=projectChartPointRadii(series.pointRadius);return{label:series.label,data:normalizedData,type:series.type,fill,...datasetType==="bar"&&this.hasConfiguredBarOption("borderRadius")?{}:{borderRadius:chartStyle.borderRadius},...datasetType==="bar"&&!Number.isFinite(series.width)&&this.hasConfiguredBarOption("borderWidth")||isArcDatasetType(datasetType)&&this.hasConfiguredElementOption(datasetType,"arc","borderWidth")?{}:{borderWidth:nonNegativeFinite(series.width,datasetType==="line"||datasetType==="radar"?chartStyle.lineBorderWidth:chartStyle.borderWidth)},borderDash:series.dash?[4,4]:chartStyle.forcedColors?[...encoding.dash]:void 0,pointStyle:chartStyle.forcedColors?encoding.pointStyle:void 0,backgroundColor:encodedBackgroundColor,borderColor:colors?.[0]??sliceBorderColors??borderFallback,pointBackgroundColor:authoredPointColors?this.canvasTokens.resolveMany(authoredPointColors,colors?.[0]??borderFallback??"transparent"):void 0,...isPointDatasetType(datasetType)&&this.hasConfiguredElementOption(datasetType,"point","radius")?{}:{pointRadius:pointRadii?(rowIndexes?rowIndexes.map(rowIndex=>pointRadii[rowIndex]):pointRadii).map(radius=>nonNegativeFinite(radius,chartStyle.pointRadius)):nonNegativeFinite(series.pointRadius,chartStyle.pointRadius)},...segmentColors?.length?{segment:{borderColor:ctx=>segmentColors[ctx.p0DataIndex%segmentColors.length]}}:{},yAxisID:series.axis==="y2"?"y2":"y",...series.stack!==void 0?{stack:series.stack}:{}}}hasConfiguredElementOption(datasetTypeKey,elementKey,option){const read=(value,key)=>{if(!isChartRecord(value))return;const descriptor=chartRecordValue(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value},options=this.effectiveConfig()?.options,dataset=read(read(options,"datasets"),datasetTypeKey),scopes=[dataset,read(read(dataset,"elements"),elementKey),read(read(options,"elements"),elementKey),options],prefixed=`${elementKey}${option[0].toUpperCase()}${option.slice(1)}`;return scopes.some(scope=>read(scope,prefixed)!==void 0||read(scope,option)!==void 0)}hasConfiguredBarOption(option){return this.hasConfiguredElementOption("bar","bar",option)}themeColors(){const cs=this.canvasTokens.sync()??this.computedStyle(),grid=cs.getPropertyValue("--grid-color").trim()||cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),tick=cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),legend=cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),tooltipBg=cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),tooltipText=cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim();return{grid:this.canvasTokens.resolve(grid,FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(tick,FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size","--_lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE),legend:this.canvasTokens.resolve(legend,FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(tooltipBg,FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(tooltipText,FALLBACK_TOOLTIP_TEXT)}}styleColor(name,fallback){const value=this.computedStyle().getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallbackToken,fallback){const computed=this.computedStyle(),value=computed.getPropertyValue(name).trim()||computed.getPropertyValue(fallbackToken).trim(),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!this.ownerWindow)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(this.computedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}explicitTickFontSize(){const resolved=this.styleNumber("--lr-chart-tick-font-size","--lr-chart-tick-font-size",NaN);return Number.isNaN(resolved)?void 0:resolved}forcedColorPattern(index,background){if(!this.ownerWindow)return background;const surface=this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG),key=`${forcedColorEncoding(index).name}
|
|
8
|
+
`)}connectedCallback(){super.connectedCallback(),this.preparedDirty=!0,this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const ownerWindow=this.ownerWindow,ResizeObserverCtor=ownerWindow?.ResizeObserver;ResizeObserverCtor&&(this.resizeObserver=new ResizeObserverCtor(entries=>{const width=entries[0]?.contentRect.width??this.getBoundingClientRect().width;if(Number.isFinite(width)&&this.lastObservedInlineSize!==void 0&&Math.abs(width-this.lastObservedInlineSize)<.5||(this.lastObservedInlineSize=width,this.resizeDrawFrame!==void 0))return;const frameOwner=this.ownerWindow;frameOwner&&(this.resizeDrawFrameOwner=frameOwner,this.resizeDrawFrame=frameOwner.requestAnimationFrame(()=>{if(this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,!this.isConnected||this.ownerWindow!==frameOwner)return;const samplingWidth=Number.isFinite(this.lastObservedInlineSize)?Math.max(0,Math.floor(this.lastObservedInlineSize)):0;if(samplingWidth!==this.samplingWidth){this.samplingWidth=samplingWidth,this.updateAutoLegendPosition();return}this.updateAutoLegendPosition()||this.drawIfVisible()}))}),this.resizeObserver.observe(this)),this.updateAutoLegendPosition();const generation=++this.loadGeneration;this.zoomable&&this.requestZoomFeature(),this.loadLibrary(this.zoomable).then(async mod=>{try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),!(generation!==this.loadGeneration||!this.isConnected)){if(this.loading=!1,!mod){this.loadFailed=!0;return}this.loadFailed=!1,this.chartJsModule=mod,this.drawIfVisible()}}),this.needsDataLabels&&this.requestDataLabelsFeature(),this.needsAnnotations&&this.requestAnnotationFeature();const IntersectionObserverCtor=ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}disconnectedCallback(){this.spatialRevealToken={},this.spatial.reset(),this.wakeSpatialWaiters(),this.preparedRequests.refresh(),this.preparedModel=this.preparedBaseModel=void 0,this.preparedEffective=void 0,this.preparedDirty=!0,this.chartSync.disconnect(),this.cancelDeferredTable?.(),this.cancelDeferredTable=void 0,this.deferredTableRows=void 0,super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.announcedFeatureWarnings.clear(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeDrawFrame!==void 0&&this.resizeDrawFrameOwner?.cancelAnimationFrame(this.resizeDrawFrame),this.resizeDrawFrame=void 0,this.resizeDrawFrameOwner=void 0,this.lastObservedInlineSize=void 0,this.loadGeneration+=1,this.zoomLoadGeneration+=1,this.dataLabelsLoadGeneration+=1,this.annotationLoadGeneration+=1,this.discardChart(!1),this.builtPlugins=[],this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.spatial.authority.adopted(),this.spatialRevealToken={},this.wakeSpatialWaiters(),this.preparedRequests.adopted(),this.chartSync.disconnect(),this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.requestUpdate(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}computedStyle(element=this){const view=this.ownerWindow;return view?view.getComputedStyle(element):"style"in element?element.style:this.style}applyDataLabelsPlugin(plugin){this.dataLabelsPlugin=plugin;let rebuilt=!1;plugin&&this.needsDataLabels&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[],rebuilt=!0),this.drawIfVisible(),rebuilt&&this.showsLegend&&this.requestUpdate("canvasPresentation",null)}get zoomFeatureAvailable(){return this.zoomable&&this.zoomFeatureState==="available"}featureWarningMessages(){if(this.loading||this.loadFailed)return[];const messages=[];return this.zoomable&&this.zoomFeatureState==="unavailable"&&messages.push(this.localize("chartZoomUnavailable")),this.dataLabelsFeatureState==="unavailable"&&(this.dataLabels&&messages.push(this.localize("chartDataLabelsUnavailable")),this.stackTotals&&messages.push(this.localize("chartStackTotalsUnavailable"))),this.needsAnnotations&&this.annotationFeatureState==="unavailable"&&messages.push(this.localize("chartAnnotationsUnavailable")),messages}requestZoomFeature(){const generation=++this.zoomLoadGeneration;if(!this.zoomable){this.zoomFeatureState="idle";return}this.zoomFeatureState="loading",this.loadZoomFeature().then(result=>{generation!==this.zoomLoadGeneration||!this.isConnected||!this.zoomable||(this.zoomFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.drawIfVisible(),this.requestUpdate("canvasPresentation",null))})}requestAnnotationFeature(){const generation=++this.annotationLoadGeneration;if(!this.needsAnnotations){this.annotationFeatureState="idle";return}this.annotationFeatureState="loading",this.loadAnnotationFeature().then(result=>{generation!==this.annotationLoadGeneration||!this.isConnected||!this.needsAnnotations||(result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.annotationFeatureState=result.kind==="available"?"available":"unavailable",this.applyAnnotationPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate("canvasPresentation",null))})}applyAnnotationPlugin(plugin){this.annotationPlugin=plugin,plugin&&this.needsAnnotations&&this.chart&&(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[]),this.drawIfVisible()}rebuildAfterAnnotationRegistration(){!this.chart||this.needsAnnotations||(this.discardChart(!0),this.builtType=void 0,this.builtPlugins=[],this.drawIfVisible())}requestDataLabelsFeature(){const generation=++this.dataLabelsLoadGeneration;if(!this.needsDataLabels){this.dataLabelsFeatureState="idle";return}this.dataLabelsFeatureState="loading",this.loadDataLabelsFeature().then(result=>{generation!==this.dataLabelsLoadGeneration||!this.isConnected||!this.needsDataLabels||(this.dataLabelsFeatureState=result.kind==="available"?"available":"unavailable",result.kind!=="core-unavailable"&&!this.loading&&!this.chartJsModule&&(this.chartJsModule=result.mod),this.applyDataLabelsPlugin(result.kind==="available"?result.plugin:void 0),this.requestUpdate("canvasPresentation",null))})}willUpdate(changed){if(super.willUpdate(changed),this.refreshPreparedModel(),this.spatialActive){this.zoomed=this.viewport!==null;return}this.zoomed&&this.effectiveType()!==this.builtType&&(this.zoomed=!1,this.emit("lr-zoom",{zoomed:!1}))}firstUpdated(changed){super.firstUpdated(changed),queueMicrotask(()=>{collectInitialSlotAssignment(this.configSlotEl,s=>this.collectConfigFromSlot(s))})}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;let canvasChanges=changed;changed.has("hiddenDatasets")&&appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.canonicalHiddenDatasets()&&(canvasChanges=new Map(changed),canvasChanges.delete("hiddenDatasets"));const contentChanged=this.preparedChanged||this.chartContentChanged(canvasChanges);this.preparedChanged=!1;const syncDataChanged=contentChanged||changed.has("hiddenDatasets")||changed.has("hiddenDatums");this.chartSync.update(this.syncGroup,typeof this.syncGroup=="string"&&this.syncGroup.trim()!==""&&this.syncCompatible(),syncDataChanged);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&this.preparedInvalid&&!this.announcedPreparedInvalid&&this.announcements.announceAssertive(this.localize("chartPreparedUnavailable")),this.announcedPreparedInvalid=this.preparedInvalid,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("chartMissingLibrary"));const dataTruncation=[this.inputLimitMessage(),this.dataTruncationMessage()].filter(Boolean).join(this.localize("chartSummarySeparator"));if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed){const featureWarnings=this.featureWarningMessages();for(const warning of featureWarnings)this.announcedFeatureWarnings.has(warning)||this.announcements.announceAssertive(warning);this.announcedFeatureWarnings=new Set(featureWarnings),!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation))}if(this.setAttribute("aria-busy",String(this.loading||this.preparedPending)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;changed.has("zoomable")&&this.requestZoomFeature(),(changed.has("dataLabels")||changed.has("stackTotals"))&&this.requestDataLabelsFeature(),changed.has("annotations")&&this.requestAnnotationFeature();const effectiveDirection=this.effectiveDirection,effectiveLocale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==effectiveDirection||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==effectiveLocale;if(this.lastDrawnDirection=effectiveDirection,this.lastDrawnLocale=effectiveLocale,!contentChanged&&!contextChanged){changed.has("hiddenDatums")&&this.visible&&this.applyDatumVisibility()&&this.chart?.update("none");return}this.drawIfVisible()}chartContentChanged(changed){return["preparedData","preparedView","spatialView","viewport","selectedPointId","type","maxRecords","samplingWidth","labels","datasets","hiddenDatasets","grid","axes","size","indexAxis","legendPosition","min","max","scaleType","annotations","plugins","autoLegendPosition","valueFormatter","formatter","tooltipTitleFormatter","tooltipFooterFormatter","area","height","xLabel","yLabel","y2Label","withoutZeroBaseline","stacked","stackedAxes","withoutAnimation","withoutLegend","withoutTooltip","syncGroup","dataLabels","stackTotals","config","slottedConfig","zoomable","locale","strings","loading"].some(name=>changed.has(name))}seriesToDataset(s,index,palette,effectiveType,chartStyle=this.chartStyleOptions(palette),rowIndexes){const series=canonicalChartSeries(s);if(!series)return{label:"",data:[]};const points=canonicalSeriesPoints(series),values=points??canonicalSeriesData(series),normalize=points?normalizedChartPoint:value=>typeof value=="number"&&Number.isFinite(value)?value:null,normalizedData=rowIndexes?rowIndexes.map(rowIndex=>normalize(values[rowIndex])):values.map(normalize),borderFallback=chartStyle.borderColors[index%chartStyle.borderColors.length]??palette[index%palette.length],fillFallback=chartStyle.fillColors[index%chartStyle.fillColors.length]??palette[index%palette.length],sourceColors=projectChartStrings(series.color),authoredColors=sourceColors?.length&&rowIndexes?rowIndexes.map(rowIndex=>sourceColors[rowIndex%sourceColors.length]??""):typeof series.color=="string"?series.color:sourceColors,colors=typeof authoredColors=="string"?[this.canvasTokens.resolve(authoredColors,borderFallback??"transparent")]:authoredColors?this.canvasTokens.resolveMany(authoredColors,borderFallback??"transparent"):void 0,sliceChart=effectiveType==="pie"||effectiveType==="doughnut"||effectiveType==="polarArea",sliceFillColors=sliceChart&&chartStyle.fillColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.fillColors[sourceIndex%chartStyle.fillColors.length]}):void 0,sliceBorderColors=sliceChart&&chartStyle.borderColors.length?normalizedData.map((_,itemIndex)=>{const sourceIndex=rowIndexes?.[itemIndex]??itemIndex;return chartStyle.borderColors[sourceIndex%chartStyle.borderColors.length]}):void 0,fill=series.fill??this.area,backgroundColor=colors??sliceFillColors??fillFallback,datasetType=series.type??effectiveType,connectedStroke=datasetType==="line"||datasetType==="radar",authoredSegmentColors=series.segmentColors?.length&&rowIndexes?rowIndexes.map(rowIndex=>series.segmentColors[rowIndex%series.segmentColors.length]):series.segmentColors,segmentColors=authoredSegmentColors?this.canvasTokens.resolveMany(authoredSegmentColors,colors?.[0]??borderFallback??"transparent"):void 0,authoredPointColors=series.pointColors?.length&&rowIndexes?rowIndexes.map(rowIndex=>series.pointColors[rowIndex%series.pointColors.length]??""):series.pointColors,backgroundColors=projectChartStrings(backgroundColor),backgroundColorValue=typeof backgroundColor=="string"?backgroundColor:void 0,resolvedBackgroundColor=datasetType==="line"&&fill&&(colors||!chartStyle.authoredFillColors[index%chartStyle.authoredFillColors.length])?backgroundColors?backgroundColors.map(color=>this.canvasTokens.translucent(color)):backgroundColorValue&&this.canvasTokens.translucent(backgroundColorValue):backgroundColor,encoding=forcedColorEncoding(index),resolvedBackgroundColors=projectChartStrings(resolvedBackgroundColor),resolvedBackgroundColorValue=typeof resolvedBackgroundColor=="string"?resolvedBackgroundColor:void 0,encodedBackgroundColor=chartStyle.forcedColors?resolvedBackgroundColors?resolvedBackgroundColors.map((color,itemIndex)=>this.forcedColorPattern(sliceChart?itemIndex:index,color)):resolvedBackgroundColorValue&&this.forcedColorPattern(index,resolvedBackgroundColorValue):resolvedBackgroundColor,pointRadii=projectChartPointRadii(series.pointRadius);return{label:series.label,data:normalizedData,type:series.type,fill,...datasetType==="bar"&&this.hasConfiguredBarOption("borderRadius")?{}:{borderRadius:chartStyle.borderRadius},...datasetType==="bar"&&!Number.isFinite(series.width)&&this.hasConfiguredBarOption("borderWidth")||isArcDatasetType(datasetType)&&this.hasConfiguredElementOption(datasetType,"arc","borderWidth")?{}:{borderWidth:nonNegativeFinite(series.width,connectedStroke?chartStyle.lineBorderWidth:chartStyle.borderWidth)},borderDash:series.dash?[4,4]:chartStyle.forcedColors?[...encoding.dash]:void 0,pointStyle:chartStyle.forcedColors?encoding.pointStyle:void 0,backgroundColor:encodedBackgroundColor,borderColor:(sourceColors?.length&&!connectedStroke?colors:colors?.[0])??sliceBorderColors??borderFallback,...connectedStroke&&sourceColors?.length?{pointBorderColor:colors}:{},pointBackgroundColor:authoredPointColors?this.canvasTokens.resolveMany(authoredPointColors,colors?.[0]??borderFallback??"transparent"):void 0,...isPointDatasetType(datasetType)&&this.hasConfiguredElementOption(datasetType,"point","radius")?{}:{pointRadius:pointRadii?(rowIndexes?rowIndexes.map(rowIndex=>pointRadii[rowIndex]):pointRadii).map(radius=>nonNegativeFinite(radius,chartStyle.pointRadius)):nonNegativeFinite(series.pointRadius,chartStyle.pointRadius)},...segmentColors?.length?{segment:{borderColor:ctx=>segmentColors[ctx.p0DataIndex%segmentColors.length]}}:{},yAxisID:series.axis==="y2"?"y2":"y",...series.stack!==void 0?{stack:series.stack}:{}}}hasConfiguredElementOption(datasetTypeKey,elementKey,option){const read=(value,key)=>{if(!isChartRecord(value))return;const descriptor=chartRecordValue(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value},options=this.effectiveConfig()?.options,dataset=read(read(options,"datasets"),datasetTypeKey),scopes=[dataset,read(read(dataset,"elements"),elementKey),read(read(options,"elements"),elementKey),options],prefixed=`${elementKey}${option[0].toUpperCase()}${option.slice(1)}`;return scopes.some(scope=>read(scope,prefixed)!==void 0||read(scope,option)!==void 0)}hasConfiguredBarOption(option){return this.hasConfiguredElementOption("bar","bar",option)}themeColors(){const cs=this.canvasTokens.sync()??this.computedStyle(),grid=cs.getPropertyValue("--grid-color").trim()||cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),tick=cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),legend=cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),tooltipBg=cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),tooltipText=cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim();return{grid:this.canvasTokens.resolve(grid,FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(tick,FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size","--_lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE),legend:this.canvasTokens.resolve(legend,FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(tooltipBg,FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(tooltipText,FALLBACK_TOOLTIP_TEXT)}}styleColor(name,fallback){const value=this.computedStyle().getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallbackToken,fallback){const computed=this.computedStyle(),value=computed.getPropertyValue(name).trim()||computed.getPropertyValue(fallbackToken).trim(),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!this.ownerWindow)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(this.computedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}explicitTickFontSize(){const resolved=this.styleNumber("--lr-chart-tick-font-size","--lr-chart-tick-font-size",NaN);return Number.isNaN(resolved)?void 0:resolved}forcedColorPattern(index,background){if(!this.ownerWindow)return background;const surface=this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG),key=`${forcedColorEncoding(index).name}
|
|
9
9
|
${background}
|
|
10
10
|
${surface}`;let pattern=this.forcedColorPatterns.get(key);return pattern||(pattern=createForcedColorPattern(this.ownerDocument,index,background,surface),this.forcedColorPatterns.set(key,pattern)),pattern}chartStyleOptions(palette){const computed=this.computedStyle(),authoredFillColors=palette.map((_,index)=>index<6&&!!computed.getPropertyValue(`--fill-color-${index+1}`).trim()),borderColors=palette.map((fallback,index)=>index<6?this.styleColor(`--border-color-${index+1}`,fallback):fallback),fillColors=palette.map((fallback,index)=>index<6?this.styleColor(`--fill-color-${index+1}`,fallback):fallback);return{borderColors,fillColors,authoredFillColors,borderRadius:this.styleNumber("--border-radius","--lr-radius",6),borderWidth:this.styleNumber("--border-width","--lr-border-width-thin",1),gridBorderWidth:this.styleNumber("--grid-border-width","--lr-border-width-thin",1),lineBorderWidth:this.styleNumber("--line-border-width","--lr-border-width-medium",2),pointRadius:this.styleNumber("--point-radius","--lr-space-2xs",4),forcedColors:forcedColorsActive(this.ownerWindow)}}get needsDataLabels(){return this.dataLabels||this.stackTotals}get needsAnnotations(){return this.normalizedAnnotations().length>0}normalizedAnnotations(){return this.canonicalAnnotations()}annotationColor(tone){const token=`--lr-color-${tone??"neutral"}`,raw=this.computedStyle().getPropertyValue(token).trim();return this.canvasTokens.resolve(raw,FALLBACK_TICK_COLOR)}annotationOptions(tick){const entries={},direction=this.effectiveDirection==="rtl"?"rtl":"ltr";return this.normalizedAnnotations().forEach((entry,index)=>{const axis=entry.axis==="x"?"x":"y",color=this.annotationColor(entry.tone),label=entry.label?{content:isolateCanvasText(entry.label,direction),display:!0,color:tick}:void 0;if(typeof entry.value=="number"){entries[`lr-annotation-${index}`]={type:"line",scaleID:axis,value:entry.value,borderColor:color,borderWidth:2,...label?{label}:{}};return}const bounds=axis==="y"?{yMin:entry.from,yMax:entry.to}:{xMin:entry.from,xMax:entry.to};entries[`lr-annotation-${index}`]={type:"box",...bounds,backgroundColor:this.canvasTokens.translucent(color),borderColor:color,borderWidth:0,...label?{label}:{}}}),entries}datalabelsOptions(theme,effectiveType){if(!this.needsDataLabels)return{display:!1};const effective=this.effectiveData(),datasets=effective.datasets,stackTotalsPossible=this.stackTotals&&(effectiveType==="bar"||effectiveType==="line"),sourceDatasetIndex=visualIndex=>this.visualDatasetSourceIndexes?.[visualIndex]??visualIndex,sourceRowIndex=visualIndex=>this.visualRowSourceIndexes?.[visualIndex]??visualIndex,topDatasetIndexByGroup=new Map;if(stackTotalsPossible){const visualDatasetCount=this.visualDatasetSourceIndexes?.length??datasets.length;for(let visualIndex=0;visualIndex<visualDatasetCount;visualIndex+=1){const dataset=datasets[sourceDatasetIndex(visualIndex)],axis=chartDatasetAxis(dataset);if(!this.axisStacked(axis))continue;let byGroup=topDatasetIndexByGroup.get(axis);byGroup||(byGroup=new Map,topDatasetIndexByGroup.set(axis,byGroup)),byGroup.set(chartDatasetStack(dataset),visualIndex)}}const totalsByGroup=new Map,totalsFor=(axis,stack)=>{let byGroup=totalsByGroup.get(axis);byGroup||(byGroup=new Map,totalsByGroup.set(axis,byGroup));let totals=byGroup.get(stack);return totals||(totals=this.computeStackTotals(axis,stack),byGroup.set(stack,totals)),totals},stackTotalsActive=[...topDatasetIndexByGroup.values()].some(byGroup=>byGroup.size>0),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",isolate=text=>text.split(`
|
|
11
11
|
`).map(line=>isolateCanvasText(line,direction)).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes<=0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}projected.length=retainedLength;try{return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total=value.length,count=Math.min(total,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total>count,total,exact:!0}}if(typeof value=="object"&&value!==null){let total=0;for(const key in value)total+=1,entries.length<limit&&entries.push([key,value[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}return{entries,truncated:!1,total:0,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{ref}from"lit/directives/ref.js";import{lyraLocaleCatalogVersion}from"../../../internal/localization-runtime.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{HierarchySourceController,hierarchyField}from"../../../internal/hierarchy-source-controller.js";import{hierarchySourceView}from"../../../internal/hierarchy-source-view.js";import{hierarchySourceStyles}from"../../../internal/hierarchy-source-view.styles.js";const INSPECTION_KINDS=new Set(["object","array","scalar","element","attribute","text","comment","processing-instruction"]);import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText,clipboardFailureReason}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_retry,LYRA_DEFAULT_sourceSearchUnavailable,LYRA_DEFAULT_treeSourceError,LYRA_DEFAULT_treeSourceSummary,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value,maxNodes){const budget={remainingNodes:maxNodes,remainingInspections:maxNodes*2,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}projected.length=retainedLength;try{return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total2=value.length,count=Math.min(total2,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total2>count,total:total2,exact:!0}}const record=value;let total=0;for(const key in record)total+=1,entries.length<limit&&entries.push([key,record[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.sourceMode=!1,this.sourceSearchDirty=!0,this.sourceSearchIntent=0,this.sourceCopyIntent=0,this.sourceNavigationIntent=0,this.sourceSearchTask=Promise.resolve(0),this.sourceHitKeys=new Set,this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.hierarchy=new HierarchySourceController(this,{normalize:(value,key)=>this.normalizeSourceNode(value,key),onChange:()=>this.requestUpdate("sourceState",null),accepted:()=>{},payload:{maxUnits:2e6,maxRowUnits:327702,unitsOf:node=>node.name.length+node.path.length+(node.value?.length??0)+node.kind.length}}),this.maxNodes=5e3,this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.explicitRefresh=0,this.matchElements=new Map,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,expand:LYRA_DEFAULT_expand,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,loading:LYRA_DEFAULT_loading,noData:LYRA_DEFAULT_noData,retry:LYRA_DEFAULT_retry,sourceSearchUnavailable:LYRA_DEFAULT_sourceSearchUnavailable,treeSourceError:LYRA_DEFAULT_treeSourceError,treeSourceSummary:LYRA_DEFAULT_treeSourceSummary,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,hierarchySourceStyles,styles,srOnly]}get treeSource(){return this._treeSource}set treeSource(value){const previous=this._treeSource;this._treeSource=value,this.invalidateSourceSearch(),this.syncSource(!0),this.requestUpdate("treeSource",previous)}revealSourceKey(key){return this.sourceNavigationIntent++,this.treeSource===void 0?Promise.resolve(!1):this.hierarchy.reveal(key)}syncSource(force=!1){if(!this.hierarchy)return;const source=this.treeSource,query=this.query??"",locale=this.effectiveLocale,binding=this.sourceBinding;source===void 0&&!this.sourceMode&&binding?.source===void 0||!force&&binding&&binding.source===source&&binding.query===query&&binding.locale===locale||(this.invalidateSourceSearch(),this.hierarchy.update(source,locale,force,{search:query,hiddenKinds:[]}),source===this.treeSource&&query===(this.query??"")&&locale===this.effectiveLocale&&(this.sourceBinding={source,query,locale}))}normalizeSourceNode(value,key){const name=hierarchyField(value,"name"),path=hierarchyField(value,"path"),kind=hierarchyField(value,"kind"),text=hierarchyField(value,"value");if(typeof name!="string"||name.length>65536||typeof path!="string"||path.length>65536||path!==key||typeof kind!="string"||!INSPECTION_KINDS.has(kind)||text!==void 0&&(typeof text!="string"||text.length>65536))throw new TypeError("Invalid inspection node");return Object.freeze({name,path,kind,...text===void 0?{}:{value:text}})}invalidateSourceSearch(){this.sourceSearchIntent=(this.sourceSearchIntent??0)+1,this.sourceCopyIntent=(this.sourceCopyIntent??0)+1,this.sourceNavigationIntent=(this.sourceNavigationIntent??0)+1,this.sourceHits=void 0,this.sourceHitKeys?.clear(),this.sourceSearchExact=!0,this.sourceSearchUnavailable=!1,this.sourceSearchDirty=!0,this.activeSearchIndex!==void 0&&(this._treeSource!==void 0||this.sourceMode)&&(this.activeSearchIndex=-1),this.copyFeedback!==void 0&&this.clearCopyFeedback()}async searchSource(){this.sourceSearchDirty=!1;const intent=this.sourceSearchIntent,provider=this.treeSource;if(!(this.query??""))return this.hierarchy.cancelSearch(),this.hasUpdated&&this.emitSearchChange(),0;const result=await this.hierarchy.search();return intent!==this.sourceSearchIntent||provider!==this.treeSource||!this.isConnected||result.status==="stale"||result.status==="ready"&&!result.isCurrent()?0:(this.sourceHits=result.status==="ready"?result:void 0,this.sourceHitKeys=new Set(this.sourceHits?.value.hits.map(hit=>hit.key)??[]),this.sourceSearchExact=result.status==="ready"&&result.value.exhaustive,this.sourceSearchUnavailable=result.status!=="ready",this.requestUpdate("sourceSearchResult",null),this.emitSearchChange(),await this.updateComplete,intent===this.sourceSearchIntent?this.sourceHitKeys.size:0)}async stepSourceSearch(direction){const navigation=++this.sourceNavigationIntent,hits=this.sourceHits;if(!hits?.isCurrent()||!hits.value.hits.length)return!1;const size=hits.value.hits.length;this.activeSearchIndex=this.activeSearchIndex<0?direction===1?0:size-1:(this.activeSearchIndex+direction+size)%size;const found=await this.hierarchy.reveal(hits.value.hits[this.activeSearchIndex].key);return!found||navigation!==this.sourceNavigationIntent||!hits.isCurrent()||this.sourceHits!==hits?!1:(this.emitSearchChange(),found)}sourceSummary(){const projection=this.hierarchy.projection;return projection?this.localize("treeSourceSummary",void 0,{visible:getNumberFormat(this.effectiveLocale).format(projection.rows.count),total:getNumberFormat(this.effectiveLocale).format(projection.total)}):""}hasSourceCopy(){const source=this.treeSource;try{const available=typeof source?.copy=="function";return source===this.treeSource&&available}catch{return!1}}async copySource(key,scope){const source=this.treeSource,epoch=this.hierarchy.epoch,owner=this.ownerDocument,intent=++this.sourceCopyIntent,current=()=>this.treeSource===source&&this.hierarchy.epoch===epoch&&this.ownerDocument===owner&&this.isConnected&&intent===this.sourceCopyIntent;this.clearCopyFeedback();const result=await this.hierarchy.copy(key,scope,25*1024*1024);if(!current()||result.status==="stale")return;const feedback=key??"toolbar";if(result.status!=="ready"){this.showCopyFeedback(feedback,!1);const message=this.localize("copyFailed");current()&&this.searchAnnouncementSink?.announce(message);return}const accepted=()=>current()&&result.isCurrent();if(!accepted())return;let outcome;try{const clipboard=owner.defaultView?.navigator.clipboard,write=clipboard?.writeText;if(!accepted())return;typeof write!="function"?outcome=Object.freeze({ok:!1,text:result.value,reason:"unsupported",error:new Error("Clipboard is unavailable")}):(await write.call(clipboard,result.value),outcome=Object.freeze({ok:!0,text:result.value}))}catch(error){outcome=Object.freeze({ok:!1,text:result.value,reason:clipboardFailureReason(error),error})}if(accepted())if(this.showCopyFeedback(feedback,outcome.ok),outcome.ok){const message=this.localize("copied");if(!accepted())return;this.searchAnnouncementSink?.announce(message),accepted()&&this.emit("lr-copy",outcome)}else{const message=this.localize("copyFailed");if(!accepted()||(this.searchAnnouncementSink?.announce(message),!accepted()))return;this.emit("lr-error"),accepted()&&this.emit("lr-copy-error",outcome)}}sourceCopyButton(node){if(!this.copyable||!this.hasSourceCopy())return nothing;const source=this.treeSource,epoch=this.hierarchy.epoch,key=node?.path??null,projection=this.hierarchy.projection,label=node?this.localize("jsonCopyLabel",void 0,{label:node.name}):this.localize("copyJson");return html`<button part="copy-button" type="button" aria-label=${this.copyLabel(key??"toolbar",label)}
|
|
2
2
|
@keydown=${event=>event.stopPropagation()}
|
|
3
3
|
@click=${event=>{event.stopPropagation();const button=event.currentTarget;button.isConnected&&button.getRootNode()===this.renderRoot&&!this.hierarchy.loading&&projection===this.hierarchy.projection&&source===this.treeSource&&epoch===this.hierarchy.epoch&&this.copySource(key,node?node.kind==="object"||node.kind==="array"||node.kind==="element"?"subtree":"node":"document")}}>${this.copyLabel(key??"toolbar",this.localize("copy"))}</button>`}renderSourceNode(node){const match=this.sourceHits?.isCurrent()&&this.sourceHitKeys.has(node.path),active=this.sourceHits?.value.hits[this.activeSearchIndex]?.key===node.path;return html`<span part="key" ?data-match=${match} ?data-active=${active}>${node.name}</span><span aria-hidden="true">:</span><span
|
|
4
4
|
part="value" data-type=${node.kind==="scalar"?"string":node.kind} ?data-match=${match} ?data-active=${active}>${node.value??node.kind}</span>${this.sourceCopyButton(node)}`}renderSource(){const partial=!this.sourceSearchExact&&!!this.query,count=this.sourceHitKeys.size;return html`<div class="source-shell" style=${styleMap({"--lr-json-viewer-max-height":sanitizeCssLength(this.maxHeight)??"var(--lr-size-20rem)"})}>
|
|
@@ -68,7 +68,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
68
68
|
</div>
|
|
69
69
|
`:nothing}
|
|
70
70
|
</div>
|
|
71
|
-
`}willUpdate(changed){super.willUpdate(changed);const wasSource=this.sourceMode;if(this.syncSource(),this.treeSource!==void 0){this.sourceMode||(this.sourceMode=!0,this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.searchState=EMPTY_SEARCH,this.treeMemo=void 0,this.matchElements.clear(),this.expandedOverrides.clear()),this.sourceSearchDirty&&(this.sourceSearchTask=this.searchSource());return}if(this.sourceMode=!1,wasSource&&(this.sourceAnnouncement=void 0,this.invalidateSourceSearch()),wasSource||!this.hasUpdated||changed.has("data")||changed.has("maxNodes")){const snapshot=snapshotJsonData(this.data,this.effectiveMaxNodes);this.dataSnapshot=snapshot.value,this.dataSnapshotTruncated=snapshot.truncated}const locale=this.effectiveLocale;if(wasSource||!this.hasUpdated||changed.has("data")||changed.has("query")||changed.has("maxNodes")||locale!==this.searchLocale){this.searchLocale=locale;const next=this.computeSearch();if(!this.hasUpdated||changed.has("data")||changed.has("maxNodes")){let pruned=null;for(const key of this.expandedOverrides.keys())next.paths.has(key)||(pruned??=new Map(this.expandedOverrides),pruned.delete(key));pruned&&(this.expandedOverrides=pruned)}this.searchState=next,this.hasUpdated&&(this.activeSearchIndex=-1,this.emitSearchChange())}}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const message=this.hierarchy.error||this.hierarchy.rowError?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&this.sourceAnnouncement!==message&&this.searchAnnouncementSink?.announce(message),this.sourceAnnouncement=message;return}this.syncActiveMatch(),this.searchAnnouncementsArmed&&changed.has("activeSearchIndex")&&this.searchAnnouncementSink?.announce(this.activeSearchAnnouncement())}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.query,this.treeSource!==void 0?this.sourceHitKeys.size:this.searchState.orderedMatches.length,this.treeSource!==void 0?this.sourceSearchExact:!this.searchState.truncated,this.activeSearchIndex))}revealActiveMatch(){const match=this.searchState.orderedMatches[this.activeSearchIndex];if(!match)return;
|
|
71
|
+
`}willUpdate(changed){super.willUpdate(changed);const wasSource=this.sourceMode;if(this.syncSource(),this.treeSource!==void 0){this.sourceMode||(this.sourceMode=!0,this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.searchState=EMPTY_SEARCH,this.treeMemo=void 0,this.matchElements.clear(),this.expandedOverrides.clear()),this.sourceSearchDirty&&(this.sourceSearchTask=this.searchSource());return}if(this.sourceMode=!1,wasSource&&(this.sourceAnnouncement=void 0,this.invalidateSourceSearch()),wasSource||!this.hasUpdated||changed.has("data")||changed.has("maxNodes")){const snapshot=snapshotJsonData(this.data,this.effectiveMaxNodes);this.dataSnapshot=snapshot.value,this.dataSnapshotTruncated=snapshot.truncated}const locale=this.effectiveLocale;if(wasSource||!this.hasUpdated||changed.has("data")||changed.has("query")||changed.has("maxNodes")||locale!==this.searchLocale){this.searchLocale=locale;const next=this.computeSearch();if(!this.hasUpdated||changed.has("data")||changed.has("maxNodes")){let pruned=null;for(const key of this.expandedOverrides.keys())next.paths.has(key)||(pruned??=new Map(this.expandedOverrides),pruned.delete(key));pruned&&(this.expandedOverrides=pruned)}this.searchState=next,this.hasUpdated&&(this.activeSearchIndex=-1,this.emitSearchChange())}}updated(changed){if(super.updated(changed),this.treeSource!==void 0){const message=this.hierarchy.error||this.hierarchy.rowError?this.localize("treeSourceError"):this.hierarchy.loading?this.localize("loading"):this.sourceSummary();this.sourceAnnouncement!==void 0&&this.sourceAnnouncement!==message&&this.searchAnnouncementSink?.announce(message),this.sourceAnnouncement=message;return}this.syncActiveMatch(),this.searchAnnouncementsArmed&&changed.has("activeSearchIndex")&&this.searchAnnouncementSink?.announce(this.activeSearchAnnouncement())}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.query,this.treeSource!==void 0?this.sourceHitKeys.size:this.searchState.orderedMatches.length,this.treeSource!==void 0?this.sourceSearchExact:!this.searchState.truncated,this.activeSearchIndex))}revealActiveMatch(){const match=this.searchState.orderedMatches[this.activeSearchIndex];if(!match)return;const path=JSON.parse(match.pathKey);if(!Array.isArray(path))return;let next=null;for(let depth=0;depth<path.length;depth++){const ancestorKey=JSON.stringify(path.slice(0,depth));this.isExpanded(ancestorKey,depth,this.searchState.forceExpand)||(next??=new Map(this.expandedOverrides),next.set(ancestorKey,!0))}next&&(this.expandedOverrides=next)}activeSearchAnnouncement(){const total=this.searchState.orderedMatches.length;if(this.activeSearchIndex<0||total===0)return"";const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("viewerSearchActiveMatch",void 0,{current:numberFormat.format(this.activeSearchIndex+1),total:this.searchState.truncated?`≥${numberFormat.format(total)}`:numberFormat.format(total)})}async runSearch(query){if(this.treeSource!==void 0){const intent=this.sourceSearchIntent;this.query=query,intent===this.sourceSearchIntent&&this.invalidateSourceSearch();const currentIntent=this.sourceSearchIntent;return this.requestUpdate("sourceSearchIntent",null),await this.updateComplete,currentIntent===this.sourceSearchIntent?this.sourceSearchTask:0}return this.query=query,await this.updateComplete,this.searchState.orderedMatches.length}async searchNext(){if(this.treeSource!==void 0)return this.stepSourceSearch(1);const total=this.searchState.orderedMatches.length;return total===0?!1:(this.activeSearchIndex=(this.activeSearchIndex+1)%total,this.revealActiveMatch(),this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0)}async searchPrevious(){if(this.treeSource!==void 0)return this.stepSourceSearch(-1);const total=this.searchState.orderedMatches.length;return total===0?!1:(this.activeSearchIndex=this.activeSearchIndex<0?total-1:(this.activeSearchIndex-1+total)%total,this.revealActiveMatch(),this.emitSearchChange(),await this.scrollActiveMatchIntoView(),!0)}clearSearch(){this.treeSource!==void 0&&(this.hierarchy.cancelSearch(),this.invalidateSourceSearch(),this.requestUpdate("sourceSearchIntent",null)),this.query=""}async scrollActiveMatchIntoView(){await this.updateComplete,this.renderRoot.querySelector("[data-active]")?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"})}render(){if(this.treeSource!==void 0)return this.renderSource();const deps=[this.dataSnapshot,this.searchState,this.expandedOverrides,this.expandDepth,this.copyable,this.copyFeedback,this.strings,this.effectiveLocale,lyraLocaleCatalogVersion(this.effectiveLocale),this.explicitRefresh,this.effectiveMaxNodes];let memo=this.treeMemo;if(!memo||deps.some((value,index)=>value!==memo.deps[index])){const budget={remaining:this.effectiveMaxNodes,truncated:!1};this.matchElements.clear();const tree2=this.renderNode(this.dataSnapshot,[],void 0,0,this.searchState,new WeakSet,budget);memo={deps,tree:tree2,limited:budget.truncated||this.searchState.truncated||this.dataSnapshotTruncated},this.treeMemo=memo}const{tree,limited}=memo;return html`
|
|
72
72
|
<div
|
|
73
73
|
part="base"
|
|
74
74
|
style=${sanitizeCssLength(this.maxHeight)?styleMap({"--lr-json-viewer-max-height":sanitizeCssLength(this.maxHeight)}):nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{guard}from"lit/directives/guard.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{tag}from"../../../internal/prefix.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{setMapCanvasReadyCallback}from"../../../internal/map-canvas-ready.js";import{loadMaplibre}from"../../media/map/map-loader.js";import{styles}from"./geojson-view.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_geojsonViewFeatureCount,LYRA_DEFAULT_geojsonViewInvalid,LYRA_DEFAULT_geojsonViewLabel,LYRA_DEFAULT_geojsonViewMissingMapLibrary,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const GEOMETRY_TYPES=new Set(["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection"]),MAX_GEOJSON_POSITIONS=1e4,MAX_GEOJSON_NODES=5e4,MAX_GEOJSON_DEPTH=64,MAX_GEOJSON_TEXT_UNITS=2*1024*1024,MAX_GEOJSON_SERIALIZED_UNITS=4*1024*1024,GEOJSON_BASE_MAP_STYLE={version:8,sources:{},layers:[]};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function assertGeoJsonSerializedSize(root){let units=0;const stringUnits=text=>{let length=2;for(let index=0;index<text.length;index++){const code=text.charCodeAt(index);code>=55296&&code<=56319&&text.charCodeAt(index+1)>=56320&&text.charCodeAt(index+1)<=57343?(length+=2,index++):length+=code>=55296&&code<=57343?6:code<32?[8,9,10,12,13].includes(code)?2:6:code===34||code===92?2:1}return length},tasks=[{value:root,depth:0}];for(;tasks.length;){const{value,depth}=tasks.pop();if(value===null)units+=4;else if(typeof value=="string")units+=stringUnits(value);else if(typeof value!="object")units+=String(value).length;else{const entries=Array.isArray(value)?value.map(entry=>[void 0,entry]):Object.entries(value);units+=2,entries.length&&(units+=entries.length*(2*(depth+1)+2)+2*depth);for(const[key,entry]of entries)key!==void 0&&(units+=stringUnits(key)+2),tasks.push({value:entry,depth:depth+1})}if(units>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.")}}function assertGeoJsonGraphWithinLimits(root){const tasks=[{value:root,depth:0}],seen=new WeakSet;let graphUnits=0,textUnits=0;const accountGraphUnit=()=>{if(graphUnits++,graphUnits+tasks.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.")},accountText=value=>{if(textUnits+=value.length,textUnits>MAX_GEOJSON_TEXT_UNITS)throw new LyraResourceLimitError("The GeoJSON contains too much text.")};for(;tasks.length>0;){const task=tasks.pop();if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");accountGraphUnit();const value=task.value;if(typeof value=="string"){accountText(value);continue}if(!(value===null||typeof value=="boolean")){if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("invalid JSON number");continue}if(typeof value!="object")throw new Error("invalid JSON value");if(seen.has(value))throw new Error("cyclic JSON graph");if(seen.add(value),Array.isArray(value)){if(graphUnits+tasks.length+value.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=value.length-1;index>=0;index--)tasks.push({value:value[index],depth:task.depth+1});continue}for(const key in value)Object.hasOwn(value,key)&&(accountGraphUnit(),accountText(key),tasks.push({value:value[key],depth:task.depth+1}))}}}function analyzeGeoJson(value){if(assertGeoJsonGraphWithinLimits(value),!isRecord(value))throw new Error("not a GeoJSON object");const root=value,tasks=[{kind:"geo",value,depth:0,mode:"any"}];let processedNodes=0,positionCount=0,bounds=null;const pushTask=task=>{if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(processedNodes+tasks.length>=MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");tasks.push(task)},pushArray=(items,kind,depth)=>{if(processedNodes+tasks.length+items.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=items.length-1;index>=0;index--)pushTask({kind,value:items[index],depth})},requireArray=(candidate,minimum=0)=>{if(!Array.isArray(candidate)||candidate.length<minimum)throw new Error("invalid GeoJSON coordinates");return candidate};for(;tasks.length>0;){const task=tasks.pop();if(processedNodes++,processedNodes>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(task.kind==="position"){const position=requireArray(task.value,2);if(!position.every(coordinate=>typeof coordinate=="number"&&Number.isFinite(coordinate)))throw new Error("invalid GeoJSON position");const[lng,lat]=position;if(lng<-180||lng>180||lat<-90||lat>90)throw new Error("invalid GeoJSON position");if(positionCount++,positionCount>MAX_GEOJSON_POSITIONS)throw new LyraResourceLimitError("The GeoJSON contains too many positions.");const shiftedLng=lng<0?lng+360:lng;bounds?(bounds.minLng=Math.min(bounds.minLng,lng),bounds.maxLng=Math.max(bounds.maxLng,lng),bounds.minShiftedLng=Math.min(bounds.minShiftedLng,shiftedLng),bounds.maxShiftedLng=Math.max(bounds.maxShiftedLng,shiftedLng),bounds.minLat=Math.min(bounds.minLat,lat),bounds.maxLat=Math.max(bounds.maxLat,lat)):bounds={minLng:lng,maxLng:lng,minShiftedLng:shiftedLng,maxShiftedLng:shiftedLng,minLat:lat,maxLat:lat};continue}if(task.kind==="positions"||task.kind==="line"||task.kind==="ring"){const minimum=task.kind==="ring"?4:task.kind==="line"?2:0,positions=requireArray(task.value,minimum);if(task.kind==="ring"){const first=positions[0],last=positions[positions.length-1];if(!Array.isArray(first)||!Array.isArray(last)||first.length!==last.length||first.some((item,index)=>item!==last[index]))throw new Error("GeoJSON polygon rings must be closed")}pushArray(positions,"position",task.depth+1);continue}if(task.kind==="polygon"||task.kind==="multi-line"){const parts=requireArray(task.value);pushArray(parts,task.kind==="polygon"?"ring":"line",task.depth+1);continue}if(task.kind==="multi-polygon"){pushArray(requireArray(task.value),"polygon",task.depth+1);continue}if(task.kind!=="geo")throw new Error("invalid GeoJSON coordinate structure");if(!isRecord(task.value)||typeof task.value.type!="string")throw new Error("invalid GeoJSON member");const member=task.value,type=member.type;if(task.mode==="feature"&&type!=="Feature")throw new Error("FeatureCollection contains a non-Feature");if(task.mode==="geometry"&&!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON geometry");if(type==="Feature"){if(task.mode==="geometry"||!Object.hasOwn(member,"geometry")||!Object.hasOwn(member,"properties"))throw new Error("invalid GeoJSON Feature");if(member.properties!==null&&!isRecord(member.properties))throw new Error("invalid GeoJSON Feature properties");member.geometry!==null&&pushTask({kind:"geo",value:member.geometry,depth:task.depth+1,mode:"geometry"});continue}if(type==="FeatureCollection"){if(task.mode!=="any"||!Array.isArray(member.features))throw new Error("invalid GeoJSON FeatureCollection");for(let index=member.features.length-1;index>=0;index--)pushTask({kind:"geo",value:member.features[index],depth:task.depth+1,mode:"feature"});continue}if(!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON type");if(type==="GeometryCollection"){if(!Array.isArray(member.geometries))throw new Error("invalid GeoJSON GeometryCollection");for(let index=member.geometries.length-1;index>=0;index--)pushTask({kind:"geo",value:member.geometries[index],depth:task.depth+1,mode:"geometry"});continue}if(!Object.hasOwn(member,"coordinates"))throw new Error("GeoJSON geometry has no coordinates");pushTask({kind:{Point:"position",LineString:"line",Polygon:"polygon",MultiPoint:"positions",MultiLineString:"multi-line",MultiPolygon:"multi-polygon"}[type],value:member.coordinates,depth:task.depth+1})}const count=root.type==="FeatureCollection"&&Array.isArray(root.features)?root.features.length:1;assertGeoJsonSerializedSize(root);const metadata=JSON.stringify(root,null,2);if(metadata.length>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.");return{value:root,metadata,featureCount:count,bounds}}const FIT_PADDING=24,MAX_FIT_ZOOM=18;function crossesAntimeridian(bounds){return bounds.maxShiftedLng-bounds.minShiftedLng<bounds.maxLng-bounds.minLng-1e-9}function fitBboxToView(bounds){const crosses=crossesAntimeridian(bounds);let centerLng=crosses?(bounds.minShiftedLng+bounds.maxShiftedLng)/2:(bounds.minLng+bounds.maxLng)/2;centerLng>180&&(centerLng-=360);const center=[centerLng,(bounds.minLat+bounds.maxLat)/2],lngSpan=Math.max(crosses?bounds.maxShiftedLng-bounds.minShiftedLng:bounds.maxLng-bounds.minLng,1e-4),latSpan=Math.max(bounds.maxLat-bounds.minLat,1e-4),span=Math.max(lngSpan,latSpan*2)*1.4,zoom=Math.max(0,Math.min(MAX_FIT_ZOOM,Math.floor(Math.log2(360/span))));return{center,zoom}}class LyraGeoJsonViewerBase extends LyraElement{}class LyraGeoJsonViewer extends TextViewerTarget(LyraGeoJsonViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.mapReady?this.mapCanvas:this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this.maxHeight="",this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.pendingFitBounds=null,this.generation=0,this.lastLoadSrc="",this.registeredMap=null,this.announcements=new ViewerAnnouncementController(this),this.forceMissingMaplibreForTesting=!1}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,geojsonViewFeatureCount:LYRA_DEFAULT_geojsonViewFeatureCount,geojsonViewInvalid:LYRA_DEFAULT_geojsonViewInvalid,geojsonViewLabel:LYRA_DEFAULT_geojsonViewLabel,geojsonViewMissingMapLibrary:LYRA_DEFAULT_geojsonViewMissingMapLibrary,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}textContentRoot(){return this.renderRoot.querySelector('[part="base"]')}stopChildEvent(event){event.stopPropagation()}onMapCanvasReady(map,canvas){if(!this.isConnected||map!==this.registeredMap||this.shadowRoot?.querySelector(tag("map"))!==map||this.loadState.kind!=="loaded"||!this.loadState.peerAvailable||this.src!==this.lastLoadSrc)return;this.mapReady=!0,this.mapCanvas=canvas;const base=this.shadowRoot?.querySelector('[part="base"]');base?.removeAttribute("role"),base?.removeAttribute("aria-label"),this.hostDescription.refresh()}syncMapCanvasReadyCallback(){const next=this.shadowRoot?.querySelector(tag("map"));next!==this.registeredMap&&(this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=next,next&&setMapCanvasReadyCallback(next,canvas=>this.onMapCanvasReady(next,canvas)))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.loadState.kind!=="loaded"&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=null,this.loadState.kind!=="loaded"&&(this.loadState={kind:"idle"}),this.mapReady=!1,this.mapCanvas=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}updated(changed){if(super.updated(changed),this.loadState.kind==="loaded"){const peerAvailable=this.loadState.peerAvailable;this.announcements.transition("load",peerAvailable?"loaded":"error",peerAvailable?this.featureCountStatus(this.loadState.featureCount):this.localize("geojsonViewMissingMapLibrary"),peerAvailable?"polite":"assertive")}else this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument"));this.syncMapCanvasReadyCallback(),this.fitLoadedData(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}fitLoadedData(){const bounds=this.pendingFitBounds,map=this.registeredMap;if(!bounds||!map||this.loadState.kind!=="loaded")return;this.pendingFitBounds=null;const crosses=crossesAntimeridian(bounds),west=crosses?bounds.minShiftedLng:bounds.minLng,east=crosses?bounds.maxShiftedLng:bounds.maxLng,fit=()=>{map.fitBounds([[west,bounds.minLat],[east,bounds.maxLat]],{padding:FIT_PADDING,maxZoom:MAX_FIT_ZOOM,animate:!1})};typeof map.fitBounds=="function"?fit():customElements.whenDefined(map.localName).then(fit)}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,this.mapReady=!1,this.mapCanvas=null,!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response,MAX_GEOJSON_SERIALIZED_UNITS);if(!this.isConnected||generation!==this.generation)return;const parsed=JSON.parse(text),analysis=analyzeGeoJson(parsed),{center,zoom}=analysis.bounds?fitBboxToView(analysis.bounds):{center:[0,0],zoom:1};this.pendingFitBounds=analysis.bounds??null;const maplibre=this.forceMissingMaplibreForTesting?null:await loadMaplibre();if(!this.isConnected||generation!==this.generation||!maplibre&&(await import("../../utility/json-viewer/json-viewer.js"),!this.isConnected||generation!==this.generation))return;this.loadState={kind:"loaded",value:analysis.value,metadata:analysis.metadata,featureCount:analysis.featureCount,center,zoom,peerAvailable:maplibre!==null,dataLayers:Object.freeze([{sourceId:"lr-geojson",geojson:analysis.value}])},maplibre||this.emit("lr-render-error",{error:new LyraUserFacingError(this.localize("geojsonViewMissingMapLibrary"))})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"geojsonViewInvalid")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.loadState={kind:"error",message},this.emit("lr-render-error",{error})}get effectiveLabel(){return hostAriaLabel(this)??(this.name?.trim()?this.name:this.localize("geojsonViewLabel"))}featureCountStatus(featureCount){return this.localize("geojsonViewFeatureCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(featureCount),pluralCount:featureCount})}renderBody(){switch(this.loadState.kind){case"loaded":{const{value,metadata,featureCount,center,zoom,peerAvailable}=this.loadState,statusText=this.featureCountStatus(featureCount);if(!peerAvailable)return html`
|
|
1
|
+
import{__decorate}from"tslib";import{guard}from"lit/directives/guard.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{tag}from"../../../internal/prefix.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{setMapCanvasReadyCallback}from"../../../internal/map-canvas-ready.js";import{loadMaplibre}from"../../media/map/map-loader.js";import{styles}from"./geojson-view.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_geojsonViewFeatureCount,LYRA_DEFAULT_geojsonViewInvalid,LYRA_DEFAULT_geojsonViewLabel,LYRA_DEFAULT_geojsonViewMissingMapLibrary,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const GEOMETRY_TYPES=new Set(["Point","LineString","Polygon","MultiPoint","MultiLineString","MultiPolygon","GeometryCollection"]),MAX_GEOJSON_POSITIONS=1e4,MAX_GEOJSON_NODES=5e4,MAX_GEOJSON_DEPTH=64,MAX_GEOJSON_TEXT_UNITS=2*1024*1024,MAX_GEOJSON_SERIALIZED_UNITS=4*1024*1024,GEOJSON_BASE_MAP_STYLE={version:8,sources:{},layers:[]};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function assertGeoJsonSerializedSize(root){let units=0;const stringUnits=text=>{let length=2;for(let index=0;index<text.length;index++){const code=text.charCodeAt(index);code>=55296&&code<=56319&&text.charCodeAt(index+1)>=56320&&text.charCodeAt(index+1)<=57343?(length+=2,index++):length+=code>=55296&&code<=57343?6:code<32?[8,9,10,12,13].includes(code)?2:6:code===34||code===92?2:1}return length},tasks=[{value:root,depth:0}];for(;tasks.length;){const{value,depth}=tasks.pop();if(value===null)units+=4;else if(typeof value=="string")units+=stringUnits(value);else if(typeof value!="object")units+=String(value).length;else{const entries=Array.isArray(value)?value.map(entry=>[void 0,entry]):Object.entries(value);units+=2,entries.length&&(units+=entries.length*(2*(depth+1)+2)+2*depth);for(const[key,entry]of entries)key!==void 0&&(units+=stringUnits(key)+2),tasks.push({value:entry,depth:depth+1})}if(units>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.")}}function assertGeoJsonGraphWithinLimits(root){const tasks=[{value:root,depth:0}],seen=new WeakSet;let graphUnits=0,textUnits=0;const accountGraphUnit=()=>{if(graphUnits++,graphUnits+tasks.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.")},accountText=value=>{if(textUnits+=value.length,textUnits>MAX_GEOJSON_TEXT_UNITS)throw new LyraResourceLimitError("The GeoJSON contains too much text.")};for(;tasks.length>0;){const task=tasks.pop();if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");accountGraphUnit();const value=task.value;if(typeof value=="string"){accountText(value);continue}if(!(value===null||typeof value=="boolean")){if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("invalid JSON number");continue}if(typeof value!="object")throw new Error("invalid JSON value");if(seen.has(value))throw new Error("cyclic JSON graph");if(seen.add(value),Array.isArray(value)){if(graphUnits+tasks.length+value.length>MAX_GEOJSON_NODES)throw new LyraResourceLimitError("The GeoJSON contains too many nested values.");for(let index=value.length-1;index>=0;index--)tasks.push({value:value[index],depth:task.depth+1});continue}for(const key in value)Object.hasOwn(value,key)&&(accountGraphUnit(),accountText(key),tasks.push({value:value[key],depth:task.depth+1}))}}}function analyzeGeoJson(value){if(assertGeoJsonGraphWithinLimits(value),!isRecord(value))throw new Error("not a GeoJSON object");const root=value,tasks=[{kind:"geo",value,depth:0,mode:"any"}];let positionCount=0,bounds=null;const pushTask=task=>{if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");tasks.push(task)},pushArray=(items,kind,depth)=>{for(let index=items.length-1;index>=0;index--)pushTask({kind,value:items[index],depth})},requireArray=(candidate,minimum=0)=>{if(!Array.isArray(candidate)||candidate.length<minimum)throw new Error("invalid GeoJSON coordinates");return candidate};for(;tasks.length>0;){const task=tasks.pop();if(task.depth>MAX_GEOJSON_DEPTH)throw new LyraResourceLimitError("The GeoJSON nesting is too deep.");if(task.kind==="position"){const position=requireArray(task.value,2);if(!position.every(coordinate=>typeof coordinate=="number"&&Number.isFinite(coordinate)))throw new Error("invalid GeoJSON position");const[lng,lat]=position;if(lng<-180||lng>180||lat<-90||lat>90)throw new Error("invalid GeoJSON position");if(positionCount++,positionCount>MAX_GEOJSON_POSITIONS)throw new LyraResourceLimitError("The GeoJSON contains too many positions.");const shiftedLng=lng<0?lng+360:lng;bounds?(bounds.minLng=Math.min(bounds.minLng,lng),bounds.maxLng=Math.max(bounds.maxLng,lng),bounds.minShiftedLng=Math.min(bounds.minShiftedLng,shiftedLng),bounds.maxShiftedLng=Math.max(bounds.maxShiftedLng,shiftedLng),bounds.minLat=Math.min(bounds.minLat,lat),bounds.maxLat=Math.max(bounds.maxLat,lat)):bounds={minLng:lng,maxLng:lng,minShiftedLng:shiftedLng,maxShiftedLng:shiftedLng,minLat:lat,maxLat:lat};continue}if(task.kind==="positions"||task.kind==="line"||task.kind==="ring"){const minimum=task.kind==="ring"?4:task.kind==="line"?2:0,positions=requireArray(task.value,minimum);if(task.kind==="ring"){const first=positions[0],last=positions[positions.length-1];if(!Array.isArray(first)||!Array.isArray(last)||first.length!==last.length||first.some((item,index)=>item!==last[index]))throw new Error("GeoJSON polygon rings must be closed")}pushArray(positions,"position",task.depth+1);continue}if(task.kind==="polygon"||task.kind==="multi-line"){const parts=requireArray(task.value);pushArray(parts,task.kind==="polygon"?"ring":"line",task.depth+1);continue}if(task.kind==="multi-polygon"){pushArray(requireArray(task.value),"polygon",task.depth+1);continue}if(task.kind!=="geo")throw new Error("invalid GeoJSON coordinate structure");if(!isRecord(task.value)||typeof task.value.type!="string")throw new Error("invalid GeoJSON member");const member=task.value,type=member.type;if(task.mode==="feature"&&type!=="Feature")throw new Error("FeatureCollection contains a non-Feature");if(task.mode==="geometry"&&!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON geometry");if(type==="Feature"){if(task.mode==="geometry"||!Object.hasOwn(member,"geometry")||!Object.hasOwn(member,"properties"))throw new Error("invalid GeoJSON Feature");if(member.properties!==null&&!isRecord(member.properties))throw new Error("invalid GeoJSON Feature properties");member.geometry!==null&&pushTask({kind:"geo",value:member.geometry,depth:task.depth+1,mode:"geometry"});continue}if(type==="FeatureCollection"){if(task.mode!=="any"||!Array.isArray(member.features))throw new Error("invalid GeoJSON FeatureCollection");for(let index=member.features.length-1;index>=0;index--)pushTask({kind:"geo",value:member.features[index],depth:task.depth+1,mode:"feature"});continue}if(!GEOMETRY_TYPES.has(type))throw new Error("invalid GeoJSON type");if(type==="GeometryCollection"){if(!Array.isArray(member.geometries))throw new Error("invalid GeoJSON GeometryCollection");for(let index=member.geometries.length-1;index>=0;index--)pushTask({kind:"geo",value:member.geometries[index],depth:task.depth+1,mode:"geometry"});continue}if(!Object.hasOwn(member,"coordinates"))throw new Error("GeoJSON geometry has no coordinates");pushTask({kind:{Point:"position",LineString:"line",Polygon:"polygon",MultiPoint:"positions",MultiLineString:"multi-line",MultiPolygon:"multi-polygon"}[type],value:member.coordinates,depth:task.depth+1})}const count=root.type==="FeatureCollection"&&Array.isArray(root.features)?root.features.length:1;assertGeoJsonSerializedSize(root);const metadata=JSON.stringify(root,null,2);if(metadata.length>MAX_GEOJSON_SERIALIZED_UNITS)throw new LyraResourceLimitError("The serialized GeoJSON is too large.");return{value:root,metadata,featureCount:count,bounds}}const FIT_PADDING=24,MAX_FIT_ZOOM=18;function crossesAntimeridian(bounds){return bounds.maxShiftedLng-bounds.minShiftedLng<bounds.maxLng-bounds.minLng-1e-9}function fitBboxToView(bounds){const crosses=crossesAntimeridian(bounds);let centerLng=crosses?(bounds.minShiftedLng+bounds.maxShiftedLng)/2:(bounds.minLng+bounds.maxLng)/2;centerLng>180&&(centerLng-=360);const center=[centerLng,(bounds.minLat+bounds.maxLat)/2],lngSpan=Math.max(crosses?bounds.maxShiftedLng-bounds.minShiftedLng:bounds.maxLng-bounds.minLng,1e-4),latSpan=Math.max(bounds.maxLat-bounds.minLat,1e-4),span=Math.max(lngSpan,latSpan*2)*1.4,zoom=Math.max(0,Math.min(MAX_FIT_ZOOM,Math.floor(Math.log2(360/span))));return{center,zoom}}class LyraGeoJsonViewerBase extends LyraElement{}class LyraGeoJsonViewer extends TextViewerTarget(LyraGeoJsonViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.mapReady?this.mapCanvas:this.renderRoot.querySelector('[part="base"][role="region"]')),this.src="",this.name="",this.maxHeight="",this.loadState={kind:"idle"},this.mapReady=!1,this.mapCanvas=null,this.pendingFitBounds=null,this.generation=0,this.lastLoadSrc="",this.registeredMap=null,this.announcements=new ViewerAnnouncementController(this),this.forceMissingMaplibreForTesting=!1}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,geojsonViewFeatureCount:LYRA_DEFAULT_geojsonViewFeatureCount,geojsonViewInvalid:LYRA_DEFAULT_geojsonViewInvalid,geojsonViewLabel:LYRA_DEFAULT_geojsonViewLabel,geojsonViewMissingMapLibrary:LYRA_DEFAULT_geojsonViewMissingMapLibrary,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,srOnly]}textContentRoot(){return this.renderRoot.querySelector('[part="base"]')}stopChildEvent(event){event.stopPropagation()}onMapCanvasReady(map,canvas){if(!this.isConnected||map!==this.registeredMap||this.shadowRoot?.querySelector(tag("map"))!==map||this.loadState.kind!=="loaded"||!this.loadState.peerAvailable||this.src!==this.lastLoadSrc)return;this.mapReady=!0,this.mapCanvas=canvas;const base=this.shadowRoot?.querySelector('[part="base"]');base?.removeAttribute("role"),base?.removeAttribute("aria-label"),this.hostDescription.refresh()}syncMapCanvasReadyCallback(){const next=this.shadowRoot?.querySelector(tag("map"));next!==this.registeredMap&&(this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=next,next&&setMapCanvasReadyCallback(next,canvas=>this.onMapCanvasReady(next,canvas)))}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.loadState.kind!=="loaded"&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.registeredMap&&setMapCanvasReadyCallback(this.registeredMap,null),this.registeredMap=null,this.loadState.kind!=="loaded"&&(this.loadState={kind:"idle"}),this.mapReady=!1,this.mapCanvas=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}updated(changed){if(super.updated(changed),this.loadState.kind==="loaded"){const peerAvailable=this.loadState.peerAvailable;this.announcements.transition("load",peerAvailable?"loaded":"error",peerAvailable?this.featureCountStatus(this.loadState.featureCount):this.localize("geojsonViewMissingMapLibrary"),peerAvailable?"polite":"assertive")}else this.announcements.transition("load",this.loadState.kind,this.loadState.kind==="error"?this.loadState.message:this.localize("loadingDocument"));this.syncMapCanvasReadyCallback(),this.fitLoadedData(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}fitLoadedData(){const bounds=this.pendingFitBounds,map=this.registeredMap;if(!bounds||!map||this.loadState.kind!=="loaded")return;this.pendingFitBounds=null;const crosses=crossesAntimeridian(bounds),west=crosses?bounds.minShiftedLng:bounds.minLng,east=crosses?bounds.maxShiftedLng:bounds.maxLng,fit=()=>{map.fitBounds([[west,bounds.minLat],[east,bounds.maxLat]],{padding:FIT_PADDING,maxZoom:MAX_FIT_ZOOM,animate:!1})};typeof map.fitBounds=="function"?fit():customElements.whenDefined(map.localName).then(fit)}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,this.mapReady=!1,this.mapCanvas=null,!this.src){this.loadState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.loadState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const text=await readResponseText(response,MAX_GEOJSON_SERIALIZED_UNITS);if(!this.isConnected||generation!==this.generation)return;const parsed=JSON.parse(text),analysis=analyzeGeoJson(parsed),{center,zoom}=analysis.bounds?fitBboxToView(analysis.bounds):{center:[0,0],zoom:1};this.pendingFitBounds=analysis.bounds??null;const maplibre=this.forceMissingMaplibreForTesting?null:await loadMaplibre();if(!this.isConnected||generation!==this.generation||!maplibre&&(await import("../../utility/json-viewer/json-viewer.js"),!this.isConnected||generation!==this.generation))return;this.loadState={kind:"loaded",value:analysis.value,metadata:analysis.metadata,featureCount:analysis.featureCount,center,zoom,peerAvailable:maplibre!==null,dataLayers:Object.freeze([{sourceId:"lr-geojson",geojson:analysis.value}])},maplibre||this.emit("lr-render-error",{error:new LyraUserFacingError(this.localize("geojsonViewMissingMapLibrary"))})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.loadState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"geojsonViewInvalid")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.loadState={kind:"error",message},this.emit("lr-render-error",{error})}get effectiveLabel(){return hostAriaLabel(this)??(this.name?.trim()?this.name:this.localize("geojsonViewLabel"))}featureCountStatus(featureCount){return this.localize("geojsonViewFeatureCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(featureCount),pluralCount:featureCount})}renderBody(){switch(this.loadState.kind){case"loaded":{const{value,metadata,featureCount,center,zoom,peerAvailable}=this.loadState,statusText=this.featureCountStatus(featureCount);if(!peerAvailable)return html`
|
|
2
2
|
<p part="missing-library">
|
|
3
3
|
${this.localize("geojsonViewMissingMapLibrary")}
|
|
4
4
|
</p>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getActiveNativeModal,getNativeModalMountTarget,isInNativeModalContext,SHARED_LIVE_REGION_ATTRIBUTE}from"./native-modal-context.js";import{finiteDuration}from"./numbers.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";const DEFAULT_THROTTLE_MS=500,ambientTimerHost={setTimeout:(handler,timeout)=>globalThis.setTimeout(handler,timeout),clearTimeout:handle=>globalThis.clearTimeout(handle)};class Announcer{constructor(options){this._throttleMs=DEFAULT_THROTTLE_MS,this.throttleMs=options.throttleMs??DEFAULT_THROTTLE_MS,this.onFlush=options.onFlush,this.timerHost=options.timerHost??ambientTimerHost}get throttleMs(){return this._throttleMs}set throttleMs(value){this._throttleMs=finiteDuration(value,DEFAULT_THROTTLE_MS)}get pendingText(){return this.pending}get isPending(){return this.timer!==void 0}announce(text,options={}){if(this.pending=text,options.force){this.flush();return}this.timer??=this.timerHost.setTimeout(()=>this.flush(),this.throttleMs)}setTimerHost(timerHost){timerHost!==this.timerHost&&(this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0),this.timerHost=timerHost,this.pending!==void 0&&(this.timer=this.timerHost.setTimeout(()=>this.flush(),this.throttleMs)))}cancel(){this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0),this.pending=void 0}flush(){this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0);const text=this.pending;this.pending=void 0,text!==void 0&&this.onFlush(text)}}class AnnouncementSinkController{constructor(host,options={}){this.host=host,this.options=options,this.sinks=new Map,this.states=new Map,options.register!==!1&&host.addController?.(this)}hostConnected(){this.connect()}hostDisconnected(){this.disconnect()}connect(){this.states.clear(),this.syncSinks();for(const politeness of this.eagerChannels())this.sink(politeness)}disconnect(){this.releaseSinks(),this.states.clear()}adopted(){this.syncSinks()}transition(channel,state,message="",politeness){const fingerprint=`${state}\0${message}`,previous=this.states.get(channel);if(this.states.set(channel,fingerprint),previous===void 0||previous===fingerprint)return;const resolved=politeness??(state==="loading"?"polite":state==="error"?"assertive":void 0);resolved&&this.announce(message,resolved)}announce(message,politeness="polite"){!message||!this.host.isConnected||(this.syncSinks(),this.sink(politeness).announce(message))}announcePolite(message){this.announce(message,"polite")}announceAssertive(message){this.announce(message,"assertive")}current(politeness){if(this.host.isConnected)return this.syncSinks(),this.sink(politeness)}releaseChannel(politeness){this.sinks.get(politeness)?.release(),this.sinks.delete(politeness)}setExclusiveChannel(politeness){this.exclusiveChannel!==politeness&&(this.exclusiveChannel=politeness,this.releaseSinks(),politeness&&this.host.isConnected&&this.sink(politeness))}eagerChannels(){return this.exclusiveChannel?[this.exclusiveChannel]:this.options.eager??[]}sink(politeness){let sink=this.sinks.get(politeness);return sink||(sink=acquireAnnouncementSink(politeness,{document:this.host.ownerDocument,source:this.host}),this.sinks.set(politeness,sink)),sink}syncSinks(){if(!this.host.isConnected){this.releaseSinks();return}for(const sink of this.sinks.values())if(sink.element.ownerDocument!==this.host.ownerDocument){this.releaseSinks();for(const politeness of this.eagerChannels())this.sink(politeness);break}}releaseSinks(){for(const sink of this.sinks.values())sink.release();this.sinks.clear()}}const ANNOUNCEMENT_SINK_ATTRIBUTE=SHARED_LIVE_REGION_ATTRIBUTE,DEFAULT_MESSAGE_TTL_MS=5e3,MAX_PENDING_MESSAGES_PER_HANDLE=32,MAX_PENDING_MESSAGES_PER_SINK=128,SINK_HIDDEN_CSS_TEXT="position:absolute;inset-block-start:0;inset-inline-start:0;width:1px;height:1px;padding:0;margin:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0;",sinksByParent=new WeakMap;function removePendingAnnouncement(record,pending){record.pending.delete(pending.element),pending.owner.delete(pending.element),pending.element.remove()}function scheduleSinkSweep(record){let earliest=Number.POSITIVE_INFINITY;for(const pending of record.pending.values())earliest=Math.min(earliest,pending.deadline);if(!Number.isFinite(earliest)){record.sweepTimer!==void 0&&(record.timerHost.clearTimeout(record.sweepTimer),record.sweepTimer=void 0,record.sweepDeadline=void 0);return}if(record.sweepTimer!==void 0&&record.sweepDeadline!==void 0&&record.sweepDeadline<=earliest)return;record.sweepTimer!==void 0&&record.timerHost.clearTimeout(record.sweepTimer),record.sweepDeadline=earliest;const scheduledDeadline=earliest;record.sweepTimer=record.timerHost.setTimeout(()=>{record.sweepTimer=void 0,record.sweepDeadline=void 0;for(const pending of[...record.pending.values()])pending.deadline<=scheduledDeadline&&removePendingAnnouncement(record,pending);scheduleSinkSweep(record)},Math.max(0,earliest-Date.now()))}function mountSink(record){record.element.parentNode!==record.parent&&record.parent.appendChild(record.element)}function sinkRecord(doc,politeness,parent){let byPoliteness=sinksByParent.get(parent);byPoliteness||(byPoliteness=new Map,sinksByParent.set(parent,byPoliteness));const existing=byPoliteness.get(politeness);if(existing)return mountSink(existing),existing;const element=doc.createElement("div");element.setAttribute(ANNOUNCEMENT_SINK_ATTRIBUTE,politeness),element.setAttribute("role",politeness==="assertive"?"alert":"status"),element.setAttribute("aria-live",politeness),element.setAttribute("aria-atomic","false"),element.setAttribute("aria-relevant","additions"),element.style.cssText=SINK_HIDDEN_CSS_TEXT;const ownerWindow=doc.defaultView,record={parent,element,refs:0,timerHost:ownerWindow?{setTimeout:(handler,timeout)=>ownerWindow.setTimeout(handler,timeout),clearTimeout:handle=>ownerWindow.clearTimeout(handle)}:ambientTimerHost,pending:new Map};return mountSink(record),byPoliteness.set(politeness,record),record}const inertSink=politeness=>({element:void 0,politeness,messageTtlMs:DEFAULT_MESSAGE_TTL_MS,announce:()=>{},release:()=>{}});function acquireAnnouncementSink(politeness,options={}){const doc=options.document??(typeof document>"u"?void 0:document);if(!doc)return inertSink(politeness);let record=sinkRecord(doc,politeness,(()=>{const modal=getActiveNativeModal(doc);return modal?getNativeModalMountTarget(modal):doc.body??doc.documentElement})());record.refs+=1;const ownMessages=new Set;let released=!1,deferredTimer,deferredMessages=[];const releaseRecord=()=>{for(const message of[...ownMessages]){const pending=record.pending.get(message);pending
|
|
1
|
+
import{getActiveNativeModal,getNativeModalMountTarget,isInNativeModalContext,SHARED_LIVE_REGION_ATTRIBUTE}from"./native-modal-context.js";import{finiteDuration}from"./numbers.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";const DEFAULT_THROTTLE_MS=500,ambientTimerHost={setTimeout:(handler,timeout)=>globalThis.setTimeout(handler,timeout),clearTimeout:handle=>globalThis.clearTimeout(handle)};class Announcer{constructor(options){this._throttleMs=DEFAULT_THROTTLE_MS,this.throttleMs=options.throttleMs??DEFAULT_THROTTLE_MS,this.onFlush=options.onFlush,this.timerHost=options.timerHost??ambientTimerHost}get throttleMs(){return this._throttleMs}set throttleMs(value){this._throttleMs=finiteDuration(value,DEFAULT_THROTTLE_MS)}get pendingText(){return this.pending}get isPending(){return this.timer!==void 0}announce(text,options={}){if(this.pending=text,options.force){this.flush();return}this.timer??=this.timerHost.setTimeout(()=>this.flush(),this.throttleMs)}setTimerHost(timerHost){timerHost!==this.timerHost&&(this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0),this.timerHost=timerHost,this.pending!==void 0&&(this.timer=this.timerHost.setTimeout(()=>this.flush(),this.throttleMs)))}cancel(){this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0),this.pending=void 0}flush(){this.timer!==void 0&&(this.timerHost.clearTimeout(this.timer),this.timer=void 0);const text=this.pending;this.pending=void 0,text!==void 0&&this.onFlush(text)}}class AnnouncementSinkController{constructor(host,options={}){this.host=host,this.options=options,this.sinks=new Map,this.states=new Map,options.register!==!1&&host.addController?.(this)}hostConnected(){this.connect()}hostDisconnected(){this.disconnect()}connect(){this.states.clear(),this.syncSinks();for(const politeness of this.eagerChannels())this.sink(politeness)}disconnect(){this.releaseSinks(),this.states.clear()}adopted(){this.syncSinks()}transition(channel,state,message="",politeness){const fingerprint=`${state}\0${message}`,previous=this.states.get(channel);if(this.states.set(channel,fingerprint),previous===void 0||previous===fingerprint)return;const resolved=politeness??(state==="loading"?"polite":state==="error"?"assertive":void 0);resolved&&this.announce(message,resolved)}announce(message,politeness="polite"){!message||!this.host.isConnected||(this.syncSinks(),this.sink(politeness).announce(message))}announcePolite(message){this.announce(message,"polite")}announceAssertive(message){this.announce(message,"assertive")}current(politeness){if(this.host.isConnected)return this.syncSinks(),this.sink(politeness)}releaseChannel(politeness){this.sinks.get(politeness)?.release(),this.sinks.delete(politeness)}setExclusiveChannel(politeness){this.exclusiveChannel!==politeness&&(this.exclusiveChannel=politeness,this.releaseSinks(),politeness&&this.host.isConnected&&this.sink(politeness))}eagerChannels(){return this.exclusiveChannel?[this.exclusiveChannel]:this.options.eager??[]}sink(politeness){let sink=this.sinks.get(politeness);return sink||(sink=acquireAnnouncementSink(politeness,{document:this.host.ownerDocument,source:this.host}),this.sinks.set(politeness,sink)),sink}syncSinks(){if(!this.host.isConnected){this.releaseSinks();return}for(const sink of this.sinks.values())if(sink.element.ownerDocument!==this.host.ownerDocument){this.releaseSinks();for(const politeness of this.eagerChannels())this.sink(politeness);break}}releaseSinks(){for(const sink of this.sinks.values())sink.release();this.sinks.clear()}}const ANNOUNCEMENT_SINK_ATTRIBUTE=SHARED_LIVE_REGION_ATTRIBUTE,DEFAULT_MESSAGE_TTL_MS=5e3,MAX_PENDING_MESSAGES_PER_HANDLE=32,MAX_PENDING_MESSAGES_PER_SINK=128,SINK_HIDDEN_CSS_TEXT="position:absolute;inset-block-start:0;inset-inline-start:0;width:1px;height:1px;padding:0;margin:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0;",sinksByParent=new WeakMap;function removePendingAnnouncement(record,pending){record.pending.delete(pending.element),pending.owner.delete(pending.element),pending.element.remove()}function scheduleSinkSweep(record){let earliest=Number.POSITIVE_INFINITY;for(const pending of record.pending.values())earliest=Math.min(earliest,pending.deadline);if(!Number.isFinite(earliest)){record.sweepTimer!==void 0&&(record.timerHost.clearTimeout(record.sweepTimer),record.sweepTimer=void 0,record.sweepDeadline=void 0);return}if(record.sweepTimer!==void 0&&record.sweepDeadline!==void 0&&record.sweepDeadline<=earliest)return;record.sweepTimer!==void 0&&record.timerHost.clearTimeout(record.sweepTimer),record.sweepDeadline=earliest;const scheduledDeadline=earliest;record.sweepTimer=record.timerHost.setTimeout(()=>{record.sweepTimer=void 0,record.sweepDeadline=void 0;for(const pending of[...record.pending.values()])pending.deadline<=scheduledDeadline&&removePendingAnnouncement(record,pending);scheduleSinkSweep(record)},Math.max(0,earliest-Date.now()))}function mountSink(record){record.element.parentNode!==record.parent&&record.parent.appendChild(record.element)}function sinkRecord(doc,politeness,parent){let byPoliteness=sinksByParent.get(parent);byPoliteness||(byPoliteness=new Map,sinksByParent.set(parent,byPoliteness));const existing=byPoliteness.get(politeness);if(existing)return mountSink(existing),existing;const element=doc.createElement("div");element.setAttribute(ANNOUNCEMENT_SINK_ATTRIBUTE,politeness),element.setAttribute("role",politeness==="assertive"?"alert":"status"),element.setAttribute("aria-live",politeness),element.setAttribute("aria-atomic","false"),element.setAttribute("aria-relevant","additions"),element.style.cssText=SINK_HIDDEN_CSS_TEXT;const ownerWindow=doc.defaultView,record={parent,element,refs:0,timerHost:ownerWindow?{setTimeout:(handler,timeout)=>ownerWindow.setTimeout(handler,timeout),clearTimeout:handle=>ownerWindow.clearTimeout(handle)}:ambientTimerHost,pending:new Map};return mountSink(record),byPoliteness.set(politeness,record),record}const inertSink=politeness=>({element:void 0,politeness,messageTtlMs:DEFAULT_MESSAGE_TTL_MS,announce:()=>{},release:()=>{}});function acquireAnnouncementSink(politeness,options={}){const doc=options.document??(typeof document>"u"?void 0:document);if(!doc)return inertSink(politeness);let record=sinkRecord(doc,politeness,(()=>{const modal=getActiveNativeModal(doc);return modal?getNativeModalMountTarget(modal):doc.body??doc.documentElement})());record.refs+=1;const ownMessages=new Set;let released=!1,deferredTimer,deferredMessages=[];const releaseRecord=()=>{for(const message of[...ownMessages]){const pending=record.pending.get(message);pending&&removePendingAnnouncement(record,pending)}if(scheduleSinkSweep(record),record.refs-=1,record.refs>0)return;record.pending.clear(),record.element.remove();const byPoliteness=sinksByParent.get(record.parent);byPoliteness?.get(politeness)===record&&byPoliteness.delete(politeness)},sink={get element(){return record.element},politeness,messageTtlMs:finiteDuration(options.messageTtlMs??DEFAULT_MESSAGE_TTL_MS,DEFAULT_MESSAGE_TTL_MS),announce(text){if(released||text===""||options.source&&(options.source.ownerDocument!==doc||!isAccessibilityVisible(options.source)))return;const modal=getActiveNativeModal(doc);if(modal&&options.source&&!isInNativeModalContext(options.source,modal))return;const parent=modal?getNativeModalMountTarget(modal):doc.body??doc.documentElement;if(record.parent!==parent&&(releaseRecord(),record=sinkRecord(doc,politeness,parent),record.refs+=1,deferredMessages=[],deferredTimer!==void 0&&record.timerHost.clearTimeout(deferredTimer),deferredTimer=record.timerHost.setTimeout(()=>{deferredTimer=void 0;const messages=deferredMessages;deferredMessages=[];for(const message2 of messages)sink.announce(message2)},0)),deferredTimer!==void 0){deferredMessages.push(text),deferredMessages.length>MAX_PENDING_MESSAGES_PER_HANDLE&&deferredMessages.shift();return}mountSink(record);const message=doc.createElement("div");message.textContent=text,record.element.appendChild(message);const ttl=finiteDuration(sink.messageTtlMs,DEFAULT_MESSAGE_TTL_MS),pending={element:message,owner:ownMessages,deadline:Date.now()+ttl};for(ownMessages.add(message),record.pending.set(message,pending);ownMessages.size>MAX_PENDING_MESSAGES_PER_HANDLE;){const oldest=ownMessages.values().next().value;if(!oldest)break;const entry=record.pending.get(oldest);entry&&removePendingAnnouncement(record,entry)}for(;record.pending.size>MAX_PENDING_MESSAGES_PER_SINK;){const oldest=record.pending.values().next().value;if(!oldest)break;removePendingAnnouncement(record,oldest)}scheduleSinkSweep(record)},release(){released||(released=!0,deferredTimer!==void 0&&record.timerHost.clearTimeout(deferredTimer),deferredTimer=void 0,deferredMessages=[],releaseRecord())}};return sink}export{ANNOUNCEMENT_SINK_ATTRIBUTE,AnnouncementSinkController,Announcer,acquireAnnouncementSink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LitElement}from"lit";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor,isPlainDataRecord as isRealmNeutralPlainRecord,readOwnArrayLength}from"./data-descriptors.js";import{devWarnOnce}from"./dev-warning.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_WORK_LIMIT=PUBLIC_COLLECTION_NODE_LIMIT*2,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value"),EXHAUSTED_COLLECTION_VALUE=Symbol("exhausted-public-collection-value"),normalizedCollectionWrites=new WeakMap,readonlySnapshotWrappers=new WeakMap;function writeNormalizedOwnedCollection(host,property,write){let active=normalizedCollectionWrites.get(host);active||normalizedCollectionWrites.set(host,active=new Set);const alreadyActive=active.has(property);active.add(property);try{write()}finally{alreadyActive||active.delete(property),active.size===0&&normalizedCollectionWrites.delete(host)}}function isCollectionSnapshotFailure(value){return value===OMIT_COLLECTION_VALUE||value===EXHAUSTED_COLLECTION_VALUE}function boundedSnapshotLimit(value,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0?Math.min(value,maximum):maximum}function recordRootLoss(budget,kept,source,retained){retained<source&&(budget.rootLoss=Object.freeze({kept,retained,source}),budget.truncated=!0)}function consumeSnapshotWork(budget){return budget.remainingWork<=0?!1:(budget.remainingWork-=1,!0)}function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){try{return ArrayBuffer.isView(value)}catch{return!1}}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){const wrapper=readonlySnapshotWrappers.get(value);if(wrapper?.kind==="date")return wrapper.time;try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return readonlySnapshotWrappers.set(snapshot,{kind:"date",time}),rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(!isCollectionSnapshotFailure(result))return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,result}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)yield key}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(null);rememberSnapshot(budget,value,output);try{for(const key of keys){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.invalid=!0);continue}if(budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;budget.remaining-=1;const disposition=budget.recordKey?.(key,descriptor.value,depth)??"copy";if(disposition==="omit"){budget.invalid=!0;continue}const entry=disposition==="preserve"||preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value));if(isCollectionSnapshotFailure(entry))return entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:budget.truncated=!0,entry;output[key]=entry}}catch{return OMIT_COLLECTION_VALUE}return Object.setPrototypeOf(output,prototype),Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>budget.depthLimit||budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;if(isArrayValue(value)){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value);if(sourceLength===void 0)return budget.invalid=!0,allowPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;if(!allowPrefixTruncation&&sourceLength>budget.entryLimit)return EXHAUSTED_COLLECTION_VALUE;const length=Math.min(sourceLength,budget.entryLimit),newest=depth===0&&allowPrefixTruncation&&budget.retention==="newest",output=new budget.realm.Array;Object.setPrototypeOf(output,null),rememberSnapshot(budget,value,output);const kept=[];let walked=0,dropped=0;for(;walked<length;walked+=1){if(budget.remaining<=0||!consumeSnapshotWork(budget)){if(!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}const index=newest?sourceLength-1-walked:walked,descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value))));if(entry===OMIT_COLLECTION_VALUE){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}if(entry===EXHAUSTED_COLLECTION_VALUE){if(budget.truncated=!0,!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}kept.push(index,entry)}output.length=walked;const offset=newest?sourceLength-walked:0;for(let index=0;index<kept.length;index+=2)output[kept[index]-offset]=kept[index+1];return Object.setPrototypeOf(output,budget.realm.Array.prototype),walked-dropped<sourceLength&&(budget.truncated=!0),allowPrefixTruncation&&depth===0&&recordRootLoss(budget,newest?"newest":"oldest",sourceLength,walked-dropped),Object.freeze(output)}if(!readonlySnapshotWrappers.has(value)&&isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth,allowPrefixTruncation);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth,allowPrefixTruncation);if(isNativeArrayBufferView(value))return budget.invalid=!0,OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:(budget.invalid=!0,OMIT_COLLECTION_VALUE)}function boundedRecordSize(value,limit=PUBLIC_COLLECTION_WORK_LIMIT){let size=0;try{for(const key in value)if(typeof key=="string"&&(size+=1),size>=limit)break}catch{return}return size}function snapshotPublicCollection(value,view,options={}){if(value===null||typeof value!="object"&&typeof value!="function")return options.onResult?.(Object.freeze({invalid:!1,truncated:!1})),value;const realm=snapshotRealm(view),nodeLimit=boundedSnapshotLimit(options.limits?.nodes,PUBLIC_COLLECTION_NODE_LIMIT),budget={remaining:nodeLimit,remainingWork:nodeLimit*2,seen:new WeakMap,additions:[],realm,entryLimit:boundedSnapshotLimit(options.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT),depthLimit:boundedSnapshotLimit(options.limits?.depth,PUBLIC_COLLECTION_DEPTH_LIMIT),nestedArrayPrefix:options.nestedArrayPrefix??!1,recordKey:options.recordKey,invalid:!1,truncated:!1,retention:options.retain??"oldest"},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(!isCollectionSnapshotFailure(snapshot))return budget.rootLoss&&options.onTruncate?.(budget.rootLoss),options.onResult?.(Object.freeze({invalid:budget.invalid,truncated:budget.truncated})),snapshot;if(options.onResult?.(Object.freeze({invalid:budget.invalid||snapshot===OMIT_COLLECTION_VALUE,truncated:budget.truncated||snapshot===EXHAUSTED_COLLECTION_VALUE})),isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const size=boundedRecordSize(value,nodeLimit*2);size&&options.onTruncate?.(Object.freeze({kept:"oldest",retained:0,source:size}));const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Map.prototype.entries.call(wrapper?.kind==="map"?wrapper.backing:value)}catch{return}}function nativeSetValues(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Set.prototype.values.call(wrapper?.kind==="set"?wrapper.backing:value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"map",backing}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"set",backing}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Map;for(let count=0;count<entryLimit;count+=1){const next=entries.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.set(next.value[0],next.value[1])}return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Set;for(let count=0;count<entryLimit;count+=1){const next=values.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.add(next.value)}return readonlySetFacade(backing,realm)}function nativeCollectionSize(source,kind){const wrapper=readonlySnapshotWrappers.get(source);try{const size=Object.getOwnPropertyDescriptor(kind==="map"?Map.prototype:Set.prototype,"size")?.get?.call(wrapper?.kind===kind?wrapper.backing:source);return typeof size=="number"?size:void 0}catch{return}}function recordNativeCollectionLoss(budget,source,kind,retained){const size=nativeCollectionSize(source,kind);size!==void 0&&recordRootLoss(budget,"oldest",size,retained)}function snapshotDetachedMap(source,entries,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"map",backing.size):(nativeCollectionSize(source,"map")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=entries.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(isCollectionSnapshotFailure(key))return key;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return isCollectionSnapshotFailure(entry)?entry:[key,entry]});if(pair===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;pair===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.set(pair[0],pair[1])}return settle()}function snapshotDetachedSet(source,values,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"set",backing.size):(nativeCollectionSize(source,"set")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=values.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));if(entry===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.add(entry)}return settle()}function snapshotIdentityCollection(value,view,budget,root){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value)??0,length=Math.min(sourceLength,boundedSnapshotLimit(root?.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT)),kept=root?.retain??"oldest",offset=kept==="newest"?sourceLength-length:0,output=new realm.Array(length);Object.setPrototypeOf(output,null),budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,String(offset+index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||(output[index]=descriptor.value)}return Object.setPrototypeOf(output,realm.Array.prototype),length<sourceLength&&root?.onTruncate?.(Object.freeze({kept,retained:length,source:sourceLength})),Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"map",output.size)),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"set",output.size)),output}return emptyRealmArray(realm)}function reportIdentityCollectionLoss(root,source,kind,retained){if(!root?.onTruncate)return;const size=nativeCollectionSize(source,kind);size!==void 0&&retained<size&&root.onTruncate(Object.freeze({kept:"oldest",retained,source:size}))}function snapshotEventDetail(value,view,preserveRootKeys=new Set,preserveCollectionItemKeys=new Set){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,remainingWork:PUBLIC_COLLECTION_WORK_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view),entryLimit:PUBLIC_COLLECTION_ENTRY_LIMIT,depthLimit:PUBLIC_COLLECTION_DEPTH_LIMIT,nestedArrayPrefix:!1,invalid:!1,truncated:!1},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return isCollectionSnapshotFailure(snapshot)?null:snapshot}function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}function lyraClassChain(ctor){const constructors=[];let current=ctor;for(;typeof current=="function"&¤t!==LitElement;)constructors.push(current),current=Object.getPrototypeOf(current);return constructors}const collectionPolicyByConstructor=new WeakMap;function collectionPropertyPolicy(ctor,name){let policies=collectionPolicyByConstructor.get(ctor);policies||(policies=new Map,collectionPolicyByConstructor.set(ctor,policies));const cached=policies.get(name);if(cached)return cached;let limits,owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1,retainsNewest=!1,immutableSource=!1;for(const constructor of lyraClassChain(ctor)){const declared=constructor;!limits&&Object.hasOwn(constructor,"ownedCollectionLimits")&&declared.ownedCollectionLimits&&Object.hasOwn(declared.ownedCollectionLimits,name)&&(limits=declared.ownedCollectionLimits[name]),Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"immutableSourceCollectionProperties")&&declared.immutableSourceCollectionProperties.includes(name)&&(immutableSource=!0),Object.prototype.hasOwnProperty.call(constructor,"appendOrderedCollectionProperties")&&declared.appendOrderedCollectionProperties.includes(name)&&(retainsNewest=!0)}const policy=Object.freeze({limits,owns,preservesItemIdentity,preservesObjectIdentity,retainsNewest,immutableSource});return policies.set(name,policy),policy}const COLLECTION_ENROLLMENT_FIELDS=["ownedCollectionProperties","identityCollectionProperties","identityCollectionObjectProperties","appendOrderedCollectionProperties","immutableSourceCollectionProperties"];function enrolledCollectionPropertyNames(ctor){const names=new Set;for(const constructor of lyraClassChain(ctor))for(const field of COLLECTION_ENROLLMENT_FIELDS){if(!Object.prototype.hasOwnProperty.call(constructor,field))continue;const declared=constructor;for(const name of declared[field])names.add(name)}return names}function inheritedPropertyDescriptor(prototype,name){let current=prototype;for(;current;){const descriptor=Object.getOwnPropertyDescriptor(current,name);if(descriptor)return descriptor;current=Object.getPrototypeOf(current)}}const installedOwnershipBoundaries=new WeakSet,ownershipBoundarySetters=new WeakMap;function samePolicy(a,b){return a.limits===b.limits&&a.owns===b.owns&&a.preservesItemIdentity===b.preservesItemIdentity&&a.preservesObjectIdentity===b.preservesObjectIdentity&&a.retainsNewest===b.retainsNewest&&a.immutableSource===b.immutableSource}function installOwnedCollectionAccessors(ctor){if(installedOwnershipBoundaries.has(ctor))return;installedOwnershipBoundaries.add(ctor);const prototype=ctor.prototype;for(const name of enrolledCollectionPropertyNames(ctor)){const policy=collectionPropertyPolicy(ctor,name);if(!policy.owns)continue;const declaration=ctor.elementProperties.get(name);if(!declaration||declaration.noAccessor)continue;const descriptor=inheritedPropertyDescriptor(prototype,name),inheritedSet=descriptor?.set;if(!inheritedSet)continue;const installed=ownershipBoundarySetters.get(inheritedSet);if(installed&&samePolicy(installed.policy,policy))continue;const originalSet=installed?.originalSet??inheritedSet,lastAssignments=new WeakMap,set=function(value){const previous=lastAssignments.get(this);if(previous&&declaration.hasChanged===void 0&&(!policy.preservesItemIdentity||policy.immutableSource)&&!policy.preservesObjectIdentity&&(("primitive"in previous.source?Object.is(value,previous.source.primitive):value!==void 0&&Object.is(value,previous.source.deref()))||Object.is(value,previous.retained)))return;const retainedLoss=previous&&!policy.preservesObjectIdentity&&Object.is(value,previous.retained)?publicCollectionTruncation(this,name):void 0,ownerView=this.ownerDocument?.defaultView;let truncation;const options={limits:policy.limits,retain:policy.retainsNewest?"newest":"oldest",onTruncate:report=>{truncation=report}},snapshot=policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView,void 0,options):snapshotPublicCollection(value,ownerView,options);if(retainedLoss){const retained=truncation?.retained??(policy.preservesItemIdentity?isArrayValue(snapshot)?readOwnArrayLength(snapshot):snapshot!==null&&typeof snapshot=="object"?nativeCollectionSize(snapshot,"map")??nativeCollectionSize(snapshot,"set"):void 0:void 0)??retainedLoss.retained;truncation=Object.freeze({kept:truncation?.kept??retainedLoss.kept,retained,source:retainedLoss.source})}recordCollectionTruncation(this,name,truncation),originalSet.call(this,snapshot);const source=normalizedCollectionWrites.get(this)?.has(name)&&previous?previous.source:typeof value=="object"&&value!==null||typeof value=="function"?new WeakRef(value):{primitive:value};lastAssignments.set(this,{source,retained:descriptor.get?.call(this)??snapshot})};ownershipBoundarySetters.set(set,{policy,originalSet}),Object.defineProperty(prototype,name,{...descriptor,set})}}const collectionTruncations=new WeakMap;function collectionTruncationWarningKey(tagName,property){return`lyra-collection-truncated:${tagName}:${String(property)}`}function recordCollectionTruncation(host,name,truncation){let byName=collectionTruncations.get(host);if(!truncation){byName?.delete(name);return}byName||(byName=new Map,collectionTruncations.set(host,byName)),byName.set(name,truncation);const tagName=host.localName,property=String(name);devWarnOnce(collectionTruncationWarningKey(tagName,property),`<${tagName}>: '${property}' kept ${truncation.retained} of ${truncation.source} entries, the ${truncation.kept}; an assignment keeps at most ${PUBLIC_COLLECTION_ENTRY_LIMIT} per array and ${PUBLIC_COLLECTION_NODE_LIMIT} values, and drops values it cannot copy.`)}function publicCollectionTruncation(host,property){return collectionTruncations.get(host)?.get(property)}function snapshotEnrolledEventDetail(host,name,detail){let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const candidate of trustedLyraConstructorChain(host)){const constructor=candidate;if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}return snapshotsDetail?snapshotEventDetail(detail,host.ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail}function declaresOwnedCollections(ctor){for(const constructor of lyraClassChain(ctor)){if(!Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties"))continue;if(constructor.ownedCollectionProperties.length>0)return!0}return!1}const collectionSupport=/* @__PURE__ */Object.freeze({installProperties:installOwnedCollectionAccessors,snapshotEvent:snapshotEnrolledEventDetail}),eventCollectionSupport=/* @__PURE__ */Object.freeze({installProperties(ctor){declaresOwnedCollections(ctor)&&devWarnOnce(`lyra-event-collection-support:${ctor.name}`,`${ctor.name} enrolls ownedCollectionProperties but declares eventCollectionSupport; declare collectionSupport so those properties cross the immutable collection boundary.`)},snapshotEvent:snapshotEnrolledEventDetail});export{collectionSupport,collectionTruncationWarningKey,eventCollectionSupport,publicCollectionTruncation,snapshotEventDetail,snapshotPublicCollection,writeNormalizedOwnedCollection};
|
|
1
|
+
import{LitElement}from"lit";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor,isPlainDataRecord as isRealmNeutralPlainRecord,readOwnArrayLength}from"./data-descriptors.js";import{devWarnOnce}from"./dev-warning.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_WORK_LIMIT=PUBLIC_COLLECTION_NODE_LIMIT*2,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value"),EXHAUSTED_COLLECTION_VALUE=Symbol("exhausted-public-collection-value"),normalizedCollectionWrites=new WeakMap,readonlySnapshotWrappers=new WeakMap;function writeNormalizedOwnedCollection(host,property,write){let active=normalizedCollectionWrites.get(host);active||normalizedCollectionWrites.set(host,active=new Set);const alreadyActive=active.has(property);active.add(property);try{write()}finally{alreadyActive||active.delete(property),active.size===0&&normalizedCollectionWrites.delete(host)}}function isCollectionSnapshotFailure(value){return value===OMIT_COLLECTION_VALUE||value===EXHAUSTED_COLLECTION_VALUE}function boundedSnapshotLimit(value,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0?Math.min(value,maximum):maximum}function recordRootLoss(budget,kept,source,retained){retained<source&&(budget.rootLoss=Object.freeze({kept,retained,source}),budget.truncated=!0)}function consumeSnapshotWork(budget){return budget.remainingWork<=0?!1:(budget.remainingWork-=1,!0)}function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){return ArrayBuffer.isView(value)}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){const wrapper=readonlySnapshotWrappers.get(value);if(wrapper?.kind==="date")return wrapper.time;try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return readonlySnapshotWrappers.set(snapshot,{kind:"date",time}),rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(!isCollectionSnapshotFailure(result))return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,result}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)yield key}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(null);rememberSnapshot(budget,value,output);try{for(const key of keys){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.invalid=!0);continue}if(budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;budget.remaining-=1;const disposition=budget.recordKey?.(key,descriptor.value,depth)??"copy";if(disposition==="omit"){budget.invalid=!0;continue}const entry=disposition==="preserve"||preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value));if(isCollectionSnapshotFailure(entry))return entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:budget.truncated=!0,entry;output[key]=entry}}catch{return OMIT_COLLECTION_VALUE}return Object.setPrototypeOf(output,prototype),Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>budget.depthLimit||budget.remaining<=0)return EXHAUSTED_COLLECTION_VALUE;if(isArrayValue(value)){if(!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value);if(sourceLength===void 0)return budget.invalid=!0,allowPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;if(!allowPrefixTruncation&&sourceLength>budget.entryLimit)return EXHAUSTED_COLLECTION_VALUE;const length=Math.min(sourceLength,budget.entryLimit),newest=depth===0&&allowPrefixTruncation&&budget.retention==="newest",output=new budget.realm.Array;Object.setPrototypeOf(output,null),rememberSnapshot(budget,value,output);const kept=[];let walked=0,dropped=0;for(;walked<length;walked+=1){if(budget.remaining<=0||!consumeSnapshotWork(budget)){if(!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}const index=newest?sourceLength-1-walked:walked,descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1,void 0,void 0,budget.nestedArrayPrefix&&isArrayValue(descriptor.value))));if(entry===OMIT_COLLECTION_VALUE){if(budget.invalid=!0,!allowPrefixTruncation)return OMIT_COLLECTION_VALUE;dropped+=1;continue}if(entry===EXHAUSTED_COLLECTION_VALUE){if(budget.truncated=!0,!allowPrefixTruncation)return EXHAUSTED_COLLECTION_VALUE;break}kept.push(index,entry)}output.length=walked;const offset=newest?sourceLength-walked:0;for(let index=0;index<kept.length;index+=2)output[kept[index]-offset]=kept[index+1];return Object.setPrototypeOf(output,budget.realm.Array.prototype),walked-dropped<sourceLength&&(budget.truncated=!0),allowPrefixTruncation&&depth===0&&recordRootLoss(budget,newest?"newest":"oldest",sourceLength,walked-dropped),Object.freeze(output)}if(!readonlySnapshotWrappers.has(value)&&isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth,allowPrefixTruncation);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth,allowPrefixTruncation);if(isNativeArrayBufferView(value))return budget.invalid=!0,OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:(budget.invalid=!0,OMIT_COLLECTION_VALUE)}function boundedRecordSize(value,limit=PUBLIC_COLLECTION_WORK_LIMIT){let size=0;try{for(const key in value)if(typeof key=="string"&&(size+=1),size>=limit)break}catch{return}return size}function snapshotPublicCollection(value,view,options={}){if(value===null||typeof value!="object"&&typeof value!="function")return options.onResult?.(Object.freeze({invalid:!1,truncated:!1})),value;const realm=snapshotRealm(view),nodeLimit=boundedSnapshotLimit(options.limits?.nodes,PUBLIC_COLLECTION_NODE_LIMIT),budget={remaining:nodeLimit,remainingWork:nodeLimit*2,seen:new WeakMap,additions:[],realm,entryLimit:boundedSnapshotLimit(options.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT),depthLimit:boundedSnapshotLimit(options.limits?.depth,PUBLIC_COLLECTION_DEPTH_LIMIT),nestedArrayPrefix:options.nestedArrayPrefix??!1,recordKey:options.recordKey,invalid:!1,truncated:!1,retention:options.retain??"oldest"},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(!isCollectionSnapshotFailure(snapshot))return budget.rootLoss&&options.onTruncate?.(budget.rootLoss),options.onResult?.(Object.freeze({invalid:budget.invalid,truncated:budget.truncated})),snapshot;if(options.onResult?.(Object.freeze({invalid:budget.invalid||snapshot===OMIT_COLLECTION_VALUE,truncated:budget.truncated||snapshot===EXHAUSTED_COLLECTION_VALUE})),isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const size=boundedRecordSize(value,nodeLimit*2);size&&options.onTruncate?.(Object.freeze({kept:"oldest",retained:0,source:size}));const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Map.prototype.entries.call(wrapper?.kind==="map"?wrapper.backing:value)}catch{return}}function nativeSetValues(value){const wrapper=readonlySnapshotWrappers.get(value);try{return Set.prototype.values.call(wrapper?.kind==="set"?wrapper.backing:value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"map",backing}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),readonlySnapshotWrappers.set(facade,{kind:"set",backing}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Map;for(let count=0;count<entryLimit;count+=1){const next=entries.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.set(next.value[0],next.value[1])}return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm(),budget,entryLimit=budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT){const backing=new realm.Set;for(let count=0;count<entryLimit;count+=1){const next=values.next();if(next.done)break;if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;backing.add(next.value)}return readonlySetFacade(backing,realm)}function nativeCollectionSize(source,kind){const wrapper=readonlySnapshotWrappers.get(source);try{const size=Object.getOwnPropertyDescriptor(kind==="map"?Map.prototype:Set.prototype,"size")?.get?.call(wrapper?.kind===kind?wrapper.backing:source);return typeof size=="number"?size:void 0}catch{return}}function recordNativeCollectionLoss(budget,source,kind,retained){const size=nativeCollectionSize(source,kind);size!==void 0&&recordRootLoss(budget,"oldest",size,retained)}function snapshotDetachedMap(source,entries,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"map",backing.size):(nativeCollectionSize(source,"map")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=entries.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(isCollectionSnapshotFailure(key))return key;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return isCollectionSnapshotFailure(entry)?entry:[key,entry]});if(pair===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;pair===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.set(pair[0],pair[1])}return settle()}function snapshotDetachedSet(source,values,budget,depth,allowPrefixTruncation){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);const settle=()=>(allowPrefixTruncation?recordNativeCollectionLoss(budget,source,"set",backing.size):(nativeCollectionSize(source,"set")??0)>budget.entryLimit&&(budget.truncated=!0),facade);for(let count=0;count<budget.entryLimit;count+=1){let next;try{next=values.next()}catch{break}if(next.done)break;if(budget.remaining<=0||!consumeSnapshotWork(budget))return allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));if(entry===EXHAUSTED_COLLECTION_VALUE)return budget.truncated=!0,allowPrefixTruncation?settle():EXHAUSTED_COLLECTION_VALUE;entry===OMIT_COLLECTION_VALUE?budget.invalid=!0:backing.add(entry)}return settle()}function snapshotIdentityCollection(value,view,budget,root){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const sourceLength=readOwnArrayLength(value)??0,length=Math.min(sourceLength,boundedSnapshotLimit(root?.limits?.entries,PUBLIC_COLLECTION_ENTRY_LIMIT)),kept=root?.retain??"oldest",offset=kept==="newest"?sourceLength-length:0,output=new realm.Array(length);Object.setPrototypeOf(output,null),budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget&&!consumeSnapshotWork(budget))return EXHAUSTED_COLLECTION_VALUE;const descriptor=getOwnDataDescriptor(value,String(offset+index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||(output[index]=descriptor.value)}return Object.setPrototypeOf(output,realm.Array.prototype),length<sourceLength&&root?.onTruncate?.(Object.freeze({kept,retained:length,source:sourceLength})),Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"map",output.size)),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm,budget,boundedSnapshotLimit(root?.limits?.entries,budget?.entryLimit??PUBLIC_COLLECTION_ENTRY_LIMIT));return output===EXHAUSTED_COLLECTION_VALUE||(budget&&rememberSnapshot(budget,value,output),reportIdentityCollectionLoss(root,value,"set",output.size)),output}return emptyRealmArray(realm)}function reportIdentityCollectionLoss(root,source,kind,retained){if(!root?.onTruncate)return;const size=nativeCollectionSize(source,kind);size!==void 0&&retained<size&&root.onTruncate(Object.freeze({kept:"oldest",retained,source:size}))}function snapshotEventDetail(value,view,preserveRootKeys=new Set,preserveCollectionItemKeys=new Set){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,remainingWork:PUBLIC_COLLECTION_WORK_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view),entryLimit:PUBLIC_COLLECTION_ENTRY_LIMIT,depthLimit:PUBLIC_COLLECTION_DEPTH_LIMIT,nestedArrayPrefix:!1,invalid:!1,truncated:!1},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return isCollectionSnapshotFailure(snapshot)?null:snapshot}function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}function lyraClassChain(ctor){const constructors=[];let current=ctor;for(;typeof current=="function"&¤t!==LitElement;)constructors.push(current),current=Object.getPrototypeOf(current);return constructors}const collectionPolicyByConstructor=new WeakMap;function collectionPropertyPolicy(ctor,name){let policies=collectionPolicyByConstructor.get(ctor);policies||(policies=new Map,collectionPolicyByConstructor.set(ctor,policies));const cached=policies.get(name);if(cached)return cached;let limits,owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1,retainsNewest=!1,immutableSource=!1;for(const constructor of lyraClassChain(ctor)){const declared=constructor;!limits&&Object.hasOwn(constructor,"ownedCollectionLimits")&&declared.ownedCollectionLimits&&Object.hasOwn(declared.ownedCollectionLimits,name)&&(limits=declared.ownedCollectionLimits[name]),Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"immutableSourceCollectionProperties")&&declared.immutableSourceCollectionProperties.includes(name)&&(immutableSource=!0),Object.prototype.hasOwnProperty.call(constructor,"appendOrderedCollectionProperties")&&declared.appendOrderedCollectionProperties.includes(name)&&(retainsNewest=!0)}const policy=Object.freeze({limits,owns,preservesItemIdentity,preservesObjectIdentity,retainsNewest,immutableSource});return policies.set(name,policy),policy}const COLLECTION_ENROLLMENT_FIELDS=["ownedCollectionProperties","identityCollectionProperties","identityCollectionObjectProperties","appendOrderedCollectionProperties","immutableSourceCollectionProperties"];function enrolledCollectionPropertyNames(ctor){const names=new Set;for(const constructor of lyraClassChain(ctor))for(const field of COLLECTION_ENROLLMENT_FIELDS){if(!Object.prototype.hasOwnProperty.call(constructor,field))continue;const declared=constructor;for(const name of declared[field])names.add(name)}return names}function inheritedPropertyDescriptor(prototype,name){let current=prototype;for(;current;){const descriptor=Object.getOwnPropertyDescriptor(current,name);if(descriptor)return descriptor;current=Object.getPrototypeOf(current)}}const installedOwnershipBoundaries=new WeakSet,ownershipBoundarySetters=new WeakMap;function samePolicy(a,b){return a.limits===b.limits&&a.owns===b.owns&&a.preservesItemIdentity===b.preservesItemIdentity&&a.preservesObjectIdentity===b.preservesObjectIdentity&&a.retainsNewest===b.retainsNewest&&a.immutableSource===b.immutableSource}function installOwnedCollectionAccessors(ctor){if(installedOwnershipBoundaries.has(ctor))return;installedOwnershipBoundaries.add(ctor);const prototype=ctor.prototype;for(const name of enrolledCollectionPropertyNames(ctor)){const policy=collectionPropertyPolicy(ctor,name);if(!policy.owns)continue;const declaration=ctor.elementProperties.get(name);if(!declaration||declaration.noAccessor)continue;const descriptor=inheritedPropertyDescriptor(prototype,name),inheritedSet=descriptor?.set;if(!inheritedSet)continue;const installed=ownershipBoundarySetters.get(inheritedSet);if(installed&&samePolicy(installed.policy,policy))continue;const originalSet=installed?.originalSet??inheritedSet,lastAssignments=new WeakMap,set=function(value){const previous=lastAssignments.get(this);if(previous&&declaration.hasChanged===void 0&&(!policy.preservesItemIdentity||policy.immutableSource)&&!policy.preservesObjectIdentity&&(("primitive"in previous.source?Object.is(value,previous.source.primitive):value!==void 0&&Object.is(value,previous.source.deref()))||Object.is(value,previous.retained)))return;const retainedLoss=previous&&!policy.preservesObjectIdentity&&Object.is(value,previous.retained)?publicCollectionTruncation(this,name):void 0,ownerView=this.ownerDocument?.defaultView;let truncation;const options={limits:policy.limits,retain:policy.retainsNewest?"newest":"oldest",onTruncate:report=>{truncation=report}},snapshot=policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView,void 0,options):snapshotPublicCollection(value,ownerView,options);if(retainedLoss){const retained=truncation?.retained??(policy.preservesItemIdentity?isArrayValue(snapshot)?readOwnArrayLength(snapshot):snapshot!==null&&typeof snapshot=="object"?nativeCollectionSize(snapshot,"map")??nativeCollectionSize(snapshot,"set"):void 0:void 0)??retainedLoss.retained;truncation=Object.freeze({kept:truncation?.kept??retainedLoss.kept,retained,source:retainedLoss.source})}recordCollectionTruncation(this,name,truncation),originalSet.call(this,snapshot);const source=normalizedCollectionWrites.get(this)?.has(name)&&previous?previous.source:typeof value=="object"&&value!==null||typeof value=="function"?new WeakRef(value):{primitive:value};lastAssignments.set(this,{source,retained:descriptor.get?.call(this)??snapshot})};ownershipBoundarySetters.set(set,{policy,originalSet}),Object.defineProperty(prototype,name,{...descriptor,set})}}const collectionTruncations=new WeakMap;function collectionTruncationWarningKey(tagName,property){return`lyra-collection-truncated:${tagName}:${String(property)}`}function recordCollectionTruncation(host,name,truncation){let byName=collectionTruncations.get(host);if(!truncation){byName?.delete(name);return}byName||(byName=new Map,collectionTruncations.set(host,byName)),byName.set(name,truncation);const tagName=host.localName,property=String(name);devWarnOnce(collectionTruncationWarningKey(tagName,property),`<${tagName}>: '${property}' kept ${truncation.retained} of ${truncation.source} entries, the ${truncation.kept}; an assignment keeps at most ${PUBLIC_COLLECTION_ENTRY_LIMIT} per array and ${PUBLIC_COLLECTION_NODE_LIMIT} values, and drops values it cannot copy.`)}function publicCollectionTruncation(host,property){return collectionTruncations.get(host)?.get(property)}function snapshotEnrolledEventDetail(host,name,detail){let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const candidate of trustedLyraConstructorChain(host)){const constructor=candidate;if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}return snapshotsDetail?snapshotEventDetail(detail,host.ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail}function declaresOwnedCollections(ctor){for(const constructor of lyraClassChain(ctor)){if(!Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties"))continue;if(constructor.ownedCollectionProperties.length>0)return!0}return!1}const collectionSupport=/* @__PURE__ */Object.freeze({installProperties:installOwnedCollectionAccessors,snapshotEvent:snapshotEnrolledEventDetail}),eventCollectionSupport=/* @__PURE__ */Object.freeze({installProperties(ctor){declaresOwnedCollections(ctor)&&devWarnOnce(`lyra-event-collection-support:${ctor.name}`,`${ctor.name} enrolls ownedCollectionProperties but declares eventCollectionSupport; declare collectionSupport so those properties cross the immutable collection boundary.`)},snapshotEvent:snapshotEnrolledEventDetail});export{collectionSupport,collectionTruncationWarningKey,eventCollectionSupport,publicCollectionTruncation,snapshotEventDetail,snapshotPublicCollection,writeNormalizedOwnedCollection};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="29.2.
|
|
1
|
+
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="29.2.2";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
|
|
@@ -514,6 +514,15 @@ value to the selected engine's `Map` type. `LyraMapInstance.prepareFeatures?()`
|
|
|
514
514
|
modular engine and absent on canonical MapLibre, so guard it or narrow to the companion `Map`
|
|
515
515
|
before calling. Identity is preserved: `.map` is the engine instance, not a proxy.
|
|
516
516
|
|
|
517
|
+
Paint or layout changes made directly on the engine instance (for example
|
|
518
|
+
`map.setPaintProperty('background', 'background-color', '#f00')`) are rendered into the WebGL
|
|
519
|
+
buffer at once, but WebKit with `preserveDrawingBuffer: false` (MapLibre's default) can keep
|
|
520
|
+
presenting the previous frame until another frame is requested; this reproduces with plain
|
|
521
|
+
`maplibre-gl` and is not specific to `lr-map`. Chromium and Firefox present immediately. After a
|
|
522
|
+
direct engine mutation that must be visible without further interaction (a screenshot, an
|
|
523
|
+
export), call the narrowed engine's `map.triggerRepaint()` once. `lr-map` does not force a
|
|
524
|
+
repaint after every idle, because that would re-render forever.
|
|
525
|
+
|
|
517
526
|
After `lr-map-load`, use the narrowed peer's `queryRenderedFeatures(point, { layers: [...] })`
|
|
518
527
|
for identities painted by style-owned vector layers; `point` is a screen position, which can be
|
|
519
528
|
obtained with the peer's `project([longitude, latitude])`. Attach peer interaction listeners when
|
package/llms/peers.md
CHANGED
|
@@ -39,7 +39,7 @@ for the page.
|
|
|
39
39
|
|---|---|---|
|
|
40
40
|
| `@aceshooting/lyra-flags` | `^2.3.0` | _(loaded by a shared internal module)_ |
|
|
41
41
|
| `@aceshooting/lyra-map` | `^1.2.0` | `lr-geojson-viewer`, `lr-map` |
|
|
42
|
-
| `@aceshooting/lyra-translations` | `^29.2.
|
|
42
|
+
| `@aceshooting/lyra-translations` | `^29.2.2` | _(not referenced by any component)_ |
|
|
43
43
|
| `@aiden0z/pptx-renderer` | `^1.4.0` | `lr-pptx-viewer` |
|
|
44
44
|
| `@sgratzl/chartjs-chart-boxplot` | `^4.0.0` | `lr-box-plot` |
|
|
45
45
|
| `chart.js` | `^4.0.1` | `lr-bar-chart`, `lr-box-plot`, `lr-bubble-chart`, `lr-chart`, `lr-doughnut-chart`, `lr-histogram`, `lr-line-chart`, `lr-pie-chart`, `lr-polar-area-chart`, `lr-radar-chart`, `lr-scatter-chart` |
|
package/llms.txt
CHANGED
|
@@ -56,7 +56,8 @@ element count and complete tag list.
|
|
|
56
56
|
AI coding agents: run `npx lyra-ui init-agents` (add `--agent <name>` if not auto-detected) to install
|
|
57
57
|
the Lyra UI skill for yourself. Humans: `npm i @aceshooting/lyra-ui && npx lyra-ui init-agents`
|
|
58
58
|
(a terminal asks which agents). Plugin marketplaces: `/plugin marketplace add aceshooting/lyra-ui`
|
|
59
|
-
(Claude Code), `codex plugin marketplace add aceshooting/lyra-ui` (Codex).
|
|
59
|
+
(Claude Code), `codex plugin marketplace add aceshooting/lyra-ui` (Codex). pnpm skills notice:
|
|
60
|
+
`pnpm approve @aceshooting/lyra-ui`.
|
|
60
61
|
|
|
61
62
|
## Rules that apply to every component
|
|
62
63
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aceshooting/lyra-ui",
|
|
3
|
-
"version": "29.2.
|
|
3
|
+
"version": "29.2.2",
|
|
4
4
|
"description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"web-components",
|
|
@@ -2605,7 +2605,7 @@
|
|
|
2605
2605
|
"peerDependencies": {
|
|
2606
2606
|
"@aceshooting/lyra-flags": "^2.3.0",
|
|
2607
2607
|
"@aceshooting/lyra-map": "^1.2.0",
|
|
2608
|
-
"@aceshooting/lyra-translations": "^29.2.
|
|
2608
|
+
"@aceshooting/lyra-translations": "^29.2.2",
|
|
2609
2609
|
"@aiden0z/pptx-renderer": "^1.4.0",
|
|
2610
2610
|
"@sgratzl/chartjs-chart-boxplot": "^4.0.0",
|
|
2611
2611
|
"chart.js": "^4.0.1",
|
|
@@ -2778,7 +2778,7 @@
|
|
|
2778
2778
|
"mammoth": "^1.13.0",
|
|
2779
2779
|
"maplibre-gl": "^6.15.0",
|
|
2780
2780
|
"marked": "^18.1.1",
|
|
2781
|
-
"oxc-parser": "^0.
|
|
2781
|
+
"oxc-parser": "^0.155.0",
|
|
2782
2782
|
"papaparse": "^5.7.0",
|
|
2783
2783
|
"pdfjs-dist": "^6.4.299",
|
|
2784
2784
|
"pixelmatch": "^8.0.0",
|