@aceshooting/lyra-ui 29.1.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 +26 -0
- package/README.md +3 -2
- package/dist/components/agent-tools/task-list/task-list.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/media/avatar-group/avatar-group.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/anchored-overlay-runtime.js +1 -1
- package/dist/internal/announcer.js +1 -1
- package/dist/internal/aria-controls.js +1 -1
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/locale-loaders.generated.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/llms/components/lr-map.md +9 -0
- package/llms/peers.md +3 -3
- package/llms/shared/imports-and-registration.md +1 -1
- package/llms/shared/localization-and-rtl.md +12 -5
- package/llms/shared/testing-and-utilities.md +5 -0
- package/llms/shared.md +18 -6
- package/llms.txt +2 -1
- package/locales.json +125 -0
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
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
|
+
|
|
11
|
+
## 29.2.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 58eb5b2: Add four regional locale catalogs as small difference catalogs: `en-GB` (British English, over the built-in English), `es-419` (Latin American Spanish, over `es`), `fr-CA` (Canadian French, over `fr`) and `zh-HK` (Hong Kong Traditional Chinese, over `zh-TW`). Each registers only the messages that differ for the region and resolves every other message through its parent, so importing one also loads its parent catalog. They ship in `@aceshooting/lyra-translations` as `en-GB.js`, `es-419.js`, `fr-CA.js` and `zh-HK.js` (plus per-family slices), appear in `locales.json` and the optional locale loader, and are recorded as AI-assisted reviews with no human or native-speaker claim. An exact `zh-HK` tag now selects the `zh-HK` catalog instead of falling back to `zh-TW`.
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- d756bce: `lr-code-block` and `lr-code-block-core` no longer throw in DOM implementations without `Element.part`, such as Happy DOM test environments, so consumers need no shim; highlighted lines keep their `line-highlight` part wherever CSS parts exist.
|
|
20
|
+
- 2fd9f5c: Moving an `lr-conversation-item` (for example inside `lr-thread-list`) into another document or iframe before it has rendered no longer throws from `adoptedCallback`. The same guard now protects every component that mirrors an authored `aria-describedby` onto its inner control (`lr-image-viewer`, `lr-map`, `lr-lightbox`, `lr-textarea`, `lr-input` and others).
|
|
21
|
+
|
|
22
|
+
`lr-avatar-group` also no longer throws when moved into another document before its first render.
|
|
23
|
+
- d3725d2: Pressing Tab on a control that has an open keyboard-focus `lr-tooltip` (or an open `lr-popover`) inside an `lr-dialog` or `lr-drawer` now moves focus to the next control instead of getting stuck. While such a hint was open, the other controls in the dialog were made inert; they stay interactive now. Focus also no longer jumps back to the first control of the dialog when the tooltip closes as focus moves on.
|
|
24
|
+
- 5dd23d3: Anchored surfaces (`lr-tooltip`, `lr-popover`, `lr-dropdown`, `lr-popup`, `lr-select`, `lr-combobox` and the other popup users) now take the resolved positioning strategy, such as `--lr-positioning-strategy: fixed`, the moment they open instead of after the first placement pass, so a tooltip that opens or closes quickly no longer lays out at an unresolved position or briefly widens an `overflow: auto` ancestor and makes the page horizontally scrollable.
|
|
25
|
+
- Updated dependencies [5112ff8]
|
|
26
|
+
- @aceshooting/lyra-map@1.2.0
|
|
27
|
+
- @aceshooting/lyra-translations@29.2.0
|
|
28
|
+
|
|
3
29
|
## 29.1.0
|
|
4
30
|
|
|
5
31
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -46,7 +46,7 @@ and no runtime dependency on either project.
|
|
|
46
46
|
[signature starter](./llms/shared/styles-and-tokens.md#lyra-signature-starter)).
|
|
47
47
|
- **Conversation and agent UI.** Progressive [Markdown](./llms/components/lr-markdown.md) and expandable
|
|
48
48
|
[tool-call blocks](./llms/components/lr-tool-call-block.md).
|
|
49
|
-
- **Languages and typography.**
|
|
49
|
+
- **Languages and typography.** 70 optional catalogs in `@aceshooting/lyra-translations` plus built-in English
|
|
50
50
|
([`locales.json`](./locales.json), [import guide](./llms/shared/localization-and-rtl.md#ready-made-catalogs-aceshootinglyra-translationslocalejs)) and
|
|
51
51
|
[typography utilities](./llms/shared.md#typography).
|
|
52
52
|
|
|
@@ -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 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{SHIKI_SOURCE_MAX_CODE_UNITS}from"./shiki-types.js";import{CodeBlockHeaderActionsController,CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockLineHasFocus,codeBlockLineCount,codeBlockLineHighlightSet,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock}from"./code-block-shared.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockLineLabel,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_collapseCode,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_expandCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockBase extends LyraElement{static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockLineLabel:LYRA_DEFAULT_codeBlockLineLabel,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,collapseCode:LYRA_DEFAULT_collapseCode,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,expandCode:LYRA_DEFAULT_expandCode}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get highlightLimited(){return(this.code??"").length>SHIKI_SOURCE_MAX_CODE_UNITS}constructor(){super(),this.hasHeaderActions=!1,this.focusedLine=1,this.highlightedHtml=null,this.shikiReady=!1,this.justCopied=!1,this.copyFailed=!1,this.isDarkTheme=!1,this.restoreFocusedLineAfterUpdate=!1,this.highlightToken=0,this.plainKey=[],this.countedLines=1,this.plainDomChanged=!1,this.paintedLines=new Map,this.previousHighlighted=new Set,this.previousActive=new Set,this.bodyId=nextId("code-block-body"),this.interactions=new CodeBlockInteractionController({host:this,setFocusedLine:line=>{this.focusedLine=line},setJustCopied:value=>{this.justCopied=value},setCopyFailed:value=>{this.copyFailed=value},setDarkTheme:value=>{this.isDarkTheme=value},emitLineActivate:line=>this.emit("lr-line-activate",{line}),emitCopy:outcome=>this.emit("lr-copy",outcome),emitError:()=>this.emit("lr-error",null),emitCopyError:outcome=>this.emit("lr-copy-error",outcome),requestToggle:collapsed=>!this.emit("lr-toggle-request",{expanded:!collapsed},{cancelable:!0}).defaultPrevented,emitToggle:collapsed=>this.emit("lr-toggle",{expanded:!collapsed}),emitTextSelect:selection=>this.emit("lr-text-select",selection)}),this.headerActions=new CodeBlockHeaderActionsController({host:this,setHasHeaderActions:value=>{this.hasHeaderActions=value}}),new ThemeWatcher(this,()=>this.refreshTheme())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.refreshTheme(),this.headerActions.observe()}disconnectedCallback(){this.highlightToken+=1,super.disconnectedCallback(),this.headerActions.disconnect(),this.interactions.disconnect(),this.highlightedHtml=null}adoptedCallback(){super.adoptedCallback(),this.interactions.disconnect()}async scrollToAnchor(target){return scrollCodeBlockToAnchor(this,target)}refreshTheme(){this.interactions.refreshTheme()}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>this.refreshTheme()),this.headerActions.sync(),this.restoreFocusedLineAfterUpdate=codeBlockLineHasFocus(this),changed.has("code")&&(this.plainTemplate=void 0,this.plainKey=[],this.focusedLine=clampCodeBlockFocusedLine(this.focusedLine,this.lineCount())),this.beforeHighlightUpdate(changed),this.interactions.needsHighlightResync(changed,this.effectiveLocale,this.localize("codeBlockLineLabel"))&&(this.highlightLimited?(this.highlightToken++,this.highlightedHtml=null):this.shikiReady||this.hasPreSuppliedGrammar()?this.syncHighlight():this.highlightedHtml=null)}updated(changed){super.updated(changed),applyCodeBlockAriaBusy(this,!this.highlightLimited&&this.showsSkeleton()),this.patchLineState(),this.interactions.syncLineButtons(this.focusedLine,this.plainDomChanged),this.plainDomChanged=!1,this.restoreFocusedLineAfterUpdate&&(restoreCodeBlockLineFocus(this,this.focusedLine),this.restoreFocusedLineAfterUpdate=!1)}beforeHighlightUpdate(_changed){}hasPreSuppliedGrammar(){return!!this.preSuppliedGrammar()}lineHighlightSet(){return codeBlockLineHighlightSet(this.highlightLines??"",this.highlights,this.lineCount())}activeHighlightLineSet(){return codeBlockActiveHighlightLineSet(this.highlights,this.activeHighlightId,this.lineCount())}lineCount(){const code=this.code??"";return code!==this.countedCode&&(this.countedCode=code,this.countedLines=codeBlockLineCount(code)),this.countedLines}tokenize(hl,lang){return this.highlightLimited?null:tokenizeCodeBlock(hl,{code:this.code??"",lang,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line)})}renderPlainCode(){return renderCodeBlockPlainCode({code:this.code??"",lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),localize:this.localize.bind(this),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line),onLineActivate:line=>this.interactions.onLineActivate(line),onLineKeyDown:(event,line)=>this.interactions.onLineKeyDown(event,line)})}patchLineState(){const code=this.renderRoot.querySelector("code");if(code!==this.paintedCode||this.plainDomChanged){this.paintedCode=code,this.paintedLines.clear();for(const line of code?.querySelectorAll(".line[data-line]")??[])line.removeAttribute("data-highlighted"),line.removeAttribute("data-active"),line.part
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{SHIKI_SOURCE_MAX_CODE_UNITS}from"./shiki-types.js";import{CodeBlockHeaderActionsController,CodeBlockInteractionController,applyCodeBlockAriaBusy,clampCodeBlockFocusedLine,codeBlockActiveHighlightLineSet,codeBlockLineHasFocus,codeBlockLineCount,codeBlockLineHighlightSet,renderCodeBlockPlainCode,renderCodeBlockShell,restoreCodeBlockLineFocus,scrollCodeBlockToAnchor,tokenizeCodeBlock}from"./code-block-shared.js";import{LYRA_DEFAULT_codeBlockHighlightLimit,LYRA_DEFAULT_codeBlockLineLabel,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_collapseCode,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_expandCode}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";class LyraCodeBlockBase extends LyraElement{static{this.defaultStrings={...super.defaultStrings,codeBlockHighlightLimit:LYRA_DEFAULT_codeBlockHighlightLimit,codeBlockLineLabel:LYRA_DEFAULT_codeBlockLineLabel,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,collapseCode:LYRA_DEFAULT_collapseCode,copied:LYRA_DEFAULT_copied,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copy:LYRA_DEFAULT_copy,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,expandCode:LYRA_DEFAULT_expandCode}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-text-select"])}get highlightLimited(){return(this.code??"").length>SHIKI_SOURCE_MAX_CODE_UNITS}constructor(){super(),this.hasHeaderActions=!1,this.focusedLine=1,this.highlightedHtml=null,this.shikiReady=!1,this.justCopied=!1,this.copyFailed=!1,this.isDarkTheme=!1,this.restoreFocusedLineAfterUpdate=!1,this.highlightToken=0,this.plainKey=[],this.countedLines=1,this.plainDomChanged=!1,this.paintedLines=new Map,this.previousHighlighted=new Set,this.previousActive=new Set,this.bodyId=nextId("code-block-body"),this.interactions=new CodeBlockInteractionController({host:this,setFocusedLine:line=>{this.focusedLine=line},setJustCopied:value=>{this.justCopied=value},setCopyFailed:value=>{this.copyFailed=value},setDarkTheme:value=>{this.isDarkTheme=value},emitLineActivate:line=>this.emit("lr-line-activate",{line}),emitCopy:outcome=>this.emit("lr-copy",outcome),emitError:()=>this.emit("lr-error",null),emitCopyError:outcome=>this.emit("lr-copy-error",outcome),requestToggle:collapsed=>!this.emit("lr-toggle-request",{expanded:!collapsed},{cancelable:!0}).defaultPrevented,emitToggle:collapsed=>this.emit("lr-toggle",{expanded:!collapsed}),emitTextSelect:selection=>this.emit("lr-text-select",selection)}),this.headerActions=new CodeBlockHeaderActionsController({host:this,setHasHeaderActions:value=>{this.hasHeaderActions=value}}),new ThemeWatcher(this,()=>this.refreshTheme())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.refreshTheme(),this.headerActions.observe()}disconnectedCallback(){this.highlightToken+=1,super.disconnectedCallback(),this.headerActions.disconnect(),this.interactions.disconnect(),this.highlightedHtml=null}adoptedCallback(){super.adoptedCallback(),this.interactions.disconnect()}async scrollToAnchor(target){return scrollCodeBlockToAnchor(this,target)}refreshTheme(){this.interactions.refreshTheme()}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>this.refreshTheme()),this.headerActions.sync(),this.restoreFocusedLineAfterUpdate=codeBlockLineHasFocus(this),changed.has("code")&&(this.plainTemplate=void 0,this.plainKey=[],this.focusedLine=clampCodeBlockFocusedLine(this.focusedLine,this.lineCount())),this.beforeHighlightUpdate(changed),this.interactions.needsHighlightResync(changed,this.effectiveLocale,this.localize("codeBlockLineLabel"))&&(this.highlightLimited?(this.highlightToken++,this.highlightedHtml=null):this.shikiReady||this.hasPreSuppliedGrammar()?this.syncHighlight():this.highlightedHtml=null)}updated(changed){super.updated(changed),applyCodeBlockAriaBusy(this,!this.highlightLimited&&this.showsSkeleton()),this.patchLineState(),this.interactions.syncLineButtons(this.focusedLine,this.plainDomChanged),this.plainDomChanged=!1,this.restoreFocusedLineAfterUpdate&&(restoreCodeBlockLineFocus(this,this.focusedLine),this.restoreFocusedLineAfterUpdate=!1)}beforeHighlightUpdate(_changed){}hasPreSuppliedGrammar(){return!!this.preSuppliedGrammar()}lineHighlightSet(){return codeBlockLineHighlightSet(this.highlightLines??"",this.highlights,this.lineCount())}activeHighlightLineSet(){return codeBlockActiveHighlightLineSet(this.highlights,this.activeHighlightId,this.lineCount())}lineCount(){const code=this.code??"";return code!==this.countedCode&&(this.countedCode=code,this.countedLines=codeBlockLineCount(code)),this.countedLines}tokenize(hl,lang){return this.highlightLimited?null:tokenizeCodeBlock(hl,{code:this.code??"",lang,lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line)})}renderPlainCode(){return renderCodeBlockPlainCode({code:this.code??"",lineNumbers:this.lineNumbers,activatableLines:this.activatableLines,focusedLine:this.focusedLine,highlightedLines:this.lineHighlightSet(),activeLines:this.activeHighlightLineSet(),localize:this.localize.bind(this),lineLabel:line=>this.localize("codeBlockLineLabel",void 0,{line:getNumberFormat(this.effectiveLocale).format(line)}),lineNumberText:line=>getNumberFormat(this.effectiveLocale).format(line),onLineActivate:line=>this.interactions.onLineActivate(line),onLineKeyDown:(event,line)=>this.interactions.onLineKeyDown(event,line)})}patchLineState(){const code=this.renderRoot.querySelector("code");if(code!==this.paintedCode||this.plainDomChanged){this.paintedCode=code,this.paintedLines.clear();for(const line of code?.querySelectorAll(".line[data-line]")??[])line.removeAttribute("data-highlighted"),line.removeAttribute("data-active"),line.part?.remove("line-highlight"),this.paintedLines.set(Number(line.dataset.line),line)}const highlighted=this.lineHighlightSet(),active=this.activeHighlightLineSet(),changed=new Set([...this.previousHighlighted,...highlighted,...this.previousActive,...active]);for(const number of changed){const line=this.paintedLines.get(number);line&&(line.toggleAttribute("data-highlighted",highlighted.has(number)),line.toggleAttribute("data-active",active.has(number)),line.part?.toggle("line-highlight",highlighted.has(number)))}this.previousHighlighted=highlighted,this.previousActive=active}cachedPlainCode(){const key=[this.code,this.lineNumbers,this.activatableLines,this.effectiveLocale,this.localize("codeBlockLineLabel")];return(!this.plainTemplate||key.some((value,index)=>value!==this.plainKey[index]))&&(this.plainDomChanged=!0,this.plainKey=key,this.plainTemplate=this.renderPlainCode()),this.plainTemplate}render(){return renderCodeBlockShell({filename:this.filename,language:this.language,copyable:!this.withoutCopyButton,copyAppearance:this.copyAppearance,hasHeaderActions:this.hasHeaderActions,collapsible:this.collapsible,collapsed:this.collapsed,justCopied:this.justCopied,copyFailed:this.copyFailed,bodyId:this.bodyId,accessibleLabel:this.accessibleLabel,maxHeight:this.maxHeight,isDarkTheme:this.isDarkTheme,showSkeleton:!this.highlightLimited&&this.showsSkeleton(),highlightLimited:this.highlightLimited&&!!this.language,highlightedHtml:this.highlightedHtml,lineNumbers:this.lineNumbers,localize:this.localize.bind(this),renderPlainCode:()=>this.cachedPlainCode(),onToggle:this.interactions.toggleCollapsed,onCopy:this.interactions.copy,onBodyMouseUp:this.interactions.onBodyMouseUp,onBodyClick:this.interactions.onBodyClick,onBodyKeyDown:this.interactions.onBodyKeyDown,onBodyFocusIn:this.interactions.onBodyFocusIn})}}__decorate([state()],LyraCodeBlockBase.prototype,"hasHeaderActions",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"highlightedHtml",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"shikiReady",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"justCopied",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"copyFailed",void 0),__decorate([state()],LyraCodeBlockBase.prototype,"isDarkTheme",void 0);export{LyraCodeBlockBase};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{LYRA_AVATAR_SHAPE_VALUES,LYRA_SIZE_VALUES,LYRA_VARIANT_VALUES}from"../../../internal/variant-values.js";import{styles}from"./avatar-group.styles.js";import{LYRA_DEFAULT_showMoreCollapsed,LYRA_DEFAULT_showMoreCount}from"../../../internal/default-strings/shared.generated.js";const OVERFLOW_IDENTITY_DETAIL_PROPERTIES=Object.freeze({"lr-overflow-activate":Object.freeze(["hiddenAvatars"])});class LyraAvatarGroup extends LyraElement{constructor(){super(...arguments),this.size="m",this.shape="circle",this.variant="neutral",this.label="",this.eligibleAvatarCount=0,this.overflowHiddenAvatars=Object.freeze([]),this.assignedAvatars=Object.freeze([]),this.observedAvatars=Object.freeze([]),this.defaultOwnership=new Map,this.pendingOwnedAttributeWrites=new WeakMap,this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)},this.onOverflowClick=()=>{const hiddenAvatars=Object.freeze([...this.overflowHiddenAvatars]);this.emit("lr-overflow-activate",Object.freeze({hiddenCount:hiddenAvatars.length,hiddenAvatars}))}}static{this.defaultStrings={...super.defaultStrings,showMoreCollapsed:LYRA_DEFAULT_showMoreCollapsed,showMoreCount:LYRA_DEFAULT_showMoreCount}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-overflow-activate"])}static{this.identityEventDetailProperties=OVERFLOW_IDENTITY_DETAIL_PROPERTIES}static{this.styles=[LyraElement.styles,styles]}get max(){return this._max}set max(next){const old=this._max;this._max=next==null?void 0:finiteCount(next),this.requestUpdate("max",old)}willUpdate(changed){super.willUpdate(changed),changed.has("size")&&!LYRA_SIZE_VALUES.includes(this.size)&&(this.size="m"),changed.has("shape")&&!LYRA_AVATAR_SHAPE_VALUES.includes(this.shape)&&(this.shape="circle"),changed.has("variant")&&!LYRA_VARIANT_VALUES.includes(this.variant)&&(this.variant="neutral"),this.hasUpdated?changed.has("max")&&this.recomputeWindow():this.seedFirstRenderState(()=>{this.assignedAvatars=Object.freeze(Array.from(this.children).filter(element=>this.isAvatar(element))),this.recomputeWindow()})}firstUpdated(changed){super.firstUpdated(changed);const slot=this.avatarsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}connectedCallback(){if(super.connectedCallback(),!this.hasUpdated)return;const slot=this.renderRoot.querySelector("slot");slot?.localName==="slot"&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))}updated(changed){super.updated(changed),this.connectAvatarObserver(this.assignedAvatars),this.applyGroupDefaults(),this.applyVisibilityMarkers()}disconnectedCallback(){this.disconnectAvatarObserver(),this.restoreOwnedState(),super.disconnectedCallback()}adoptedCallback(){if(super.adoptedCallback(),this.disconnectAvatarObserver(),!this.isConnected)return;const slot=this.renderRoot.querySelector("slot");slot?.localName==="slot"&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))}get hasOverflow(){const max=this.max;return max!=null&&this.eligibleAvatarCount>max}get hiddenCount(){return this.overflowHiddenAvatars.length}isAvatar(element){return element.localName===tag("avatar")}sameAvatars(a,b){return a.length===b.length&&a.every((avatar,index)=>avatar===b[index])}reconcileAvatars(elements){if(!this.isConnected)return;const next=Object.freeze(elements.filter(element=>this.isAvatar(element))),nextSet=new Set(next);for(const avatar of this.assignedAvatars)nextSet.has(avatar)||this.restoreAvatarState(avatar);this.assignedAvatars=next,this.connectAvatarObserver(next),this.applyGroupDefaults(),this.recomputeWindow(),this.applyVisibilityMarkers()}recomputeWindow(){const eligible=this.assignedAvatars.filter(avatar=>!avatar.hasAttribute("hidden")&&!avatar.hasAttribute("inert")),hidden=this.max==null?[]:eligible.slice(this.max);this.eligibleAvatarCount!==eligible.length&&(this.eligibleAvatarCount=eligible.length),this.sameAvatars(this.overflowHiddenAvatars,hidden)||(this.overflowHiddenAvatars=Object.freeze([...hidden]))}connectAvatarObserver(avatars){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!!this.sameAvatars(this.observedAvatars,avatars)&&this.avatarObserverWindow===ownerWindow&&this.avatarObserver)return;this.disconnectAvatarObserver(),this.observedAvatars=Object.freeze([...avatars]),this.avatarObserverWindow=ownerWindow;const observer=new ownerWindow.MutationObserver(records=>{if(!(this.avatarObserver!==observer||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)){for(const record of records){const attribute=record.attributeName;if(!attribute||attribute!=="size"&&attribute!=="shape"&&attribute!=="variant"||!this.isAvatar(record.target))continue;const avatar=record.target;if(this.consumeOwnedAttributeWrite(avatar,attribute))continue;const ownership=this.defaultOwnership.get(avatar);ownership?.delete(attribute),ownership?.size===0&&this.defaultOwnership.delete(avatar)}this.applyGroupDefaults(),this.recomputeWindow(),this.applyVisibilityMarkers()}});this.avatarObserver=observer;for(const avatar of avatars)observer.observe(avatar,{attributes:!0,attributeFilter:["hidden","inert","size","shape","variant"]})}disconnectAvatarObserver(){this.avatarObserver?.disconnect();for(const avatar of this.observedAvatars)this.pendingOwnedAttributeWrites.delete(avatar);this.avatarObserver=void 0,this.avatarObserverWindow=void 0,this.observedAvatars=Object.freeze([])}markOwnedAttributeWrite(avatar,attribute){if(!this.avatarObserver||!this.observedAvatars.includes(avatar))return;let writes=this.pendingOwnedAttributeWrites.get(avatar);writes||(writes=new Map,this.pendingOwnedAttributeWrites.set(avatar,writes)),writes.set(attribute,(writes.get(attribute)??0)+1)}consumeOwnedAttributeWrite(avatar,attribute){const writes=this.pendingOwnedAttributeWrites.get(avatar),count=writes?.get(attribute)??0;return count===0?!1:(count===1?writes.delete(attribute):writes.set(attribute,count-1),writes.size===0&&this.pendingOwnedAttributeWrites.delete(avatar),!0)}applyGroupDefaults(){const values={size:this.size,shape:this.shape,variant:this.variant};for(const avatar of this.assignedAvatars){let ownership=this.defaultOwnership.get(avatar);for(const attribute of["size","shape","variant"]){const applied=ownership?.get(attribute);applied!=null&&avatar.getAttribute(attribute)!==applied&&ownership.delete(attribute),avatar.hasAttribute(attribute)?ownership?.has(attribute)&&avatar.getAttribute(attribute)===applied&&applied!==values[attribute]&&(ownership.set(attribute,values[attribute]),this.markOwnedAttributeWrite(avatar,attribute),avatar.setAttribute(attribute,values[attribute])):(ownership??=new Map,ownership.set(attribute,values[attribute]),this.markOwnedAttributeWrite(avatar,attribute),avatar.setAttribute(attribute,values[attribute]))}ownership?.size?this.defaultOwnership.set(avatar,ownership):this.defaultOwnership.delete(avatar)}}applyVisibilityMarkers(){const hidden=new Set(this.overflowHiddenAvatars),firstVisible=this.assignedAvatars.find(avatar=>!avatar.hasAttribute("hidden")&&!avatar.hasAttribute("inert")&&!hidden.has(avatar));for(const avatar of this.assignedAvatars)hidden.has(avatar)?avatar.setAttribute("data-lr-avatar-group-hidden",""):avatar.removeAttribute("data-lr-avatar-group-hidden"),avatar===firstVisible?avatar.setAttribute("data-lr-avatar-group-first",""):avatar.removeAttribute("data-lr-avatar-group-first")}restoreAvatarState(avatar){avatar.removeAttribute("data-lr-avatar-group-hidden"),avatar.removeAttribute("data-lr-avatar-group-first");const ownership=this.defaultOwnership.get(avatar);if(ownership){for(const[attribute,applied]of ownership)avatar.getAttribute(attribute)===applied&&avatar.removeAttribute(attribute);this.defaultOwnership.delete(avatar)}}restoreOwnedState(){for(const avatar of this.assignedAvatars)this.restoreAvatarState(avatar);this.assignedAvatars=Object.freeze([]),this.overflowHiddenAvatars=Object.freeze([]),this.eligibleAvatarCount=0}onSlotChangeFromSlot(slot){this.updateBrowserDerivedState(()=>{this.isConnected&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))})}render(){const overflowing=this.hasOverflow,hiddenCount=this.hiddenCount,badgeIsFirstVisible=overflowing&&hiddenCount===this.eligibleAvatarCount,accessibleLabel=hostAriaLabel(this)??(this.label||nothing),localizedHiddenCount=getNumberFormat(this.effectiveLocale).format(hiddenCount);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{LYRA_AVATAR_SHAPE_VALUES,LYRA_SIZE_VALUES,LYRA_VARIANT_VALUES}from"../../../internal/variant-values.js";import{styles}from"./avatar-group.styles.js";import{LYRA_DEFAULT_showMoreCollapsed,LYRA_DEFAULT_showMoreCount}from"../../../internal/default-strings/shared.generated.js";const OVERFLOW_IDENTITY_DETAIL_PROPERTIES=Object.freeze({"lr-overflow-activate":Object.freeze(["hiddenAvatars"])});class LyraAvatarGroup extends LyraElement{constructor(){super(...arguments),this.size="m",this.shape="circle",this.variant="neutral",this.label="",this.eligibleAvatarCount=0,this.overflowHiddenAvatars=Object.freeze([]),this.assignedAvatars=Object.freeze([]),this.observedAvatars=Object.freeze([]),this.defaultOwnership=new Map,this.pendingOwnedAttributeWrites=new WeakMap,this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)},this.onOverflowClick=()=>{const hiddenAvatars=Object.freeze([...this.overflowHiddenAvatars]);this.emit("lr-overflow-activate",Object.freeze({hiddenCount:hiddenAvatars.length,hiddenAvatars}))}}static{this.defaultStrings={...super.defaultStrings,showMoreCollapsed:LYRA_DEFAULT_showMoreCollapsed,showMoreCount:LYRA_DEFAULT_showMoreCount}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-overflow-activate"])}static{this.identityEventDetailProperties=OVERFLOW_IDENTITY_DETAIL_PROPERTIES}static{this.styles=[LyraElement.styles,styles]}get max(){return this._max}set max(next){const old=this._max;this._max=next==null?void 0:finiteCount(next),this.requestUpdate("max",old)}willUpdate(changed){super.willUpdate(changed),changed.has("size")&&!LYRA_SIZE_VALUES.includes(this.size)&&(this.size="m"),changed.has("shape")&&!LYRA_AVATAR_SHAPE_VALUES.includes(this.shape)&&(this.shape="circle"),changed.has("variant")&&!LYRA_VARIANT_VALUES.includes(this.variant)&&(this.variant="neutral"),this.hasUpdated?changed.has("max")&&this.recomputeWindow():this.seedFirstRenderState(()=>{this.assignedAvatars=Object.freeze(Array.from(this.children).filter(element=>this.isAvatar(element))),this.recomputeWindow()})}firstUpdated(changed){super.firstUpdated(changed);const slot=this.avatarsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}connectedCallback(){if(super.connectedCallback(),!this.hasUpdated)return;const slot=this.renderRoot.querySelector("slot");slot?.localName==="slot"&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))}updated(changed){super.updated(changed),this.connectAvatarObserver(this.assignedAvatars),this.applyGroupDefaults(),this.applyVisibilityMarkers()}disconnectedCallback(){this.disconnectAvatarObserver(),this.restoreOwnedState(),super.disconnectedCallback()}adoptedCallback(){if(super.adoptedCallback(),this.disconnectAvatarObserver(),!this.isConnected||!this.hasUpdated)return;const slot=this.renderRoot.querySelector("slot");slot?.localName==="slot"&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))}get hasOverflow(){const max=this.max;return max!=null&&this.eligibleAvatarCount>max}get hiddenCount(){return this.overflowHiddenAvatars.length}isAvatar(element){return element.localName===tag("avatar")}sameAvatars(a,b){return a.length===b.length&&a.every((avatar,index)=>avatar===b[index])}reconcileAvatars(elements){if(!this.isConnected)return;const next=Object.freeze(elements.filter(element=>this.isAvatar(element))),nextSet=new Set(next);for(const avatar of this.assignedAvatars)nextSet.has(avatar)||this.restoreAvatarState(avatar);this.assignedAvatars=next,this.connectAvatarObserver(next),this.applyGroupDefaults(),this.recomputeWindow(),this.applyVisibilityMarkers()}recomputeWindow(){const eligible=this.assignedAvatars.filter(avatar=>!avatar.hasAttribute("hidden")&&!avatar.hasAttribute("inert")),hidden=this.max==null?[]:eligible.slice(this.max);this.eligibleAvatarCount!==eligible.length&&(this.eligibleAvatarCount=eligible.length),this.sameAvatars(this.overflowHiddenAvatars,hidden)||(this.overflowHiddenAvatars=Object.freeze([...hidden]))}connectAvatarObserver(avatars){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!!this.sameAvatars(this.observedAvatars,avatars)&&this.avatarObserverWindow===ownerWindow&&this.avatarObserver)return;this.disconnectAvatarObserver(),this.observedAvatars=Object.freeze([...avatars]),this.avatarObserverWindow=ownerWindow;const observer=new ownerWindow.MutationObserver(records=>{if(!(this.avatarObserver!==observer||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)){for(const record of records){const attribute=record.attributeName;if(!attribute||attribute!=="size"&&attribute!=="shape"&&attribute!=="variant"||!this.isAvatar(record.target))continue;const avatar=record.target;if(this.consumeOwnedAttributeWrite(avatar,attribute))continue;const ownership=this.defaultOwnership.get(avatar);ownership?.delete(attribute),ownership?.size===0&&this.defaultOwnership.delete(avatar)}this.applyGroupDefaults(),this.recomputeWindow(),this.applyVisibilityMarkers()}});this.avatarObserver=observer;for(const avatar of avatars)observer.observe(avatar,{attributes:!0,attributeFilter:["hidden","inert","size","shape","variant"]})}disconnectAvatarObserver(){this.avatarObserver?.disconnect();for(const avatar of this.observedAvatars)this.pendingOwnedAttributeWrites.delete(avatar);this.avatarObserver=void 0,this.avatarObserverWindow=void 0,this.observedAvatars=Object.freeze([])}markOwnedAttributeWrite(avatar,attribute){if(!this.avatarObserver||!this.observedAvatars.includes(avatar))return;let writes=this.pendingOwnedAttributeWrites.get(avatar);writes||(writes=new Map,this.pendingOwnedAttributeWrites.set(avatar,writes)),writes.set(attribute,(writes.get(attribute)??0)+1)}consumeOwnedAttributeWrite(avatar,attribute){const writes=this.pendingOwnedAttributeWrites.get(avatar),count=writes?.get(attribute)??0;return count===0?!1:(count===1?writes.delete(attribute):writes.set(attribute,count-1),writes.size===0&&this.pendingOwnedAttributeWrites.delete(avatar),!0)}applyGroupDefaults(){const values={size:this.size,shape:this.shape,variant:this.variant};for(const avatar of this.assignedAvatars){let ownership=this.defaultOwnership.get(avatar);for(const attribute of["size","shape","variant"]){const applied=ownership?.get(attribute);applied!=null&&avatar.getAttribute(attribute)!==applied&&ownership.delete(attribute),avatar.hasAttribute(attribute)?ownership?.has(attribute)&&avatar.getAttribute(attribute)===applied&&applied!==values[attribute]&&(ownership.set(attribute,values[attribute]),this.markOwnedAttributeWrite(avatar,attribute),avatar.setAttribute(attribute,values[attribute])):(ownership??=new Map,ownership.set(attribute,values[attribute]),this.markOwnedAttributeWrite(avatar,attribute),avatar.setAttribute(attribute,values[attribute]))}ownership?.size?this.defaultOwnership.set(avatar,ownership):this.defaultOwnership.delete(avatar)}}applyVisibilityMarkers(){const hidden=new Set(this.overflowHiddenAvatars),firstVisible=this.assignedAvatars.find(avatar=>!avatar.hasAttribute("hidden")&&!avatar.hasAttribute("inert")&&!hidden.has(avatar));for(const avatar of this.assignedAvatars)hidden.has(avatar)?avatar.setAttribute("data-lr-avatar-group-hidden",""):avatar.removeAttribute("data-lr-avatar-group-hidden"),avatar===firstVisible?avatar.setAttribute("data-lr-avatar-group-first",""):avatar.removeAttribute("data-lr-avatar-group-first")}restoreAvatarState(avatar){avatar.removeAttribute("data-lr-avatar-group-hidden"),avatar.removeAttribute("data-lr-avatar-group-first");const ownership=this.defaultOwnership.get(avatar);if(ownership){for(const[attribute,applied]of ownership)avatar.getAttribute(attribute)===applied&&avatar.removeAttribute(attribute);this.defaultOwnership.delete(avatar)}}restoreOwnedState(){for(const avatar of this.assignedAvatars)this.restoreAvatarState(avatar);this.assignedAvatars=Object.freeze([]),this.overflowHiddenAvatars=Object.freeze([]),this.eligibleAvatarCount=0}onSlotChangeFromSlot(slot){this.updateBrowserDerivedState(()=>{this.isConnected&&this.reconcileAvatars(slot.assignedElements({flatten:!0}))})}render(){const overflowing=this.hasOverflow,hiddenCount=this.hiddenCount,badgeIsFirstVisible=overflowing&&hiddenCount===this.eligibleAvatarCount,accessibleLabel=hostAriaLabel(this)??(this.label||nothing),localizedHiddenCount=getNumberFormat(this.effectiveLocale).format(hiddenCount);return html`
|
|
2
2
|
<div part="base" role="group" aria-label=${accessibleLabel}>
|
|
3
3
|
<slot @slotchange=${this.onSlotChange}></slot>
|
|
4
4
|
${overflowing?html`<button
|
|
@@ -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
|
-
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup){activePlacementByPopup.get(popup)?.();const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
1
|
+
const defaultRuntimeLoader=()=>import("./positioner.js").then(runtime=>({place:runtime.placeAnchoredSurface,trackRect:runtime.trackRect,releaseTopLayer:runtime.releaseTopLayer}));let runtimeLoader=defaultRuntimeLoader,runtimePromise;function loadAnchoredOverlayRuntime(){if(runtimePromise)return runtimePromise;const pending=runtimeLoader().catch(error=>{throw runtimePromise===pending&&(runtimePromise=void 0),error});return runtimePromise=pending}const activePlacementByPopup=new WeakMap;function concealPendingPopup(popup,strategy){activePlacementByPopup.get(popup)?.(),popup.style.position=strategy??"fixed";const pending=[popup.style.visibility,popup.style.getPropertyPriority("visibility")];return popup.style.setProperty("visibility","hidden","important"),pending}function releasePendingPopup(popup,pending){const[value,priority]=pending;popup.style.visibility!=="hidden"||popup.style.getPropertyPriority("visibility")!=="important"||popup.style.setProperty("visibility",value,priority)}function deferredPlace(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,positioned=!1;const dispose=()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility))};return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(positioned||(positioned=!0,releasePendingPopup(popup,pendingVisibility)),options.onPlaced?.(result))}})}catch{}},()=>{}),dispose}function deferredPlaceReady(...args){const[anchor,popup,options={}]=args,pendingVisibility=concealPendingPopup(popup,options.strategy);let active=!0,cleanup,settle;const ready=new Promise(resolve=>{settle=resolve}),dispose=(()=>{active&&(active=!1,activePlacementByPopup.delete(popup),cleanup?.(),releasePendingPopup(popup,pendingVisibility),settle?.(!1))});return activePlacementByPopup.set(popup,dispose),loadAnchoredOverlayRuntime().then(runtime=>{if(active)try{cleanup=runtime.place(anchor,popup,{...options,onPlaced:result=>{active&&(settle&&(releasePendingPopup(popup,pendingVisibility),settle(!0),settle=void 0),options.onPlaced?.(result))}})}catch{settle?.(!1)}},()=>settle?.(!1)),dispose.ready=ready,dispose}async function waitForDeferredPlacement(current){let operation;for(;operation=current();){const positioned=await operation.ready;if(operation===current())return!!positioned}return!0}async function awaitPopupAnimations(host,popup,isCurrent){const ownerDocument=host.ownerDocument;if(!isCurrent())return!1;if(!host.isConnected)return!0;const view=ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),host.ownerDocument!==ownerDocument||!isCurrent())return!1;const animations=popup()?.getAnimations({subtree:!0})??[];return await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),host.ownerDocument===ownerDocument&&isCurrent()}async function settlePopupTransition(options){const{host,isCurrent}=options,ownerDocument=host.ownerDocument,current=()=>host.ownerDocument===ownerDocument&&isCurrent();await host.updateComplete,current()&&(options.waitForPosition&&(!await options.waitForPosition()||!current()||(await host.updateComplete,!current()))||await awaitPopupAnimations(host,options.popup,current)&&(options.conceal&&(options.conceal(),await host.updateComplete,!current())||options.onSettled()))}class PopupTransitionWaiters{#waiters=new Map;wait(event){return new Promise(resolve=>{const waiters=this.#waiters.get(event)??new Set;waiters.add(resolve),this.#waiters.set(event,waiters)})}resolve(event){const waiters=this.#waiters.get(event);if(waiters){this.#waiters.delete(event);for(const resolve of waiters)resolve()}}}function deferredTrackRect(...args){let active=!0,cleanup;return loadAnchoredOverlayRuntime().then(runtime=>{active&&(cleanup=runtime.trackRect(...args))}).catch(()=>{}),()=>{active=!1,cleanup?.(),cleanup=void 0}}function __setAnchoredOverlayRuntimeLoaderForTesting(loader){runtimeLoader=loader??defaultRuntimeLoader,runtimePromise=void 0}function topLayerPlacement(topLayer,strategy){return{strategy:topLayer?"fixed":strategy,topLayer}}function syncTopLayerRelease(popup,wasPromoted,topLayer,runtime){if(wasPromoted&&!topLayer){if(runtime)return runtime.releaseTopLayer?.(popup),topLayer;loadAnchoredOverlayRuntime().then(runtime2=>runtime2.releaseTopLayer?.(popup),()=>{})}return topLayer}export{PopupTransitionWaiters,__setAnchoredOverlayRuntimeLoaderForTesting,awaitPopupAnimations,deferredPlace,deferredPlaceReady,deferredTrackRect,loadAnchoredOverlayRuntime,settlePopupTransition,syncTopLayerRelease,topLayerPlacement,waitForDeferredPlacement};
|
|
@@ -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{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{asciiWhitespaceTokens,isSingleAsciiWhitespaceToken}from"./ascii-whitespace.js";import{sharedRealmRegistry}from"./a11y.js";import{registerDescriptionBaselineUpdater,resolveIdReferencesIn}from"./aria-reflection.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"./aria-reflection.js";const DESCRIPTION_RELATIONSHIP={attribute:"aria-describedby",property:"ariaDescribedByElements"},LABEL_RELATIONSHIP={attribute:"aria-labelledby",property:"ariaLabelledByElements"},CONTROLS_RELATIONSHIP={attribute:"aria-controls",property:"ariaControlsElements"},DESCRIPTION_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-description-ownership.v1"),LABEL_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-label-ownership.v1"),CONTROLS_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-controls-relationship-ownership.v1"),fallbackDescriptionOwnership=new WeakMap,fallbackLabelOwnership=new WeakMap,fallbackControlsOwnership=new WeakMap,descriptionOwnership=sharedRealmRegistry(DESCRIPTION_OWNERSHIP,()=>new WeakMap,fallbackDescriptionOwnership),labelOwnership=sharedRealmRegistry(LABEL_OWNERSHIP,()=>new WeakMap,fallbackLabelOwnership),controlsOwnership=sharedRealmRegistry(CONTROLS_OWNERSHIP,()=>new WeakMap,fallbackControlsOwnership);function relationshipDefinition(relationship){return relationship==="aria-describedby"?DESCRIPTION_RELATIONSHIP:LABEL_RELATIONSHIP}function relationshipOwnership(relationship){return relationship==="aria-describedby"?descriptionOwnership:relationship==="aria-labelledby"?labelOwnership:controlsOwnership}function reflectedRelationshipElements(target,definition){if(!(definition.property in target))return null;try{const reflected=Reflect.get(target,definition.property);return reflected===null?null:[...reflected]}catch{return null}}function relationshipSnapshot(target,definition){return{elements:reflectedRelationshipElements(target,definition),had:target.hasAttribute(definition.attribute),value:target.getAttribute(definition.attribute)}}function setLastApplied(state,definition){state.lastApplied=relationshipSnapshot(state.target,definition),state.lastAppliedDocument=state.target.ownerDocument,state.lastAppliedEndpointRoots=new Map(projectedRelationshipElements(state).map(element=>[element,element.getRootNode()])),state.lastAppliedResolvability=new Map(projectedRelationshipElements(state).map(element=>[element,isIdResolvableFromTarget(state.target,element)])),state.lastAppliedRoot=state.target.getRootNode(),state.lastAppliedUnresolvedBaselineIds=state.baseline.kind==="attribute"?[...asciiWhitespaceTokens(state.baseline.value)].filter(id=>!isIdResolvableIdFromTarget(state.target,id)):[]}function sameElements(first,second){return first===null||second===null?first===second:first.length===second.length&&first.every((element,index)=>element===second[index])}function sameRelationshipSnapshot(first,second){return first.had===second.had&&first.value===second.value&&sameElements(first.elements,second.elements)}function baselineFromSnapshot(snapshot){return snapshot.value===""&&snapshot.elements!==null?{elements:snapshot.elements,kind:"elements"}:{had:snapshot.had,kind:"attribute",value:snapshot.value}}function baselineElements(state){if(state.baseline.kind==="elements")return[...state.baseline.elements];try{return resolveIdReferencesIn(state.target.getRootNode(),state.baseline.value)}catch{return[]}}function relationshipElements(state,position){const elements=[],seen=new Set;for(const record of state.leases.values())if(record.position===position)for(const element of record.elements)seen.has(element)||(seen.add(element),elements.push(element));return elements}function projectedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...relationshipElements(state,"before"),...baselineElements(state),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function managedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...baselineElements(state),...relationshipElements(state,"before"),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function isIdResolvableFromTarget(target,element){if(!isSingleAsciiWhitespaceToken(element.id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(element.id)===element}catch{return!1}}function isIdResolvableIdFromTarget(target,id){if(!isSingleAsciiWhitespaceToken(id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(id)!==null}catch{return!1}}function setReflectedRelationshipElements(state,definition,elements){try{return state.writing+=1,Reflect.set(state.target,definition.property,elements===null?null:[...elements])}catch{return!1}finally{state.writing-=1}}function serializedRelationshipIds(state){const ids=[],seen=new Set,add=id=>{!id||seen.has(id)||(seen.add(id),ids.push(id))};for(const element of relationshipElements(state,"before"))isIdResolvableFromTarget(state.target,element)&&add(element.id);if(state.baseline.kind==="attribute")for(const id of asciiWhitespaceTokens(state.baseline.value))add(id);else for(const element of state.baseline.elements)isIdResolvableFromTarget(state.target,element)&&add(element.id);for(const element of relationshipElements(state,"after"))isIdResolvableFromTarget(state.target,element)&&add(element.id);return ids}function applyLatestRelationshipOwnership(state,definition,ownership){ownership.get(state.target)===state&&applyRelationshipOwnership(state,definition)}function applyRelationshipOwnership(state,definition){const before=relationshipElements(state,"before"),after=relationshipElements(state,"after");if(before.length===0&&after.length===0){restoreRelationshipBaseline(state,definition);return}const elements=projectedRelationshipElements(state),canReflect=definition.property in state.target,needsElementReferences=state.baseline.kind==="elements"||[...before,...after].some(element=>!isIdResolvableFromTarget(state.target,element));if(canReflect&&needsElementReferences&&setReflectedRelationshipElements(state,definition,elements)){setLastApplied(state,definition);return}canReflect&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);const ids=serializedRelationshipIds(state);try{state.writing+=1,ids.length>0?state.target.setAttribute(definition.attribute,ids.join(" ")):state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function restoreRelationshipBaseline(state,definition){if(state.baseline.kind==="elements"&&definition.property in state.target&&setReflectedRelationshipElements(state,definition,state.baseline.elements)){setLastApplied(state,definition);return}definition.property in state.target&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);try{state.writing+=1,state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,state.baseline.value??""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function adoptExternalRelationshipBaseline(state,definition,force=!1){if(state.writing>0)return!1;const current=relationshipSnapshot(state.target,definition);if(!force&&sameRelationshipSnapshot(current,state.lastApplied))return!1;if(!force&¤t.had===state.lastApplied.had&¤t.value===state.lastApplied.value)try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id)))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(wasResolvable&&!isIdResolvableFromTarget(state.target,element))return!1}catch{return!1}return state.baseline=baselineFromSnapshot(current),!0}function sameElementLists(first,second){return first.length===second.length&&first.every((element,index)=>element===second[index])}function clearRelationshipObserver(state,observer=state.observer){state.observer===observer&&(state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[]);try{observer?.disconnect()}catch{}}function processRelationshipRecords(state,definition,ownership,records){if(ownership.get(state.target)!==state||records.length===0)return;const targetChanged=records.some(record=>record.target===state.target&&record.type==="attributes"&&record.attributeName===definition.attribute);targetChanged&&adoptExternalRelationshipBaseline(state,definition,!0),(state.leases.size>0||targetChanged)&&(applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0))}function drainRelationshipObserver(state,definition,ownership){const observer=state.observer;if(!observer)return;let records;try{records=observer.takeRecords()}catch{clearRelationshipObserver(state,observer);return}processRelationshipRecords(state,definition,ownership,records)}function observeRelationshipOwnership(state,definition,ownership,force=!1){if(ownership.get(state.target)!==state||state.leases.size===0)return;let ownerDocument,root;try{ownerDocument=state.target.ownerDocument,root=state.target.getRootNode()}catch{return}const elements=managedRelationshipElements(state);if(!force&&state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&sameElementLists(state.observerElements,elements))return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[];try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(records=>{state.observer!==observer||state.observerGeneration!==generation||ownership.get(state.target)!==state||processRelationshipRecords(state,definition,ownership,records)})}catch{return}if(ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerElements=elements;try{observer.observe(state.target,{attributes:!0,attributeFilter:[definition.attribute]});for(const element of elements)element!==state.target&&observer.observe(element,{attributes:!0,attributeFilter:["id"]})}catch{clearRelationshipObserver(state,observer)}}function isRelationshipCurrent(state,definition){try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||!sameRelationshipSnapshot(relationshipSnapshot(state.target,definition),state.lastApplied))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(isIdResolvableFromTarget(state.target,element)!==wasResolvable)return!1;return!state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id))}catch{return!1}}function acquireFixedRelationship(target,elements,definition,position){const ownership=relationshipOwnership(definition.attribute);let state=ownership.get(target);if(state)drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition);else{const initial=relationshipSnapshot(target,definition);state={baseline:baselineFromSnapshot(initial),lastApplied:initial,lastAppliedDocument:target.ownerDocument,lastAppliedEndpointRoots:new Map,lastAppliedResolvability:new Map,lastAppliedRoot:target.getRootNode(),lastAppliedUnresolvedBaselineIds:[],leases:new Map,observerElements:[],observerGeneration:0,target,writing:0},ownership.set(target,state)}const token=Symbol(`aria-${definition.attribute}-owner`),record={elements:[...elements],position};state.leases.set(token,record),applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0);let active=!0;return{target,update(nextElements){if(!active||ownership.get(target)!==state)return;if(drainRelationshipObserver(state,definition,ownership),!adoptExternalRelationshipBaseline(state,definition)&&sameElementLists(record.elements,nextElements)&&isRelationshipCurrent(state,definition)){observeRelationshipOwnership(state,definition,ownership);return}record.elements=[...nextElements],applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0)},release(){active&&(active=!1,ownership.get(target)===state&&(drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition),state.leases.delete(token),applyLatestRelationshipOwnership(state,definition,ownership),state.leases.size===0?(clearRelationshipObserver(state),ownership.delete(target)):observeRelationshipOwnership(state,definition,ownership,!0)))}}}function updateExternalDescriptionBaseline(target,update){const state=descriptionOwnership.get(target);if(!state){update();return}drainRelationshipObserver(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),update(),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),applyLatestRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),observeRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership,!0)}registerDescriptionBaselineUpdater(updateExternalDescriptionBaseline);function acquireAriaDescription(target,descriptions){return acquireFixedRelationship(target,descriptions,DESCRIPTION_RELATIONSHIP,"after")}function acquireAriaControls(target,controls){return acquireFixedRelationship(target,controls,CONTROLS_RELATIONSHIP,"after")}function clearResolvedRelationshipObserver(state){const observer=state.observer;state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{observer?.disconnect()}catch{}}function resolvedRelationshipElements(state){try{return resolveIdReferencesIn(state.host.getRootNode(),state.host.getAttribute(state.relationship))}catch{return[]}}function refreshResolvedRelationship(state){!state.active||!state.target||!state.fixed||state.fixed.update(resolvedRelationshipElements(state))}function observeResolvedRelationship(state){if(!state.active)return;let ownerDocument,root;try{ownerDocument=state.host.ownerDocument,root=state.host.getRootNode()}catch{return}const watchesRoot=root!==state.host&&!asciiWhitespaceTokens(state.host.getAttribute(state.relationship)).next().done;if(state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&state.observerWatchesRoot===watchesRoot)return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||!state.active||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))})}catch{return}if(!state.active||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerWatchesRoot=watchesRoot;try{observer.observe(state.host,{attributes:!0,attributeFilter:[state.relationship]}),watchesRoot&&(state.stopRootObservation=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))}}))}catch{clearResolvedRelationshipObserver(state)}}function acquireResolvedAriaRelationship(host,initialTarget,relationship){const state={active:!0,host,observerGeneration:0,observerWatchesRoot:!1,relationship,target:null},definition=relationshipDefinition(relationship),update=nextTarget=>{if(state.active){if(state.target!==nextTarget){const previousFixed=state.fixed;state.fixed=void 0,state.target=nextTarget,previousFixed?.release(),nextTarget&&(state.fixed=acquireFixedRelationship(nextTarget,resolvedRelationshipElements(state),definition,"before"))}else refreshResolvedRelationship(state);observeResolvedRelationship(state)}},lease={host,relationship,get target(){return state.target},update,release(){if(!state.active)return;state.active=!1,clearResolvedRelationshipObserver(state);const fixed=state.fixed;state.fixed=void 0,state.target=null,fixed?.release()}};return update(initialTarget),lease}class HostDescriptionController{constructor(host,target,requiredDescriptions=()=>[]){this.host=host,this.target=target,this.requiredDescriptions=requiredDescriptions,host.addController(this)}hostConnected(){this.refresh()}hostUpdated(){this.refresh()}adopted(){this.release(),this.refresh()}hostDisconnected(){this.release()}refresh(){if(!this.host.isConnected)return;const target=this.target();if(this.external?this.external.update(target):this.external=acquireResolvedAriaRelationship(this.host,target,"aria-describedby"),!target){this.required?.release(),this.required=void 0;return}const descriptions=this.requiredDescriptions();if(!descriptions.length){this.required?.release(),this.required=void 0;return}this.required?.target!==target?(this.required?.release(),this.required=acquireAriaDescription(target,descriptions)):this.required.update(descriptions)}release(){this.required?.release(),this.required=void 0,this.external?.release(),this.external=void 0}}export{HostDescriptionController,acquireAriaControls,acquireAriaDescription,acquireResolvedAriaRelationship,syncAriaControlsElements,syncAriaDescribedByElements};
|
|
1
|
+
import{subscribeInheritedAttributes}from"./inherited-attribute-hub.js";import{asciiWhitespaceTokens,isSingleAsciiWhitespaceToken}from"./ascii-whitespace.js";import{sharedRealmRegistry}from"./a11y.js";import{registerDescriptionBaselineUpdater,resolveIdReferencesIn}from"./aria-reflection.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"./aria-reflection.js";const DESCRIPTION_RELATIONSHIP={attribute:"aria-describedby",property:"ariaDescribedByElements"},LABEL_RELATIONSHIP={attribute:"aria-labelledby",property:"ariaLabelledByElements"},CONTROLS_RELATIONSHIP={attribute:"aria-controls",property:"ariaControlsElements"},DESCRIPTION_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-description-ownership.v1"),LABEL_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-label-ownership.v1"),CONTROLS_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.aria-controls-relationship-ownership.v1"),fallbackDescriptionOwnership=new WeakMap,fallbackLabelOwnership=new WeakMap,fallbackControlsOwnership=new WeakMap,descriptionOwnership=sharedRealmRegistry(DESCRIPTION_OWNERSHIP,()=>new WeakMap,fallbackDescriptionOwnership),labelOwnership=sharedRealmRegistry(LABEL_OWNERSHIP,()=>new WeakMap,fallbackLabelOwnership),controlsOwnership=sharedRealmRegistry(CONTROLS_OWNERSHIP,()=>new WeakMap,fallbackControlsOwnership);function relationshipDefinition(relationship){return relationship==="aria-describedby"?DESCRIPTION_RELATIONSHIP:LABEL_RELATIONSHIP}function relationshipOwnership(relationship){return relationship==="aria-describedby"?descriptionOwnership:relationship==="aria-labelledby"?labelOwnership:controlsOwnership}function reflectedRelationshipElements(target,definition){if(!(definition.property in target))return null;try{const reflected=Reflect.get(target,definition.property);return reflected===null?null:[...reflected]}catch{return null}}function relationshipSnapshot(target,definition){return{elements:reflectedRelationshipElements(target,definition),had:target.hasAttribute(definition.attribute),value:target.getAttribute(definition.attribute)}}function setLastApplied(state,definition){state.lastApplied=relationshipSnapshot(state.target,definition),state.lastAppliedDocument=state.target.ownerDocument,state.lastAppliedEndpointRoots=new Map(projectedRelationshipElements(state).map(element=>[element,element.getRootNode()])),state.lastAppliedResolvability=new Map(projectedRelationshipElements(state).map(element=>[element,isIdResolvableFromTarget(state.target,element)])),state.lastAppliedRoot=state.target.getRootNode(),state.lastAppliedUnresolvedBaselineIds=state.baseline.kind==="attribute"?[...asciiWhitespaceTokens(state.baseline.value)].filter(id=>!isIdResolvableIdFromTarget(state.target,id)):[]}function sameElements(first,second){return first===null||second===null?first===second:first.length===second.length&&first.every((element,index)=>element===second[index])}function sameRelationshipSnapshot(first,second){return first.had===second.had&&first.value===second.value&&sameElements(first.elements,second.elements)}function baselineFromSnapshot(snapshot){return snapshot.value===""&&snapshot.elements!==null?{elements:snapshot.elements,kind:"elements"}:{had:snapshot.had,kind:"attribute",value:snapshot.value}}function baselineElements(state){if(state.baseline.kind==="elements")return[...state.baseline.elements];try{return resolveIdReferencesIn(state.target.getRootNode(),state.baseline.value)}catch{return[]}}function relationshipElements(state,position){const elements=[],seen=new Set;for(const record of state.leases.values())if(record.position===position)for(const element of record.elements)seen.has(element)||(seen.add(element),elements.push(element));return elements}function projectedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...relationshipElements(state,"before"),...baselineElements(state),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function managedRelationshipElements(state){const elements=[],seen=new Set;for(const element of[...baselineElements(state),...relationshipElements(state,"before"),...relationshipElements(state,"after")])seen.has(element)||(seen.add(element),elements.push(element));return elements}function isIdResolvableFromTarget(target,element){if(!isSingleAsciiWhitespaceToken(element.id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(element.id)===element}catch{return!1}}function isIdResolvableIdFromTarget(target,id){if(!isSingleAsciiWhitespaceToken(id))return!1;try{const root=target.getRootNode();return"getElementById"in root&&root.getElementById(id)!==null}catch{return!1}}function setReflectedRelationshipElements(state,definition,elements){try{return state.writing+=1,Reflect.set(state.target,definition.property,elements===null?null:[...elements])}catch{return!1}finally{state.writing-=1}}function serializedRelationshipIds(state){const ids=[],seen=new Set,add=id=>{!id||seen.has(id)||(seen.add(id),ids.push(id))};for(const element of relationshipElements(state,"before"))isIdResolvableFromTarget(state.target,element)&&add(element.id);if(state.baseline.kind==="attribute")for(const id of asciiWhitespaceTokens(state.baseline.value))add(id);else for(const element of state.baseline.elements)isIdResolvableFromTarget(state.target,element)&&add(element.id);for(const element of relationshipElements(state,"after"))isIdResolvableFromTarget(state.target,element)&&add(element.id);return ids}function applyLatestRelationshipOwnership(state,definition,ownership){ownership.get(state.target)===state&&applyRelationshipOwnership(state,definition)}function applyRelationshipOwnership(state,definition){const before=relationshipElements(state,"before"),after=relationshipElements(state,"after");if(before.length===0&&after.length===0){restoreRelationshipBaseline(state,definition);return}const elements=projectedRelationshipElements(state),canReflect=definition.property in state.target,needsElementReferences=state.baseline.kind==="elements"||[...before,...after].some(element=>!isIdResolvableFromTarget(state.target,element));if(canReflect&&needsElementReferences&&setReflectedRelationshipElements(state,definition,elements)){setLastApplied(state,definition);return}canReflect&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);const ids=serializedRelationshipIds(state);try{state.writing+=1,ids.length>0?state.target.setAttribute(definition.attribute,ids.join(" ")):state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function restoreRelationshipBaseline(state,definition){if(state.baseline.kind==="elements"&&definition.property in state.target&&setReflectedRelationshipElements(state,definition,state.baseline.elements)){setLastApplied(state,definition);return}definition.property in state.target&&state.lastApplied.value===""&&setReflectedRelationshipElements(state,definition,null);try{state.writing+=1,state.baseline.kind==="attribute"&&state.baseline.had?state.target.setAttribute(definition.attribute,state.baseline.value??""):state.target.removeAttribute(definition.attribute)}finally{state.writing-=1}setLastApplied(state,definition)}function adoptExternalRelationshipBaseline(state,definition,force=!1){if(state.writing>0)return!1;const current=relationshipSnapshot(state.target,definition);if(!force&&sameRelationshipSnapshot(current,state.lastApplied))return!1;if(!force&¤t.had===state.lastApplied.had&¤t.value===state.lastApplied.value)try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id)))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(wasResolvable&&!isIdResolvableFromTarget(state.target,element))return!1}catch{return!1}return state.baseline=baselineFromSnapshot(current),!0}function sameElementLists(first,second){return first.length===second.length&&first.every((element,index)=>element===second[index])}function clearRelationshipObserver(state,observer=state.observer){state.observer===observer&&(state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[]);try{observer?.disconnect()}catch{}}function processRelationshipRecords(state,definition,ownership,records){if(ownership.get(state.target)!==state||records.length===0)return;const targetChanged=records.some(record=>record.target===state.target&&record.type==="attributes"&&record.attributeName===definition.attribute);targetChanged&&adoptExternalRelationshipBaseline(state,definition,!0),(state.leases.size>0||targetChanged)&&(applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0))}function drainRelationshipObserver(state,definition,ownership){const observer=state.observer;if(!observer)return;let records;try{records=observer.takeRecords()}catch{clearRelationshipObserver(state,observer);return}processRelationshipRecords(state,definition,ownership,records)}function observeRelationshipOwnership(state,definition,ownership,force=!1){if(ownership.get(state.target)!==state||state.leases.size===0)return;let ownerDocument,root;try{ownerDocument=state.target.ownerDocument,root=state.target.getRootNode()}catch{return}const elements=managedRelationshipElements(state);if(!force&&state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&sameElementLists(state.observerElements,elements))return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerElements=[];try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(records=>{state.observer!==observer||state.observerGeneration!==generation||ownership.get(state.target)!==state||processRelationshipRecords(state,definition,ownership,records)})}catch{return}if(ownership.get(state.target)!==state||state.leases.size===0||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerElements=elements;try{observer.observe(state.target,{attributes:!0,attributeFilter:[definition.attribute]});for(const element of elements)element!==state.target&&observer.observe(element,{attributes:!0,attributeFilter:["id"]})}catch{clearRelationshipObserver(state,observer)}}function isRelationshipCurrent(state,definition){try{if(state.target.ownerDocument!==state.lastAppliedDocument||state.target.getRootNode()!==state.lastAppliedRoot||!sameRelationshipSnapshot(relationshipSnapshot(state.target,definition),state.lastApplied))return!1;for(const[element,root]of state.lastAppliedEndpointRoots)if(element.getRootNode()!==root)return!1;for(const[element,wasResolvable]of state.lastAppliedResolvability)if(isIdResolvableFromTarget(state.target,element)!==wasResolvable)return!1;return!state.lastAppliedUnresolvedBaselineIds.some(id=>isIdResolvableIdFromTarget(state.target,id))}catch{return!1}}function acquireFixedRelationship(target,elements,definition,position){const ownership=relationshipOwnership(definition.attribute);let state=ownership.get(target);if(state)drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition);else{const initial=relationshipSnapshot(target,definition);state={baseline:baselineFromSnapshot(initial),lastApplied:initial,lastAppliedDocument:target.ownerDocument,lastAppliedEndpointRoots:new Map,lastAppliedResolvability:new Map,lastAppliedRoot:target.getRootNode(),lastAppliedUnresolvedBaselineIds:[],leases:new Map,observerElements:[],observerGeneration:0,target,writing:0},ownership.set(target,state)}const token=Symbol(`aria-${definition.attribute}-owner`),record={elements:[...elements],position};state.leases.set(token,record),applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0);let active=!0;return{target,update(nextElements){if(!active||ownership.get(target)!==state)return;if(drainRelationshipObserver(state,definition,ownership),!adoptExternalRelationshipBaseline(state,definition)&&sameElementLists(record.elements,nextElements)&&isRelationshipCurrent(state,definition)){observeRelationshipOwnership(state,definition,ownership);return}record.elements=[...nextElements],applyLatestRelationshipOwnership(state,definition,ownership),observeRelationshipOwnership(state,definition,ownership,!0)},release(){active&&(active=!1,ownership.get(target)===state&&(drainRelationshipObserver(state,definition,ownership),adoptExternalRelationshipBaseline(state,definition),state.leases.delete(token),applyLatestRelationshipOwnership(state,definition,ownership),state.leases.size===0?(clearRelationshipObserver(state),ownership.delete(target)):observeRelationshipOwnership(state,definition,ownership,!0)))}}}function updateExternalDescriptionBaseline(target,update){const state=descriptionOwnership.get(target);if(!state){update();return}drainRelationshipObserver(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),update(),adoptExternalRelationshipBaseline(state,DESCRIPTION_RELATIONSHIP),applyLatestRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership),observeRelationshipOwnership(state,DESCRIPTION_RELATIONSHIP,descriptionOwnership,!0)}registerDescriptionBaselineUpdater(updateExternalDescriptionBaseline);function acquireAriaDescription(target,descriptions){return acquireFixedRelationship(target,descriptions,DESCRIPTION_RELATIONSHIP,"after")}function acquireAriaControls(target,controls){return acquireFixedRelationship(target,controls,CONTROLS_RELATIONSHIP,"after")}function clearResolvedRelationshipObserver(state){const observer=state.observer;state.observerGeneration+=1,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{observer?.disconnect()}catch{}}function resolvedRelationshipElements(state){try{return resolveIdReferencesIn(state.host.getRootNode(),state.host.getAttribute(state.relationship))}catch{return[]}}function refreshResolvedRelationship(state){!state.active||!state.target||!state.fixed||state.fixed.update(resolvedRelationshipElements(state))}function observeResolvedRelationship(state){if(!state.active)return;let ownerDocument,root;try{ownerDocument=state.host.ownerDocument,root=state.host.getRootNode()}catch{return}const watchesRoot=root!==state.host&&!asciiWhitespaceTokens(state.host.getAttribute(state.relationship)).next().done;if(state.observer&&state.observerDocument===ownerDocument&&state.observerRoot===root&&state.observerWatchesRoot===watchesRoot)return;const previousObserver=state.observer,generation=state.observerGeneration+1;state.observerGeneration=generation,state.observer=void 0,state.observerDocument=void 0,state.observerRoot=void 0,state.observerWatchesRoot=!1,state.stopRootObservation?.(),state.stopRootObservation=void 0;try{previousObserver?.disconnect()}catch{}let Observer;try{Observer=ownerDocument.defaultView?.MutationObserver}catch{return}if(!Observer||!state.active||state.observerGeneration!==generation)return;let observer;try{observer=new Observer(()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))})}catch{return}if(!state.active||state.observerGeneration!==generation){try{observer.disconnect()}catch{}return}state.observer=observer,state.observerDocument=ownerDocument,state.observerRoot=root,state.observerWatchesRoot=watchesRoot;try{observer.observe(state.host,{attributes:!0,attributeFilter:[state.relationship]}),watchesRoot&&(state.stopRootObservation=subscribeInheritedAttributes(root,Observer,{attributes:["id"],childList:!0,changed:()=>{!state.active||state.observer!==observer||state.observerGeneration!==generation||(refreshResolvedRelationship(state),observeResolvedRelationship(state))}}))}catch{clearResolvedRelationshipObserver(state)}}function acquireResolvedAriaRelationship(host,initialTarget,relationship){const state={active:!0,host,observerGeneration:0,observerWatchesRoot:!1,relationship,target:null},definition=relationshipDefinition(relationship),update=nextTarget=>{if(state.active){if(state.target!==nextTarget){const previousFixed=state.fixed;state.fixed=void 0,state.target=nextTarget,previousFixed?.release(),nextTarget&&(state.fixed=acquireFixedRelationship(nextTarget,resolvedRelationshipElements(state),definition,"before"))}else refreshResolvedRelationship(state);observeResolvedRelationship(state)}},lease={host,relationship,get target(){return state.target},update,release(){if(!state.active)return;state.active=!1,clearResolvedRelationshipObserver(state);const fixed=state.fixed;state.fixed=void 0,state.target=null,fixed?.release()}};return update(initialTarget),lease}class HostDescriptionController{constructor(host,target,requiredDescriptions=()=>[]){this.host=host,this.target=target,this.requiredDescriptions=requiredDescriptions,host.addController(this)}hostConnected(){this.refresh()}hostUpdated(){this.refresh()}adopted(){this.release(),this.refresh()}hostDisconnected(){this.release()}refresh(){if(!this.host.isConnected)return;const lit=this.host;if(typeof lit.createRenderRoot=="function"&&lit.renderRoot===void 0)return;const target=this.target();if(this.external?this.external.update(target):this.external=acquireResolvedAriaRelationship(this.host,target,"aria-describedby"),!target){this.required?.release(),this.required=void 0;return}const descriptions=this.requiredDescriptions();if(!descriptions.length){this.required?.release(),this.required=void 0;return}this.required?.target!==target?(this.required?.release(),this.required=acquireAriaDescription(target,descriptions)):this.required.update(descriptions)}release(){this.required?.release(),this.required=void 0,this.external?.release(),this.external=void 0}}export{HostDescriptionController,acquireAriaControls,acquireAriaDescription,acquireResolvedAriaRelationship,syncAriaControlsElements,syncAriaDescribedByElements};
|