@aceshooting/lyra-ui 29.1.0 → 29.2.0

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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 29.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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`.
8
+
9
+ ### Patch Changes
10
+
11
+ - 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.
12
+ - 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).
13
+
14
+ `lr-avatar-group` also no longer throws when moved into another document before its first render.
15
+ - 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.
16
+ - 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.
17
+ - Updated dependencies [5112ff8]
18
+ - @aceshooting/lyra-map@1.2.0
19
+ - @aceshooting/lyra-translations@29.2.0
20
+
3
21
  ## 29.1.0
4
22
 
5
23
  ### 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.** 66 optional catalogs in `@aceshooting/lyra-translations` plus built-in English
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
 
@@ -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.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)),highlighted.has(number)?line.part.add("line-highlight"):line.part.remove("line-highlight"))}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
+ 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 +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{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&&current.had===state.lastApplied.had&&current.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&&current.had===state.lastApplied.had&&current.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};
@@ -1 +1 @@
1
- const localeLoaders=Object.freeze({am:()=>import("@aceshooting/lyra-translations/am.js"),ar:()=>import("@aceshooting/lyra-translations/ar.js"),bho:()=>import("@aceshooting/lyra-translations/bho.js"),bn:()=>import("@aceshooting/lyra-translations/bn.js"),cs:()=>import("@aceshooting/lyra-translations/cs.js"),da:()=>import("@aceshooting/lyra-translations/da.js"),de:()=>import("@aceshooting/lyra-translations/de.js"),"de-CH":()=>import("@aceshooting/lyra-translations/de-CH.js"),el:()=>import("@aceshooting/lyra-translations/el.js"),es:()=>import("@aceshooting/lyra-translations/es.js"),fa:()=>import("@aceshooting/lyra-translations/fa.js"),"fa-AF":()=>import("@aceshooting/lyra-translations/fa-AF.js"),fi:()=>import("@aceshooting/lyra-translations/fi.js"),fil:()=>import("@aceshooting/lyra-translations/tl.js"),fr:()=>import("@aceshooting/lyra-translations/fr.js"),gu:()=>import("@aceshooting/lyra-translations/gu.js"),ha:()=>import("@aceshooting/lyra-translations/ha.js"),he:()=>import("@aceshooting/lyra-translations/he.js"),hi:()=>import("@aceshooting/lyra-translations/hi.js"),hr:()=>import("@aceshooting/lyra-translations/hr.js"),hu:()=>import("@aceshooting/lyra-translations/hu.js"),id:()=>import("@aceshooting/lyra-translations/id.js"),ig:()=>import("@aceshooting/lyra-translations/ig.js"),it:()=>import("@aceshooting/lyra-translations/it.js"),ja:()=>import("@aceshooting/lyra-translations/ja.js"),jv:()=>import("@aceshooting/lyra-translations/jv.js"),kk:()=>import("@aceshooting/lyra-translations/kk.js"),kn:()=>import("@aceshooting/lyra-translations/kn.js"),ko:()=>import("@aceshooting/lyra-translations/ko.js"),lah:()=>import("@aceshooting/lyra-translations/pnb.js"),ln:()=>import("@aceshooting/lyra-translations/ln.js"),ml:()=>import("@aceshooting/lyra-translations/ml.js"),mr:()=>import("@aceshooting/lyra-translations/mr.js"),ms:()=>import("@aceshooting/lyra-translations/ms.js"),my:()=>import("@aceshooting/lyra-translations/my.js"),nb:()=>import("@aceshooting/lyra-translations/nb.js"),ne:()=>import("@aceshooting/lyra-translations/ne.js"),nl:()=>import("@aceshooting/lyra-translations/nl.js"),nn:()=>import("@aceshooting/lyra-translations/nn.js"),om:()=>import("@aceshooting/lyra-translations/om.js"),or:()=>import("@aceshooting/lyra-translations/or.js"),pa:()=>import("@aceshooting/lyra-translations/pa.js"),pcm:()=>import("@aceshooting/lyra-translations/pcm.js"),pl:()=>import("@aceshooting/lyra-translations/pl.js"),ps:()=>import("@aceshooting/lyra-translations/ps.js"),"pt-BR":()=>import("@aceshooting/lyra-translations/pt-BR.js"),"pt-PT":()=>import("@aceshooting/lyra-translations/pt-PT.js"),ro:()=>import("@aceshooting/lyra-translations/ro.js"),ru:()=>import("@aceshooting/lyra-translations/ru.js"),sd:()=>import("@aceshooting/lyra-translations/sd.js"),sl:()=>import("@aceshooting/lyra-translations/sl.js"),su:()=>import("@aceshooting/lyra-translations/su.js"),sv:()=>import("@aceshooting/lyra-translations/sv.js"),sw:()=>import("@aceshooting/lyra-translations/sw.js"),ta:()=>import("@aceshooting/lyra-translations/ta.js"),te:()=>import("@aceshooting/lyra-translations/te.js"),th:()=>import("@aceshooting/lyra-translations/th.js"),tr:()=>import("@aceshooting/lyra-translations/tr.js"),uk:()=>import("@aceshooting/lyra-translations/uk.js"),ur:()=>import("@aceshooting/lyra-translations/ur.js"),uz:()=>import("@aceshooting/lyra-translations/uz.js"),vi:()=>import("@aceshooting/lyra-translations/vi.js"),yo:()=>import("@aceshooting/lyra-translations/yo.js"),"zh-CN":()=>import("@aceshooting/lyra-translations/zh-CN.js"),"zh-TW":()=>import("@aceshooting/lyra-translations/zh-TW.js"),zu:()=>import("@aceshooting/lyra-translations/zu.js")});export{localeLoaders};
1
+ const localeLoaders=Object.freeze({am:()=>import("@aceshooting/lyra-translations/am.js"),ar:()=>import("@aceshooting/lyra-translations/ar.js"),bho:()=>import("@aceshooting/lyra-translations/bho.js"),bn:()=>import("@aceshooting/lyra-translations/bn.js"),cs:()=>import("@aceshooting/lyra-translations/cs.js"),da:()=>import("@aceshooting/lyra-translations/da.js"),de:()=>import("@aceshooting/lyra-translations/de.js"),"de-CH":()=>import("@aceshooting/lyra-translations/de-CH.js"),el:()=>import("@aceshooting/lyra-translations/el.js"),"en-GB":()=>import("@aceshooting/lyra-translations/en-GB.js"),es:()=>import("@aceshooting/lyra-translations/es.js"),"es-419":()=>import("@aceshooting/lyra-translations/es-419.js"),fa:()=>import("@aceshooting/lyra-translations/fa.js"),"fa-AF":()=>import("@aceshooting/lyra-translations/fa-AF.js"),fi:()=>import("@aceshooting/lyra-translations/fi.js"),fil:()=>import("@aceshooting/lyra-translations/tl.js"),fr:()=>import("@aceshooting/lyra-translations/fr.js"),"fr-CA":()=>import("@aceshooting/lyra-translations/fr-CA.js"),gu:()=>import("@aceshooting/lyra-translations/gu.js"),ha:()=>import("@aceshooting/lyra-translations/ha.js"),he:()=>import("@aceshooting/lyra-translations/he.js"),hi:()=>import("@aceshooting/lyra-translations/hi.js"),hr:()=>import("@aceshooting/lyra-translations/hr.js"),hu:()=>import("@aceshooting/lyra-translations/hu.js"),id:()=>import("@aceshooting/lyra-translations/id.js"),ig:()=>import("@aceshooting/lyra-translations/ig.js"),it:()=>import("@aceshooting/lyra-translations/it.js"),ja:()=>import("@aceshooting/lyra-translations/ja.js"),jv:()=>import("@aceshooting/lyra-translations/jv.js"),kk:()=>import("@aceshooting/lyra-translations/kk.js"),kn:()=>import("@aceshooting/lyra-translations/kn.js"),ko:()=>import("@aceshooting/lyra-translations/ko.js"),lah:()=>import("@aceshooting/lyra-translations/pnb.js"),ln:()=>import("@aceshooting/lyra-translations/ln.js"),ml:()=>import("@aceshooting/lyra-translations/ml.js"),mr:()=>import("@aceshooting/lyra-translations/mr.js"),ms:()=>import("@aceshooting/lyra-translations/ms.js"),my:()=>import("@aceshooting/lyra-translations/my.js"),nb:()=>import("@aceshooting/lyra-translations/nb.js"),ne:()=>import("@aceshooting/lyra-translations/ne.js"),nl:()=>import("@aceshooting/lyra-translations/nl.js"),nn:()=>import("@aceshooting/lyra-translations/nn.js"),om:()=>import("@aceshooting/lyra-translations/om.js"),or:()=>import("@aceshooting/lyra-translations/or.js"),pa:()=>import("@aceshooting/lyra-translations/pa.js"),pcm:()=>import("@aceshooting/lyra-translations/pcm.js"),pl:()=>import("@aceshooting/lyra-translations/pl.js"),ps:()=>import("@aceshooting/lyra-translations/ps.js"),"pt-BR":()=>import("@aceshooting/lyra-translations/pt-BR.js"),"pt-PT":()=>import("@aceshooting/lyra-translations/pt-PT.js"),ro:()=>import("@aceshooting/lyra-translations/ro.js"),ru:()=>import("@aceshooting/lyra-translations/ru.js"),sd:()=>import("@aceshooting/lyra-translations/sd.js"),sl:()=>import("@aceshooting/lyra-translations/sl.js"),su:()=>import("@aceshooting/lyra-translations/su.js"),sv:()=>import("@aceshooting/lyra-translations/sv.js"),sw:()=>import("@aceshooting/lyra-translations/sw.js"),ta:()=>import("@aceshooting/lyra-translations/ta.js"),te:()=>import("@aceshooting/lyra-translations/te.js"),th:()=>import("@aceshooting/lyra-translations/th.js"),tr:()=>import("@aceshooting/lyra-translations/tr.js"),uk:()=>import("@aceshooting/lyra-translations/uk.js"),ur:()=>import("@aceshooting/lyra-translations/ur.js"),uz:()=>import("@aceshooting/lyra-translations/uz.js"),vi:()=>import("@aceshooting/lyra-translations/vi.js"),yo:()=>import("@aceshooting/lyra-translations/yo.js"),"zh-CN":()=>import("@aceshooting/lyra-translations/zh-CN.js"),"zh-HK":()=>import("@aceshooting/lyra-translations/zh-HK.js"),"zh-TW":()=>import("@aceshooting/lyra-translations/zh-TW.js"),zu:()=>import("@aceshooting/lyra-translations/zu.js")});export{localeLoaders};
@@ -1 +1 @@
1
- import{getActiveNativeModal,isPageHelperRegion}from"./native-modal-context.js";import{activateNonmodalOverlay}from"./nonmodal-overlay-manager.js";import{RenderedStateController}from"./rendered-state.js";import{lockScroll}from"./scroll-lock.js";import{acquireOverlayRoutingSuspension,activateOverlayStack,observeOverlayStack}from"./overlay-stack.js";const EMPTY_STACK={entries:[]},modalStates=new WeakMap;function authoredOverlayInert(host){const state=modalStates.get(host.ownerDocument);if(!state)return host.inert;const records=state.observer?.takeRecords();return records?.length&&handleMutations(state,records),state.inerted.get(host)??host.inert}function modalStateFor(doc){const existing=modalStates.get(doc);if(existing)return existing;const state={document:doc,snapshot:EMPTY_STACK,registrations:0,externalModalSuspensions:new Set,inerted:new Map,pendingInertWrites:new Map,observedRoots:new Set,allowedParents:new Set,inertUpdateQueued:!1,started:!1};return modalStates.set(doc,state),state}function scheduleInertUpdate(state){state.inertUpdateQueued||(state.inertUpdateQueued=!0,queueMicrotask(()=>{state.inertUpdateQueued=!1,applyTopmostInert(state)}))}function pruneExternalModalSuspensions(state){let changed=!1;for(const entry of state.externalModalSuspensions)entry.root.isConnected&&entry.root.ownerDocument===state.document||(entry.active=!1,state.externalModalSuspensions.delete(entry),entry.releaseRouting(),changed=!0);return changed}function movesStackHost(state,record){for(const entry of state.snapshot.entries)for(const list of[record.addedNodes,record.removedNodes])for(const node of list)if(node.contains(entry.host))return!0;return!1}function handleMutations(state,records){const prunedExternalModal=pruneExternalModalSuspensions(state);let needsInertUpdate=prunedExternalModal;for(let index=0;index<records.length;index++){const record=records[index];if(!record)continue;if(record.type==="childList"){(state.allowedParents.has(record.target)||movesStackHost(state,record))&&(needsInertUpdate=!0);continue}if(record.attributeName==="open"){needsInertUpdate=!0;continue}const element=record.target;let nextRecord;for(let nextIndex=index+1;nextIndex<records.length;nextIndex++){const candidate=records[nextIndex];if(candidate?.type==="attributes"&&candidate.attributeName==="inert"&&candidate.target===element){nextRecord=candidate;break}}const newValue=nextRecord?nextRecord.oldValue!==null:element.hasAttribute("inert"),pending=state.pendingInertWrites.get(element);if(pending?.[0]===newValue){pending.shift(),pending.length===0&&state.pendingInertWrites.delete(element);continue}state.inerted.has(element)&&(state.inerted.set(element,newValue),needsInertUpdate=!0)}needsInertUpdate&&(prunedExternalModal?applyTopmostInert(state):scheduleInertUpdate(state)),stopModalStateIfIdle(state)}const mutationObserverOptions={attributeFilter:["inert","open"],attributeOldValue:!0,attributes:!0,childList:!0,subtree:!0};function observeMutationRoot(state,root){!state.observer||state.observedRoots.has(root)||(state.observer.observe(root===state.document?state.document.documentElement:root,mutationObserverOptions),state.observedRoots.add(root))}function startModalState(state){if(state.started)return;state.started=!0;const Observer=state.document.defaultView?.MutationObserver??MutationObserver;state.observer=new Observer(records=>handleMutations(state,records)),observeMutationRoot(state,state.document),state.unsubscribeStack=observeOverlayStack(state.document,snapshot=>{state.snapshot=snapshot,applyTopmostInert(state)})}function stopModalState(state){if(state.started){state.started=!1,state.unsubscribeStack?.(),state.unsubscribeStack=void 0;for(const[element,intended]of state.inerted)element.inert=intended;state.inerted.clear(),state.observer?.disconnect(),state.observer=void 0,state.observedRoots.clear(),state.pendingInertWrites.clear(),state.snapshot=EMPTY_STACK}}function stopModalStateIfIdle(state){state.registrations===0&&state.externalModalSuspensions.size===0&&stopModalState(state)}function retainModalState(doc){const state=modalStateFor(doc);state.registrations++,startModalState(state);let active=!0;return()=>{active&&(active=!1,state.registrations--,stopModalStateIfIdle(state))}}function setInertByManager(state,element,value){if(element.inert!==value){if(state.observer&&state.observedRoots.has(element.getRootNode())){let pending=state.pendingInertWrites.get(element);pending||(pending=[],state.pendingInertWrites.set(element,pending)),pending.push(value)}else state.pendingInertWrites.delete(element);element.inert=value}}function inertElement(state,element,desired){if(!("inert"in element)||element.localName==="dialog"&&element.matches(":modal")||isPageHelperRegion(element))return;const htmlElement=element;desired.add(htmlElement),state.inerted.has(htmlElement)||state.inerted.set(htmlElement,htmlElement.inert),setInertByManager(state,htmlElement,!0)}function pathParent(element){return element.assignedSlot??element.parentNode}function parentPathElement(parent){return parent.nodeType===Node.ELEMENT_NODE?parent:parent.host??null}function composedChildren(parent){return parent.localName==="slot"?parent.assignedElements({flatten:!0}):"children"in parent?Array.from(parent.children):[]}function isShadowRoot(node){return node.nodeType===11&&"host"in node}function addAllowedPath(allowed,host,doc){let current=host;for(;current&&current!==doc.body&&current!==doc.documentElement;){const parent=pathParent(current);if(!parent)break;let children=allowed.get(parent);children||(children=new Set,allowed.set(parent,children)),children.add(current),current=parentPathElement(parent)}}function modalAllowedRoot(entry,doc){const explicit=entry.modalRoot?.()??null;return explicit?.isConnected&&explicit.ownerDocument===doc?explicit:entry.host}function applyTopmostInert(state){let modalIndex=-1;for(let index=state.snapshot.entries.length-1;index>=0;index--)if(state.snapshot.entries[index]?.modal){modalIndex=index;break}const desired=new Set;if(state.allowedParents=new Set,state.externalModalSuspensions.size>0){const allowed=new Map;for(const suspension of state.externalModalSuspensions)addAllowedPath(allowed,suspension.root,state.document);inertOutsideAllowedPaths(state,allowed,desired)}else if(modalIndex!==-1){const allowed=new Map;for(const entry of state.snapshot.entries.slice(modalIndex))if(entry.host.isConnected){addAllowedPath(allowed,modalAllowedRoot(entry,state.document),state.document);for(const root of entry.auxiliaryRoots?.()??[])root.isConnected&&root.ownerDocument===state.document&&addAllowedPath(allowed,root,state.document)}const nativeModal=getActiveNativeModal(state.document);nativeModal&&addAllowedPath(allowed,nativeModal,state.document),inertOutsideAllowedPaths(state,allowed,desired)}for(const[element,intended]of state.inerted)desired.has(element)||(setInertByManager(state,element,intended),state.inerted.delete(element))}function inertOutsideAllowedPaths(state,allowed,desired){for(const[parent,children]of allowed){state.allowedParents.add(parent),isShadowRoot(parent)&&observeMutationRoot(state,parent);for(const child of composedChildren(parent))children.has(child)||inertElement(state,child,desired)}}function activateOverlay(options){if(options.modal===!1&&options.trapFocus===!1&&!options.suspendWhenUnrendered&&!options.lockScroll)return activateNonmodalOverlay(options);const modal=options.modal!==!1;let releaseModalState,releaseScrollLock,renderedState;const coreHandle=activateOverlayStack({...options,initiallySuspended:options.suspendWhenUnrendered===!0,modal,trapFocus:options.trapFocus!==!1,onRegistered:doc=>{modal&&(releaseModalState=retainModalState(doc)),options.lockScroll&&(releaseScrollLock=lockScroll(doc))},onUnregistered:(_doc,deferResourceRelease)=>{const releaseModal=releaseModalState;releaseModalState=void 0;const release=releaseScrollLock;releaseScrollLock=void 0;const deferredRelease=release&&deferResourceRelease?release:void 0;return release&&!deferResourceRelease&&release(),releaseModal?.(),deferredRelease},onDeactivate:()=>renderedState?.stop()});return coreHandle.isActive()?(options.suspendWhenUnrendered&&(renderedState=new RenderedStateController(options.host,options.panel,rendered=>{if(!coreHandle.isActive())return;if(!rendered){coreHandle.suspend();return}const wasTopmost=coreHandle.isTopmost();coreHandle.resume(),!wasTopmost&&coreHandle.isTopmost()&&queueMicrotask(()=>coreHandle.focusInitial())}),renderedState.start()),{focusInitial:()=>{renderedState?.check(),coreHandle.focusInitial()},focusAutofocus:()=>(renderedState?.check(),coreHandle.focusAutofocus()),updateRestoreFocusTo:target=>coreHandle.updateRestoreFocusTo(target),deactivate:deactivateOptions=>coreHandle.deactivate(deactivateOptions),suspend:()=>coreHandle.suspend(),resume:()=>{renderedState&&!renderedState.check()||coreHandle.resume()},isTopmost:()=>(renderedState?.check(),coreHandle.isTopmost()),isActive:()=>coreHandle.isActive(),dismissBackdrop:()=>(renderedState?.check(),coreHandle.dismissBackdrop())}):coreHandle}function suspendLyraModalsFor(externalModal){if(!externalModal.isConnected)return()=>{};const state=modalStateFor(externalModal.ownerDocument);startModalState(state);const entry={root:externalModal,active:!0,releaseRouting:()=>{},state};return state.externalModalSuspensions.add(entry),entry.releaseRouting=acquireOverlayRoutingSuspension(state.document),applyTopmostInert(state),()=>{entry.active&&(entry.active=!1,entry.state.externalModalSuspensions.delete(entry),entry.releaseRouting(),applyTopmostInert(entry.state),stopModalStateIfIdle(entry.state))}}import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement}from"./overlay-stack.js";export{activateOverlay,authoredOverlayInert,collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,suspendLyraModalsFor};
1
+ import{getActiveNativeModal,isPageHelperRegion}from"./native-modal-context.js";import{activateNonmodalOverlay}from"./nonmodal-overlay-manager.js";import{RenderedStateController}from"./rendered-state.js";import{lockScroll}from"./scroll-lock.js";import{acquireOverlayRoutingSuspension,activateOverlayStack,composedContains,observeOverlayStack}from"./overlay-stack.js";const EMPTY_STACK={entries:[]},modalStates=new WeakMap;function authoredOverlayInert(host){const state=modalStates.get(host.ownerDocument);if(!state)return host.inert;const records=state.observer?.takeRecords();return records?.length&&handleMutations(state,records),state.inerted.get(host)??host.inert}function modalStateFor(doc){const existing=modalStates.get(doc);if(existing)return existing;const state={document:doc,snapshot:EMPTY_STACK,registrations:0,externalModalSuspensions:new Set,inerted:new Map,pendingInertWrites:new Map,observedRoots:new Set,allowedParents:new Set,inertUpdateQueued:!1,started:!1};return modalStates.set(doc,state),state}function scheduleInertUpdate(state){state.inertUpdateQueued||(state.inertUpdateQueued=!0,queueMicrotask(()=>{state.inertUpdateQueued=!1,applyTopmostInert(state)}))}function pruneExternalModalSuspensions(state){let changed=!1;for(const entry of state.externalModalSuspensions)entry.root.isConnected&&entry.root.ownerDocument===state.document||(entry.active=!1,state.externalModalSuspensions.delete(entry),entry.releaseRouting(),changed=!0);return changed}function movesStackHost(state,record){for(const entry of state.snapshot.entries)for(const list of[record.addedNodes,record.removedNodes])for(const node of list)if(node.contains(entry.host))return!0;return!1}function handleMutations(state,records){const prunedExternalModal=pruneExternalModalSuspensions(state);let needsInertUpdate=prunedExternalModal;for(let index=0;index<records.length;index++){const record=records[index];if(!record)continue;if(record.type==="childList"){(state.allowedParents.has(record.target)||movesStackHost(state,record))&&(needsInertUpdate=!0);continue}if(record.attributeName==="open"){needsInertUpdate=!0;continue}const element=record.target;let nextRecord;for(let nextIndex=index+1;nextIndex<records.length;nextIndex++){const candidate=records[nextIndex];if(candidate?.type==="attributes"&&candidate.attributeName==="inert"&&candidate.target===element){nextRecord=candidate;break}}const newValue=nextRecord?nextRecord.oldValue!==null:element.hasAttribute("inert"),pending=state.pendingInertWrites.get(element);if(pending?.[0]===newValue){pending.shift(),pending.length===0&&state.pendingInertWrites.delete(element);continue}state.inerted.has(element)&&(state.inerted.set(element,newValue),needsInertUpdate=!0)}needsInertUpdate&&(prunedExternalModal?applyTopmostInert(state):scheduleInertUpdate(state)),stopModalStateIfIdle(state)}const mutationObserverOptions={attributeFilter:["inert","open"],attributeOldValue:!0,attributes:!0,childList:!0,subtree:!0};function observeMutationRoot(state,root){!state.observer||state.observedRoots.has(root)||(state.observer.observe(root===state.document?state.document.documentElement:root,mutationObserverOptions),state.observedRoots.add(root))}function startModalState(state){if(state.started)return;state.started=!0;const Observer=state.document.defaultView?.MutationObserver??MutationObserver;state.observer=new Observer(records=>handleMutations(state,records)),observeMutationRoot(state,state.document),state.unsubscribeStack=observeOverlayStack(state.document,snapshot=>{state.snapshot=snapshot,applyTopmostInert(state)})}function stopModalState(state){if(state.started){state.started=!1,state.unsubscribeStack?.(),state.unsubscribeStack=void 0;for(const[element,intended]of state.inerted)element.inert=intended;state.inerted.clear(),state.observer?.disconnect(),state.observer=void 0,state.observedRoots.clear(),state.pendingInertWrites.clear(),state.snapshot=EMPTY_STACK}}function stopModalStateIfIdle(state){state.registrations===0&&state.externalModalSuspensions.size===0&&stopModalState(state)}function retainModalState(doc){const state=modalStateFor(doc);state.registrations++,startModalState(state);let active=!0;return()=>{active&&(active=!1,state.registrations--,stopModalStateIfIdle(state))}}function setInertByManager(state,element,value){if(element.inert!==value){if(state.observer&&state.observedRoots.has(element.getRootNode())){let pending=state.pendingInertWrites.get(element);pending||(pending=[],state.pendingInertWrites.set(element,pending)),pending.push(value)}else state.pendingInertWrites.delete(element);element.inert=value}}function inertElement(state,element,desired){if(!("inert"in element)||element.localName==="dialog"&&element.matches(":modal")||isPageHelperRegion(element))return;const htmlElement=element;desired.add(htmlElement),state.inerted.has(htmlElement)||state.inerted.set(htmlElement,htmlElement.inert),setInertByManager(state,htmlElement,!0)}function pathParent(element){return element.assignedSlot??element.parentNode}function parentPathElement(parent){return parent.nodeType===Node.ELEMENT_NODE?parent:parent.host??null}function composedChildren(parent){return parent.localName==="slot"?parent.assignedElements({flatten:!0}):"children"in parent?Array.from(parent.children):[]}function isShadowRoot(node){return node.nodeType===11&&"host"in node}function addAllowedPath(allowed,host,doc){let current=host;for(;current&&current!==doc.body&&current!==doc.documentElement;){const parent=pathParent(current);if(!parent)break;let children=allowed.get(parent);children||(children=new Set,allowed.set(parent,children)),children.add(current),current=parentPathElement(parent)}}function modalAllowedRoot(entry,doc){const explicit=entry.modalRoot?.()??null;return explicit?.isConnected&&explicit.ownerDocument===doc?explicit:entry.host}function applyTopmostInert(state){let modalIndex=-1;for(let index=state.snapshot.entries.length-1;index>=0;index--)if(state.snapshot.entries[index]?.modal){modalIndex=index;break}const desired=new Set;if(state.allowedParents=new Set,state.externalModalSuspensions.size>0){const allowed=new Map;for(const suspension of state.externalModalSuspensions)addAllowedPath(allowed,suspension.root,state.document);inertOutsideAllowedPaths(state,allowed,desired)}else if(modalIndex!==-1){const allowed=new Map,interactiveRoots=[];for(const entry of state.snapshot.entries.slice(modalIndex)){if(!entry.host.isConnected||interactiveRoots.some(root=>composedContains(root,entry.host)))continue;const modalRoot=modalAllowedRoot(entry,state.document);addAllowedPath(allowed,modalRoot,state.document),interactiveRoots.push(modalRoot);for(const root of entry.auxiliaryRoots?.()??[])root.isConnected&&root.ownerDocument===state.document&&(addAllowedPath(allowed,root,state.document),interactiveRoots.push(root))}const nativeModal=getActiveNativeModal(state.document);nativeModal&&addAllowedPath(allowed,nativeModal,state.document),inertOutsideAllowedPaths(state,allowed,desired)}for(const[element,intended]of state.inerted)desired.has(element)||(setInertByManager(state,element,intended),state.inerted.delete(element))}function inertOutsideAllowedPaths(state,allowed,desired){for(const[parent,children]of allowed){state.allowedParents.add(parent),isShadowRoot(parent)&&observeMutationRoot(state,parent);for(const child of composedChildren(parent))children.has(child)||inertElement(state,child,desired)}}function activateOverlay(options){if(options.modal===!1&&options.trapFocus===!1&&!options.suspendWhenUnrendered&&!options.lockScroll)return activateNonmodalOverlay(options);const modal=options.modal!==!1;let releaseModalState,releaseScrollLock,renderedState;const coreHandle=activateOverlayStack({...options,initiallySuspended:options.suspendWhenUnrendered===!0,modal,trapFocus:options.trapFocus!==!1,onRegistered:doc=>{modal&&(releaseModalState=retainModalState(doc)),options.lockScroll&&(releaseScrollLock=lockScroll(doc))},onUnregistered:(_doc,deferResourceRelease)=>{const releaseModal=releaseModalState;releaseModalState=void 0;const release=releaseScrollLock;releaseScrollLock=void 0;const deferredRelease=release&&deferResourceRelease?release:void 0;return release&&!deferResourceRelease&&release(),releaseModal?.(),deferredRelease},onDeactivate:()=>renderedState?.stop()});return coreHandle.isActive()?(options.suspendWhenUnrendered&&(renderedState=new RenderedStateController(options.host,options.panel,rendered=>{if(!coreHandle.isActive())return;if(!rendered){coreHandle.suspend();return}const wasTopmost=coreHandle.isTopmost();coreHandle.resume(),!wasTopmost&&coreHandle.isTopmost()&&queueMicrotask(()=>coreHandle.focusInitial())}),renderedState.start()),{focusInitial:()=>{renderedState?.check(),coreHandle.focusInitial()},focusAutofocus:()=>(renderedState?.check(),coreHandle.focusAutofocus()),updateRestoreFocusTo:target=>coreHandle.updateRestoreFocusTo(target),deactivate:deactivateOptions=>coreHandle.deactivate(deactivateOptions),suspend:()=>coreHandle.suspend(),resume:()=>{renderedState&&!renderedState.check()||coreHandle.resume()},isTopmost:()=>(renderedState?.check(),coreHandle.isTopmost()),isActive:()=>coreHandle.isActive(),dismissBackdrop:()=>(renderedState?.check(),coreHandle.dismissBackdrop())}):coreHandle}function suspendLyraModalsFor(externalModal){if(!externalModal.isConnected)return()=>{};const state=modalStateFor(externalModal.ownerDocument);startModalState(state);const entry={root:externalModal,active:!0,releaseRouting:()=>{},state};return state.externalModalSuspensions.add(entry),entry.releaseRouting=acquireOverlayRoutingSuspension(state.document),applyTopmostInert(state),()=>{entry.active&&(entry.active=!1,entry.state.externalModalSuspensions.delete(entry),entry.releaseRouting(),applyTopmostInert(entry.state),stopModalStateIfIdle(entry.state))}}import{collectAutofocusElements,collectFocusableElements,composedContains as composedContains2,deepActiveElement}from"./overlay-stack.js";export{activateOverlay,authoredOverlayInert,collectAutofocusElements,collectFocusableElements,composedContains2 as composedContains,deepActiveElement,suspendLyraModalsFor};
@@ -1 +1 @@
1
- import{getActiveNativeModal}from"./native-modal-context.js";import{takeOverlayOrder}from"./overlay-order.js";import{deepActiveElementIn}from"./active-element.js";import{composedContains,flattenedParentElement}from"./composed-tree.js";import{scheduleDeferredFocusReturn,cancelDeferredFocusReturn}from"./deferred-focus-return.js";import{collectComposedAutofocusElements,collectComposedFocusTargets,isComposedFocusAvailable}from"./focus-navigation.js";import{isHtmlElement}from"./dom-guards.js";import{leaseInlineStyleProperty}from"./style-property-lease.js";const STACK_PROPERTY="--lr-overlay-stack-index",STACK_BASE=1e3,STACK_STEP=2,states=new WeakMap,hostEntries=new WeakMap;function createInactiveOverlayHandle(){return{focusInitial:()=>{},focusAutofocus:()=>!1,updateRestoreFocusTo:()=>{},deactivate:()=>{},suspend:()=>{},resume:()=>{},isTopmost:()=>!1,isActive:()=>!1,dismissBackdrop:()=>!1}}function deepActiveElement(doc=typeof document>"u"?void 0:document){return deepActiveElementIn(doc)}function collectFocusableElements(root){return collectComposedFocusTargets(root).elements}function collectAutofocusElements(root){return collectComposedAutofocusElements(root).elements}function tryFocus(target){if(!target||!isComposedFocusAvailable(target))return!1;target.focus();const active=deepActiveElement(target.ownerDocument);return active===target||composedContains(target,active)}function focusAutofocusTarget(panel){for(const candidate of collectAutofocusElements(panel)){if(tryFocus(candidate))return!0;for(const inner of collectFocusableElements(candidate))if(tryFocus(inner))return!0}return!1}function auxiliaryRoots(entry){const panel=entry.options.panel();return[...new Set(entry.options.auxiliaryRoots?.()??[])].filter(root=>root.isConnected&&root.ownerDocument===entry.state.document&&(!panel||!composedContains(panel,root)))}function entryContainsFocus(entry,panel,active){return entry.options.auxiliaryRoots?active!==null&&isComposedFocusAvailable(active)&&[panel,...auxiliaryRoots(entry)].some(root=>composedContains(root,active)):composedContains(panel,active)}function entryTabStops(entry,panel){const roots=entry.options.auxiliaryRoots?[panel,...auxiliaryRoots(entry)]:[panel];return[...new Set(roots.flatMap(root=>collectComposedFocusTargets(root,{browserTabOrder:!0}).elements))]}function composedPath(element){const path=[];for(let current=element;current;current=flattenedParentElement(current))path.unshift(current);return path}function precedes(first,second){let index=0;for(;first[index]&&first[index]===second[index];)index+=1;return first[index]?!!(second[index]&&first[index].compareDocumentPosition(second[index])&4):!!second[index]}function focusEntry(entry,preserveCurrent=!0){const panel=entry.options.panel();if(!panel)return;const active=deepActiveElement(entry.state.document);if(preserveCurrent&&entryContainsFocus(entry,panel,active)||(entry.initialFocusDecision===void 0&&(entry.initialFocusDecision=entry.options.beforeInitialFocus?.()!==!1),!entry.initialFocusDecision)||focusAutofocusTarget(panel))return;const preferred=entry.options.preferredInitialFocus?.()??null;if(!(preferred&&composedContains(panel,preferred)&&tryFocus(preferred))){for(const target of collectFocusableElements(panel))if(tryFocus(target))return;panel.focus()}}function handleTab(state,entry,event){const panel=entry.options.panel();if(!panel)return;const focusable=entryTabStops(entry,panel);if(focusable.length===0){event.preventDefault(),panel.focus();return}const active=deepActiveElement(state.document),first=focusable[0],last=focusable[focusable.length-1],activeIndex=active?focusable.indexOf(active):-1;if(activeIndex===-1){let target;const roots=entry.options.auxiliaryRoots?[panel,...auxiliaryRoots(entry)]:[panel];if(active&&roots.some(root=>composedContains(root,active))){const activePath=composedPath(active);if(event.shiftKey)for(let index=focusable.length-1;index>=0&&!target;index-=1)precedes(composedPath(focusable[index]),activePath)&&(target=focusable[index]);else target=focusable.find(stop=>precedes(activePath,composedPath(stop)));if(target&&target.tabIndex>=0&&!entry.options.auxiliaryRoots)return}event.preventDefault(),(target??(event.shiftKey?last:first)).focus()}else if(event.shiftKey&&active===first)event.preventDefault(),last.focus();else if(!event.shiftKey&&active===last)event.preventDefault(),first.focus();else{const next=focusable[activeIndex+(event.shiftKey?-1:1)];next&&(next.tabIndex<0||auxiliaryRoots(entry).length>0)&&(event.preventDefault(),next.focus())}}function nearestTrappingEntryBelowTop(state){for(let index=state.stack.length-2;index>=0;index-=1){const entry=state.stack[index];if(entry&&entry.options.trapFocus!==!1)return entry}}function snapshotFor(state){return{entries:state.stack.map(entry=>({host:entry.options.host,modal:entry.options.modal,modalRoot:entry.options.modalRoot,auxiliaryRoots:entry.options.auxiliaryRoots}))}}function notifyStackObservers(state){if(state.observers.size===0)return;const snapshot=snapshotFor(state);for(const observer of state.observers)observer(snapshot)}function startState(state){state.started||(state.started=!0,state.document.addEventListener("keydown",state.onKeyDown))}function stopState(state){state.started&&(state.started=!1,state.document.removeEventListener("keydown",state.onKeyDown))}function stopStateIfIdle(state){state.stack.length===0&&stopState(state)}function createState(doc){const state={};return state.document=doc,state.stack=[],state.routingSuspensions=new Set,state.observers=new Set,state.started=!1,state.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||state.routingSuspensions.size>0)return;const entry=state.stack[state.stack.length-1];if(!entry||event.key!=="Escape"&&event.key!=="Tab")return;const nativeModal=getActiveNativeModal(doc),panel=entry.options.panel();if(!(nativeModal&&(!panel||!composedContains(nativeModal,panel)))){if(event.key==="Escape")event.preventDefault(),entry.options.onEscape();else if(event.key==="Tab"){if(entry.options.trapFocus!==!1){handleTab(state,entry,event);return}entry.options.onTab?.();const trapping=nearestTrappingEntryBelowTop(state),trappingPanel=trapping?.options.panel();trapping&&trappingPanel&&!event.defaultPrevented&&(!nativeModal||composedContains(nativeModal,trappingPanel))&&entryContainsFocus(trapping,trappingPanel,deepActiveElement(doc))&&handleTab(state,trapping,event)}}},states.set(doc,state),state}function stateFor(doc){return states.get(doc)??createState(doc)}function observeOverlayStack(doc,observer){const state=stateFor(doc);return state.observers.add(observer),observer(snapshotFor(state)),()=>{state.observers.delete(observer)}}function acquireOverlayRoutingSuspension(doc){const state=stateFor(doc),token=Symbol();let active=!0;return state.routingSuspensions.add(token),()=>{active&&(active=!1,state.routingSuspensions.delete(token))}}function restoreStackStyle(entry){entry.stackStyleLease?.release(),entry.stackStyleLease=void 0}function updateStackStyles(state){state.stack.forEach((entry,index)=>{const value=String(STACK_BASE+index*STACK_STEP);entry.stackStyleLease?entry.stackStyleLease.set(value):entry.stackStyleLease=leaseInlineStyleProperty(entry.options.host,STACK_PROPERTY,value)})}function registerEntry(entry,state,preserveStackOrder=!1){if(entry.registered)return;startState(state),(!preserveStackOrder||entry.state!==state)&&(entry.stackOrder=takeOverlayOrder(state.document)),entry.state=state,entry.registered=!0,entry.options.onRegistered?.(state.document);const nextIndex=state.stack.findIndex(candidate=>candidate.stackOrder>entry.stackOrder);nextIndex===-1?state.stack.push(entry):state.stack.splice(nextIndex,0,entry),updateStackStyles(state),notifyStackObservers(state)}function unregisterEntry(entry,deferResourceRelease=!1){if(!entry.registered){const hasHigherEntry=entry.state.stack.some(candidate=>candidate.stackOrder>entry.stackOrder);return entry.state.routingSuspensions.size===0&&entry.wasTopmostOnSuspend&&!hasHigherEntry}const state=entry.state,index=state.stack.indexOf(entry),wasTopmost=state.routingSuspensions.size===0&&index===state.stack.length-1;return index!==-1&&state.stack.splice(index,1),entry.registered=!1,entry.wasTopmostOnSuspend=wasTopmost,entry.deferredResourceRelease=entry.options.onUnregistered?.(state.document,deferResourceRelease),restoreStackStyle(entry),updateStackStyles(state),notifyStackObservers(state),stopStateIfIdle(state),wasTopmost}function syncEntryRegistration(entry){if(!entry.active||entry.manuallySuspended){unregisterEntry(entry);return}const state=stateFor(entry.options.host.ownerDocument);registerEntry(entry,state,entry.state===state)}function validRestoreFocusElement(value,doc){return isHtmlElement(value)&&value.ownerDocument===doc?value:null}function resolveRestoreFocusTarget(entry){const source=entry.restoreFocusTo;if(typeof source!="function")return validRestoreFocusElement(source,entry.state.document);try{return validRestoreFocusElement(source(),entry.state.document)}catch{return null}}function rebaseReturnTargets(entry){for(const candidate of entry.state.stack){if(candidate===entry||candidate.stackOrder<=entry.stackOrder)continue;const candidateTarget=typeof candidate.restoreFocusTo=="function"?null:validRestoreFocusElement(candidate.restoreFocusTo,entry.state.document);candidateTarget&&composedContains(entry.options.host,candidateTarget)&&(candidate.restoreFocusTo=entry.restoreFocusTo)}}function restoreEntryFocus(entry){if(tryFocus(resolveRestoreFocusTarget(entry)))return;const next=entry.state.stack[entry.state.stack.length-1];next&&focusEntry(next,!1)}function deactivateEntry(entry,restoreFocus,deferResourceRelease=!1){if(!entry.active)return;const host=entry.options.host;cancelDeferredFocusReturn(host);const release=deactivateActiveEntry(entry,restoreFocus,deferResourceRelease);if(restoreFocus){const pass=entry.options.deferredReturn?.();pass&&scheduleDeferredFocusReturn({...pass,host})}return release}function deactivateActiveEntry(entry,restoreFocus,deferResourceRelease){const heldFocus=panelHoldsFocus(entry);rebaseReturnTargets(entry);const wasTopmost=unregisterEntry(entry,deferResourceRelease),deferredResourceRelease=entry.deferredResourceRelease;if(entry.deferredResourceRelease=void 0,entry.active=!1,entry.manuallySuspended=!1,entry.suspendGeneration++,entry.options.onDeactivate?.(),hostEntries.get(entry.options.host)===entry&&hostEntries.delete(entry.options.host),!wasTopmost)return deferredResourceRelease;if(restoreFocus)return restoreEntryFocus(entry),deferredResourceRelease;const next=entry.state.stack[entry.state.stack.length-1];return next&&(heldFocus||next.options.trapFocus)&&focusEntry(next),deferredResourceRelease}function panelHoldsFocus(entry){const panel=entry.options.panel();return panel!==null&&entryContainsFocus(entry,panel,deepActiveElement(entry.state.document))}function activateOverlayStack(options){cancelDeferredFocusReturn(options.host);const previous=hostEntries.get(options.host),inheritedReturnTarget=previous?.active?previous.restoreFocusTo:void 0;previous?.active&&previous.handle.deactivate({restoreFocus:!1});const doc=options.host.ownerDocument;if(!doc)return createInactiveOverlayHandle();const active=deepActiveElement(doc),captured=active&&typeof active.focus=="function"?active:null,entry={};return entry.options=options,entry.restoreFocusTo=options.restoreFocusTo!==void 0?options.restoreFocusTo:inheritedReturnTarget??captured,entry.active=!0,entry.registered=!1,entry.manuallySuspended=options.initiallySuspended===!0,entry.initialFocusDecision=void 0,entry.wasTopmostOnSuspend=!1,entry.suspendGeneration=0,entry.state=stateFor(doc),entry.stackOrder=takeOverlayOrder(doc,options.orderReservation),entry.handle={focusInitial:()=>{entry.active&&entry.registered&&entry.state.routingSuspensions.size===0&&entry.state.stack[entry.state.stack.length-1]===entry&&focusEntry(entry)},focusAutofocus:()=>{if(!entry.active||!entry.registered||entry.state.routingSuspensions.size>0)return!1;const panel=entry.options.panel();if(!panel)return!1;const active2=deepActiveElement(entry.state.document);return entryContainsFocus(entry,panel,active2)?!1:focusAutofocusTarget(panel)},updateRestoreFocusTo:target=>{entry.active&&(entry.restoreFocusTo=target)},deactivate:(deactivateOptions={})=>deactivateEntry(entry,deactivateOptions.restoreFocus!==!1,deactivateOptions.deferScrollLockRelease===!0),suspend:()=>{if(!entry.active||entry.manuallySuspended)return;entry.manuallySuspended=!0,syncEntryRegistration(entry);const generation=++entry.suspendGeneration;queueMicrotask(()=>{entry.active&&!entry.registered&&entry.suspendGeneration===generation&&!entry.options.host.isConnected&&deactivateEntry(entry,!0)})},resume:()=>{!entry.active||!entry.manuallySuspended||(entry.suspendGeneration++,entry.manuallySuspended=!1,syncEntryRegistration(entry))},isTopmost:()=>entry.active&&entry.registered&&entry.state.routingSuspensions.size===0&&entry.state.stack[entry.state.stack.length-1]===entry,isActive:()=>entry.active,dismissBackdrop:()=>!entry.handle.isTopmost()||!entry.options.onBackdrop?!1:(entry.options.onBackdrop(),!0)},hostEntries.set(options.host,entry),entry.manuallySuspended||registerEntry(entry,entry.state,!0),entry.handle}export{acquireOverlayRoutingSuspension,activateOverlayStack,collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack};
1
+ import{getActiveNativeModal}from"./native-modal-context.js";import{takeOverlayOrder}from"./overlay-order.js";import{deepActiveElementIn}from"./active-element.js";import{composedContains,flattenedParentElement}from"./composed-tree.js";import{scheduleDeferredFocusReturn,cancelDeferredFocusReturn}from"./deferred-focus-return.js";import{collectComposedAutofocusElements,collectComposedFocusTargets,isComposedFocusAvailable}from"./focus-navigation.js";import{isHtmlElement}from"./dom-guards.js";import{leaseInlineStyleProperty}from"./style-property-lease.js";const STACK_PROPERTY="--lr-overlay-stack-index",STACK_BASE=1e3,STACK_STEP=2,states=new WeakMap,hostEntries=new WeakMap;function createInactiveOverlayHandle(){return{focusInitial:()=>{},focusAutofocus:()=>!1,updateRestoreFocusTo:()=>{},deactivate:()=>{},suspend:()=>{},resume:()=>{},isTopmost:()=>!1,isActive:()=>!1,dismissBackdrop:()=>!1}}function deepActiveElement(doc=typeof document>"u"?void 0:document){return deepActiveElementIn(doc)}function collectFocusableElements(root){return collectComposedFocusTargets(root).elements}function collectAutofocusElements(root){return collectComposedAutofocusElements(root).elements}function tryFocus(target){if(!target||!isComposedFocusAvailable(target))return!1;target.focus();const active=deepActiveElement(target.ownerDocument);return active===target||composedContains(target,active)}function focusAutofocusTarget(panel){for(const candidate of collectAutofocusElements(panel)){if(tryFocus(candidate))return!0;for(const inner of collectFocusableElements(candidate))if(tryFocus(inner))return!0}return!1}function auxiliaryRoots(entry){const panel=entry.options.panel();return[...new Set(entry.options.auxiliaryRoots?.()??[])].filter(root=>root.isConnected&&root.ownerDocument===entry.state.document&&(!panel||!composedContains(panel,root)))}function entryContainsFocus(entry,panel,active){return entry.options.auxiliaryRoots?active!==null&&isComposedFocusAvailable(active)&&[panel,...auxiliaryRoots(entry)].some(root=>composedContains(root,active)):composedContains(panel,active)}function entryTabStops(entry,panel){const roots=entry.options.auxiliaryRoots?[panel,...auxiliaryRoots(entry)]:[panel];return[...new Set(roots.flatMap(root=>collectComposedFocusTargets(root,{browserTabOrder:!0}).elements))]}function composedPath(element){const path=[];for(let current=element;current;current=flattenedParentElement(current))path.unshift(current);return path}function precedes(first,second){let index=0;for(;first[index]&&first[index]===second[index];)index+=1;return first[index]?!!(second[index]&&first[index].compareDocumentPosition(second[index])&4):!!second[index]}function focusEntry(entry,preserveCurrent=!0){const panel=entry.options.panel();if(!panel)return;const active=deepActiveElement(entry.state.document);if(preserveCurrent&&entryContainsFocus(entry,panel,active)||(entry.initialFocusDecision===void 0&&(entry.initialFocusDecision=entry.options.beforeInitialFocus?.()!==!1),!entry.initialFocusDecision)||focusAutofocusTarget(panel))return;const preferred=entry.options.preferredInitialFocus?.()??null;if(!(preferred&&composedContains(panel,preferred)&&tryFocus(preferred))){for(const target of collectFocusableElements(panel))if(tryFocus(target))return;panel.focus()}}function handleTab(state,entry,event){const panel=entry.options.panel();if(!panel)return;const focusable=entryTabStops(entry,panel);if(focusable.length===0){event.preventDefault(),panel.focus();return}const active=deepActiveElement(state.document),first=focusable[0],last=focusable[focusable.length-1],activeIndex=active?focusable.indexOf(active):-1;if(activeIndex===-1){let target;const roots=entry.options.auxiliaryRoots?[panel,...auxiliaryRoots(entry)]:[panel];if(active&&roots.some(root=>composedContains(root,active))){const activePath=composedPath(active);if(event.shiftKey)for(let index=focusable.length-1;index>=0&&!target;index-=1)precedes(composedPath(focusable[index]),activePath)&&(target=focusable[index]);else target=focusable.find(stop=>precedes(activePath,composedPath(stop)));if(target&&target.tabIndex>=0&&!entry.options.auxiliaryRoots)return}event.preventDefault(),(target??(event.shiftKey?last:first)).focus()}else if(event.shiftKey&&active===first)event.preventDefault(),last.focus();else if(!event.shiftKey&&active===last)event.preventDefault(),first.focus();else{const next=focusable[activeIndex+(event.shiftKey?-1:1)];next&&(next.tabIndex<0||auxiliaryRoots(entry).length>0)&&(event.preventDefault(),next.focus())}}function nearestTrappingEntryBelowTop(state){for(let index=state.stack.length-2;index>=0;index-=1){const entry=state.stack[index];if(entry&&entry.options.trapFocus!==!1)return entry}}function snapshotFor(state){return{entries:state.stack.map(entry=>({host:entry.options.host,modal:entry.options.modal,modalRoot:entry.options.modalRoot,auxiliaryRoots:entry.options.auxiliaryRoots}))}}function notifyStackObservers(state){if(state.observers.size===0)return;const snapshot=snapshotFor(state);for(const observer of state.observers)observer(snapshot)}function startState(state){state.started||(state.started=!0,state.document.addEventListener("keydown",state.onKeyDown))}function stopState(state){state.started&&(state.started=!1,state.document.removeEventListener("keydown",state.onKeyDown))}function stopStateIfIdle(state){state.stack.length===0&&stopState(state)}function createState(doc){const state={};return state.document=doc,state.stack=[],state.routingSuspensions=new Set,state.observers=new Set,state.started=!1,state.onKeyDown=event=>{if(event.defaultPrevented||event.isComposing||event.keyCode===229||state.routingSuspensions.size>0)return;const entry=state.stack[state.stack.length-1];if(!entry||event.key!=="Escape"&&event.key!=="Tab")return;const nativeModal=getActiveNativeModal(doc),panel=entry.options.panel();if(!(nativeModal&&(!panel||!composedContains(nativeModal,panel)))){if(event.key==="Escape")event.preventDefault(),entry.options.onEscape();else if(event.key==="Tab"){if(entry.options.trapFocus!==!1){handleTab(state,entry,event);return}entry.options.onTab?.();const trapping=nearestTrappingEntryBelowTop(state),trappingPanel=trapping?.options.panel();trapping&&trappingPanel&&!event.defaultPrevented&&(!nativeModal||composedContains(nativeModal,trappingPanel))&&entryContainsFocus(trapping,trappingPanel,deepActiveElement(doc))&&handleTab(state,trapping,event)}}},states.set(doc,state),state}function stateFor(doc){return states.get(doc)??createState(doc)}function observeOverlayStack(doc,observer){const state=stateFor(doc);return state.observers.add(observer),observer(snapshotFor(state)),()=>{state.observers.delete(observer)}}function acquireOverlayRoutingSuspension(doc){const state=stateFor(doc),token=Symbol();let active=!0;return state.routingSuspensions.add(token),()=>{active&&(active=!1,state.routingSuspensions.delete(token))}}function restoreStackStyle(entry){entry.stackStyleLease?.release(),entry.stackStyleLease=void 0}function updateStackStyles(state){state.stack.forEach((entry,index)=>{const value=String(STACK_BASE+index*STACK_STEP);entry.stackStyleLease?entry.stackStyleLease.set(value):entry.stackStyleLease=leaseInlineStyleProperty(entry.options.host,STACK_PROPERTY,value)})}function registerEntry(entry,state,preserveStackOrder=!1){if(entry.registered)return;startState(state),(!preserveStackOrder||entry.state!==state)&&(entry.stackOrder=takeOverlayOrder(state.document)),entry.state=state,entry.registered=!0,entry.options.onRegistered?.(state.document);const nextIndex=state.stack.findIndex(candidate=>candidate.stackOrder>entry.stackOrder);nextIndex===-1?state.stack.push(entry):state.stack.splice(nextIndex,0,entry),updateStackStyles(state),notifyStackObservers(state)}function unregisterEntry(entry,deferResourceRelease=!1){if(!entry.registered){const hasHigherEntry=entry.state.stack.some(candidate=>candidate.stackOrder>entry.stackOrder);return entry.state.routingSuspensions.size===0&&entry.wasTopmostOnSuspend&&!hasHigherEntry}const state=entry.state,index=state.stack.indexOf(entry),wasTopmost=state.routingSuspensions.size===0&&index===state.stack.length-1;return index!==-1&&state.stack.splice(index,1),entry.registered=!1,entry.wasTopmostOnSuspend=wasTopmost,entry.deferredResourceRelease=entry.options.onUnregistered?.(state.document,deferResourceRelease),restoreStackStyle(entry),updateStackStyles(state),notifyStackObservers(state),stopStateIfIdle(state),wasTopmost}function syncEntryRegistration(entry){if(!entry.active||entry.manuallySuspended){unregisterEntry(entry);return}const state=stateFor(entry.options.host.ownerDocument);registerEntry(entry,state,entry.state===state)}function validRestoreFocusElement(value,doc){return isHtmlElement(value)&&value.ownerDocument===doc?value:null}function resolveRestoreFocusTarget(entry){const source=entry.restoreFocusTo;if(typeof source!="function")return validRestoreFocusElement(source,entry.state.document);try{return validRestoreFocusElement(source(),entry.state.document)}catch{return null}}function rebaseReturnTargets(entry){for(const candidate of entry.state.stack){if(candidate===entry||candidate.stackOrder<=entry.stackOrder)continue;const candidateTarget=typeof candidate.restoreFocusTo=="function"?null:validRestoreFocusElement(candidate.restoreFocusTo,entry.state.document);candidateTarget&&composedContains(entry.options.host,candidateTarget)&&(candidate.restoreFocusTo=entry.restoreFocusTo)}}function restoreEntryFocus(entry){if(tryFocus(resolveRestoreFocusTarget(entry)))return;const next=entry.state.stack[entry.state.stack.length-1];next&&focusEntry(next,!1)}function deactivateEntry(entry,restoreFocus,deferResourceRelease=!1){if(!entry.active)return;const host=entry.options.host;cancelDeferredFocusReturn(host);const release=deactivateActiveEntry(entry,restoreFocus,deferResourceRelease);if(restoreFocus){const pass=entry.options.deferredReturn?.();pass&&scheduleDeferredFocusReturn({...pass,host})}return release}function deactivateActiveEntry(entry,restoreFocus,deferResourceRelease){const heldFocus=panelHoldsFocus(entry);rebaseReturnTargets(entry);const wasTopmost=unregisterEntry(entry,deferResourceRelease),deferredResourceRelease=entry.deferredResourceRelease;if(entry.deferredResourceRelease=void 0,entry.active=!1,entry.manuallySuspended=!1,entry.suspendGeneration++,entry.options.onDeactivate?.(),hostEntries.get(entry.options.host)===entry&&hostEntries.delete(entry.options.host),!wasTopmost)return deferredResourceRelease;if(restoreFocus)return restoreEntryFocus(entry),deferredResourceRelease;const next=entry.state.stack[entry.state.stack.length-1];if(!next)return deferredResourceRelease;if(heldFocus)focusEntry(next);else if(next.options.trapFocus){const doc=entry.state.document,active=deepActiveElement(doc);!entry.options.host.isConnected||active&&active!==doc.body&&active!==doc.documentElement?focusEntry(next):setTimeout(()=>{next.active&&next.registered&&entry.state.stack[entry.state.stack.length-1]===next&&focusEntry(next)},0)}return deferredResourceRelease}function panelHoldsFocus(entry){const panel=entry.options.panel();return panel!==null&&entryContainsFocus(entry,panel,deepActiveElement(entry.state.document))}function activateOverlayStack(options){cancelDeferredFocusReturn(options.host);const previous=hostEntries.get(options.host),inheritedReturnTarget=previous?.active?previous.restoreFocusTo:void 0;previous?.active&&previous.handle.deactivate({restoreFocus:!1});const doc=options.host.ownerDocument;if(!doc)return createInactiveOverlayHandle();const active=deepActiveElement(doc),captured=active&&typeof active.focus=="function"?active:null,entry={};return entry.options=options,entry.restoreFocusTo=options.restoreFocusTo!==void 0?options.restoreFocusTo:inheritedReturnTarget??captured,entry.active=!0,entry.registered=!1,entry.manuallySuspended=options.initiallySuspended===!0,entry.initialFocusDecision=void 0,entry.wasTopmostOnSuspend=!1,entry.suspendGeneration=0,entry.state=stateFor(doc),entry.stackOrder=takeOverlayOrder(doc,options.orderReservation),entry.handle={focusInitial:()=>{entry.active&&entry.registered&&entry.state.routingSuspensions.size===0&&entry.state.stack[entry.state.stack.length-1]===entry&&focusEntry(entry)},focusAutofocus:()=>{if(!entry.active||!entry.registered||entry.state.routingSuspensions.size>0)return!1;const panel=entry.options.panel();if(!panel)return!1;const active2=deepActiveElement(entry.state.document);return entryContainsFocus(entry,panel,active2)?!1:focusAutofocusTarget(panel)},updateRestoreFocusTo:target=>{entry.active&&(entry.restoreFocusTo=target)},deactivate:(deactivateOptions={})=>deactivateEntry(entry,deactivateOptions.restoreFocus!==!1,deactivateOptions.deferScrollLockRelease===!0),suspend:()=>{if(!entry.active||entry.manuallySuspended)return;entry.manuallySuspended=!0,syncEntryRegistration(entry);const generation=++entry.suspendGeneration;queueMicrotask(()=>{entry.active&&!entry.registered&&entry.suspendGeneration===generation&&!entry.options.host.isConnected&&deactivateEntry(entry,!0)})},resume:()=>{!entry.active||!entry.manuallySuspended||(entry.suspendGeneration++,entry.manuallySuspended=!1,syncEntryRegistration(entry))},isTopmost:()=>entry.active&&entry.registered&&entry.state.routingSuspensions.size===0&&entry.state.stack[entry.state.stack.length-1]===entry,isActive:()=>entry.active,dismissBackdrop:()=>!entry.handle.isTopmost()||!entry.options.onBackdrop?!1:(entry.options.onBackdrop(),!0)},hostEntries.set(options.host,entry),entry.manuallySuspended||registerEntry(entry,entry.state,!0),entry.handle}export{acquireOverlayRoutingSuspension,activateOverlayStack,collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack};
@@ -1 +1 @@
1
- const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="29.1.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
1
+ const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="29.2.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
@@ -1 +1 @@
1
- import{devWarnOnce,litDevWarnings}from"../internal/dev-warning.js";import{readStyleOwnership}from"./style-ownership.js";import{resolveStyleStartup}from"./startup-resolution.js";const STORAGE_KEY="lyra-theme",TOKEN_NAME_PATTERN=/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/,TOKEN_NAME_MAX_LENGTH=80,TOKEN_RESERVED_NAME="--lr-theme-accent",TOKEN_ENTRY_MAX=512,TOKEN_SYNTHESIZED_MAX=16,TOKEN_VALUE_MAX_LENGTH=256,TOKEN_FORBIDDEN_PATTERN=/[\x00-\x1f\x7f\\;{}!<>@[\]`$^|~=?&:\u2028\u2029]|\/\*|\*\//,TOKEN_CSS_WIDE_PATTERN=/^(?:inherit|initial|revert(?:-layer)?|unset)$/i,TOKEN_FUNCTION_PATTERN=/([a-z0-9_-]+)\s*\(/gi,TOKEN_ALLOWED_FUNCTIONS="rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark calc min max clamp var cubic-bezier steps linear".split(" "),TOKEN_OWNERSHIP_MAX=TOKEN_ENTRY_MAX+TOKEN_SYNTHESIZED_MAX,TOKEN_OWNERSHIP_SYMBOL="@aceshooting/lyra-ui.theme-tokens.v1",MODE_SURFACES={light:[255,255,255],dark:[10,10,10]},COLOR_SCHEME_QUERY="(prefers-color-scheme: dark)",SEMANTIC_ROLES=["brand","success","warning","danger","neutral"],RAMP_CHANNELS=["fill","border","on"],RAMP_TIERS=["quiet","normal","loud"];function roleRampProperties(role){const properties=[];for(const channel of RAMP_CHANNELS)for(const tier of RAMP_TIERS)properties.push(`--lr-theme-color-${role}-${channel}-${tier}`);return properties}const ALL_RAMP_PROPERTIES=[...SEMANTIC_ROLES.flatMap(roleRampProperties),"--lr-theme-color-focus"],MODE_ATTRIBUTES=["data-lr-theme","data-theme"];function isBalancedCssValue(value){let depth=0,quote="";for(const character of value){if(quote){character===quote&&(quote="");continue}if(character==="'"||character==='"')quote=character;else if(character==="(")depth+=1;else if(character===")"&&(depth-=1)<0)return!1}return quote===""&&depth===0}function isLyraThemeTokenName(name){return typeof name=="string"&&name.length<=TOKEN_NAME_MAX_LENGTH&&TOKEN_NAME_PATTERN.test(name)&&name!==TOKEN_RESERVED_NAME}function isSafeLyraThemeTokenValue(value){if(typeof value!="string")return!1;const trimmed=value.trim();if(!trimmed||trimmed.length>TOKEN_VALUE_MAX_LENGTH||TOKEN_FORBIDDEN_PATTERN.test(trimmed)||TOKEN_CSS_WIDE_PATTERN.test(trimmed))return!1;for(const match of trimmed.matchAll(TOKEN_FUNCTION_PATTERN))if(!TOKEN_ALLOWED_FUNCTIONS.includes((match[1]??"").toLowerCase()))return!1;return isBalancedCssValue(trimmed)}function isPlainRecord(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);if(prototype===Object.prototype||prototype===null)return!0;if(Object.getPrototypeOf(prototype)!==null)return!1;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return typeof constructor=="function"&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(Object)}function normalizeTokenBranch(value){return isSafeLyraThemeTokenValue(value)?value.trim():null}function normalizeTokens(raw){try{if(!isPlainRecord(raw))return null;const names=Object.keys(raw);if(names.length===0||names.length>TOKEN_ENTRY_MAX)return null;const result={};let kept=0;for(const name of names){if(!isLyraThemeTokenName(name))continue;const value=ownField(raw,name);if(typeof value=="string"){const normalized=normalizeTokenBranch(value);if(normalized===null)continue;result[name]=normalized,kept+=1;continue}if(!isPlainRecord(value))continue;const keys=Object.keys(value),hasLight=Object.prototype.hasOwnProperty.call(value,"light"),hasDark=Object.prototype.hasOwnProperty.call(value,"dark");if(!hasLight&&!hasDark||keys.some(key=>key!=="light"&&key!=="dark"))continue;const light=normalizeTokenBranch(ownField(value,"light")),dark=normalizeTokenBranch(ownField(value,"dark"));light===null&&dark===null||(result[name]=Object.freeze({light,dark}),kept+=1)}return kept>0?Object.freeze(result):null}catch{return null}}function tokensEqual(left,right){const leftNames=left?Object.keys(left):[],rightNames=right?Object.keys(right):[];if(leftNames.length!==rightNames.length)return!1;if(leftNames.length===0)return!0;const leftMap=left,rightMap=right;return leftNames.every(name=>{if(!Object.prototype.hasOwnProperty.call(rightMap,name))return!1;const a=leftMap[name],b=rightMap[name];return typeof a=="string"||typeof b=="string"?a===b:!a||!b?!1:(a.light??null)===(b.light??null)&&(a.dark??null)===(b.dark??null)})}function normalizeColor(value,owner=document){if(typeof value!="string"||!value.trim())return null;const candidate=value.trim();if(!isBalancedCssValue(candidate)||TOKEN_CSS_WIDE_PATTERN.test(candidate)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(candidate)||/\bcurrentcolor\b/i.test(candidate)||/\bvar\s*\(/i.test(candidate)||/\blight-dark\s*\(/i.test(candidate)||/\b(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\s*\(\s*from\b/i.test(candidate))return null;const probe=owner.createElement("span");return probe.style.color=candidate,probe.style.color?candidate:null}function normalizeAccentValue(value){if(typeof value=="string"||value===null)return normalizeColor(value);if(typeof value!="object"||Array.isArray(value))return null;const record=value;if(!("light"in record)&&!("dark"in record))return null;const light=normalizeColor(record.light),dark=normalizeColor(record.dark);return light||dark?{light,dark}:null}function normalizeAccent(value){if(typeof value=="string")return normalizeColor(value);if(value===null||typeof value!="object"||Array.isArray(value))return null;const record=value,result={};let hasRole=!1;for(const role of SEMANTIC_ROLES)role in record&&(hasRole=!0,result[role]=normalizeAccentValue(record[role]));return hasRole?result:null}function resolveAccentValueForMode(value,mode){return typeof value=="string"?value:value?value[mode]??null:null}function accentValueEqual(left,right){return left===right?!0:typeof left=="string"||typeof right=="string"||left===null||right===null?!1:(left.light??null)===(right.light??null)&&(left.dark??null)===(right.dark??null)}function accentsEqual(left,right){if(left===right)return!0;if(typeof left=="string"||typeof right=="string"||left===null||right===null)return!1;const leftKeys=Object.keys(left),rightKeys=Object.keys(right);return leftKeys.length!==rightKeys.length?!1:leftKeys.every(role=>accentValueEqual(left[role],right[role]))}function parseResolvedRgb(value,background,owner=document){if(!normalizeColor(value,owner))return null;try{const canvas=owner.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0});if(!context)return null;context.clearRect(0,0,1,1),context.fillStyle=value,context.fillRect(0,0,1,1);const channels=context.getImageData(0,0,1,1).data,red=channels[0]??0,green=channels[1]??0,blue=channels[2]??0,alpha=(channels[3]??0)/255;return[Math.round(red*alpha+background[0]*(1-alpha)),Math.round(green*alpha+background[1]*(1-alpha)),Math.round(blue*alpha+background[2]*(1-alpha))]}catch{return null}}function hexRgb(color){return[parseInt(color.slice(1,3),16),parseInt(color.slice(3,5),16),parseInt(color.slice(5,7),16)]}function mixRgb(base,color,colorWeight){return[Math.round(base[0]*(1-colorWeight)+color[0]*colorWeight),Math.round(base[1]*(1-colorWeight)+color[1]*colorWeight),Math.round(base[2]*(1-colorWeight)+color[2]*colorWeight)]}function serializeRgb(color){return`rgb(${color.join(" ")})`}function relativeLuminance(color){const linearize=channel=>{const normalized=channel/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4};return linearize(color[0])*.2126+linearize(color[1])*.7152+linearize(color[2])*.0722}function contrastRatio(left,right){const a=relativeLuminance(left),b=relativeLuminance(right);return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}function contrastForeground(fill){const black=[0,0,0],white=[255,255,255];return contrastRatio(fill,black)>=contrastRatio(fill,white)?black:white}function ensureSurfaceContrast(color,background,minimum=3,alsoAgainst=background,references=[]){const passes=candidate=>contrastRatio(candidate,background)>=minimum&&contrastRatio(candidate,alsoAgainst)>=minimum&&references.every(reference=>contrastRatio(candidate,reference)>=minimum);if(passes(color))return color;const black=[0,0,0],white=[255,255,255],target=contrastRatio(background,black)>=contrastRatio(background,white)?black:white;for(let step=1;step<=10;step+=1){const candidate=mixRgb(color,target,step/10);if(passes(candidate))return candidate}return target}function createRoleRamp(role,base,mode,background,owner=document){const references=STYLE_CONTRAST_SURFACES[mode].map(hexRgb),resolved=parseResolvedRgb(base,background,owner);if(!resolved)return null;const quiet=mixRgb(background,resolved,mode==="dark"?.24:.14),normal=mixRgb(background,resolved,mode==="dark"?.62:.55),loud=ensureSurfaceContrast(resolved,background,4.5,quiet,references),borderTarget=mode==="dark"?[255,255,255]:[0,0,0],borderQuiet=mixRgb(background,resolved,mode==="dark"?.46:.38),borderNormal=ensureSurfaceContrast(mixRgb(background,resolved,mode==="dark"?.78:.72),background,3,background,references),borderLoud=ensureSurfaceContrast(mixRgb(loud,borderTarget,.2),background,3,background,references),prefix=`--lr-theme-color-${role}`,ramp={[`${prefix}-fill-quiet`]:serializeRgb(quiet),[`${prefix}-fill-normal`]:serializeRgb(normal),[`${prefix}-fill-loud`]:serializeRgb(loud),[`${prefix}-border-quiet`]:serializeRgb(borderQuiet),[`${prefix}-border-normal`]:serializeRgb(borderNormal),[`${prefix}-border-loud`]:serializeRgb(borderLoud),[`${prefix}-on-quiet`]:serializeRgb(contrastForeground(quiet)),[`${prefix}-on-normal`]:serializeRgb(contrastForeground(normal)),[`${prefix}-on-loud`]:serializeRgb(contrastForeground(loud))};return role==="brand"&&(ramp["--lr-theme-color-focus"]=serializeRgb(ensureSurfaceContrast(resolved,background,3,background,references))),ramp}function paintAccent(accent,mode,background,owner=document){const properties=new Map;if(!accent)return{applied:null,properties};if(!mode)return{applied:accent,properties};if(typeof accent=="string"){const ramp=createRoleRamp("brand",accent,mode,background,owner);if(!ramp)return{applied:null,properties};properties.set("--lr-theme-accent",accent);for(const[property,value]of Object.entries(ramp))properties.set(property,value);return{applied:accent,properties}}const applied={};let appliedBrandColor=null;for(const role of SEMANTIC_ROLES){const value=accent[role];if(!value)continue;const isPerMode=typeof value!="string",base=resolveAccentValueForMode(value,mode);let painted=!1;if(base){const ramp=createRoleRamp(role,base,mode,background,owner);if(ramp){for(const[property,propertyValue]of Object.entries(ramp))properties.set(property,propertyValue);painted=!0,role==="brand"&&(appliedBrandColor=base)}}(painted||isPerMode)&&(applied[role]=value)}return appliedBrandColor&&properties.set("--lr-theme-accent",appliedBrandColor),{applied:Object.keys(applied).length>0?applied:null,properties}}function tokenEntries(tokens,mode){const entries=new Map;if(!tokens)return entries;for(const[name,value]of Object.entries(tokens))if(typeof value=="string")entries.set(name,value);else if(mode){const branch=value[mode];branch&&entries.set(name,branch)}return entries}function resolveTokenColor(value,background,owner){return value===void 0||!background||!normalizeColor(value,owner)?null:parseResolvedRgb(value,background,owner)}function floorTokenEntries(entries,surface,owner,references){if(!entries.size)return new Map;const resolveColor=(value,background)=>resolveTokenColor(value,background,owner),painted=new Map(entries),prefix="--lr-theme-",raised=resolveColor(entries.get(`${prefix}color-surface-raised`)??references[1],surface),floor=(name,over,against,minimum,alsoAgainst)=>{const value=painted.get(name);if(value===void 0||!against||alsoAgainst===null)return;const color=resolveColor(value,over);if(!color)return;const repaired=ensureSurfaceContrast(color,against,minimum,alsoAgainst??against);repaired!==color&&painted.set(name,serializeRgb(repaired))};floor(`${prefix}color-text-normal`,surface,surface,4.5,raised),floor(`${prefix}color-text-quiet`,surface,surface,4.5,raised);const text=entries.has(`${prefix}color-text-normal`)?resolveColor(painted.get(`${prefix}color-text-normal`),surface):resolveColor(references[2],surface),pairForeground=(onName,fill)=>{if(!fill)return;const on=painted.get(onName);if(on===void 0){painted.set(onName,serializeRgb(contrastForeground(fill)));return}const color=resolveColor(on,fill);color&&contrastRatio(color,fill)<4.5&&painted.set(onName,serializeRgb(contrastForeground(fill)))};for(const role of SEMANTIC_ROLES)for(const tier of RAMP_TIERS){const fillName=`${prefix}color-${role}-fill-${tier}`;entries.has(fillName)&&pairForeground(`${prefix}color-${role}-on-${tier}`,resolveColor(entries.get(fillName),surface))}const overlayName=`${prefix}color-overlay-strong`,overlay=entries.has(overlayName)?resolveColor(entries.get(overlayName),surface):resolveColor(references[3],surface);(entries.has(overlayName)||entries.has(`${prefix}color-on-strong-overlay`))&&pairForeground(`${prefix}color-on-strong-overlay`,overlay);for(const name of entries.keys())/^--lr-theme-color-(?:(?:brand|success|warning|danger|neutral)-border-(?:normal|loud)|surface-border|border-strong|focus|chart-\d+)$/.test(name)?floor(name,surface,surface,3):/^--lr-theme-terminal-color-[a-z0-9-]+$/.test(name)?floor(name,raised,raised,4.5):/^--lr-theme-terminal-bg-[a-z0-9-]+$/.test(name)&&floor(name,raised,text,4.5);return painted}function readOwnershipList(){try{const list=document.documentElement[Symbol.for(TOKEN_OWNERSHIP_SYMBOL)];if(!Array.isArray(list))return[];const names=[],length=Math.min(list.length,TOKEN_OWNERSHIP_MAX);for(let index=0;index<length;index+=1){const name=list[index];isLyraThemeTokenName(name)&&names.push(name)}return names}catch{return[]}}function applyStoredThemeBeforePaint(){const R=["brand","success","warning","danger","neutral"],Q=["quiet","normal","loud"],W=/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/,_="--lr-theme-accent",G=/[\x00-\x1f\x7f\\;{}!<>@[\]`$^|~=?&:\u2028\u2029]|\/\*|\*\//,H=/^(?:inherit|initial|revert(?:-layer)?|unset)$/i,J=/([a-z0-9_-]+)\s*\(/gi,K="rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark calc min max clamp var cubic-bezier steps linear".split(" "),U={light:[255,255,255],dark:[10,10,10]},X=r=>{let o=0,h="";for(const a of r){if(h){a===h&&(h="");continue}if(a==="'"||a==='"')h=a;else if(a==="(")o+=1;else if(a===")"&&(o-=1)<0)return!1}return h===""&&o===0},Y=r=>typeof r=="string"&&r.length<=80&&W.test(r)&&r!==_,P=r=>{if(typeof r!="string")return null;const o=r.trim();if(!o||o.length>256||G.test(o)||H.test(o))return null;for(const h of o.matchAll(J))if(!K.includes((h[1]??"").toLowerCase()))return null;return X(o)?o:null},A=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const o=Object.getPrototypeOf(r);return o===Object.prototype||o===null},Z=r=>{const o={};try{if(!A(r))return o;const h=Object.keys(r);if(h.length<=512)for(const a of h){if(!Y(a))continue;const g=r[a];if(typeof g=="string"){const u=P(g);u!==null&&(o[a]=u);continue}if(!A(g))continue;const j=Object.hasOwn(g,"light"),i=Object.hasOwn(g,"dark");if(!j&&!i||Object.keys(g).some(u=>u!=="light"&&u!=="dark"))continue;const M=P(g.light),y=P(g.dark);(M!==null||y!==null)&&(o[a]={light:M,dark:y})}}catch{}return o},C=r=>{const o=P(r);if(!(!o||/\b(?:var|light-dark)\s*\(|\b(?:currentcolor|from)\b/i.test(o)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(o)))return CSS.supports("color",o)?o:void 0};return[Z,C,(r,o,h,a,g,j)=>{const i=new Map;for(const[t,n]of Object.entries(r)){const e=typeof n=="string"?n:n[o];e&&i.set(t,e)}const M=typeof a=="string"?{brand:a}:a,y={};for(const t of R){const n=M?.[t],e=typeof n=="string"?n:n?.[o];e&&(y[t]=e)}let u=null;if(i.size>0||Object.keys(y).length>0)try{const t=document.createElement("canvas");t.width=1,t.height=1,u=t.getContext("2d",{willReadFrequently:!0})}catch{u=null}const S=(t,n)=>{if(!u)return null;try{u.clearRect(0,0,1,1),u.fillStyle=t,u.fillRect(0,0,1,1);const e=u.getImageData(0,0,1,1).data,c=(e[3]??0)/255;return[0,1,2].map(f=>Math.round((e[f]??0)*c+(n[f]??0)*(1-c)))}catch{return null}},z=(t,n,e)=>t.map((c,f)=>Math.round(c*(1-e)+(n[f]??0)*e)),B=t=>{const n=t.map(e=>{const c=e/255;return c<=.04045?c/12.92:((c+.055)/1.055)**2.4});return(n[0]??0)*.2126+(n[1]??0)*.7152+(n[2]??0)*.0722},O=(t,n)=>{const e=B(t),c=B(n);return(Math.max(e,c)+.05)/(Math.min(e,c)+.05)},v=[0,0,0],F=[255,255,255],w=t=>O(t,v)>=O(t,F)?v:F,q=(t,n,e=3,c=n)=>{const f=d=>O(d,n)>=e&&O(d,c)>=e&&g.every(k=>O(d,k)>=e);if(f(t))return t;const p=w(n);for(let d=1;d<=10;d+=1){const k=z(t,p,d/10);if(f(k))return k}return p},m=t=>`rgb(${t.join(" ")})`,D=U[o],E=C(h)??C(i.get("--lr-theme-color-surface-default")),s=E&&S(E,D)||D,l=new Map(i),b="--lr-theme-",$=(t,n)=>t!==void 0&&n&&C(t)?S(t,n):null,tt=`${b}color-surface-raised`,N=$(i.get(tt)??j[1],s),L=(t,n,e,c,f)=>{const p=l.get(t);if(p===void 0||!e||f===null)return;const d=$(p,n);if(!d)return;const k=q(d,e,c,f??e);k!==d&&l.set(t,m(k))};L(`${b}color-text-normal`,s,s,4.5,N),L(`${b}color-text-quiet`,s,s,4.5,N);const et=i.has(`${b}color-text-normal`)?$(l.get(`${b}color-text-normal`),s):$(j[2],s),I=(t,n)=>{if(!n)return;const e=l.get(t),c=e===void 0?null:$(e,n);(e===void 0||c&&O(c,n)<4.5)&&l.set(t,m(w(n)))};for(const t of R)for(const n of Q){const e=`${b}color-${t}-fill-${n}`;i.has(e)&&I(`${b}color-${t}-on-${n}`,$(i.get(e),s))}const T=`${b}color-overlay-strong`;(i.has(T)||i.has(`${b}color-on-strong-overlay`))&&I(`${b}color-on-strong-overlay`,i.has(T)?$(i.get(T),s):$(j[3],s));for(const t of i.keys())/^--lr-theme-color-(?:(?:brand|success|warning|danger|neutral)-border-(?:normal|loud)|surface-border|border-strong|focus|chart-\d+)$/.test(t)?L(t,s,s,3):/^--lr-theme-terminal-color-[a-z0-9-]+$/.test(t)?L(t,N,N,4.5):/^--lr-theme-terminal-bg-[a-z0-9-]+$/.test(t)&&L(t,N,et,4.5);if(!u)return l;let V=null;for(const t of R){const n=y[t];if(!n)continue;const e=S(n,s);if(!e)continue;const c=z(s,e,o==="dark"?.24:.14),f=z(s,e,o==="dark"?.62:.55),p=q(e,s,4.5,c),d=o==="dark"?F:v,k=z(s,e,o==="dark"?.46:.38),nt=q(z(s,e,o==="dark"?.78:.72),s),ot=q(z(p,d,.2),s),x=`--lr-theme-color-${t}`;l.set(`${x}-fill-quiet`,m(c)),l.set(`${x}-fill-normal`,m(f)),l.set(`${x}-fill-loud`,m(p)),l.set(`${x}-border-quiet`,m(k)),l.set(`${x}-border-normal`,m(nt)),l.set(`${x}-border-loud`,m(ot)),l.set(`${x}-on-quiet`,m(w(c))),l.set(`${x}-on-normal`,m(w(f))),l.set(`${x}-on-loud`,m(w(p))),t==="brand"&&(l.set("--lr-theme-color-focus",m(q(e,s))),V=n)}return V&&l.set("--lr-theme-accent",V),l}]}function styleMaterial(l,n){const t=n==="glass";for(const[a,i]of Object.entries({enabled:t?"1":"0",content:t?"''":"none",isolation:t?"isolate":"auto","root-filter":t?"initial":"none","child-filter":t?"none":"initial","child-opacity":t?"1":"0"}))l.set(`--_lr-surface-${a}`,i);l.set("--_lr-glass-blocker",t?"initial":"none"),t||(l.set("--_lr-glass-parent-opacity","0"),l.set("--_lr-next-glass-opacity","0"))}function applyStoredStyleBeforePaint(U,q,D,N,G,J,W,S){const{surfaces:R,contrast:H,accent:Q}=S,b=new Map;for(const r of S.inputs.split(" "))b.set(`--lr-theme-${r.slice(1)}`,Number(r[0]));const _=[...b.keys()];function v(r,n,s=!1){return`--_lr-${s?"a":"l"}${n==="light"?"l":"d"}-${r.slice(11)}`}function V(r,n){const s=b.get(r)??0;let g=`var(${v(r,n)})`;if(s&2){const k=n==="light"?"l":"d",u=r.replace(/color-(?:success|warning|danger|neutral)-/,"color-brand-");g=`var(--_lr-f${k}-${r.slice(11)},${g})var(--_lr-o${k}-${r.slice(11)},var(${v(u,n,!0)},var(${v(u,n)})))`}return s&4?`var(${v(r,n,!0)},${g})`:g}function X(r){const n=`var(--_lr-dark-on,${V(r,"light")})var(--_lr-light-on,${V(r,"dark")})`;if(!((b.get(r)??0)&1))return n;const s=r.startsWith("--lr-theme-space-");return`var(--_lr-dense-on,${n})var(--_lr-dense-off,max(calc((${n}) * var(--_lr-density-${s?"space":"control"},1)),${s?"0px":"var(--_lr-density-target-min,0px)"}))`}try{const r=document.currentScript,n=r?.getAttribute("data-lr-theme-restore"),s=(n==="all"||n==="mode"?n:S.restore)==="mode",g=r?.getAttribute("data-lr-theme-storage-key"),k=g&&g.length<=200?g:U,u=r?.getAttribute("data-lr-theme-attributes")?.trim().split(/\s+/),A=u?.length&&u.length<=8&&new Set(u).size===u.length&&u.every(t=>t.length<=64&&/^data-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t))?u:q;let w;try{w=JSON.parse(localStorage.getItem(k)??"null")}catch{}if(s){const t=w;w={version:t?.version,mode:t?.mode}}const o=document.documentElement,[Z,tt,et]=D(),f=J(w,S.defaults,Z,tt,(t,e)=>N(t,e,_),Q),y=f.mode,$=y==="unset"?null:y==="system"?matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":y,p={},j=!s&&getComputedStyle(o).getPropertyValue("--_lr-style-resolver").trim()==="1",C=(t,e)=>typeof t=="string"?t:t?.[e],rt=f.tokens,ot=f.overrides,E={...rt,...ot},L=f.look;if(s||(p["data-lr-look"]=L,p["data-lr-density"]=f.density,p["data-lr-surface"]=f.treatment),y!=="unset"&&(p["data-lr-mode"]=y),$)for(const t of A)p[t]=$;const O=f.accentName;let h=f.accent;y!=="unset"&&h&&typeof h=="object"&&!Object.values(h).some(t=>typeof t=="string"||t&&Object.values(t).some(Boolean))&&(h=null),s||(p["data-lr-accent"]=O??(h?"custom":"none"));const a=new Map;if(y==="unset")for(const[t,e]of Object.entries(E))typeof e=="string"&&a.set(t,e);for(const t of s?[]:["light","dark"]){const e=C(f.surface,t),T=C(E["--lr-theme-color-surface-default"],t),c=(R[L]??R.lyra)[t],z=e??T??c[0];for(const m of[!1,!0]){if(m&&(!h||O))continue;const st=et(m?{}:E,t,z,m?h:null,m?H[t].map(l=>[1,3,5].map(d=>parseInt(l.slice(d,d+2),16))):[],c);for(const[l,d]of st){if(l==="--lr-theme-accent"){t===$&&a.set(l,d);continue}const B=b.get(l);if(B!==void 0&&N(l,d,_)){const F=l.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1],M=!m&&F&&d===`var(--lr-theme-color-brand-${F})`,I=l.slice(11),K=t==="light"?"l":"d";M||a.set(v(l,t,m),d),!m&&B&2&&(a.set(`--_lr-f${K}-${I}`,M?" ":"initial"),a.set(`--_lr-o${K}-${I}`,M?"initial":" ")),t===$&&a.set(l,j?X(l):d)}else t===$&&a.set(l,d)}}}(a.size||y==="unset"&&h&&!O)&&(p["data-lr-theme-scope"]=""),!s&&!j&&W(a,f.treatment);const Y=Symbol.for("@aceshooting/lyra-ui.style-ownership.v1"),P=o;let x;try{x=G(P[Y])}catch{}const i=x??{attributes:new Map,properties:new Map};if(y==="unset")for(const t of A)i.attributes.has(t)||o.removeAttribute(t);try{const t=Symbol.for("@aceshooting/lyra-ui.theme-tokens.v1"),e=P[t];if(!s&&Array.isArray(e)){const T=e.slice(0,528).filter(c=>typeof c=="string"&&c.length<=80&&/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c));for(const c of[...T,..._.filter(z=>b.get(z)&4),"--lr-theme-accent"])!i.properties.has(c)&&o.style.getPropertyValue(c)&&i.properties.set(c,{before:null,priority:"",written:o.style.getPropertyValue(c)});try{delete P[t]}catch{}}}catch{}for(const[t,e]of i.attributes)s&&t!=="data-lr-mode"&&!A.includes(t)||Object.hasOwn(p,t)||(o.getAttribute(t)===e.written&&(e.before===null?o.removeAttribute(t):o.setAttribute(t,e.before)),i.attributes.delete(t));for(const[t,e]of Object.entries(p))i.attributes.has(t)||i.attributes.set(t,{before:o.getAttribute(t),priority:"",written:e}),o.setAttribute(t,e),i.attributes.get(t).written=e;for(const[t,e]of i.properties)s||a.has(t)||(o.style.getPropertyValue(t)===e.written&&!o.style.getPropertyPriority(t)&&(e.before?o.style.setProperty(t,e.before,e.priority):o.style.removeProperty(t)),i.properties.delete(t));for(const[t,e]of a)i.properties.has(t)||i.properties.set(t,{before:o.style.getPropertyValue(t),priority:o.style.getPropertyPriority(t),written:null}),o.style.getPropertyPriority(t)&&o.style.removeProperty(t),o.style.setProperty(t,e,""),i.properties.get(t).written=o.style.getPropertyValue(t);try{P[Y]=i}catch{}}catch{}}const LINE_SEPARATOR="\u2028",PARAGRAPH_SEPARATOR="\u2029";function serializeInlineScriptData(value){return JSON.stringify(value).replace(/</g,"\\u003c").replace(new RegExp(LINE_SEPARATOR,"g"),"\\u2028").replace(new RegExp(PARAGRAPH_SEPARATOR,"g"),"\\u2029")}function createLyraThemeBootstrap(options={}){const storageKey=options.storageKey??STORAGE_KEY,inputs=STYLE_SLOTTED.map(name=>`${Number(STYLE_DENSITY.includes(name))|Number(STYLE_FOLLOW.includes(name))<<1|Number(ALL_RAMP_PROPERTIES.includes(name))<<2}${name.slice(11)}`).join(" "),model=JSON.stringify({restore:options.restore==="mode"?"mode":"all",defaults:STYLE_DEFAULTS,inputs,surfaces:STYLE_REFERENCE_SURFACES,contrast:STYLE_CONTRAST_SURFACES,accent:STYLE_GEMSTONES}),functions=[applyStoredStyleBeforePaint,applyStoredThemeBeforePaint,styleTokenAllowed,readStyleOwnership,resolveStyleStartup,styleMaterial].map(helper=>helper.toString().replace(/^function\s+[\w$]+/,"function"));return`(${functions[0]})(${serializeInlineScriptData(storageKey)},${serializeInlineScriptData(MODE_ATTRIBUTES)},${functions.slice(1).join(",")},${model});`}const STYLE_DEFAULTS=Object.freeze({look:"shadcn",surface:"glass",density:"comfortable",mode:"system",accent:"emerald"}),STYLE_SLOTTED=["--lr-theme-color-border-strong","--lr-theme-color-brand-border-loud","--lr-theme-color-brand-border-normal","--lr-theme-color-brand-border-quiet","--lr-theme-color-brand-fill-loud","--lr-theme-color-brand-fill-normal","--lr-theme-color-brand-fill-quiet","--lr-theme-color-brand-on-loud","--lr-theme-color-brand-on-normal","--lr-theme-color-brand-on-quiet","--lr-theme-color-chart-1","--lr-theme-color-chart-2","--lr-theme-color-chart-3","--lr-theme-color-chart-4","--lr-theme-color-chart-5","--lr-theme-color-chart-6","--lr-theme-color-chart-7","--lr-theme-color-chart-8","--lr-theme-color-chart-diverging-1","--lr-theme-color-chart-diverging-2","--lr-theme-color-chart-diverging-3","--lr-theme-color-chart-sequential-1","--lr-theme-color-chart-sequential-2","--lr-theme-color-chart-sequential-3","--lr-theme-color-danger-border-loud","--lr-theme-color-danger-border-normal","--lr-theme-color-danger-border-quiet","--lr-theme-color-danger-fill-loud","--lr-theme-color-danger-fill-normal","--lr-theme-color-danger-fill-quiet","--lr-theme-color-danger-on-loud","--lr-theme-color-danger-on-normal","--lr-theme-color-danger-on-quiet","--lr-theme-color-focus","--lr-theme-color-mix-partner","--lr-theme-color-neutral-border-loud","--lr-theme-color-neutral-border-normal","--lr-theme-color-neutral-border-quiet","--lr-theme-color-neutral-fill-loud","--lr-theme-color-neutral-fill-normal","--lr-theme-color-neutral-fill-quiet","--lr-theme-color-neutral-on-loud","--lr-theme-color-neutral-on-normal","--lr-theme-color-neutral-on-quiet","--lr-theme-color-no-data","--lr-theme-color-on-strong-overlay","--lr-theme-color-overlay","--lr-theme-color-overlay-strong","--lr-theme-color-success-border-loud","--lr-theme-color-success-border-normal","--lr-theme-color-success-border-quiet","--lr-theme-color-success-fill-loud","--lr-theme-color-success-fill-normal","--lr-theme-color-success-fill-quiet","--lr-theme-color-success-on-loud","--lr-theme-color-success-on-normal","--lr-theme-color-success-on-quiet","--lr-theme-color-surface-border","--lr-theme-color-surface-border-subtle","--lr-theme-color-surface-container","--lr-theme-color-surface-container-high","--lr-theme-color-surface-container-highest","--lr-theme-color-surface-container-low","--lr-theme-color-surface-container-lowest","--lr-theme-color-surface-default","--lr-theme-color-surface-overlay","--lr-theme-color-surface-raised","--lr-theme-color-text-normal","--lr-theme-color-text-quiet","--lr-theme-color-warning-border-loud","--lr-theme-color-warning-border-normal","--lr-theme-color-warning-border-quiet","--lr-theme-color-warning-fill-loud","--lr-theme-color-warning-fill-normal","--lr-theme-color-warning-fill-quiet","--lr-theme-color-warning-on-loud","--lr-theme-color-warning-on-normal","--lr-theme-color-warning-on-quiet","--lr-theme-form-control-height-2xs","--lr-theme-form-control-height-l","--lr-theme-form-control-height-m","--lr-theme-form-control-height-s","--lr-theme-form-control-height-xl","--lr-theme-form-control-height-xs","--lr-theme-graph-cat-1","--lr-theme-graph-cat-2","--lr-theme-graph-cat-3","--lr-theme-graph-cat-4","--lr-theme-graph-cat-5","--lr-theme-graph-cat-6","--lr-theme-graph-cat-7","--lr-theme-graph-cat-8","--lr-theme-icon-button-size","--lr-theme-shadow-l","--lr-theme-shadow-m","--lr-theme-shadow-s","--lr-theme-shadow-xl","--lr-theme-shadow-xs","--lr-theme-space-2xl","--lr-theme-space-2xs","--lr-theme-space-l","--lr-theme-space-m","--lr-theme-space-s","--lr-theme-space-xs","--lr-theme-terminal-bg-black","--lr-theme-terminal-bg-blue","--lr-theme-terminal-bg-bright-black","--lr-theme-terminal-bg-bright-blue","--lr-theme-terminal-bg-bright-cyan","--lr-theme-terminal-bg-bright-green","--lr-theme-terminal-bg-bright-magenta","--lr-theme-terminal-bg-bright-red","--lr-theme-terminal-bg-bright-white","--lr-theme-terminal-bg-bright-yellow","--lr-theme-terminal-bg-cyan","--lr-theme-terminal-bg-green","--lr-theme-terminal-bg-magenta","--lr-theme-terminal-bg-red","--lr-theme-terminal-bg-white","--lr-theme-terminal-bg-yellow","--lr-theme-terminal-color-black","--lr-theme-terminal-color-blue","--lr-theme-terminal-color-bright-black","--lr-theme-terminal-color-bright-blue","--lr-theme-terminal-color-bright-cyan","--lr-theme-terminal-color-bright-green","--lr-theme-terminal-color-bright-magenta","--lr-theme-terminal-color-bright-red","--lr-theme-terminal-color-bright-white","--lr-theme-terminal-color-bright-yellow","--lr-theme-terminal-color-cyan","--lr-theme-terminal-color-green","--lr-theme-terminal-color-magenta","--lr-theme-terminal-color-red","--lr-theme-terminal-color-white","--lr-theme-terminal-color-yellow"],STYLE_DENSITY=["--lr-theme-space-2xs","--lr-theme-space-xs","--lr-theme-space-s","--lr-theme-space-m","--lr-theme-space-l","--lr-theme-space-2xl","--lr-theme-form-control-height-2xs","--lr-theme-form-control-height-xs","--lr-theme-form-control-height-s","--lr-theme-form-control-height-m","--lr-theme-form-control-height-l","--lr-theme-form-control-height-xl","--lr-theme-icon-button-size"],STYLE_FOLLOW=["--lr-theme-color-danger-border-loud","--lr-theme-color-danger-border-normal","--lr-theme-color-danger-border-quiet","--lr-theme-color-danger-fill-loud","--lr-theme-color-danger-fill-normal","--lr-theme-color-danger-fill-quiet","--lr-theme-color-danger-on-loud","--lr-theme-color-danger-on-normal","--lr-theme-color-danger-on-quiet","--lr-theme-color-neutral-border-loud","--lr-theme-color-neutral-border-normal","--lr-theme-color-neutral-border-quiet","--lr-theme-color-neutral-fill-loud","--lr-theme-color-neutral-fill-normal","--lr-theme-color-neutral-fill-quiet","--lr-theme-color-neutral-on-loud","--lr-theme-color-neutral-on-normal","--lr-theme-color-neutral-on-quiet","--lr-theme-color-success-border-loud","--lr-theme-color-success-border-normal","--lr-theme-color-success-border-quiet","--lr-theme-color-success-fill-loud","--lr-theme-color-success-fill-normal","--lr-theme-color-success-fill-quiet","--lr-theme-color-success-on-loud","--lr-theme-color-success-on-normal","--lr-theme-color-success-on-quiet","--lr-theme-color-warning-border-loud","--lr-theme-color-warning-border-normal","--lr-theme-color-warning-border-quiet","--lr-theme-color-warning-fill-loud","--lr-theme-color-warning-fill-normal","--lr-theme-color-warning-fill-quiet","--lr-theme-color-warning-on-loud","--lr-theme-color-warning-on-normal","--lr-theme-color-warning-on-quiet"],STYLE_REFERENCE_SURFACES={lyra:{light:["#ffffff","#f6f8fa","#1a1a1a","rgb(0 0 0 / 0.92)"],dark:["#1a1a1a","#22272e","#f2f2f2","rgb(0 0 0 / 0.95)"]},data:{light:["#ffffff","#f2f5f8","#10202c","#17212b"],dark:["#101820","#192630","#eef5fa","#e7eef4"]},"high-contrast":{light:["#ffffff","#ffffff","#000000","#17212b"],dark:["#000000","#000000","#ffffff","#e7eef4"]},material:{light:["#fff8f5","#f8eeea","#241b17","rgb(0 0 0 / 0.92)"],dark:["#18120f","#251d19","#f8eee8","rgb(0 0 0 / 0.95)"]},shadcn:{light:["#ffffff","#fafafa","#0a0a0a","rgb(0 0 0 / 0.92)"],dark:["#0a0a0a","#171717","#fafafa","rgb(0 0 0 / 0.95)"]},terminal:{light:["#fcfdf9","#f1f5eb","#0d2115","#17212b"],dark:["#0e1713","#18271e","#e5f5e9","#e7eef4"]}},STYLE_CONTRAST_SURFACES={light:["#ffffff","#f6f8fa","#f2f5f8","#fff8f5","#f8eeea","#fcf2ed","#f2e7e0","#ecdfd7","#fafafa","#fcfdf9","#f1f5eb"],dark:["#1a1a1a","#22272e","#2b3038","#101820","#192630","#202e39","#000000","#18120f","#251d19","#302621","#120d0a","#211914","#352a24","#0a0a0a","#171717","#0e1713","#18271e","#203227"]},STYLE_GEMSTONES={emerald:"#34d399",peridot:"#a8d84a",topaz:"#f0a83c",ruby:"#e63950",tourmaline:"#ec4899",amethyst:"#9d6df0",aquamarine:"#22d3ee",sapphire:"#4f8ff7",hematite:"#94a3b8"},LOOK_ID=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,LOOK_STAMP=Symbol.for("@aceshooting/lyra-ui.look.v1"),STYLE_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.style-ownership.v1"),STYLE_FIELDS=["look","surface","density","mode","accent","accentBackground","overrides"],DEFAULT_STYLE=Object.freeze({...STYLE_DEFAULTS,tokens:null,accent:STYLE_GEMSTONES[STYLE_DEFAULTS.accent],accentName:STYLE_DEFAULTS.accent,accentBackground:null,overrides:null});let lastStyle={...DEFAULT_STYLE},stylePersistenceFailed=!1,styleModeCleanup,styleModeRoot;const styleOwnershipFallback=new WeakMap,scopeModes=new WeakMap;function ownField(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}function styleId(value){return typeof value=="string"&&value.length<=64&&LOOK_ID.test(value)}function styleTokenAllowed(e,r,o=STYLE_SLOTTED){if(e.startsWith("--lr-theme-surface-")||typeof r!="string"&&!o.includes(e))return!1;for(const t of typeof r=="string"?[r]:[r.light,r.dark])if(t)for(const c of t.matchAll(/var\(\s*(--[\w-]+)/g)){if(c[1]==="--lr-theme-shadow-color")continue;const n=e.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1];if(!n||t!==`var(--lr-theme-color-brand-${n})`)return!1}return!0}function styleTokens(value){const tokens=normalizeTokens(value);if(!tokens)return null;const entries=Object.entries(tokens).filter(([name,input])=>styleTokenAllowed(name,input));return entries.length?Object.freeze(Object.fromEntries(entries)):null}function defineLyraLook(look){if(!look||!styleId(ownField(look,"id"))||look.id==="custom")throw new TypeError("Invalid look id");const raw=ownField(look,"tokens");if(!isPlainRecord(raw)||Object.keys(raw).length>TOKEN_ENTRY_MAX)throw new TypeError("Invalid look tokens");for(const[name,descriptor]of Object.entries(Object.getOwnPropertyDescriptors(raw))){if(!("value"in descriptor))throw new TypeError(`Look inputs must be data properties: ${name}`);const value=descriptor.value;if(typeof value=="string"){if(!isSafeLyraThemeTokenValue(value))throw new TypeError(`Invalid look value: ${name}`);continue}if(!isPlainRecord(value)||!STYLE_SLOTTED.includes(name))throw new TypeError(`Invalid per-mode look input: ${name}`);const branches=Object.entries(Object.getOwnPropertyDescriptors(value));if(!branches.length||branches.some(([key,branch])=>!["light","dark"].includes(key)||!("value"in branch)||branch.value!==null&&!isSafeLyraThemeTokenValue(branch.value)))throw new TypeError(`Invalid look mode pair: ${name}`)}const tokens=styleTokens(raw);if(Object.keys(raw).length!==Object.keys(tokens??{}).length)throw new TypeError("Invalid look token or cross-axis reference");const stamped={...tokens,[LOOK_STAMP]:look.id};return Object.freeze(stamped),Object.freeze({id:look.id,tokens:stamped})}function styleColor(value,browserColors=!1){if(!isSafeLyraThemeTokenValue(value))return null;const text=value.trim();return/\b(?:var|light-dark)\s*\(|\b(?:currentcolor|from)\b/i.test(text)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(text)?null:browserColors&&typeof CSS<"u"?CSS.supports("color",text)?text:null:/^(?:#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})|[a-z]+|(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\(.+\))$/i.test(text)?text:null}function styleColorPair(value){if(typeof value=="string")return styleColor(value);if(!isPlainRecord(value))return null;const light=styleColor(ownField(value,"light")),dark=styleColor(ownField(value,"dark"));return light||dark?Object.freeze({light,dark}):null}function styleAccent(value){if(typeof value=="string")return styleColor(value);if(!isPlainRecord(value))return null;const entries=SEMANTIC_ROLES.filter(role=>Object.hasOwn(value,role)).map(role=>[role,styleColorPair(ownField(value,role))]);return entries.length?Object.freeze(Object.fromEntries(entries)):null}function normalizeStyleChoices(raw,base){const next={...base};if(!isPlainRecord(raw))return next;const look=ownField(raw,"look");if(look!==void 0){if(next.look=DEFAULT_STYLE.look,next.tokens=null,styleId(look))next.look=look;else if(isPlainRecord(look))try{const definition=defineLyraLook(look);next.look=definition.id,next.tokens=definition.tokens}catch{}}const surface=ownField(raw,"surface");surface!==void 0&&(next.surface=surface==="glass"||surface==="solid"?surface:DEFAULT_STYLE.surface);const density=ownField(raw,"density");density!==void 0&&(next.density=density==="comfortable"||density==="compact"||density==="touch"?density:DEFAULT_STYLE.density);const mode=ownField(raw,"mode");mode!==void 0&&(next.mode=mode==="light"||mode==="dark"||mode==="system"||mode==="unset"?mode:DEFAULT_STYLE.mode);const accent=ownField(raw,"accent");accent!==void 0&&(next.accentName=typeof accent=="string"&&Object.hasOwn(STYLE_GEMSTONES,accent)?accent:null,next.accent=next.accentName?STYLE_GEMSTONES[next.accentName]:styleAccent(accent));const background=ownField(raw,"accentBackground");background!==void 0&&(next.accentBackground=styleColorPair(background));const overrides=ownField(raw,"overrides");return overrides!==void 0&&(next.overrides=styleTokens(overrides)),next}function styleFromRecord(value,browserColors=!1){const record=resolveStyleStartup(value,STYLE_DEFAULTS,normalizeTokens,input=>styleColor(input,browserColors)??void 0,styleTokenAllowed,STYLE_GEMSTONES),state=normalizeStyleChoices({look:ownField(record,"look"),mode:ownField(record,"mode"),density:ownField(record,"density"),surface:ownField(record,"treatment"),overrides:ownField(record,"overrides"),accentBackground:ownField(record,"surface")},{...DEFAULT_STYLE});state.accent=styleAccent(ownField(record,"accent"));const accentName=ownField(record,"accentName");return state.accentName=null,typeof accentName=="string"&&Object.hasOwn(STYLE_GEMSTONES,accentName)&&(state.accentName=accentName,state.accent=STYLE_GEMSTONES[accentName]),state.tokens=normalizeTokens(ownField(record,"tokens")),state.tokens&&!styleId(ownField(record,"look"))&&(state.look="custom"),state}function styleRecord(state){return{version:2,mode:state.mode,look:state.look,density:state.density,treatment:state.surface,accent:state.accent,surface:state.accentBackground,...state.accentName?{accentName:state.accentName}:{},...state.tokens?{tokens:state.tokens}:{},...state.overrides?{overrides:state.overrides}:{}}}function styleResolvedMode(mode,view){return mode==="unset"?null:mode!=="system"?mode:view?.matchMedia?.(COLOR_SCHEME_QUERY).matches?"dark":"light"}function styleSnapshot(state,view){return Object.freeze({look:state.look,lookForm:state.tokens?"runtime":"stylesheet",surface:state.surface,density:state.density,mode:state.mode,accent:state.accentName??state.accent,accentName:state.accentName,accentBackground:state.accentBackground,...state.overrides?{overrides:state.overrides}:{},resolvedMode:styleResolvedMode(state.mode,view)})}function parseLyraStyleRecord(value){const state=styleFromRecord(value),result=styleSnapshot(state);return state.mode==="system"?Object.freeze({...result,resolvedMode:null}):result}function lyraStyleAttributes(style){const attributes={};return styleId(style.look)&&(attributes["data-lr-look"]=style.look),(style.surface==="solid"||style.surface==="glass")&&(attributes["data-lr-surface"]=style.surface),(style.density==="compact"||style.density==="comfortable"||style.density==="touch")&&(attributes["data-lr-density"]=style.density),(style.mode==="light"||style.mode==="dark"||style.mode==="system")&&(attributes["data-lr-mode"]=style.mode),style.accent!==void 0&&(attributes["data-lr-accent"]=style.accent===null?"none":style.accentName===null?"custom":typeof style.accent=="string"&&Object.hasOwn(STYLE_GEMSTONES,style.accent)?style.accent:"custom"),Object.freeze(attributes)}function readStyleState(){if(stylePersistenceFailed)return{...lastStyle};let stored;try{stored=localStorage.getItem(STORAGE_KEY)}catch{return{...lastStyle}}try{return styleFromRecord(JSON.parse(stored??"null"),!0)}catch{return{...DEFAULT_STYLE}}}function persistStyle(state){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(styleRecord(state))),stylePersistenceFailed=!1}catch{stylePersistenceFailed=!0}lastStyle=state}function ownershipFor(element){const node=element;try{const existing=readStyleOwnership(node[STYLE_OWNERSHIP]);if(existing){styleOwnershipFallback.set(element,existing);try{node[STYLE_OWNERSHIP]=existing}catch{}return existing}}catch{}const fallback=styleOwnershipFallback.get(element);if(fallback)return fallback;const record={attributes:new Map,properties:new Map};styleOwnershipFallback.set(element,record);try{node[STYLE_OWNERSHIP]=record}catch{}return record}function writeStyleAttributes(element,desired){const ownership=ownershipFor(element).attributes;for(const[name,value]of ownership)Object.hasOwn(desired,name)||(element.getAttribute(name)===value.written&&(value.before===null?element.removeAttribute(name):element.setAttribute(name,value.before)),ownership.delete(name));for(const[name,value]of Object.entries(desired))ownership.has(name)||ownership.set(name,{before:element.getAttribute(name),priority:"",written:value}),element.getAttribute(name)!==value&&element.setAttribute(name,value),ownership.get(name).written=value}function writeStyleProperties(element,desired){const style=element.style;if(!style)return;const ownership=ownershipFor(element).properties;for(const[name,value]of ownership)desired.has(name)||(style.getPropertyValue(name)===value.written&&style.getPropertyPriority(name)===""&&(value.before?style.setProperty(name,value.before,value.priority):style.removeProperty(name)),ownership.delete(name));for(const[name,value]of desired){ownership.has(name)||ownership.set(name,{before:style.getPropertyValue(name),priority:style.getPropertyPriority(name),written:null});const record=ownership.get(name);(style.getPropertyPriority(name)!==""||style.getPropertyValue(name)!==value&&!(record.requested===value&&record.written===style.getPropertyValue(name)))&&(style.getPropertyPriority(name)&&style.removeProperty(name),style.setProperty(name,value,"")),record.requested=value,record.written=style.getPropertyValue(name)}}function styleSlot(name,mode,accent=!1){return`--_lr-${accent?"a":"l"}${mode==="light"?"l":"d"}-${name.slice(11)}`}function styleFollow(name,value){const channel=name.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1];return!!(channel&&value===`var(--lr-theme-color-brand-${channel})`)}function styleBranch(name,mode){let result=`var(${styleSlot(name,mode)})`;if(STYLE_FOLLOW.includes(name)){const key=mode==="light"?"l":"d",target=name.replace(/color-(?:success|warning|danger|neutral)-/,"color-brand-");result=`var(--_lr-f${key}-${name.slice(11)},${result})var(--_lr-o${key}-${name.slice(11)},var(${styleSlot(target,mode,!0)},var(${styleSlot(target,mode)})))`}return ALL_RAMP_PROPERTIES.includes(name)?`var(${styleSlot(name,mode,!0)},${result})`:result}function styleResolvedInput(name){const input=`var(--_lr-dark-on,${styleBranch(name,"light")})var(--_lr-light-on,${styleBranch(name,"dark")})`;if(!STYLE_DENSITY.includes(name))return input;const spacing=name.startsWith("--lr-theme-space-");return`var(--_lr-dense-on,${input})var(--_lr-dense-off,max(calc((${input}) * var(--_lr-density-${spacing?"space":"control"},1)),${spacing?"0px":"var(--_lr-density-target-min,0px)"}))`}function styleReferences(state,entries,mode,element,previous){const look=element.closest("[data-lr-look]")?.getAttribute("data-lr-look"),colors=(STYLE_REFERENCE_SURFACES[look??STYLE_DEFAULTS.look]??STYLE_REFERENCE_SURFACES.lyra)[mode],names=["color-surface-default","color-surface-raised","color-text-normal","color-overlay-strong"].slice(0,entries.size?4:1).map(suffix=>`--lr-theme-${suffix}`),supplied=names.map(name=>entries.get(name)),background=typeof state.accentBackground=="string"?state.accentBackground:state.accentBackground?.[mode],style=element.style,ownership=ownershipFor(element).properties,projected=names.flatMap((name,index)=>{const slot=styleSlot(name,mode),owned=ownership.get(slot),before=style?.getPropertyValue(slot)??"",priority=style?.getPropertyPriority(slot)??"",owns=owned&&before===owned.written&&!priority;if(supplied[index]!==void 0&&previous?.[index]===supplied[index]&&owns)return[];if(supplied[index]===void 0&&!owns)return[];const value=supplied[index]??owned?.before??"",nextPriority=supplied[index]===void 0?owned?.priority??"":"";return before===value&&priority===nextPriority?[]:[{slot,before,priority,value,nextPriority}]});try{for(const{slot,value,nextPriority}of projected)style.getPropertyPriority(slot)&&style.removeProperty(slot),value?style.setProperty(slot,value,nextPriority):style.removeProperty(slot);const computed=element.ownerDocument.defaultView?.getComputedStyle(element);return{supplied,colors:names.map((name,index)=>(index===0?background:void 0)??supplied[index]??(computed?.getPropertyValue(styleSlot(name,mode)).trim()||colors[index]))}}finally{for(const{slot,before,priority}of projected)style.getPropertyPriority(slot)&&style.removeProperty(slot),before?style.setProperty(slot,before,priority):style.removeProperty(slot)}}const stylePaintCache=new WeakMap;function stylePaint(state,element,wholeDocument){const desired=new Map,mode=styleResolvedMode(state.mode,element.ownerDocument.defaultView),tokens={...state.tokens,...state.overrides};if(wholeDocument&&mode===null)for(const[name,value]of tokenEntries(tokens,null))desired.set(name,value);if(!Object.keys(tokens).length&&(!state.accent||state.accentName))return stylePaintCache.delete(element),desired;const resolver=element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue("--_lr-style-resolver").trim()==="1";let cache=stylePaintCache.get(element);cache||(cache=new Map,stylePaintCache.set(element,cache));let applied=state.accent;for(const branch of["light","dark"]){const entries=tokenEntries(tokens,branch),{colors:references,supplied}=styleReferences(state,entries,branch,element,cache.get(branch)?.supplied),reference=references[0],key=JSON.stringify([tokens,state.accent,state.accentName,references]);let cached=cache.get(branch);if(!cached||cached.key!==key){const background=reference?parseResolvedRgb(reference,MODE_SURFACES[branch],element.ownerDocument)??MODE_SURFACES[branch]:MODE_SURFACES[branch],accent=state.accentName?{applied:state.accent,properties:new Map}:paintAccent(state.accent,branch,background,element.ownerDocument);cached={key,supplied,tokens:floorTokenEntries(entries,background,element.ownerDocument,references),accent:accent.properties,applied:accent.applied},cache.set(branch,cached)}branch===mode&&(applied=cached.applied);const painted=cached.tokens;for(const[name,value]of painted)STYLE_SLOTTED.includes(name)&&styleTokenAllowed(name,value)?(styleFollow(name,value)?(desired.set(`--_lr-f${branch==="light"?"l":"d"}-${name.slice(11)}`," "),desired.set(`--_lr-o${branch==="light"?"l":"d"}-${name.slice(11)}`,"initial")):(desired.set(styleSlot(name,branch),value),STYLE_FOLLOW.includes(name)&&(desired.set(`--_lr-f${branch==="light"?"l":"d"}-${name.slice(11)}`,"initial"),desired.set(`--_lr-o${branch==="light"?"l":"d"}-${name.slice(11)}`," "))),wholeDocument&&branch===mode&&desired.set(name,resolver?styleResolvedInput(name):value)):(wholeDocument?branch===mode:typeof tokens[name]=="string"&&!STYLE_SLOTTED.includes(name))&&desired.set(name,value);if(state.accent&&!state.accentName)for(const[name,value]of cached.accent){if(name==="--lr-theme-accent"){branch===mode&&desired.set(name,value);continue}desired.set(styleSlot(name,branch,!0),value),wholeDocument&&branch===mode&&desired.set(name,resolver?styleResolvedInput(name):value)}}return state.accent=applied,desired}const styleModeGroups=new WeakMap;function attachStyleMode(element,callback){const view=element.ownerDocument.defaultView;if(!view?.matchMedia)return()=>{};let group=styleModeGroups.get(view);if(!group){const query=view.matchMedia(COLOR_SCHEME_QUERY),subscriptions=new Set,modern=typeof query.addEventListener=="function"&&typeof query.removeEventListener=="function",detach=()=>{modern?query.removeEventListener("change",listener):query.removeListener?.(listener)},listener=()=>{for(const subscription2 of subscriptions){const node=subscription2.element.deref();node?.ownerDocument.defaultView===view?subscription2.callback(node):subscriptions.delete(subscription2)}subscriptions.size||(detach(),styleModeGroups.delete(view))};group={query,subscriptions,detach},styleModeGroups.set(view,group),modern?query.addEventListener("change",listener):query.addListener?.(listener)}const subscription={element:new WeakRef(element),callback};group.subscriptions.add(subscription);const active=group;return()=>{active.subscriptions.delete(subscription),active.subscriptions.size||(active.detach(),styleModeGroups.delete(view))}}function applyStyleState(element,state,fields){const snapshot=styleSnapshot(state,element.ownerDocument.defaultView),attributes={...lyraStyleAttributes(snapshot)};if(fields)for(const[field,name]of[["look","look"],["surface","surface"],["density","density"],["mode","mode"],["accent","accent"]])fields.has(field)||delete attributes[`data-lr-${name}`];state.accent&&!state.accentName&&(!fields||fields.has("accent"))&&(attributes["data-lr-accent"]="custom"),(!fields||fields.has("mode"))&&snapshot.resolvedMode&&(attributes["data-lr-theme"]=snapshot.resolvedMode,attributes["data-theme"]=snapshot.resolvedMode),(state.tokens||state.overrides||state.accent&&!state.accentName)&&(attributes["data-lr-theme-scope"]=""),writeStyleAttributes(element,attributes);const desired=stylePaint(state,element,!fields);(!fields||fields.has("surface"))&&element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue("--_lr-style-resolver").trim()!=="1"&&styleMaterial(desired,state.surface),!state.accent&&snapshot.accent&&(attributes["data-lr-accent"]="none",!state.tokens&&!state.overrides&&delete attributes["data-lr-theme-scope"],writeStyleAttributes(element,attributes)),writeStyleProperties(element,desired),adoptTokenLayerForScope(element),diagnoseStyleSheets(element,state,fields)}function adoptTokenLayerForScope(element){const root=element.getRootNode();if(root===element.ownerDocument||root.nodeType!==11)return;const adopt=globalThis[Symbol.for("@aceshooting/lyra-ui.adopt-lyra-tokens.v1")];typeof adopt=="function"&&adopt(root)}function diagnoseStyleSheets(element,state,fields){if(!litDevWarnings())return;const selected=field=>!fields||fields.has(field),required=[];selected("look")&&!state.tokens&&state.look!=="lyra"&&state.look!==DEFAULT_STYLE.look&&required.push(["--_lr-look-installed",`${state.look}-1`,`the stylesheet for look '${state.look}'`]),selected("surface")&&state.surface==="glass"&&state.surface!==DEFAULT_STYLE.surface&&required.push(["--_lr-surface-installed","1","surfaces/glass.css"]),selected("density")&&state.density!=="comfortable"&&required.push(["--_lr-density-installed","1","density.css"]),selected("accent")&&state.accentName&&state.accentName!==DEFAULT_STYLE.accentName&&required.push(["--_lr-accent-installed",`${state.accentName}-1`,"accents.css"]);const scopedRuntime=!!(fields&&(state.tokens||state.overrides||state.accent&&!state.accentName)),alternateProfile=selected("look")&&!state.tokens&&state.look!==DEFAULT_STYLE.look||selected("accent")&&!state.accent;if(!required.length&&!scopedRuntime&&!alternateProfile)return;const computed=element.ownerDocument.defaultView?.getComputedStyle(element);if(computed){computed.getPropertyValue("--_lr-style-resolver").trim()!=="1"&&devWarnOnce("lyra-style:resolver","Lyra style choices require theme.css in the scope that owns their attributes.");for(const[property,expected,stylesheet]of required)computed.getPropertyValue(property).trim()!==expected&&devWarnOnce(`lyra-style:${property}:${expected}`,`Lyra could not find ${stylesheet} in this style scope; import or adopt the stylesheet before selecting it.`)}}function emitStyleChange(state,changed){const style=styleSnapshot(state,window);window.dispatchEvent(new CustomEvent("lr-style-change",{detail:Object.freeze({style,changed:Object.freeze([...changed])})}))}function setLyraStyle(choices){const before=readStyleState();return commitStyle(before,normalizeStyleChoices(choices,before))}function commitStyle(before,next){if(typeof document<"u"&&(next.accent=normalizeAccent(next.accent),typeof next.accentBackground=="string"&&(next.accentBackground=normalizeColor(next.accentBackground)),next.accent||(next.accentName=null)),persistStyle(next),typeof document<"u"){applyRootStyle(next)&&persistStyle(next);const changed=STYLE_FIELDS.filter(field=>field==="look"?before.look!==next.look||!tokensEqual(before.tokens,next.tokens):field==="accent"?before.accentName!==next.accentName||!accentsEqual(before.accent,next.accent):JSON.stringify(before[field])!==JSON.stringify(next[field]));emitStyleChange(next,changed)}return styleSnapshot(next,typeof window>"u"?void 0:window)}function applyRootStyle(next){const root=document.documentElement;(next.mode!=="system"||styleModeRoot?.deref()!==root)&&(styleModeCleanup?.(),styleModeCleanup=void 0,styleModeRoot=void 0),adoptLegacyOwnership(root);const requestedAccent=next.accent;return applyStyleState(root,next),next.mode==="system"&&!styleModeCleanup&&(styleModeRoot=new WeakRef(root),styleModeCleanup=attachStyleMode(root,element=>{applyStyleState(element,lastStyle),emitStyleChange(lastStyle,["resolvedMode"])})),!accentsEqual(requestedAccent,next.accent)}function adoptLegacyOwnership(root){const symbol=Symbol.for(TOKEN_OWNERSHIP_SYMBOL),node=root;try{if(!Array.isArray(node[symbol]))return}catch{return}const ownership=ownershipFor(root).properties;for(const name of[...readOwnershipList(),...ALL_RAMP_PROPERTIES,"--lr-theme-accent"])ownership.has(name)||!root.style.getPropertyValue(name)||ownership.set(name,{before:null,priority:"",written:root.style.getPropertyValue(name)});try{delete node[symbol]}catch{}}function getLyraStyle(){return styleSnapshot(readStyleState(),typeof window>"u"?void 0:window)}function startLyraStyle(){const state=readStyleState();return typeof document>"u"?styleSnapshot(state):(state.accent=normalizeAccent(state.accent),typeof state.accentBackground=="string"&&(state.accentBackground=normalizeColor(state.accentBackground)),state.accent||(state.accentName=null),lastStyle=state,applyRootStyle(state),styleSnapshot(state,window))}function resetLyraStyle(fields=STYLE_FIELDS){const defaults={...STYLE_DEFAULTS,accentBackground:null,overrides:null};return setLyraStyle(Object.fromEntries(fields.filter(field=>STYLE_FIELDS.includes(field)).map(field=>[field,defaults[field]])))}function applyLyraStyleScope(element,choices){if(scopeModes.get(element)?.(),scopeModes.delete(element),choices===null){writeStyleAttributes(element,{}),writeStyleProperties(element,new Map);return}const state=normalizeStyleChoices(choices,{...DEFAULT_STYLE}),fields=new Set(STYLE_FIELDS.filter(field=>ownField(choices,field)!==void 0));applyStyleState(element,state,fields),choices.mode==="system"&&scopeModes.set(element,attachStyleMode(element,node=>applyStyleState(node,state,fields)))}const lyraThemeBootstrap=/* @__PURE__ */createLyraThemeBootstrap();export{accentsEqual,applyLyraStyleScope,createLyraThemeBootstrap,defineLyraLook,getLyraStyle,isLyraThemeTokenName,isSafeLyraThemeTokenValue,lyraStyleAttributes,lyraThemeBootstrap,parseLyraStyleRecord,resetLyraStyle,setLyraStyle,startLyraStyle,tokensEqual};
1
+ import{devWarnOnce,litDevWarnings}from"../internal/dev-warning.js";import{readStyleOwnership}from"./style-ownership.js";import{resolveStyleStartup}from"./startup-resolution.js";const STORAGE_KEY="lyra-theme",TOKEN_NAME_PATTERN=/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/,TOKEN_NAME_MAX_LENGTH=80,TOKEN_RESERVED_NAME="--lr-theme-accent",TOKEN_ENTRY_MAX=512,TOKEN_SYNTHESIZED_MAX=16,TOKEN_VALUE_MAX_LENGTH=256,TOKEN_FORBIDDEN_PATTERN=/[\x00-\x1f\x7f\\;{}!<>@[\]`$^|~=?&:\u2028\u2029]|\/\*|\*\//,TOKEN_CSS_WIDE_PATTERN=/^(?:inherit|initial|revert(?:-layer)?|unset)$/i,TOKEN_FUNCTION_PATTERN=/([a-z0-9_-]+)\s*\(/gi,TOKEN_ALLOWED_FUNCTIONS="rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark calc min max clamp var cubic-bezier steps linear".split(" "),TOKEN_OWNERSHIP_MAX=TOKEN_ENTRY_MAX+TOKEN_SYNTHESIZED_MAX,TOKEN_OWNERSHIP_SYMBOL="@aceshooting/lyra-ui.theme-tokens.v1",MODE_SURFACES={light:[255,255,255],dark:[10,10,10]},COLOR_SCHEME_QUERY="(prefers-color-scheme: dark)",SEMANTIC_ROLES=["brand","success","warning","danger","neutral"],RAMP_CHANNELS=["fill","border","on"],RAMP_TIERS=["quiet","normal","loud"];function roleRampProperties(role){const properties=[];for(const channel of RAMP_CHANNELS)for(const tier of RAMP_TIERS)properties.push(`--lr-theme-color-${role}-${channel}-${tier}`);return properties}const ALL_RAMP_PROPERTIES=[...SEMANTIC_ROLES.flatMap(roleRampProperties),"--lr-theme-color-focus"],MODE_ATTRIBUTES=["data-lr-theme","data-theme"];function isBalancedCssValue(value){let depth=0,quote="";for(const character of value){if(quote){character===quote&&(quote="");continue}if(character==="'"||character==='"')quote=character;else if(character==="(")depth+=1;else if(character===")"&&(depth-=1)<0)return!1}return quote===""&&depth===0}function isLyraThemeTokenName(name){return typeof name=="string"&&name.length<=TOKEN_NAME_MAX_LENGTH&&TOKEN_NAME_PATTERN.test(name)&&name!==TOKEN_RESERVED_NAME}function isSafeLyraThemeTokenValue(value){if(typeof value!="string")return!1;const trimmed=value.trim();if(!trimmed||trimmed.length>TOKEN_VALUE_MAX_LENGTH||TOKEN_FORBIDDEN_PATTERN.test(trimmed)||TOKEN_CSS_WIDE_PATTERN.test(trimmed))return!1;for(const match of trimmed.matchAll(TOKEN_FUNCTION_PATTERN))if(!TOKEN_ALLOWED_FUNCTIONS.includes((match[1]??"").toLowerCase()))return!1;return isBalancedCssValue(trimmed)}function isPlainRecord(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);if(prototype===Object.prototype||prototype===null)return!0;if(Object.getPrototypeOf(prototype)!==null)return!1;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return typeof constructor=="function"&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(Object)}function normalizeTokenBranch(value){return isSafeLyraThemeTokenValue(value)?value.trim():null}function normalizeTokens(raw){try{if(!isPlainRecord(raw))return null;const names=Object.keys(raw);if(names.length===0||names.length>TOKEN_ENTRY_MAX)return null;const result={};let kept=0;for(const name of names){if(!isLyraThemeTokenName(name))continue;const value=ownField(raw,name);if(typeof value=="string"){const normalized=normalizeTokenBranch(value);if(normalized===null)continue;result[name]=normalized,kept+=1;continue}if(!isPlainRecord(value))continue;const keys=Object.keys(value),hasLight=Object.prototype.hasOwnProperty.call(value,"light"),hasDark=Object.prototype.hasOwnProperty.call(value,"dark");if(!hasLight&&!hasDark||keys.some(key=>key!=="light"&&key!=="dark"))continue;const light=normalizeTokenBranch(ownField(value,"light")),dark=normalizeTokenBranch(ownField(value,"dark"));light===null&&dark===null||(result[name]=Object.freeze({light,dark}),kept+=1)}return kept>0?Object.freeze(result):null}catch{return null}}function tokensEqual(left,right){const leftNames=left?Object.keys(left):[],rightNames=right?Object.keys(right):[];if(leftNames.length!==rightNames.length)return!1;if(leftNames.length===0)return!0;const leftMap=left,rightMap=right;return leftNames.every(name=>{if(!Object.prototype.hasOwnProperty.call(rightMap,name))return!1;const a=leftMap[name],b=rightMap[name];return typeof a=="string"||typeof b=="string"?a===b:!a||!b?!1:(a.light??null)===(b.light??null)&&(a.dark??null)===(b.dark??null)})}function normalizeColor(value,owner=document){if(typeof value!="string"||!value.trim())return null;const candidate=value.trim();if(!isBalancedCssValue(candidate)||TOKEN_CSS_WIDE_PATTERN.test(candidate)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(candidate)||/\bcurrentcolor\b/i.test(candidate)||/\bvar\s*\(/i.test(candidate)||/\blight-dark\s*\(/i.test(candidate)||/\b(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)\s*\(\s*from\b/i.test(candidate))return null;const probe=owner.createElement("span");return probe.style.color=candidate,probe.style.color?candidate:null}function normalizeAccentValue(value){if(typeof value=="string"||value===null)return normalizeColor(value);if(typeof value!="object"||Array.isArray(value))return null;const record=value;if(!("light"in record)&&!("dark"in record))return null;const light=normalizeColor(record.light),dark=normalizeColor(record.dark);return light||dark?{light,dark}:null}function normalizeAccent(value){if(typeof value=="string")return normalizeColor(value);if(value===null||typeof value!="object"||Array.isArray(value))return null;const record=value,result={};let hasRole=!1;for(const role of SEMANTIC_ROLES)role in record&&(hasRole=!0,result[role]=normalizeAccentValue(record[role]));return hasRole?result:null}function resolveAccentValueForMode(value,mode){return typeof value=="string"?value:value?value[mode]??null:null}function accentValueEqual(left,right){return left===right?!0:typeof left=="string"||typeof right=="string"||left===null||right===null?!1:(left.light??null)===(right.light??null)&&(left.dark??null)===(right.dark??null)}function accentsEqual(left,right){if(left===right)return!0;if(typeof left=="string"||typeof right=="string"||left===null||right===null)return!1;const leftKeys=Object.keys(left),rightKeys=Object.keys(right);return leftKeys.length!==rightKeys.length?!1:leftKeys.every(role=>accentValueEqual(left[role],right[role]))}function parseResolvedRgb(value,background,owner=document){if(!normalizeColor(value,owner))return null;try{const canvas=owner.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0});if(!context)return null;context.clearRect(0,0,1,1),context.fillStyle=value,context.fillRect(0,0,1,1);const channels=context.getImageData(0,0,1,1).data,red=channels[0]??0,green=channels[1]??0,blue=channels[2]??0,alpha=(channels[3]??0)/255;return[Math.round(red*alpha+background[0]*(1-alpha)),Math.round(green*alpha+background[1]*(1-alpha)),Math.round(blue*alpha+background[2]*(1-alpha))]}catch{return null}}function hexRgb(color){return[parseInt(color.slice(1,3),16),parseInt(color.slice(3,5),16),parseInt(color.slice(5,7),16)]}function mixRgb(base,color,colorWeight){return[Math.round(base[0]*(1-colorWeight)+color[0]*colorWeight),Math.round(base[1]*(1-colorWeight)+color[1]*colorWeight),Math.round(base[2]*(1-colorWeight)+color[2]*colorWeight)]}function serializeRgb(color){return`rgb(${color.join(" ")})`}function relativeLuminance(color){const linearize=channel=>{const normalized=channel/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4};return linearize(color[0])*.2126+linearize(color[1])*.7152+linearize(color[2])*.0722}function contrastRatio(left,right){const a=relativeLuminance(left),b=relativeLuminance(right);return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}function contrastForeground(fill){const black=[0,0,0],white=[255,255,255];return contrastRatio(fill,black)>=contrastRatio(fill,white)?black:white}function ensureSurfaceContrast(color,background,minimum=3,alsoAgainst=background,references=[]){const passes=candidate=>contrastRatio(candidate,background)>=minimum&&contrastRatio(candidate,alsoAgainst)>=minimum&&references.every(reference=>contrastRatio(candidate,reference)>=minimum);if(passes(color))return color;const black=[0,0,0],white=[255,255,255],target=contrastRatio(background,black)>=contrastRatio(background,white)?black:white;for(let step=1;step<=10;step+=1){const candidate=mixRgb(color,target,step/10);if(passes(candidate))return candidate}return target}function createRoleRamp(role,base,mode,background,owner=document){const references=STYLE_CONTRAST_SURFACES[mode].map(hexRgb),resolved=parseResolvedRgb(base,background,owner);if(!resolved)return null;const quiet=mixRgb(background,resolved,mode==="dark"?.24:.14),normal=mixRgb(background,resolved,mode==="dark"?.62:.55),loud=ensureSurfaceContrast(resolved,background,4.5,quiet,references),borderTarget=mode==="dark"?[255,255,255]:[0,0,0],borderQuiet=mixRgb(background,resolved,mode==="dark"?.46:.38),borderNormal=ensureSurfaceContrast(mixRgb(background,resolved,mode==="dark"?.78:.72),background,3,background,references),borderLoud=ensureSurfaceContrast(mixRgb(loud,borderTarget,.2),background,3,background,references),prefix=`--lr-theme-color-${role}`,ramp={[`${prefix}-fill-quiet`]:serializeRgb(quiet),[`${prefix}-fill-normal`]:serializeRgb(normal),[`${prefix}-fill-loud`]:serializeRgb(loud),[`${prefix}-border-quiet`]:serializeRgb(borderQuiet),[`${prefix}-border-normal`]:serializeRgb(borderNormal),[`${prefix}-border-loud`]:serializeRgb(borderLoud),[`${prefix}-on-quiet`]:serializeRgb(contrastForeground(quiet)),[`${prefix}-on-normal`]:serializeRgb(contrastForeground(normal)),[`${prefix}-on-loud`]:serializeRgb(contrastForeground(loud))};return role==="brand"&&(ramp["--lr-theme-color-focus"]=serializeRgb(ensureSurfaceContrast(resolved,background,3,background,references))),ramp}function paintAccent(accent,mode,background,owner=document){const properties=new Map;if(!accent)return{applied:null,properties};if(!mode)return{applied:accent,properties};if(typeof accent=="string"){const ramp=createRoleRamp("brand",accent,mode,background,owner);if(!ramp)return{applied:null,properties};properties.set("--lr-theme-accent",accent);for(const[property,value]of Object.entries(ramp))properties.set(property,value);return{applied:accent,properties}}const applied={};let appliedBrandColor=null;for(const role of SEMANTIC_ROLES){const value=accent[role];if(!value)continue;const isPerMode=typeof value!="string",base=resolveAccentValueForMode(value,mode);let painted=!1;if(base){const ramp=createRoleRamp(role,base,mode,background,owner);if(ramp){for(const[property,propertyValue]of Object.entries(ramp))properties.set(property,propertyValue);painted=!0,role==="brand"&&(appliedBrandColor=base)}}(painted||isPerMode)&&(applied[role]=value)}return appliedBrandColor&&properties.set("--lr-theme-accent",appliedBrandColor),{applied:Object.keys(applied).length>0?applied:null,properties}}function tokenEntries(tokens,mode){const entries=new Map;if(!tokens)return entries;for(const[name,value]of Object.entries(tokens))if(typeof value=="string")entries.set(name,value);else if(mode){const branch=value[mode];branch&&entries.set(name,branch)}return entries}function resolveTokenColor(value,background,owner){return value===void 0||!background||!normalizeColor(value,owner)?null:parseResolvedRgb(value,background,owner)}function floorTokenEntries(entries,surface,owner,references){if(!entries.size)return new Map;const resolveColor=(value,background)=>resolveTokenColor(value,background,owner),painted=new Map(entries),prefix="--lr-theme-",raised=resolveColor(entries.get(`${prefix}color-surface-raised`)??references[1],surface),floor=(name,over,against,minimum,alsoAgainst)=>{const value=painted.get(name);if(value===void 0||!against||alsoAgainst===null)return;const color=resolveColor(value,over);if(!color)return;const repaired=ensureSurfaceContrast(color,against,minimum,alsoAgainst??against);repaired!==color&&painted.set(name,serializeRgb(repaired))};floor(`${prefix}color-text-normal`,surface,surface,4.5,raised),floor(`${prefix}color-text-quiet`,surface,surface,4.5,raised);const text=entries.has(`${prefix}color-text-normal`)?resolveColor(painted.get(`${prefix}color-text-normal`),surface):resolveColor(references[2],surface),pairForeground=(onName,fill)=>{if(!fill)return;const on=painted.get(onName);if(on===void 0){painted.set(onName,serializeRgb(contrastForeground(fill)));return}const color=resolveColor(on,fill);color&&contrastRatio(color,fill)<4.5&&painted.set(onName,serializeRgb(contrastForeground(fill)))};for(const role of SEMANTIC_ROLES)for(const tier of RAMP_TIERS){const fillName=`${prefix}color-${role}-fill-${tier}`;entries.has(fillName)&&pairForeground(`${prefix}color-${role}-on-${tier}`,resolveColor(entries.get(fillName),surface))}const overlayName=`${prefix}color-overlay-strong`,overlay=entries.has(overlayName)?resolveColor(entries.get(overlayName),surface):resolveColor(references[3],surface);(entries.has(overlayName)||entries.has(`${prefix}color-on-strong-overlay`))&&pairForeground(`${prefix}color-on-strong-overlay`,overlay);for(const name of entries.keys())/^--lr-theme-color-(?:(?:brand|success|warning|danger|neutral)-border-(?:normal|loud)|surface-border|border-strong|focus|chart-\d+)$/.test(name)?floor(name,surface,surface,3):/^--lr-theme-terminal-color-[a-z0-9-]+$/.test(name)?floor(name,raised,raised,4.5):/^--lr-theme-terminal-bg-[a-z0-9-]+$/.test(name)&&floor(name,raised,text,4.5);return painted}function readOwnershipList(){try{const list=document.documentElement[Symbol.for(TOKEN_OWNERSHIP_SYMBOL)];if(!Array.isArray(list))return[];const names=[],length=Math.min(list.length,TOKEN_OWNERSHIP_MAX);for(let index=0;index<length;index+=1){const name=list[index];isLyraThemeTokenName(name)&&names.push(name)}return names}catch{return[]}}function applyStoredThemeBeforePaint(){const R=["brand","success","warning","danger","neutral"],Q=["quiet","normal","loud"],W=/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/,_="--lr-theme-accent",G=/[\x00-\x1f\x7f\\;{}!<>@[\]`$^|~=?&:\u2028\u2029]|\/\*|\*\//,H=/^(?:inherit|initial|revert(?:-layer)?|unset)$/i,J=/([a-z0-9_-]+)\s*\(/gi,K="rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark calc min max clamp var cubic-bezier steps linear".split(" "),U={light:[255,255,255],dark:[10,10,10]},X=r=>{let o=0,h="";for(const a of r){if(h){a===h&&(h="");continue}if(a==="'"||a==='"')h=a;else if(a==="(")o+=1;else if(a===")"&&(o-=1)<0)return!1}return h===""&&o===0},Y=r=>typeof r=="string"&&r.length<=80&&W.test(r)&&r!==_,P=r=>{if(typeof r!="string")return null;const o=r.trim();if(!o||o.length>256||G.test(o)||H.test(o))return null;for(const h of o.matchAll(J))if(!K.includes((h[1]??"").toLowerCase()))return null;return X(o)?o:null},A=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const o=Object.getPrototypeOf(r);return o===Object.prototype||o===null},Z=r=>{const o={};try{if(!A(r))return o;const h=Object.keys(r);if(h.length<=512)for(const a of h){if(!Y(a))continue;const g=r[a];if(typeof g=="string"){const u=P(g);u!==null&&(o[a]=u);continue}if(!A(g))continue;const j=Object.hasOwn(g,"light"),i=Object.hasOwn(g,"dark");if(!j&&!i||Object.keys(g).some(u=>u!=="light"&&u!=="dark"))continue;const M=P(g.light),y=P(g.dark);(M!==null||y!==null)&&(o[a]={light:M,dark:y})}}catch{}return o},C=r=>{const o=P(r);if(!(!o||/\b(?:var|light-dark)\s*\(|\b(?:currentcolor|from)\b/i.test(o)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(o)))return CSS.supports("color",o)?o:void 0};return[Z,C,(r,o,h,a,g,j)=>{const i=new Map;for(const[t,n]of Object.entries(r)){const e=typeof n=="string"?n:n[o];e&&i.set(t,e)}const M=typeof a=="string"?{brand:a}:a,y={};for(const t of R){const n=M?.[t],e=typeof n=="string"?n:n?.[o];e&&(y[t]=e)}let u=null;if(i.size>0||Object.keys(y).length>0)try{const t=document.createElement("canvas");t.width=1,t.height=1,u=t.getContext("2d",{willReadFrequently:!0})}catch{u=null}const S=(t,n)=>{if(!u)return null;try{u.clearRect(0,0,1,1),u.fillStyle=t,u.fillRect(0,0,1,1);const e=u.getImageData(0,0,1,1).data,c=(e[3]??0)/255;return[0,1,2].map(f=>Math.round((e[f]??0)*c+(n[f]??0)*(1-c)))}catch{return null}},z=(t,n,e)=>t.map((c,f)=>Math.round(c*(1-e)+(n[f]??0)*e)),B=t=>{const n=t.map(e=>{const c=e/255;return c<=.04045?c/12.92:((c+.055)/1.055)**2.4});return(n[0]??0)*.2126+(n[1]??0)*.7152+(n[2]??0)*.0722},O=(t,n)=>{const e=B(t),c=B(n);return(Math.max(e,c)+.05)/(Math.min(e,c)+.05)},v=[0,0,0],F=[255,255,255],w=t=>O(t,v)>=O(t,F)?v:F,q=(t,n,e=3,c=n)=>{const f=d=>O(d,n)>=e&&O(d,c)>=e&&g.every(k=>O(d,k)>=e);if(f(t))return t;const p=w(n);for(let d=1;d<=10;d+=1){const k=z(t,p,d/10);if(f(k))return k}return p},m=t=>`rgb(${t.join(" ")})`,D=U[o],E=C(h)??C(i.get("--lr-theme-color-surface-default")),s=E&&S(E,D)||D,l=new Map(i),b="--lr-theme-",$=(t,n)=>t!==void 0&&n&&C(t)?S(t,n):null,tt=`${b}color-surface-raised`,N=$(i.get(tt)??j[1],s),L=(t,n,e,c,f)=>{const p=l.get(t);if(p===void 0||!e||f===null)return;const d=$(p,n);if(!d)return;const k=q(d,e,c,f??e);k!==d&&l.set(t,m(k))};L(`${b}color-text-normal`,s,s,4.5,N),L(`${b}color-text-quiet`,s,s,4.5,N);const et=i.has(`${b}color-text-normal`)?$(l.get(`${b}color-text-normal`),s):$(j[2],s),I=(t,n)=>{if(!n)return;const e=l.get(t),c=e===void 0?null:$(e,n);(e===void 0||c&&O(c,n)<4.5)&&l.set(t,m(w(n)))};for(const t of R)for(const n of Q){const e=`${b}color-${t}-fill-${n}`;i.has(e)&&I(`${b}color-${t}-on-${n}`,$(i.get(e),s))}const T=`${b}color-overlay-strong`;(i.has(T)||i.has(`${b}color-on-strong-overlay`))&&I(`${b}color-on-strong-overlay`,i.has(T)?$(i.get(T),s):$(j[3],s));for(const t of i.keys())/^--lr-theme-color-(?:(?:brand|success|warning|danger|neutral)-border-(?:normal|loud)|surface-border|border-strong|focus|chart-\d+)$/.test(t)?L(t,s,s,3):/^--lr-theme-terminal-color-[a-z0-9-]+$/.test(t)?L(t,N,N,4.5):/^--lr-theme-terminal-bg-[a-z0-9-]+$/.test(t)&&L(t,N,et,4.5);if(!u)return l;let V=null;for(const t of R){const n=y[t];if(!n)continue;const e=S(n,s);if(!e)continue;const c=z(s,e,o==="dark"?.24:.14),f=z(s,e,o==="dark"?.62:.55),p=q(e,s,4.5,c),d=o==="dark"?F:v,k=z(s,e,o==="dark"?.46:.38),nt=q(z(s,e,o==="dark"?.78:.72),s),ot=q(z(p,d,.2),s),x=`--lr-theme-color-${t}`;l.set(`${x}-fill-quiet`,m(c)),l.set(`${x}-fill-normal`,m(f)),l.set(`${x}-fill-loud`,m(p)),l.set(`${x}-border-quiet`,m(k)),l.set(`${x}-border-normal`,m(nt)),l.set(`${x}-border-loud`,m(ot)),l.set(`${x}-on-quiet`,m(w(c))),l.set(`${x}-on-normal`,m(w(f))),l.set(`${x}-on-loud`,m(w(p))),t==="brand"&&(l.set("--lr-theme-color-focus",m(q(e,s))),V=n)}return V&&l.set("--lr-theme-accent",V),l}]}function styleMaterial(l,n){const t=n==="glass";for(const[a,i]of Object.entries({enabled:t?"1":"0",content:t?"''":"none",isolation:t?"isolate":"auto","root-filter":t?"initial":"none","child-filter":t?"none":"initial","child-opacity":t?"1":"0"}))l.set(`--_lr-surface-${a}`,i);l.set("--_lr-glass-blocker",t?"initial":"none"),t||(l.set("--_lr-glass-parent-opacity","0"),l.set("--_lr-next-glass-opacity","0"))}function applyStoredStyleBeforePaint(U,q,D,N,G,J,W,S){const{surfaces:R,contrast:H,accent:Q}=S,b=new Map;for(const r of S.inputs.split(" "))b.set(`--lr-theme-${r.slice(1)}`,Number(r[0]));const _=[...b.keys()];function v(r,n,s=!1){return`--_lr-${s?"a":"l"}${n==="light"?"l":"d"}-${r.slice(11)}`}function V(r,n){const s=b.get(r)??0;let g=`var(${v(r,n)})`;if(s&2){const k=n==="light"?"l":"d",u=r.replace(/color-(?:success|warning|danger|neutral)-/,"color-brand-");g=`var(--_lr-f${k}-${r.slice(11)},${g})var(--_lr-o${k}-${r.slice(11)},var(${v(u,n,!0)},var(${v(u,n)})))`}return s&4?`var(${v(r,n,!0)},${g})`:g}function X(r){const n=`var(--_lr-dark-on,${V(r,"light")})var(--_lr-light-on,${V(r,"dark")})`;if(!((b.get(r)??0)&1))return n;const s=r.startsWith("--lr-theme-space-");return`var(--_lr-dense-on,${n})var(--_lr-dense-off,max(calc((${n}) * var(--_lr-density-${s?"space":"control"},1)),${s?"0px":"var(--_lr-density-target-min,0px)"}))`}try{const r=document.currentScript,n=r?.getAttribute("data-lr-theme-restore"),s=(n==="all"||n==="mode"?n:S.restore)==="mode",g=r?.getAttribute("data-lr-theme-storage-key"),k=g&&g.length<=200?g:U,u=r?.getAttribute("data-lr-theme-attributes")?.trim().split(/\s+/),A=u?.length&&u.length<=8&&new Set(u).size===u.length&&u.every(t=>t.length<=64&&/^data-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t))?u:q;let w;try{w=JSON.parse(localStorage.getItem(k)??"null")}catch{}if(s){const t=w;w={version:t?.version,mode:t?.mode}}const o=document.documentElement,[Z,tt,et]=D(),f=J(w,S.defaults,Z,tt,(t,e)=>N(t,e,_),Q),y=f.mode,$=y==="unset"?null:y==="system"?matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":y,p={},j=!s&&getComputedStyle(o).getPropertyValue("--_lr-style-resolver").trim()==="1",C=(t,e)=>typeof t=="string"?t:t?.[e],rt=f.tokens,ot=f.overrides,E={...rt,...ot},L=f.look;if(s||(p["data-lr-look"]=L,p["data-lr-density"]=f.density,p["data-lr-surface"]=f.treatment),y!=="unset"&&(p["data-lr-mode"]=y),$)for(const t of A)p[t]=$;const O=f.accentName;let h=f.accent;y!=="unset"&&h&&typeof h=="object"&&!Object.values(h).some(t=>typeof t=="string"||t&&Object.values(t).some(Boolean))&&(h=null),s||(p["data-lr-accent"]=O??(h?"custom":"none"));const a=new Map;if(y==="unset")for(const[t,e]of Object.entries(E))typeof e=="string"&&a.set(t,e);for(const t of s?[]:["light","dark"]){const e=C(f.surface,t),T=C(E["--lr-theme-color-surface-default"],t),c=(R[L]??R.lyra)[t],z=e??T??c[0];for(const m of[!1,!0]){if(m&&(!h||O))continue;const st=et(m?{}:E,t,z,m?h:null,m?H[t].map(l=>[1,3,5].map(d=>parseInt(l.slice(d,d+2),16))):[],c);for(const[l,d]of st){if(l==="--lr-theme-accent"){t===$&&a.set(l,d);continue}const B=b.get(l);if(B!==void 0&&N(l,d,_)){const F=l.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1],M=!m&&F&&d===`var(--lr-theme-color-brand-${F})`,I=l.slice(11),K=t==="light"?"l":"d";M||a.set(v(l,t,m),d),!m&&B&2&&(a.set(`--_lr-f${K}-${I}`,M?" ":"initial"),a.set(`--_lr-o${K}-${I}`,M?"initial":" ")),t===$&&a.set(l,j?X(l):d)}else t===$&&a.set(l,d)}}}(a.size||y==="unset"&&h&&!O)&&(p["data-lr-theme-scope"]=""),!s&&!j&&W(a,f.treatment);const Y=Symbol.for("@aceshooting/lyra-ui.style-ownership.v1"),P=o;let x;try{x=G(P[Y])}catch{}const i=x??{attributes:new Map,properties:new Map};if(y==="unset")for(const t of A)i.attributes.has(t)||o.removeAttribute(t);try{const t=Symbol.for("@aceshooting/lyra-ui.theme-tokens.v1"),e=P[t];if(!s&&Array.isArray(e)){const T=e.slice(0,528).filter(c=>typeof c=="string"&&c.length<=80&&/^--lr-theme-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c));for(const c of[...T,..._.filter(z=>b.get(z)&4),"--lr-theme-accent"])!i.properties.has(c)&&o.style.getPropertyValue(c)&&i.properties.set(c,{before:null,priority:"",written:o.style.getPropertyValue(c)});try{delete P[t]}catch{}}}catch{}for(const[t,e]of i.attributes)s&&t!=="data-lr-mode"&&!A.includes(t)||Object.hasOwn(p,t)||(o.getAttribute(t)===e.written&&(e.before===null?o.removeAttribute(t):o.setAttribute(t,e.before)),i.attributes.delete(t));for(const[t,e]of Object.entries(p))i.attributes.has(t)||i.attributes.set(t,{before:o.getAttribute(t),priority:"",written:e}),o.setAttribute(t,e),i.attributes.get(t).written=e;for(const[t,e]of i.properties)s||a.has(t)||(o.style.getPropertyValue(t)===e.written&&!o.style.getPropertyPriority(t)&&(e.before?o.style.setProperty(t,e.before,e.priority):o.style.removeProperty(t)),i.properties.delete(t));for(const[t,e]of a)i.properties.has(t)||i.properties.set(t,{before:o.style.getPropertyValue(t),priority:o.style.getPropertyPriority(t),written:null}),o.style.getPropertyPriority(t)&&o.style.removeProperty(t),o.style.setProperty(t,e,""),i.properties.get(t).written=o.style.getPropertyValue(t);try{P[Y]=i}catch{}}catch{}}const LINE_SEPARATOR="\u2028",PARAGRAPH_SEPARATOR="\u2029";function serializeInlineScriptData(value){return JSON.stringify(value).replace(/</g,"\\u003c").replace(new RegExp(LINE_SEPARATOR,"g"),"\\u2028").replace(new RegExp(PARAGRAPH_SEPARATOR,"g"),"\\u2029")}const BOOTSTRAP_FUNCTIONS=[applyStoredStyleBeforePaint,applyStoredThemeBeforePaint,styleTokenAllowed,readStyleOwnership,resolveStyleStartup,styleMaterial];function bootstrapParts(options){const storageKey=options.storageKey??STORAGE_KEY,inputs=STYLE_SLOTTED.map(name=>`${Number(STYLE_DENSITY.includes(name))|Number(STYLE_FOLLOW.includes(name))<<1|Number(ALL_RAMP_PROPERTIES.includes(name))<<2}${name.slice(11)}`).join(" "),model=JSON.stringify({restore:options.restore==="mode"?"mode":"all",defaults:STYLE_DEFAULTS,inputs,surfaces:STYLE_REFERENCE_SURFACES,contrast:STYLE_CONTRAST_SURFACES,accent:STYLE_GEMSTONES});return{storageKey,model}}function createLyraThemeBootstrap(options={}){const{storageKey,model}=bootstrapParts(options),functions=BOOTSTRAP_FUNCTIONS.map(helper=>helper.toString().replace(/^function\s+[\w$]+/,"function"));return`(${functions[0]})(${serializeInlineScriptData(storageKey)},${serializeInlineScriptData(MODE_ATTRIBUTES)},${functions.slice(1).join(",")},${model});`}const STYLE_DEFAULTS=Object.freeze({look:"shadcn",surface:"glass",density:"comfortable",mode:"system",accent:"emerald"}),STYLE_SLOTTED=["--lr-theme-color-border-strong","--lr-theme-color-brand-border-loud","--lr-theme-color-brand-border-normal","--lr-theme-color-brand-border-quiet","--lr-theme-color-brand-fill-loud","--lr-theme-color-brand-fill-normal","--lr-theme-color-brand-fill-quiet","--lr-theme-color-brand-on-loud","--lr-theme-color-brand-on-normal","--lr-theme-color-brand-on-quiet","--lr-theme-color-chart-1","--lr-theme-color-chart-2","--lr-theme-color-chart-3","--lr-theme-color-chart-4","--lr-theme-color-chart-5","--lr-theme-color-chart-6","--lr-theme-color-chart-7","--lr-theme-color-chart-8","--lr-theme-color-chart-diverging-1","--lr-theme-color-chart-diverging-2","--lr-theme-color-chart-diverging-3","--lr-theme-color-chart-sequential-1","--lr-theme-color-chart-sequential-2","--lr-theme-color-chart-sequential-3","--lr-theme-color-danger-border-loud","--lr-theme-color-danger-border-normal","--lr-theme-color-danger-border-quiet","--lr-theme-color-danger-fill-loud","--lr-theme-color-danger-fill-normal","--lr-theme-color-danger-fill-quiet","--lr-theme-color-danger-on-loud","--lr-theme-color-danger-on-normal","--lr-theme-color-danger-on-quiet","--lr-theme-color-focus","--lr-theme-color-mix-partner","--lr-theme-color-neutral-border-loud","--lr-theme-color-neutral-border-normal","--lr-theme-color-neutral-border-quiet","--lr-theme-color-neutral-fill-loud","--lr-theme-color-neutral-fill-normal","--lr-theme-color-neutral-fill-quiet","--lr-theme-color-neutral-on-loud","--lr-theme-color-neutral-on-normal","--lr-theme-color-neutral-on-quiet","--lr-theme-color-no-data","--lr-theme-color-on-strong-overlay","--lr-theme-color-overlay","--lr-theme-color-overlay-strong","--lr-theme-color-success-border-loud","--lr-theme-color-success-border-normal","--lr-theme-color-success-border-quiet","--lr-theme-color-success-fill-loud","--lr-theme-color-success-fill-normal","--lr-theme-color-success-fill-quiet","--lr-theme-color-success-on-loud","--lr-theme-color-success-on-normal","--lr-theme-color-success-on-quiet","--lr-theme-color-surface-border","--lr-theme-color-surface-border-subtle","--lr-theme-color-surface-container","--lr-theme-color-surface-container-high","--lr-theme-color-surface-container-highest","--lr-theme-color-surface-container-low","--lr-theme-color-surface-container-lowest","--lr-theme-color-surface-default","--lr-theme-color-surface-overlay","--lr-theme-color-surface-raised","--lr-theme-color-text-normal","--lr-theme-color-text-quiet","--lr-theme-color-warning-border-loud","--lr-theme-color-warning-border-normal","--lr-theme-color-warning-border-quiet","--lr-theme-color-warning-fill-loud","--lr-theme-color-warning-fill-normal","--lr-theme-color-warning-fill-quiet","--lr-theme-color-warning-on-loud","--lr-theme-color-warning-on-normal","--lr-theme-color-warning-on-quiet","--lr-theme-form-control-height-2xs","--lr-theme-form-control-height-l","--lr-theme-form-control-height-m","--lr-theme-form-control-height-s","--lr-theme-form-control-height-xl","--lr-theme-form-control-height-xs","--lr-theme-graph-cat-1","--lr-theme-graph-cat-2","--lr-theme-graph-cat-3","--lr-theme-graph-cat-4","--lr-theme-graph-cat-5","--lr-theme-graph-cat-6","--lr-theme-graph-cat-7","--lr-theme-graph-cat-8","--lr-theme-icon-button-size","--lr-theme-shadow-l","--lr-theme-shadow-m","--lr-theme-shadow-s","--lr-theme-shadow-xl","--lr-theme-shadow-xs","--lr-theme-space-2xl","--lr-theme-space-2xs","--lr-theme-space-l","--lr-theme-space-m","--lr-theme-space-s","--lr-theme-space-xs","--lr-theme-terminal-bg-black","--lr-theme-terminal-bg-blue","--lr-theme-terminal-bg-bright-black","--lr-theme-terminal-bg-bright-blue","--lr-theme-terminal-bg-bright-cyan","--lr-theme-terminal-bg-bright-green","--lr-theme-terminal-bg-bright-magenta","--lr-theme-terminal-bg-bright-red","--lr-theme-terminal-bg-bright-white","--lr-theme-terminal-bg-bright-yellow","--lr-theme-terminal-bg-cyan","--lr-theme-terminal-bg-green","--lr-theme-terminal-bg-magenta","--lr-theme-terminal-bg-red","--lr-theme-terminal-bg-white","--lr-theme-terminal-bg-yellow","--lr-theme-terminal-color-black","--lr-theme-terminal-color-blue","--lr-theme-terminal-color-bright-black","--lr-theme-terminal-color-bright-blue","--lr-theme-terminal-color-bright-cyan","--lr-theme-terminal-color-bright-green","--lr-theme-terminal-color-bright-magenta","--lr-theme-terminal-color-bright-red","--lr-theme-terminal-color-bright-white","--lr-theme-terminal-color-bright-yellow","--lr-theme-terminal-color-cyan","--lr-theme-terminal-color-green","--lr-theme-terminal-color-magenta","--lr-theme-terminal-color-red","--lr-theme-terminal-color-white","--lr-theme-terminal-color-yellow"],STYLE_DENSITY=["--lr-theme-space-2xs","--lr-theme-space-xs","--lr-theme-space-s","--lr-theme-space-m","--lr-theme-space-l","--lr-theme-space-2xl","--lr-theme-form-control-height-2xs","--lr-theme-form-control-height-xs","--lr-theme-form-control-height-s","--lr-theme-form-control-height-m","--lr-theme-form-control-height-l","--lr-theme-form-control-height-xl","--lr-theme-icon-button-size"],STYLE_FOLLOW=["--lr-theme-color-danger-border-loud","--lr-theme-color-danger-border-normal","--lr-theme-color-danger-border-quiet","--lr-theme-color-danger-fill-loud","--lr-theme-color-danger-fill-normal","--lr-theme-color-danger-fill-quiet","--lr-theme-color-danger-on-loud","--lr-theme-color-danger-on-normal","--lr-theme-color-danger-on-quiet","--lr-theme-color-neutral-border-loud","--lr-theme-color-neutral-border-normal","--lr-theme-color-neutral-border-quiet","--lr-theme-color-neutral-fill-loud","--lr-theme-color-neutral-fill-normal","--lr-theme-color-neutral-fill-quiet","--lr-theme-color-neutral-on-loud","--lr-theme-color-neutral-on-normal","--lr-theme-color-neutral-on-quiet","--lr-theme-color-success-border-loud","--lr-theme-color-success-border-normal","--lr-theme-color-success-border-quiet","--lr-theme-color-success-fill-loud","--lr-theme-color-success-fill-normal","--lr-theme-color-success-fill-quiet","--lr-theme-color-success-on-loud","--lr-theme-color-success-on-normal","--lr-theme-color-success-on-quiet","--lr-theme-color-warning-border-loud","--lr-theme-color-warning-border-normal","--lr-theme-color-warning-border-quiet","--lr-theme-color-warning-fill-loud","--lr-theme-color-warning-fill-normal","--lr-theme-color-warning-fill-quiet","--lr-theme-color-warning-on-loud","--lr-theme-color-warning-on-normal","--lr-theme-color-warning-on-quiet"],STYLE_REFERENCE_SURFACES={lyra:{light:["#ffffff","#f6f8fa","#1a1a1a","rgb(0 0 0 / 0.92)"],dark:["#1a1a1a","#22272e","#f2f2f2","rgb(0 0 0 / 0.95)"]},data:{light:["#ffffff","#f2f5f8","#10202c","#17212b"],dark:["#101820","#192630","#eef5fa","#e7eef4"]},"high-contrast":{light:["#ffffff","#ffffff","#000000","#17212b"],dark:["#000000","#000000","#ffffff","#e7eef4"]},material:{light:["#fff8f5","#f8eeea","#241b17","rgb(0 0 0 / 0.92)"],dark:["#18120f","#251d19","#f8eee8","rgb(0 0 0 / 0.95)"]},shadcn:{light:["#ffffff","#fafafa","#0a0a0a","rgb(0 0 0 / 0.92)"],dark:["#0a0a0a","#171717","#fafafa","rgb(0 0 0 / 0.95)"]},terminal:{light:["#fcfdf9","#f1f5eb","#0d2115","#17212b"],dark:["#0e1713","#18271e","#e5f5e9","#e7eef4"]}},STYLE_CONTRAST_SURFACES={light:["#ffffff","#f6f8fa","#f2f5f8","#fff8f5","#f8eeea","#fcf2ed","#f2e7e0","#ecdfd7","#fafafa","#fcfdf9","#f1f5eb"],dark:["#1a1a1a","#22272e","#2b3038","#101820","#192630","#202e39","#000000","#18120f","#251d19","#302621","#120d0a","#211914","#352a24","#0a0a0a","#171717","#0e1713","#18271e","#203227"]},STYLE_GEMSTONES={emerald:"#34d399",peridot:"#a8d84a",topaz:"#f0a83c",ruby:"#e63950",tourmaline:"#ec4899",amethyst:"#9d6df0",aquamarine:"#22d3ee",sapphire:"#4f8ff7",hematite:"#94a3b8"},LOOK_ID=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,LOOK_STAMP=Symbol.for("@aceshooting/lyra-ui.look.v1"),STYLE_OWNERSHIP=Symbol.for("@aceshooting/lyra-ui.style-ownership.v1"),STYLE_FIELDS=["look","surface","density","mode","accent","accentBackground","overrides"],DEFAULT_STYLE=Object.freeze({...STYLE_DEFAULTS,tokens:null,accent:STYLE_GEMSTONES[STYLE_DEFAULTS.accent],accentName:STYLE_DEFAULTS.accent,accentBackground:null,overrides:null});let lastStyle={...DEFAULT_STYLE},stylePersistenceFailed=!1,styleModeCleanup,styleModeRoot;const styleOwnershipFallback=new WeakMap,scopeModes=new WeakMap;function ownField(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}function styleId(value){return typeof value=="string"&&value.length<=64&&LOOK_ID.test(value)}function styleTokenAllowed(e,r,o=STYLE_SLOTTED){if(e.startsWith("--lr-theme-surface-")||typeof r!="string"&&!o.includes(e))return!1;for(const t of typeof r=="string"?[r]:[r.light,r.dark])if(t)for(const c of t.matchAll(/var\(\s*(--[\w-]+)/g)){if(c[1]==="--lr-theme-shadow-color")continue;const n=e.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1];if(!n||t!==`var(--lr-theme-color-brand-${n})`)return!1}return!0}function styleTokens(value){const tokens=normalizeTokens(value);if(!tokens)return null;const entries=Object.entries(tokens).filter(([name,input])=>styleTokenAllowed(name,input));return entries.length?Object.freeze(Object.fromEntries(entries)):null}function defineLyraLook(look){if(!look||!styleId(ownField(look,"id"))||look.id==="custom")throw new TypeError("Invalid look id");const raw=ownField(look,"tokens");if(!isPlainRecord(raw)||Object.keys(raw).length>TOKEN_ENTRY_MAX)throw new TypeError("Invalid look tokens");for(const[name,descriptor]of Object.entries(Object.getOwnPropertyDescriptors(raw))){if(!("value"in descriptor))throw new TypeError(`Look inputs must be data properties: ${name}`);const value=descriptor.value;if(typeof value=="string"){if(!isSafeLyraThemeTokenValue(value))throw new TypeError(`Invalid look value: ${name}`);continue}if(!isPlainRecord(value)||!STYLE_SLOTTED.includes(name))throw new TypeError(`Invalid per-mode look input: ${name}`);const branches=Object.entries(Object.getOwnPropertyDescriptors(value));if(!branches.length||branches.some(([key,branch])=>!["light","dark"].includes(key)||!("value"in branch)||branch.value!==null&&!isSafeLyraThemeTokenValue(branch.value)))throw new TypeError(`Invalid look mode pair: ${name}`)}const tokens=styleTokens(raw);if(Object.keys(raw).length!==Object.keys(tokens??{}).length)throw new TypeError("Invalid look token or cross-axis reference");const stamped={...tokens,[LOOK_STAMP]:look.id};return Object.freeze(stamped),Object.freeze({id:look.id,tokens:stamped})}function styleColor(value,browserColors=!1){if(!isSafeLyraThemeTokenValue(value))return null;const text=value.trim();return/\b(?:var|light-dark)\s*\(|\b(?:currentcolor|from)\b/i.test(text)||/^(?:accentcolor|accentcolortext|activetext|buttonborder|buttonface|buttontext|canvas|canvastext|field|fieldtext|graytext|highlight|highlighttext|linktext|mark|marktext|selecteditem|selecteditemtext|visitedtext)$/i.test(text)?null:browserColors&&typeof CSS<"u"?CSS.supports("color",text)?text:null:/^(?:#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})|[a-z]+|(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\(.+\))$/i.test(text)?text:null}function styleColorPair(value){if(typeof value=="string")return styleColor(value);if(!isPlainRecord(value))return null;const light=styleColor(ownField(value,"light")),dark=styleColor(ownField(value,"dark"));return light||dark?Object.freeze({light,dark}):null}function styleAccent(value){if(typeof value=="string")return styleColor(value);if(!isPlainRecord(value))return null;const entries=SEMANTIC_ROLES.filter(role=>Object.hasOwn(value,role)).map(role=>[role,styleColorPair(ownField(value,role))]);return entries.length?Object.freeze(Object.fromEntries(entries)):null}function normalizeStyleChoices(raw,base){const next={...base};if(!isPlainRecord(raw))return next;const look=ownField(raw,"look");if(look!==void 0){if(next.look=DEFAULT_STYLE.look,next.tokens=null,styleId(look))next.look=look;else if(isPlainRecord(look))try{const definition=defineLyraLook(look);next.look=definition.id,next.tokens=definition.tokens}catch{}}const surface=ownField(raw,"surface");surface!==void 0&&(next.surface=surface==="glass"||surface==="solid"?surface:DEFAULT_STYLE.surface);const density=ownField(raw,"density");density!==void 0&&(next.density=density==="comfortable"||density==="compact"||density==="touch"?density:DEFAULT_STYLE.density);const mode=ownField(raw,"mode");mode!==void 0&&(next.mode=mode==="light"||mode==="dark"||mode==="system"||mode==="unset"?mode:DEFAULT_STYLE.mode);const accent=ownField(raw,"accent");accent!==void 0&&(next.accentName=typeof accent=="string"&&Object.hasOwn(STYLE_GEMSTONES,accent)?accent:null,next.accent=next.accentName?STYLE_GEMSTONES[next.accentName]:styleAccent(accent));const background=ownField(raw,"accentBackground");background!==void 0&&(next.accentBackground=styleColorPair(background));const overrides=ownField(raw,"overrides");return overrides!==void 0&&(next.overrides=styleTokens(overrides)),next}function styleFromRecord(value,browserColors=!1){const record=resolveStyleStartup(value,STYLE_DEFAULTS,normalizeTokens,input=>styleColor(input,browserColors)??void 0,styleTokenAllowed,STYLE_GEMSTONES),state=normalizeStyleChoices({look:ownField(record,"look"),mode:ownField(record,"mode"),density:ownField(record,"density"),surface:ownField(record,"treatment"),overrides:ownField(record,"overrides"),accentBackground:ownField(record,"surface")},{...DEFAULT_STYLE});state.accent=styleAccent(ownField(record,"accent"));const accentName=ownField(record,"accentName");return state.accentName=null,typeof accentName=="string"&&Object.hasOwn(STYLE_GEMSTONES,accentName)&&(state.accentName=accentName,state.accent=STYLE_GEMSTONES[accentName]),state.tokens=normalizeTokens(ownField(record,"tokens")),state.tokens&&!styleId(ownField(record,"look"))&&(state.look="custom"),state}function styleRecord(state){return{version:2,mode:state.mode,look:state.look,density:state.density,treatment:state.surface,accent:state.accent,surface:state.accentBackground,...state.accentName?{accentName:state.accentName}:{},...state.tokens?{tokens:state.tokens}:{},...state.overrides?{overrides:state.overrides}:{}}}function styleResolvedMode(mode,view){return mode==="unset"?null:mode!=="system"?mode:view?.matchMedia?.(COLOR_SCHEME_QUERY).matches?"dark":"light"}function styleSnapshot(state,view){return Object.freeze({look:state.look,lookForm:state.tokens?"runtime":"stylesheet",surface:state.surface,density:state.density,mode:state.mode,accent:state.accentName??state.accent,accentName:state.accentName,accentBackground:state.accentBackground,...state.overrides?{overrides:state.overrides}:{},resolvedMode:styleResolvedMode(state.mode,view)})}function parseLyraStyleRecord(value){const state=styleFromRecord(value),result=styleSnapshot(state);return state.mode==="system"?Object.freeze({...result,resolvedMode:null}):result}function lyraStyleAttributes(style){const attributes={};return styleId(style.look)&&(attributes["data-lr-look"]=style.look),(style.surface==="solid"||style.surface==="glass")&&(attributes["data-lr-surface"]=style.surface),(style.density==="compact"||style.density==="comfortable"||style.density==="touch")&&(attributes["data-lr-density"]=style.density),(style.mode==="light"||style.mode==="dark"||style.mode==="system")&&(attributes["data-lr-mode"]=style.mode),style.accent!==void 0&&(attributes["data-lr-accent"]=style.accent===null?"none":style.accentName===null?"custom":typeof style.accent=="string"&&Object.hasOwn(STYLE_GEMSTONES,style.accent)?style.accent:"custom"),Object.freeze(attributes)}function readStyleState(){if(stylePersistenceFailed)return{...lastStyle};let stored;try{stored=localStorage.getItem(STORAGE_KEY)}catch{return{...lastStyle}}try{return styleFromRecord(JSON.parse(stored??"null"),!0)}catch{return{...DEFAULT_STYLE}}}function persistStyle(state){try{localStorage.setItem(STORAGE_KEY,JSON.stringify(styleRecord(state))),stylePersistenceFailed=!1}catch{stylePersistenceFailed=!0}lastStyle=state}function ownershipFor(element){const node=element;try{const existing=readStyleOwnership(node[STYLE_OWNERSHIP]);if(existing){styleOwnershipFallback.set(element,existing);try{node[STYLE_OWNERSHIP]=existing}catch{}return existing}}catch{}const fallback=styleOwnershipFallback.get(element);if(fallback)return fallback;const record={attributes:new Map,properties:new Map};styleOwnershipFallback.set(element,record);try{node[STYLE_OWNERSHIP]=record}catch{}return record}function writeStyleAttributes(element,desired){const ownership=ownershipFor(element).attributes;for(const[name,value]of ownership)Object.hasOwn(desired,name)||(element.getAttribute(name)===value.written&&(value.before===null?element.removeAttribute(name):element.setAttribute(name,value.before)),ownership.delete(name));for(const[name,value]of Object.entries(desired))ownership.has(name)||ownership.set(name,{before:element.getAttribute(name),priority:"",written:value}),element.getAttribute(name)!==value&&element.setAttribute(name,value),ownership.get(name).written=value}function writeStyleProperties(element,desired){const style=element.style;if(!style)return;const ownership=ownershipFor(element).properties;for(const[name,value]of ownership)desired.has(name)||(style.getPropertyValue(name)===value.written&&style.getPropertyPriority(name)===""&&(value.before?style.setProperty(name,value.before,value.priority):style.removeProperty(name)),ownership.delete(name));for(const[name,value]of desired){ownership.has(name)||ownership.set(name,{before:style.getPropertyValue(name),priority:style.getPropertyPriority(name),written:null});const record=ownership.get(name);(style.getPropertyPriority(name)!==""||style.getPropertyValue(name)!==value&&!(record.requested===value&&record.written===style.getPropertyValue(name)))&&(style.getPropertyPriority(name)&&style.removeProperty(name),style.setProperty(name,value,"")),record.requested=value,record.written=style.getPropertyValue(name)}}function styleSlot(name,mode,accent=!1){return`--_lr-${accent?"a":"l"}${mode==="light"?"l":"d"}-${name.slice(11)}`}function styleFollow(name,value){const channel=name.match(/^--lr-theme-color-(?:success|warning|danger|neutral)-((?:fill|border|on)-(?:quiet|normal|loud))$/)?.[1];return!!(channel&&value===`var(--lr-theme-color-brand-${channel})`)}function styleBranch(name,mode){let result=`var(${styleSlot(name,mode)})`;if(STYLE_FOLLOW.includes(name)){const key=mode==="light"?"l":"d",target=name.replace(/color-(?:success|warning|danger|neutral)-/,"color-brand-");result=`var(--_lr-f${key}-${name.slice(11)},${result})var(--_lr-o${key}-${name.slice(11)},var(${styleSlot(target,mode,!0)},var(${styleSlot(target,mode)})))`}return ALL_RAMP_PROPERTIES.includes(name)?`var(${styleSlot(name,mode,!0)},${result})`:result}function styleResolvedInput(name){const input=`var(--_lr-dark-on,${styleBranch(name,"light")})var(--_lr-light-on,${styleBranch(name,"dark")})`;if(!STYLE_DENSITY.includes(name))return input;const spacing=name.startsWith("--lr-theme-space-");return`var(--_lr-dense-on,${input})var(--_lr-dense-off,max(calc((${input}) * var(--_lr-density-${spacing?"space":"control"},1)),${spacing?"0px":"var(--_lr-density-target-min,0px)"}))`}function styleReferences(state,entries,mode,element,previous){const look=element.closest("[data-lr-look]")?.getAttribute("data-lr-look"),colors=(STYLE_REFERENCE_SURFACES[look??STYLE_DEFAULTS.look]??STYLE_REFERENCE_SURFACES.lyra)[mode],names=["color-surface-default","color-surface-raised","color-text-normal","color-overlay-strong"].slice(0,entries.size?4:1).map(suffix=>`--lr-theme-${suffix}`),supplied=names.map(name=>entries.get(name)),background=typeof state.accentBackground=="string"?state.accentBackground:state.accentBackground?.[mode],style=element.style,ownership=ownershipFor(element).properties,projected=names.flatMap((name,index)=>{const slot=styleSlot(name,mode),owned=ownership.get(slot),before=style?.getPropertyValue(slot)??"",priority=style?.getPropertyPriority(slot)??"",owns=owned&&before===owned.written&&!priority;if(supplied[index]!==void 0&&previous?.[index]===supplied[index]&&owns)return[];if(supplied[index]===void 0&&!owns)return[];const value=supplied[index]??owned?.before??"",nextPriority=supplied[index]===void 0?owned?.priority??"":"";return before===value&&priority===nextPriority?[]:[{slot,before,priority,value,nextPriority}]});try{for(const{slot,value,nextPriority}of projected)style.getPropertyPriority(slot)&&style.removeProperty(slot),value?style.setProperty(slot,value,nextPriority):style.removeProperty(slot);const computed=element.ownerDocument.defaultView?.getComputedStyle(element);return{supplied,colors:names.map((name,index)=>(index===0?background:void 0)??supplied[index]??(computed?.getPropertyValue(styleSlot(name,mode)).trim()||colors[index]))}}finally{for(const{slot,before,priority}of projected)style.getPropertyPriority(slot)&&style.removeProperty(slot),before?style.setProperty(slot,before,priority):style.removeProperty(slot)}}const stylePaintCache=new WeakMap;function stylePaint(state,element,wholeDocument){const desired=new Map,mode=styleResolvedMode(state.mode,element.ownerDocument.defaultView),tokens={...state.tokens,...state.overrides};if(wholeDocument&&mode===null)for(const[name,value]of tokenEntries(tokens,null))desired.set(name,value);if(!Object.keys(tokens).length&&(!state.accent||state.accentName))return stylePaintCache.delete(element),desired;const resolver=element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue("--_lr-style-resolver").trim()==="1";let cache=stylePaintCache.get(element);cache||(cache=new Map,stylePaintCache.set(element,cache));let applied=state.accent;for(const branch of["light","dark"]){const entries=tokenEntries(tokens,branch),{colors:references,supplied}=styleReferences(state,entries,branch,element,cache.get(branch)?.supplied),reference=references[0],key=JSON.stringify([tokens,state.accent,state.accentName,references]);let cached=cache.get(branch);if(!cached||cached.key!==key){const background=reference?parseResolvedRgb(reference,MODE_SURFACES[branch],element.ownerDocument)??MODE_SURFACES[branch]:MODE_SURFACES[branch],accent=state.accentName?{applied:state.accent,properties:new Map}:paintAccent(state.accent,branch,background,element.ownerDocument);cached={key,supplied,tokens:floorTokenEntries(entries,background,element.ownerDocument,references),accent:accent.properties,applied:accent.applied},cache.set(branch,cached)}branch===mode&&(applied=cached.applied);const painted=cached.tokens;for(const[name,value]of painted)STYLE_SLOTTED.includes(name)&&styleTokenAllowed(name,value)?(styleFollow(name,value)?(desired.set(`--_lr-f${branch==="light"?"l":"d"}-${name.slice(11)}`," "),desired.set(`--_lr-o${branch==="light"?"l":"d"}-${name.slice(11)}`,"initial")):(desired.set(styleSlot(name,branch),value),STYLE_FOLLOW.includes(name)&&(desired.set(`--_lr-f${branch==="light"?"l":"d"}-${name.slice(11)}`,"initial"),desired.set(`--_lr-o${branch==="light"?"l":"d"}-${name.slice(11)}`," "))),wholeDocument&&branch===mode&&desired.set(name,resolver?styleResolvedInput(name):value)):(wholeDocument?branch===mode:typeof tokens[name]=="string"&&!STYLE_SLOTTED.includes(name))&&desired.set(name,value);if(state.accent&&!state.accentName)for(const[name,value]of cached.accent){if(name==="--lr-theme-accent"){branch===mode&&desired.set(name,value);continue}desired.set(styleSlot(name,branch,!0),value),wholeDocument&&branch===mode&&desired.set(name,resolver?styleResolvedInput(name):value)}}return state.accent=applied,desired}const styleModeGroups=new WeakMap;function attachStyleMode(element,callback){const view=element.ownerDocument.defaultView;if(!view?.matchMedia)return()=>{};let group=styleModeGroups.get(view);if(!group){const query=view.matchMedia(COLOR_SCHEME_QUERY),subscriptions=new Set,modern=typeof query.addEventListener=="function"&&typeof query.removeEventListener=="function",detach=()=>{modern?query.removeEventListener("change",listener):query.removeListener?.(listener)},listener=()=>{for(const subscription2 of subscriptions){const node=subscription2.element.deref();node?.ownerDocument.defaultView===view?subscription2.callback(node):subscriptions.delete(subscription2)}subscriptions.size||(detach(),styleModeGroups.delete(view))};group={query,subscriptions,detach},styleModeGroups.set(view,group),modern?query.addEventListener("change",listener):query.addListener?.(listener)}const subscription={element:new WeakRef(element),callback};group.subscriptions.add(subscription);const active=group;return()=>{active.subscriptions.delete(subscription),active.subscriptions.size||(active.detach(),styleModeGroups.delete(view))}}function applyStyleState(element,state,fields){const snapshot=styleSnapshot(state,element.ownerDocument.defaultView),attributes={...lyraStyleAttributes(snapshot)};if(fields)for(const[field,name]of[["look","look"],["surface","surface"],["density","density"],["mode","mode"],["accent","accent"]])fields.has(field)||delete attributes[`data-lr-${name}`];state.accent&&!state.accentName&&(!fields||fields.has("accent"))&&(attributes["data-lr-accent"]="custom"),(!fields||fields.has("mode"))&&snapshot.resolvedMode&&(attributes["data-lr-theme"]=snapshot.resolvedMode,attributes["data-theme"]=snapshot.resolvedMode),(state.tokens||state.overrides||state.accent&&!state.accentName)&&(attributes["data-lr-theme-scope"]=""),writeStyleAttributes(element,attributes);const desired=stylePaint(state,element,!fields);(!fields||fields.has("surface"))&&element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue("--_lr-style-resolver").trim()!=="1"&&styleMaterial(desired,state.surface),!state.accent&&snapshot.accent&&(attributes["data-lr-accent"]="none",!state.tokens&&!state.overrides&&delete attributes["data-lr-theme-scope"],writeStyleAttributes(element,attributes)),writeStyleProperties(element,desired),adoptTokenLayerForScope(element),diagnoseStyleSheets(element,state,fields)}function adoptTokenLayerForScope(element){const root=element.getRootNode();if(root===element.ownerDocument||root.nodeType!==11)return;const adopt=globalThis[Symbol.for("@aceshooting/lyra-ui.adopt-lyra-tokens.v1")];typeof adopt=="function"&&adopt(root)}function diagnoseStyleSheets(element,state,fields){if(!litDevWarnings())return;const selected=field=>!fields||fields.has(field),required=[];selected("look")&&!state.tokens&&state.look!=="lyra"&&state.look!==DEFAULT_STYLE.look&&required.push(["--_lr-look-installed",`${state.look}-1`,`the stylesheet for look '${state.look}'`]),selected("surface")&&state.surface==="glass"&&state.surface!==DEFAULT_STYLE.surface&&required.push(["--_lr-surface-installed","1","surfaces/glass.css"]),selected("density")&&state.density!=="comfortable"&&required.push(["--_lr-density-installed","1","density.css"]),selected("accent")&&state.accentName&&state.accentName!==DEFAULT_STYLE.accentName&&required.push(["--_lr-accent-installed",`${state.accentName}-1`,"accents.css"]);const scopedRuntime=!!(fields&&(state.tokens||state.overrides||state.accent&&!state.accentName)),alternateProfile=selected("look")&&!state.tokens&&state.look!==DEFAULT_STYLE.look||selected("accent")&&!state.accent;if(!required.length&&!scopedRuntime&&!alternateProfile)return;const computed=element.ownerDocument.defaultView?.getComputedStyle(element);if(computed){computed.getPropertyValue("--_lr-style-resolver").trim()!=="1"&&devWarnOnce("lyra-style:resolver","Lyra style choices require theme.css in the scope that owns their attributes.");for(const[property,expected,stylesheet]of required)computed.getPropertyValue(property).trim()!==expected&&devWarnOnce(`lyra-style:${property}:${expected}`,`Lyra could not find ${stylesheet} in this style scope; import or adopt the stylesheet before selecting it.`)}}function emitStyleChange(state,changed){const style=styleSnapshot(state,window);window.dispatchEvent(new CustomEvent("lr-style-change",{detail:Object.freeze({style,changed:Object.freeze([...changed])})}))}function setLyraStyle(choices){const before=readStyleState();return commitStyle(before,normalizeStyleChoices(choices,before))}function commitStyle(before,next){if(typeof document<"u"&&(next.accent=normalizeAccent(next.accent),typeof next.accentBackground=="string"&&(next.accentBackground=normalizeColor(next.accentBackground)),next.accent||(next.accentName=null)),persistStyle(next),typeof document<"u"){applyRootStyle(next)&&persistStyle(next);const changed=STYLE_FIELDS.filter(field=>field==="look"?before.look!==next.look||!tokensEqual(before.tokens,next.tokens):field==="accent"?before.accentName!==next.accentName||!accentsEqual(before.accent,next.accent):JSON.stringify(before[field])!==JSON.stringify(next[field]));emitStyleChange(next,changed)}return styleSnapshot(next,typeof window>"u"?void 0:window)}function applyRootStyle(next){const root=document.documentElement;(next.mode!=="system"||styleModeRoot?.deref()!==root)&&(styleModeCleanup?.(),styleModeCleanup=void 0,styleModeRoot=void 0),adoptLegacyOwnership(root);const requestedAccent=next.accent;return applyStyleState(root,next),next.mode==="system"&&!styleModeCleanup&&(styleModeRoot=new WeakRef(root),styleModeCleanup=attachStyleMode(root,element=>{applyStyleState(element,lastStyle),emitStyleChange(lastStyle,["resolvedMode"])})),!accentsEqual(requestedAccent,next.accent)}function adoptLegacyOwnership(root){const symbol=Symbol.for(TOKEN_OWNERSHIP_SYMBOL),node=root;try{if(!Array.isArray(node[symbol]))return}catch{return}const ownership=ownershipFor(root).properties;for(const name of[...readOwnershipList(),...ALL_RAMP_PROPERTIES,"--lr-theme-accent"])ownership.has(name)||!root.style.getPropertyValue(name)||ownership.set(name,{before:null,priority:"",written:root.style.getPropertyValue(name)});try{delete node[symbol]}catch{}}function getLyraStyle(){return styleSnapshot(readStyleState(),typeof window>"u"?void 0:window)}function startLyraStyle(){const state=readStyleState();return typeof document>"u"?styleSnapshot(state):(state.accent=normalizeAccent(state.accent),typeof state.accentBackground=="string"&&(state.accentBackground=normalizeColor(state.accentBackground)),state.accent||(state.accentName=null),lastStyle=state,applyRootStyle(state),styleSnapshot(state,window))}function resetLyraStyle(fields=STYLE_FIELDS){const defaults={...STYLE_DEFAULTS,accentBackground:null,overrides:null};return setLyraStyle(Object.fromEntries(fields.filter(field=>STYLE_FIELDS.includes(field)).map(field=>[field,defaults[field]])))}function applyLyraStyleScope(element,choices){if(scopeModes.get(element)?.(),scopeModes.delete(element),choices===null){writeStyleAttributes(element,{}),writeStyleProperties(element,new Map);return}const state=normalizeStyleChoices(choices,{...DEFAULT_STYLE}),fields=new Set(STYLE_FIELDS.filter(field=>ownField(choices,field)!==void 0));applyStyleState(element,state,fields),choices.mode==="system"&&scopeModes.set(element,attachStyleMode(element,node=>applyStyleState(node,state,fields)))}const lyraThemeBootstrap=/* @__PURE__ */createLyraThemeBootstrap();export{accentsEqual,applyLyraStyleScope,createLyraThemeBootstrap,defineLyraLook,getLyraStyle,isLyraThemeTokenName,isSafeLyraThemeTokenValue,lyraStyleAttributes,lyraThemeBootstrap,parseLyraStyleRecord,resetLyraStyle,setLyraStyle,startLyraStyle,tokensEqual};
package/llms/peers.md CHANGED
@@ -38,9 +38,9 @@ for the page.
38
38
  | Peer | Range | Needed by |
