@aceshooting/lyra-ui 29.2.0 → 29.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +2 -1
- package/dist/components/agent-tools/task-list/task-list.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 +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 29.2.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- 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.
|
|
9
|
+
- @aceshooting/lyra-translations@29.2.1
|
|
10
|
+
|
|
3
11
|
## 29.2.0
|
|
4
12
|
|
|
5
13
|
### 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"
|
|
@@ -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.1";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.1` | _(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.1",
|
|
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.1",
|
|
2609
2609
|
"@aiden0z/pptx-renderer": "^1.4.0",
|
|
2610
2610
|
"@sgratzl/chartjs-chart-boxplot": "^4.0.0",
|
|
2611
2611
|
"chart.js": "^4.0.1",
|