39
39
  |---|---|---|
40
40
  | `@aceshooting/lyra-flags` | `^2.3.0` | _(loaded by a shared internal module)_ |
41
- | `@aceshooting/lyra-map` | `^1.1.0` | `lr-geojson-viewer`, `lr-map` |
42
- | `@aceshooting/lyra-translations` | `^29.1.0` | _(not referenced by any component)_ |
43
- | `@aiden0z/pptx-renderer` | `^1.3.0` | `lr-pptx-viewer` |
41
+ | `@aceshooting/lyra-map` | `^1.2.0` | `lr-geojson-viewer`, `lr-map` |
42
+ | `@aceshooting/lyra-translations` | `^29.2.0` | _(not referenced by any component)_ |
43
+ | `@aiden0z/pptx-renderer` | `^1.4.0` | `lr-pptx-viewer` |
44
44
  | `@sgratzl/chartjs-chart-boxplot` | `^4.0.0` | `lr-box-plot` |
45
45
  | `chart.js` | `^4.0.1` | `lr-bar-chart`, `lr-box-plot`, `lr-bubble-chart`, `lr-chart`, `lr-doughnut-chart`, `lr-histogram`, `lr-line-chart`, `lr-pie-chart`, `lr-polar-area-chart`, `lr-radar-chart`, `lr-scatter-chart` |
46
46
  | `chartjs-plugin-annotation` | `^3.0.0` | `lr-bar-chart`, `lr-bubble-chart`, `lr-chart`, `lr-doughnut-chart`, `lr-histogram`, `lr-line-chart`, `lr-pie-chart`, `lr-polar-area-chart`, `lr-radar-chart`, `lr-scatter-chart` |
@@ -183,7 +183,7 @@ The entry points, then:
183
183
  `@aceshooting/lyra-ui/localization.js` (side-effect-free locale runtime),
184
184
  `@aceshooting/lyra-ui/autoloader.js` (side-effect-free on-demand tag loading),
185
185
  `@aceshooting/lyra-ui/autoloader-cdn.js` (browser-guarded auto-start side effect),
186
- `@aceshooting/lyra-translations/<locale>.js` (the sixty-six message catalogs, in the companion package),
186
+ `@aceshooting/lyra-translations/<locale>.js` (the seventy message catalogs, in the companion package),
187
187
  `@aceshooting/lyra-ui/events` (the global typed-event map — types only, no runtime),
188
188
  `@aceshooting/lyra-ui/ai` (provider-neutral data types), `@aceshooting/lyra-ui/testing`
189
189
  (happy-dom shims, `createLyraEvent()` for building a validated test event, a small set of
@@ -117,7 +117,7 @@ category selection walks the same chain, so the two can never disagree:
117
117
  _regional-only_ catalog is reached from a less specific tag (`lang="zh"` finds `zh-CN`,
118
118
  `lang="pt"` finds `pt-BR`). Order is deterministic and independent of import order:
119
119
  1. **Same likely script** — the explicit script subtag, else CLDR likely subtags via
120
- `Intl.Locale#maximize()`. `zh-Hant`, `zh-HK`, `zh-MO` and `zh-Hant-CN` reach Traditional
120
+ `Intl.Locale#maximize()`. `zh-Hant`, `zh-HK` (when `zh-HK` is not itself imported), `zh-MO` and `zh-Hant-CN` reach Traditional
121
121
  `zh-TW`; `zh`, `zh-Hans`, `zh-SG` and `zh-Hans-HK` reach Simplified `zh-CN`. An unknown
122
122
  script (none, `Zzzz`, or no `Intl.Locale`) never matches.
123
123
  2. **Same likely region** — a region-less tag reaches its CLDR default region: bare `pt` picks
@@ -200,7 +200,7 @@ silently defeats a registered catalog — omit it, or pass `undefined`.
200
200
 
201
201
  ### Ready-made catalogs: `@aceshooting/lyra-translations/<locale>.js`
202
202
 
203
- Sixty-six full catalogs ship in the companion package `@aceshooting/lyra-translations` (`pnpm add @aceshooting/lyra-translations`, same version as `@aceshooting/lyra-ui`), each covering every key in `LYRA_DEFAULT_STRINGS`.
203
+ Seventy catalogs ship in the companion package `@aceshooting/lyra-translations` (`pnpm add @aceshooting/lyra-translations`, same version as `@aceshooting/lyra-ui`), each covering every key in `LYRA_DEFAULT_STRINGS`.
204
204
  The public `@aceshooting/lyra-ui/locales.json` manifest lists their canonical identities, authored
205
205
  source spellings, import paths, and structural coverage. It also distinguishes translation
206
206
  coverage from linguistic review tier. The catalogs are **side-effect-only modules**: import one
@@ -209,6 +209,9 @@ bare, read nothing from it, and it calls `registerLyraLocale()` for you.
209
209
  ```ts
210
210
  import "@aceshooting/lyra-translations/de.js";
211
211
  import "@aceshooting/lyra-translations/de-CH.js"; // Swiss Standard German
212
+ import "@aceshooting/lyra-translations/en-GB.js"; // British English: a small difference catalog over the built-in English
213
+ import "@aceshooting/lyra-translations/es-419.js"; // Latin American Spanish: differences over es
214
+ import "@aceshooting/lyra-translations/fr-CA.js"; // Canadian French: differences over fr
212
215
  import "@aceshooting/lyra-translations/ar.js"; // declares dir: 'rtl'; direction still comes from dir
213
216
  import "@aceshooting/lyra-translations/fa.js"; // fa-IR falls back to this base catalog
214
217
  import "@aceshooting/lyra-translations/he.js"; // he-IL falls back to this base catalog
@@ -217,7 +220,8 @@ import "@aceshooting/lyra-translations/pt-BR.js"; // Brazilian: serves pt and pt
217
220
  import "@aceshooting/lyra-translations/pt-PT.js"; // European: serves pt-PT, pt-AO, pt-MZ
218
221
  import "@aceshooting/lyra-translations/ro.js"; // Romanian
219
222
  import "@aceshooting/lyra-translations/zh-CN.js"; // Simplified: serves zh, zh-Hans, zh-SG and zh-Hans-CN
220
- import "@aceshooting/lyra-translations/zh-TW.js"; // Traditional: serves zh-Hant, zh-HK and zh-MO
223
+ import "@aceshooting/lyra-translations/zh-TW.js"; // Traditional: serves zh-Hant and zh-MO
224
+ import "@aceshooting/lyra-translations/zh-HK.js"; // Hong Kong: differences over zh-TW
221
225
  ```
222
226
 
223
227
  Persian and Hebrew use CLDR plural categories (`fa`: `one`/`other`; `he`:
@@ -229,11 +233,14 @@ and `he` declare `dir: 'rtl'`, so `getLyraLocaleDirection()`
229
233
  answers for them (and for `ar-EG`, `fa-IR`, `he-IL`) — but locale selection still does not _force_
230
234
  writing direction: set `dir="rtl"` on the page or an ancestor yourself.
231
235
 
232
- `de-CH`, `pt-BR`, `pt-PT`, `zh-CN`, and `zh-TW` are regional catalogs: an exact tag always selects
236
+ `de-CH`, `en-GB`, `es-419`, `fr-CA`, `pt-BR`, `pt-PT`, `zh-CN`, `zh-HK`, and `zh-TW` are regional catalogs: an exact tag always selects
233
237
  its own catalog, and a less specific tag reaches one through step 2 only when nothing on its
234
238
  truncation walk answers first (with `de` imported, `lang="de-AT"` resolves to `de`, never `de-CH`).
235
239
  The same routing drives plural selection and `getLyraLocaleDirection()`. They are listed under
236
- their real tags in `getRegisteredLyraLocales()`.
240
+ their real tags in `getRegisteredLyraLocales()`. `de-CH`, `en-GB`, `es-419`, `fr-CA` and `zh-HK` are difference catalogs:
241
+ they register only the messages that differ and resolve every other message through their parent
242
+ (`de`, the built-in English, `es`, `fr`, `zh-TW`), and importing one also imports its parent catalog (`en-GB` has none: English is built in).
243
+ The four regional additions are AI-assisted translations; no human or native-speaker review is claimed.
237
244
 
238
245
  Import only the locales the application can actually offer — each is a separate module, so unimported
239
246
  ones cost nothing. A catalog registered this way is merged like any other, so a later
@@ -43,6 +43,11 @@ insertions and removals; nested shadow trees and constructed `adoptedStyleSheets
43
43
  This lets marked application scopes discover and adopt their token provider under Happy DOM.
44
44
  An existing platform collection is never replaced, and plain Node remains unchanged.
45
45
 
46
+ `lr-code-block` and `lr-code-block-core` no longer need an `Element.part` shim: where the DOM lacks
47
+ `Element.part` (Happy DOM), rendering does not throw, and highlighted lines keep their
48
+ `line-highlight` part wherever CSS parts exist. If a setup file patches `Element.prototype.part`
49
+ only for code blocks, remove it; `installHappyDomShims()` does not install one.
50
+
46
51
  When Happy DOM lacks the HTML `dir="ltr"`/`dir="rtl"` presentational hints,
47
52
  `installHappyDomShims()` adds zero-specificity direction rules to the document head. This restores
48
53
  computed direction and inherited component direction while preserving explicit author CSS.
package/llms/shared.md CHANGED
@@ -182,7 +182,7 @@ The entry points, then:
182
182
  `@aceshooting/lyra-ui/localization.js` (side-effect-free locale runtime),
183
183
  `@aceshooting/lyra-ui/autoloader.js` (side-effect-free on-demand tag loading),
184
184
  `@aceshooting/lyra-ui/autoloader-cdn.js` (browser-guarded auto-start side effect),
185
- `@aceshooting/lyra-translations/<locale>.js` (the sixty-six message catalogs, in the companion package),
185
+ `@aceshooting/lyra-translations/<locale>.js` (the seventy message catalogs, in the companion package),
186
186
  `@aceshooting/lyra-ui/events` (the global typed-event map — types only, no runtime),
187
187
  `@aceshooting/lyra-ui/ai` (provider-neutral data types), `@aceshooting/lyra-ui/testing`
188
188
  (happy-dom shims, `createLyraEvent()` for building a validated test event, a small set of
@@ -2483,7 +2483,7 @@ category selection walks the same chain, so the two can never disagree:
2483
2483
  _regional-only_ catalog is reached from a less specific tag (`lang="zh"` finds `zh-CN`,
2484
2484
  `lang="pt"` finds `pt-BR`). Order is deterministic and independent of import order:
2485
2485
  1. **Same likely script** — the explicit script subtag, else CLDR likely subtags via
2486
- `Intl.Locale#maximize()`. `zh-Hant`, `zh-HK`, `zh-MO` and `zh-Hant-CN` reach Traditional
2486
+ `Intl.Locale#maximize()`. `zh-Hant`, `zh-HK` (when `zh-HK` is not itself imported), `zh-MO` and `zh-Hant-CN` reach Traditional
2487
2487
  `zh-TW`; `zh`, `zh-Hans`, `zh-SG` and `zh-Hans-HK` reach Simplified `zh-CN`. An unknown
2488
2488
  script (none, `Zzzz`, or no `Intl.Locale`) never matches.
2489
2489
  2. **Same likely region** — a region-less tag reaches its CLDR default region: bare `pt` picks
@@ -2566,7 +2566,7 @@ silently defeats a registered catalog — omit it, or pass `undefined`.
2566
2566
 
2567
2567
  ### Ready-made catalogs: `@aceshooting/lyra-translations/<locale>.js`
2568
2568
 
2569
- Sixty-six full catalogs ship in the companion package `@aceshooting/lyra-translations` (`pnpm add @aceshooting/lyra-translations`, same version as `@aceshooting/lyra-ui`), each covering every key in `LYRA_DEFAULT_STRINGS`.
2569
+ Seventy catalogs ship in the companion package `@aceshooting/lyra-translations` (`pnpm add @aceshooting/lyra-translations`, same version as `@aceshooting/lyra-ui`), each covering every key in `LYRA_DEFAULT_STRINGS`.
2570
2570
  The public `@aceshooting/lyra-ui/locales.json` manifest lists their canonical identities, authored
2571
2571
  source spellings, import paths, and structural coverage. It also distinguishes translation
2572
2572
  coverage from linguistic review tier. The catalogs are **side-effect-only modules**: import one
@@ -2575,6 +2575,9 @@ bare, read nothing from it, and it calls `registerLyraLocale()` for you.
2575
2575
  ```ts
2576
2576
  import "@aceshooting/lyra-translations/de.js";
2577
2577
  import "@aceshooting/lyra-translations/de-CH.js"; // Swiss Standard German
2578
+ import "@aceshooting/lyra-translations/en-GB.js"; // British English: a small difference catalog over the built-in English
2579
+ import "@aceshooting/lyra-translations/es-419.js"; // Latin American Spanish: differences over es
2580
+ import "@aceshooting/lyra-translations/fr-CA.js"; // Canadian French: differences over fr
2578
2581
  import "@aceshooting/lyra-translations/ar.js"; // declares dir: 'rtl'; direction still comes from dir
2579
2582
  import "@aceshooting/lyra-translations/fa.js"; // fa-IR falls back to this base catalog
2580
2583
  import "@aceshooting/lyra-translations/he.js"; // he-IL falls back to this base catalog
@@ -2583,7 +2586,8 @@ import "@aceshooting/lyra-translations/pt-BR.js"; // Brazilian: serves pt and pt
2583
2586
  import "@aceshooting/lyra-translations/pt-PT.js"; // European: serves pt-PT, pt-AO, pt-MZ
2584
2587
  import "@aceshooting/lyra-translations/ro.js"; // Romanian
2585
2588
  import "@aceshooting/lyra-translations/zh-CN.js"; // Simplified: serves zh, zh-Hans, zh-SG and zh-Hans-CN
2586
- import "@aceshooting/lyra-translations/zh-TW.js"; // Traditional: serves zh-Hant, zh-HK and zh-MO
2589
+ import "@aceshooting/lyra-translations/zh-TW.js"; // Traditional: serves zh-Hant and zh-MO
2590
+ import "@aceshooting/lyra-translations/zh-HK.js"; // Hong Kong: differences over zh-TW
2587
2591
  ```
2588
2592
 
2589
2593
  Persian and Hebrew use CLDR plural categories (`fa`: `one`/`other`; `he`:
@@ -2595,11 +2599,14 @@ and `he` declare `dir: 'rtl'`, so `getLyraLocaleDirection()`
2595
2599
  answers for them (and for `ar-EG`, `fa-IR`, `he-IL`) — but locale selection still does not _force_
2596
2600
  writing direction: set `dir="rtl"` on the page or an ancestor yourself.
2597
2601
 
2598
- `de-CH`, `pt-BR`, `pt-PT`, `zh-CN`, and `zh-TW` are regional catalogs: an exact tag always selects
2602
+ `de-CH`, `en-GB`, `es-419`, `fr-CA`, `pt-BR`, `pt-PT`, `zh-CN`, `zh-HK`, and `zh-TW` are regional catalogs: an exact tag always selects
2599
2603
  its own catalog, and a less specific tag reaches one through step 2 only when nothing on its
2600
2604
  truncation walk answers first (with `de` imported, `lang="de-AT"` resolves to `de`, never `de-CH`).
2601
2605
  The same routing drives plural selection and `getLyraLocaleDirection()`. They are listed under
2602
- their real tags in `getRegisteredLyraLocales()`.
2606
+ their real tags in `getRegisteredLyraLocales()`. `de-CH`, `en-GB`, `es-419`, `fr-CA` and `zh-HK` are difference catalogs:
2607
+ they register only the messages that differ and resolve every other message through their parent
2608
+ (`de`, the built-in English, `es`, `fr`, `zh-TW`), and importing one also imports its parent catalog (`en-GB` has none: English is built in).
2609
+ The four regional additions are AI-assisted translations; no human or native-speaker review is claimed.
2603
2610
 
2604
2611
  Import only the locales the application can actually offer — each is a separate module, so unimported
2605
2612
  ones cost nothing. A catalog registered this way is merged like any other, so a later
@@ -3048,6 +3055,11 @@ insertions and removals; nested shadow trees and constructed `adoptedStyleSheets
3048
3055
  This lets marked application scopes discover and adopt their token provider under Happy DOM.
3049
3056
  An existing platform collection is never replaced, and plain Node remains unchanged.
3050
3057
 
3058
+ `lr-code-block` and `lr-code-block-core` no longer need an `Element.part` shim: where the DOM lacks
3059
+ `Element.part` (Happy DOM), rendering does not throw, and highlighted lines keep their
3060
+ `line-highlight` part wherever CSS parts exist. If a setup file patches `Element.prototype.part`
3061
+ only for code blocks, remove it; `installHappyDomShims()` does not install one.
3062
+
3051
3063
  When Happy DOM lacks the HTML `dir="ltr"`/`dir="rtl"` presentational hints,
3052
3064
  `installHappyDomShims()` adds zero-specificity direction rules to the document head. This restores
3053
3065
  computed direction and inherited component direction while preserving explicit author CSS.
package/locales.json CHANGED
@@ -350,6 +350,34 @@
350
350
  "other"
351
351
  ]
352
352
  },
353
+ {
354
+ "locale": "en-GB",
355
+ "kind": "translated",
356
+ "direction": "ltr",
357
+ "script": "Latn",
358
+ "parent": "en",
359
+ "aggregateImport": "@aceshooting/lyra-translations/en-GB.js",
360
+ "familyImports": {
361
+ "agent-tools": "@aceshooting/lyra-translations/en-GB/agent-tools.js",
362
+ "conversation": "@aceshooting/lyra-translations/en-GB/conversation.js",
363
+ "data": "@aceshooting/lyra-translations/en-GB/data.js",
364
+ "forms": "@aceshooting/lyra-translations/en-GB/forms.js",
365
+ "media": "@aceshooting/lyra-translations/en-GB/media.js",
366
+ "retrieval": "@aceshooting/lyra-translations/en-GB/retrieval.js",
367
+ "shared": "@aceshooting/lyra-translations/en-GB/shared.js",
368
+ "viewers": "@aceshooting/lyra-translations/en-GB/viewers.js"
369
+ },
370
+ "sourceKeyCount": 1531,
371
+ "translatedOwnKeyCount": 20,
372
+ "inheritedKeyCount": 1511,
373
+ "missingKeyCount": 0,
374
+ "reviewTier": "ai-assisted",
375
+ "reviewStatus": "approved",
376
+ "pluralCategories": [
377
+ "one",
378
+ "other"
379
+ ]
380
+ },
353
381
  {
354
382
  "locale": "en-XA",
355
383
  "kind": "testing-only",
@@ -403,6 +431,39 @@
403
431
  "other"
404
432
  ]
405
433
  },
434
+ {
435
+ "locale": "es-419",
436
+ "kind": "translated",
437
+ "direction": "ltr",
438
+ "script": "Latn",
439
+ "parent": "es",
440
+ "aggregateImport": "@aceshooting/lyra-translations/es-419.js",
441
+ "familyImports": {
442
+ "agent-tools": "@aceshooting/lyra-translations/es-419/agent-tools.js",
443
+ "charts": "@aceshooting/lyra-translations/es-419/charts.js",
444
+ "conversation": "@aceshooting/lyra-translations/es-419/conversation.js",
445
+ "data": "@aceshooting/lyra-translations/es-419/data.js",
446
+ "forms": "@aceshooting/lyra-translations/es-419/forms.js",
447
+ "layout": "@aceshooting/lyra-translations/es-419/layout.js",
448
+ "media": "@aceshooting/lyra-translations/es-419/media.js",
449
+ "overlays": "@aceshooting/lyra-translations/es-419/overlays.js",
450
+ "retrieval": "@aceshooting/lyra-translations/es-419/retrieval.js",
451
+ "shared": "@aceshooting/lyra-translations/es-419/shared.js",
452
+ "utility": "@aceshooting/lyra-translations/es-419/utility.js",
453
+ "viewers": "@aceshooting/lyra-translations/es-419/viewers.js"
454
+ },
455
+ "sourceKeyCount": 1531,
456
+ "translatedOwnKeyCount": 61,
457
+ "inheritedKeyCount": 1470,
458
+ "missingKeyCount": 0,
459
+ "reviewTier": "ai-assisted",
460
+ "reviewStatus": "approved",
461
+ "pluralCategories": [
462
+ "many",
463
+ "one",
464
+ "other"
465
+ ]
466
+ },
406
467
  {
407
468
  "locale": "fa",
408
469
  "kind": "translated",
@@ -565,6 +626,39 @@
565
626
  "other"
566
627
  ]
567
628
  },
629
+ {
630
+ "locale": "fr-CA",
631
+ "kind": "translated",
632
+ "direction": "ltr",
633
+ "script": "Latn",
634
+ "parent": "fr",
635
+ "aggregateImport": "@aceshooting/lyra-translations/fr-CA.js",
636
+ "familyImports": {
637
+ "agent-tools": "@aceshooting/lyra-translations/fr-CA/agent-tools.js",
638
+ "charts": "@aceshooting/lyra-translations/fr-CA/charts.js",
639
+ "conversation": "@aceshooting/lyra-translations/fr-CA/conversation.js",
640
+ "data": "@aceshooting/lyra-translations/fr-CA/data.js",
641
+ "forms": "@aceshooting/lyra-translations/fr-CA/forms.js",
642
+ "layout": "@aceshooting/lyra-translations/fr-CA/layout.js",
643
+ "media": "@aceshooting/lyra-translations/fr-CA/media.js",
644
+ "overlays": "@aceshooting/lyra-translations/fr-CA/overlays.js",
645
+ "retrieval": "@aceshooting/lyra-translations/fr-CA/retrieval.js",
646
+ "shared": "@aceshooting/lyra-translations/fr-CA/shared.js",
647
+ "utility": "@aceshooting/lyra-translations/fr-CA/utility.js",
648
+ "viewers": "@aceshooting/lyra-translations/fr-CA/viewers.js"
649
+ },
650
+ "sourceKeyCount": 1531,
651
+ "translatedOwnKeyCount": 11,
652
+ "inheritedKeyCount": 1520,
653
+ "missingKeyCount": 0,
654
+ "reviewTier": "ai-assisted",
655
+ "reviewStatus": "approved",
656
+ "pluralCategories": [
657
+ "many",
658
+ "one",
659
+ "other"
660
+ ]
661
+ },
568
662
  {
569
663
  "locale": "gu",
570
664
  "kind": "translated",
@@ -2136,6 +2230,37 @@
2136
2230
  "other"
2137
2231
  ]
2138
2232
  },
2233
+ {
2234
+ "locale": "zh-HK",
2235
+ "kind": "translated",
2236
+ "direction": "ltr",
2237
+ "script": "Hant",
2238
+ "parent": "zh-TW",
2239
+ "aggregateImport": "@aceshooting/lyra-translations/zh-HK.js",
2240
+ "familyImports": {
2241
+ "agent-tools": "@aceshooting/lyra-translations/zh-HK/agent-tools.js",
2242
+ "charts": "@aceshooting/lyra-translations/zh-HK/charts.js",
2243
+ "conversation": "@aceshooting/lyra-translations/zh-HK/conversation.js",
2244
+ "data": "@aceshooting/lyra-translations/zh-HK/data.js",
2245
+ "forms": "@aceshooting/lyra-translations/zh-HK/forms.js",
2246
+ "layout": "@aceshooting/lyra-translations/zh-HK/layout.js",
2247
+ "media": "@aceshooting/lyra-translations/zh-HK/media.js",
2248
+ "overlays": "@aceshooting/lyra-translations/zh-HK/overlays.js",
2249
+ "retrieval": "@aceshooting/lyra-translations/zh-HK/retrieval.js",
2250
+ "shared": "@aceshooting/lyra-translations/zh-HK/shared.js",
2251
+ "utility": "@aceshooting/lyra-translations/zh-HK/utility.js",
2252
+ "viewers": "@aceshooting/lyra-translations/zh-HK/viewers.js"
2253
+ },
2254
+ "sourceKeyCount": 1531,
2255
+ "translatedOwnKeyCount": 21,
2256
+ "inheritedKeyCount": 1510,
2257
+ "missingKeyCount": 0,
2258
+ "reviewTier": "ai-assisted",
2259
+ "reviewStatus": "approved",
2260
+ "pluralCategories": [
2261
+ "other"
2262
+ ]
2263
+ },
2139
2264
  {
2140
2265
  "locale": "zh-TW",
2141
2266
  "kind": "translated",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aceshooting/lyra-ui",
3
- "version": "29.1.0",
3
+ "version": "29.2.0",
4
4
  "description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
5
5
  "keywords": [
6
6
  "web-components",
@@ -2604,9 +2604,9 @@
2604
2604
  },
2605
2605
  "peerDependencies": {
2606
2606
  "@aceshooting/lyra-flags": "^2.3.0",
2607
- "@aceshooting/lyra-map": "^1.1.0",
2608
- "@aceshooting/lyra-translations": "^29.1.0",
2609
- "@aiden0z/pptx-renderer": "^1.3.0",
2607
+ "@aceshooting/lyra-map": "^1.2.0",
2608
+ "@aceshooting/lyra-translations": "^29.2.0",
2609
+ "@aiden0z/pptx-renderer": "^1.4.0",
2610
2610
  "@sgratzl/chartjs-chart-boxplot": "^4.0.0",
2611
2611
  "chart.js": "^4.0.1",
2612
2612
  "chartjs-plugin-annotation": "^3.0.0",
@@ -2732,8 +2732,8 @@
2732
2732
  },
2733
2733
  "devDependencies": {
2734
2734
  "@aceshooting/lyra-flags": "^2.3.0",
2735
- "@aceshooting/lyra-map": "1.1.0",
2736
- "@aiden0z/pptx-renderer": "^1.3.0",
2735
+ "@aceshooting/lyra-map": "1.2.0",
2736
+ "@aiden0z/pptx-renderer": "^1.4.0",
2737
2737
  "@codecov/bundle-analyzer": "^2.0.1",
2738
2738
  "@custom-elements-manifest/analyzer": "^0.11.0",
2739
2739
  "@lit-labs/ssr": "^4.1.0",
@@ -2776,7 +2776,7 @@
2776
2776
  "katex": "^0.19.0",
2777
2777
  "libphonenumber-js": "^1.13.15",
2778
2778
  "mammoth": "^1.13.0",
2779
- "maplibre-gl": "^6.14.0",
2779
+ "maplibre-gl": "^6.15.0",
2780
2780
  "marked": "^18.1.1",
2781
2781
  "oxc-parser": "^0.154.0",
2782
2782
  "papaparse": "^5.7.0",
@@ -2784,7 +2784,7 @@
2784
2784
  "pixelmatch": "^8.0.0",
2785
2785
  "playwright": "^1.64.1",
2786
2786
  "pngjs": "^7.0.0",
2787
- "postal-mime": "^4.0.7",
2787
+ "postal-mime": "^4.0.11",
2788
2788
  "qrcode": "^1.5.4",
2789
2789
  "react": "^19.3.1",
2790
2790
  "shiki": "^4.5.0",