@aceshooting/lyra-ui 18.4.0 → 19.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/cli/migration-contract.json +1 -1
  4. package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +6 -2
  5. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  6. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
  7. package/dist/components/charts/chart/chart.class.d.ts +12 -3
  8. package/dist/components/charts/chart/chart.class.js +2 -2
  9. package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +2 -2
  10. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +3 -3
  11. package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
  12. package/dist/components/data/table/table.class.d.ts +2 -1
  13. package/dist/components/data/table/table.class.js +1 -1
  14. package/dist/components/forms/combobox/combobox.class.d.ts +2 -2
  15. package/dist/components/forms/combobox/combobox.class.js +3 -2
  16. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  17. package/dist/components/forms/date-picker/calendar-core.js +1 -1
  18. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  19. package/dist/components/forms/select/select.class.d.ts +2 -2
  20. package/dist/components/forms/select/select.class.js +4 -2
  21. package/dist/components/forms/select/select.styles.js +1 -1
  22. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  23. package/dist/components/media/file-input/file-input.class.d.ts +6 -5
  24. package/dist/components/media/file-input/file-input.class.js +1 -1
  25. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  26. package/dist/components/media/lightbox/lightbox.class.d.ts +1 -1
  27. package/dist/components/media/pan-zoom/pan-zoom.class.d.ts +1 -1
  28. package/dist/components/media/pan-zoom/pan-zoom.d.ts +1 -1
  29. package/dist/components/overlays/dialog/dialog.class.d.ts +12 -6
  30. package/dist/components/overlays/dialog/dialog.class.js +3 -6
  31. package/dist/components/retrieval/retrieval-search/retrieval-search.class.d.ts +3 -4
  32. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +2 -2
  33. package/dist/components/utility/copy-button/copy-button.class.d.ts +9 -6
  34. package/dist/components/utility/copy-button/copy-button.class.js +1 -1
  35. package/dist/components/utility/icon/icon.class.d.ts +3 -2
  36. package/dist/components/utility/icon/icon.class.js +1 -1
  37. package/dist/internal/accessibility-visibility.js +1 -1
  38. package/dist/internal/overlay-stack.js +1 -1
  39. package/dist/internal/package-metadata.d.ts +1 -1
  40. package/dist/internal/package-metadata.js +1 -1
  41. package/dist/internal/safe-svg.d.ts +15 -11
  42. package/dist/internal/safe-svg.js +1 -1
  43. package/llms/components/lr-agent-workspace.md +2 -2
  44. package/llms/components/lr-chart.md +13 -6
  45. package/llms/components/lr-copy-button.md +6 -6
  46. package/llms/components/lr-dialog.md +5 -3
  47. package/llms/components/lr-file-input.md +3 -2
  48. package/llms/components/lr-mcp-app.md +5 -0
  49. package/llms/components/lr-retrieval-search.md +2 -2
  50. package/llms-full.txt +37 -21
  51. package/package.json +2 -2
  52. package/vscode-html-data.json +1 -1
  53. package/web-types.json +1 -1
@@ -1,4 +1,4 @@
1
- import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAnchor,LyraAnchorKind,HighlightActivateDetail,AnchorResultDetail}from'../../viewers/document-viewer/anchors.js';export type LyraImageFit='contain'|'width'|'actual';export type LyraImageRotation=0|90|180|270;
1
+ import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAnchor,LyraAnchorKind,HighlightActivateDetail,AnchorResultDetail}from'../../viewers/document-viewer/anchors.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export type{LyraImageFit}from'../../../internal/image-fit.js';export type LyraImageRotation=0|90|180|270;
2
2
  /** Finite percentage coordinates. Negative widths/heights are rejected when rendered. */
3
3
  export interface LyraImageRegionRect{x:number;y:number;width:number;height:number;}
4
4
  /** Maximum region buttons projected at once. An active region beyond the leading window replaces
@@ -139,4 +139,4 @@ zoomIn:()=>void;
139
139
  /** Decreases the embedded pan/zoom scale by one configured step. */
140
140
  zoomOut:()=>void;
141
141
  /** Restores the embedded pan/zoom scale and translation. */
142
- resetZoom:()=>void;rotate():void;protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private onImgLoad;private onImgError;connectedCallback():void;adoptedCallback():void;private disconnectGeometryObserver;private updateMediaLayoutSize;private scheduleMediaLayoutSize;private syncGeometryObserver;private syncErrorAnnouncementSink;private releaseErrorAnnouncementSink;private announceLoadError;private onFrameZoomChange;private onHighlightActivate;private toggleAnnotatable;private onFitChange;private announceDraftPosition;private onWrapperKeyDown;private commitDraft;private pointerDraftId;private pointerOrigin;private cancelPointerDraft;private onWrapperPointerDown;private onWrapperPointerMove;private onWrapperPointerUp;private canonicalRegionHighlights;private boundedRegionHighlights;private onHighlightFocus;private onHighlightKeyDown;private renderHighlights;private renderDraft;private renderRevealTarget;private renderBody;render():TemplateResult;disconnectedCallback():void;}declare global{interface HTMLElementTagNameMap{'lr-image-viewer':LyraImageViewer;}}export{};
142
+ resetZoom:()=>void;rotate():void;protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private onImgLoad;private onImgError;connectedCallback():void;adoptedCallback():void;private disconnectGeometryObserver;private updateMediaLayoutSize;private scheduleMediaLayoutSize;private syncGeometryObserver;private syncErrorAnnouncementSink;private releaseErrorAnnouncementSink;private announceLoadError;private onFrameZoomChange;private onHighlightActivate;private toggleAnnotatable;private onFitChange;private announceDraftPosition;private onWrapperKeyDown;private commitDraft;private pointerDraftId;private pointerOrigin;private cancelPointerDraft;private onWrapperPointerDown;private onWrapperPointerMove;private onWrapperPointerUp;private canonicalRegionHighlights;private boundedRegionHighlights;private onHighlightFocus;private onHighlightKeyDown;private renderHighlights;private renderDraft;private renderRevealTarget;private renderBody;render():TemplateResult;disconnectedCallback():void;}declare global{interface HTMLElementTagNameMap{'lr-image-viewer':LyraImageViewer;}}
@@ -1,4 +1,4 @@
1
- import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';import'../pan-zoom/pan-zoom.class.js';
1
+ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';import'../pan-zoom/pan-zoom.class.js';export type{LyraImageFit}from'../../../internal/image-fit.js';
2
2
  /** One image in the set `<lr-lightbox>` browses. `alt`/`caption` are caller-supplied data
3
3
  * (like a filename), not routed through `localize()` -- only the component's own chrome
4
4
  * strings are. */
@@ -1,4 +1,4 @@
1
- import{type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export interface LyraPanZoomEventMap{'lr-zoom-change':CustomEvent<{zoom:number;}>;blur:FocusEvent;focus:FocusEvent;}
1
+ import{type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export type{LyraImageFit}from'../../../internal/image-fit.js';export interface LyraPanZoomEventMap{'lr-zoom-change':CustomEvent<{zoom:number;}>;blur:FocusEvent;focus:FocusEvent;}
2
2
  /**
3
3
  * `<lr-pan-zoom>` — a scrollable frame for inspecting slotted or image content at a bounded zoom
4
4
  * level. This is the intentionally renamed home of the original Lyra `lr-zoomable-frame`
@@ -1 +1 @@
1
- export{LyraPanZoom}from'./pan-zoom.class.js';export type{LyraPanZoomEventMap}from'./pan-zoom.class.js';
1
+ export{LyraPanZoom}from'./pan-zoom.class.js';export type{LyraPanZoomEventMap}from'./pan-zoom.class.js';export type{LyraImageFit}from'./pan-zoom.class.js';
@@ -60,11 +60,12 @@ export interface LyraDialogModalController{activateExternal():void;deactivateExt
60
60
  * no heading text, if neither `heading` nor the `label` slot is set) that closes the dialog via
61
61
  * the same `close()` path as Escape/backdrop-dismiss, with reason `'close-button'`.
62
62
  *
63
- * The `body` part is the element that scrolls, so it carries `tabindex="-1"`: a dialog holding
64
- * only prose, a table, or a rendered document would otherwise have no keyboard stop at all and
65
- * its content would be readable by mouse alone. It joins the Tab order only while it actually
66
- * overflows, sorts behind any control inside it for initial focus, and shows the standard focus
67
- * ring on `::part(body)` when it takes focus.
63
+ * The `body` part is the element that scrolls, so it carries `tabindex="0"` only while it
64
+ * actually overflows; a short body keeps `tabindex="-1"`. A dialog holding only prose, a table,
65
+ * or a rendered document would otherwise have no keyboard stop at all and its content would be
66
+ * readable by mouse alone. It joins the Tab order only while it actually overflows, sorts behind
67
+ * any control inside it for initial focus, and shows the standard focus ring on `::part(body)` when
68
+ * it takes focus.
68
69
  *
69
70
  * Stacking: opening one `<lr-dialog>` while another is already open (e.g. a
70
71
  * `confirm()` launched from within an already-open dialog) is supported --
@@ -261,7 +262,7 @@ lightDismiss:boolean;private hasFooterSlot;private hasLabelSlot;private hasHeade
261
262
  /** Set by `deactivateOverlay()` when a close defers releasing the scroll lock. Flushed once the
262
263
  * exit animation actually finishes (`settleTransition()`'s `'lr-after-hide'` branch), or right
263
264
  * away on disconnect/reopen, since nothing is left to visually protect in either case. */
264
- private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverGeneration;
265
+ private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverGeneration;private bodyOverflowObserver?;private bodyOverflowObservedBody?;
265
266
  /** Invalidates any in-flight `lr-after-show`/`lr-after-hide` wait, so a lifecycle interrupted by
266
267
  * the opposite transition (or by a disconnect) never announces a completion that never
267
268
  * happened. */
@@ -278,6 +279,11 @@ protected get modalSurface():boolean;protected willUpdate(changed:PropertyValues
278
279
  * first. Safe to call unconditionally -- a no-op once already flushed or when nothing is
279
280
  * pending. */
280
281
  private flushPendingScrollLockRelease;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private armHeadingObserver;private resetHeadingObserver;
282
+ /** Keep the scroll surface in native sequential focus order only while it has scrollable content.
283
+ * The overlay trap also measures live overflow so it can account for browsers' scroll-region
284
+ * differences; this reflected DOM state additionally satisfies the platform's accessible
285
+ * scroll-region contract and keeps short bodies out of the Tab order. */
286
+ private syncBodyTabIndex;private armBodyOverflowObserver;private resetBodyOverflowObserver;private defaultSlotElements;
281
287
  /** Whether an external-removal hide request can preserve open state for a later reconnect. */
282
288
  protected get disconnectHideCancelable():boolean;private onDefaultSlotChange;private onFooterSlotChange;private detectLightDomChrome;
283
289
  /**
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements}from"../../../internal/overlay-manager.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{constructor(){super(...arguments),this._open=!1,this.label="",this.headingLevel="3",this.closable=!0,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.accessibleLabel="",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),changed.has("open")&&(this.flushPendingScrollLockRelease(),this.open?this.isConnected&&this.modalSurface&&this.activateOverlay():this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0}))}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),changed.has("open")&&this.open&&this.isConnected&&this.modalSurface&&(this.enterTopLayer(),this.focusInitial())}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.hasUpdated&&this.open&&this.modalSurface&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),this.enterTopLayer(),queueMicrotask(()=>this.focusInitial()))}disconnectedCallback(){this.resetHeadingObserver(),super.disconnectedCallback(),this.overlay?.suspend(),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close","unmount"),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver()}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.detectLightDomChrome()});this.headingObserver=observer,this.headingObserverDocument=ownerDocument,observer.observe(this,{childList:!0,characterData:!0,subtree:!0,attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"]})}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){return this.coalesceOpenRequest(!1)||!this._open?Promise.resolve():(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):this.emit("lr-close",reason,{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):(this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")))}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){if(!(!this.isConnected||typeof this.showPopover!="function")){this.getAttribute("popover")!=="manual"&&this.setAttribute("popover","manual");try{this.isTopLayer()||this.showPopover()}catch{}}}leaveTopLayer(){if(typeof this.hidePopover=="function")try{this.isTopLayer()&&this.hidePopover()}catch{}}isTopLayer(){try{return this.matches(":popover-open")}catch{return!1}}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.accessibleLabel||this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||this.closable),headingLevel=resolveHeadingLevel(this.headingLevel);return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements}from"../../../internal/overlay-manager.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{constructor(){super(...arguments),this._open=!1,this.label="",this.headingLevel="3",this.closable=!0,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.accessibleLabel="",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetBodyOverflowObserver(),this.armBodyOverflowObserver()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),changed.has("open")&&(this.flushPendingScrollLockRelease(),this.open?this.isConnected&&this.modalSurface&&this.activateOverlay():this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0}))}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),changed.has("open")&&this.open&&this.isConnected&&this.modalSurface&&(this.enterTopLayer(),this.focusInitial())}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),this.hasUpdated&&this.open&&this.modalSurface&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),this.enterTopLayer(),queueMicrotask(()=>this.focusInitial()))}disconnectedCallback(){this.resetHeadingObserver(),this.resetBodyOverflowObserver(),super.disconnectedCallback(),this.overlay?.suspend(),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close","unmount"),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver(),this.resetBodyOverflowObserver(),this.isConnected&&(this.armHeadingObserver(),this.armBodyOverflowObserver(),this.syncBodyTabIndex())}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.detectLightDomChrome(),this.syncBodyTabIndex())});this.headingObserver=observer,this.headingObserverDocument=ownerDocument,observer.observe(this,{childList:!0,characterData:!0,subtree:!0,attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"]})}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0}syncBodyTabIndex(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body)return;const next=this.open&&(body.scrollHeight>body.clientHeight&&body.scrollHeight>0||body.scrollWidth>body.clientWidth&&body.scrollWidth>0)?0:-1;body.tabIndex!==next&&(body.tabIndex=next)}armBodyOverflowObserver(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body||!this.isConnected||this.bodyOverflowObservedBody===body)return;this.resetBodyOverflowObserver();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{this.bodyOverflowObserver!==observer||this.bodyOverflowObservedBody!==body||!this.isConnected||this.syncBodyTabIndex()});this.bodyOverflowObserver=observer,this.bodyOverflowObservedBody=body,observer.observe(body);for(const element of this.defaultSlotElements())observer.observe(element)}resetBodyOverflowObserver(){this.bodyOverflowObserver?.disconnect(),this.bodyOverflowObserver=void 0,this.bodyOverflowObservedBody=void 0}defaultSlotElements(){return this.renderRoot?.querySelector('[part="body"] slot:not([name])')?.assignedElements({flatten:!0})??[]}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){return this.coalesceOpenRequest(!1)||!this._open?Promise.resolve():(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):this.emit("lr-close",reason,{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):(this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")))}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){if(!(!this.isConnected||typeof this.showPopover!="function")){this.getAttribute("popover")!=="manual"&&this.setAttribute("popover","manual");try{this.isTopLayer()||this.showPopover()}catch{}}}leaveTopLayer(){if(typeof this.hidePopover=="function")try{this.isTopLayer()&&this.hidePopover()}catch{}}isTopLayer(){try{return this.matches(":popover-open")}catch{return!1}}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.accessibleLabel||this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||this.closable),headingLevel=resolveHeadingLevel(this.headingLevel);return html`
2
2
  <div part="base">
3
3
  <div part="backdrop overlay" @click=${this.onBackdropClick}></div>
4
4
  <div
@@ -31,11 +31,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
31
31
  `:nothing}
32
32
  </div>
33
33
  `:nothing}
34
- <!-- tabindex keeps the scrolling body reachable: it is the element that overflows, so a
35
- dialog holding only prose, a table, or a rendered document would otherwise be
36
- mouse-scrollable with no keyboard way in at all. -1 keeps it out of the page's
37
- sequential order; the overlay manager promotes it to a stop only while it actually
38
- scrolls (see isOverflowingAndTabbable in internal/overlay-manager.ts). -->
34
+ <!-- The owner sets tabindex to 0 only while this scrolling surface actually overflows;
35
+ short bodies stay out of the sequential order. -->
39
36
  <div part="body" tabindex="-1">
40
37
  <slot @slotchange=${this.onDefaultSlotChange}></slot>
41
38
  </div>
@@ -120,10 +120,9 @@ empty:boolean;
120
120
  * it is set -- otherwise the initial state is announced twice, through the native role and
121
121
  * again through the shared sink. */
122
122
  announce:boolean;
123
- /** Placeholder for the query field. Empty string (the default) falls back to the localized
124
- * generic "Search" placeholder, which also becomes that field's accessible name (mirroring
125
- * `<lr-input>`'s own placeholder-as-label fallback). */
126
- placeholder:string;
123
+ /** Placeholder for the query field. When omitted, the localized generic "Search" placeholder
124
+ * is used; an explicit empty string intentionally suppresses that fallback. */
125
+ placeholder?:string;
127
126
  /** Accessible name for the inner search landmark when the host has no `aria-label`. Omitting it
128
127
  * falls back to the localized default; an explicit empty string clears it. */
129
128
  label?:string;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../forms/input/input.class.js";import"../../layout/segmented/segmented.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import"../../overlays/spinner/spinner.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./retrieval-search.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{formatBoundedRetrievalValue}from"../retrieval-value-format.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{announceAfterFirstPaint}from"../retrieval-announcements.js";import{literalSetConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{canonicalIdentityList,isRecord}from"../retrieval-identity.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_retrievalFilterChipLabel,LYRA_DEFAULT_retrievalFiltersLabel,LYRA_DEFAULT_retrievalModeHybrid,LYRA_DEFAULT_retrievalModeKeyword,LYRA_DEFAULT_retrievalModeLabel,LYRA_DEFAULT_retrievalModeVector,LYRA_DEFAULT_retrievalSearchEmptyDescription,LYRA_DEFAULT_retrievalSearchLabel,LYRA_DEFAULT_search,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const RETRIEVAL_MODE=literalSetConverter(["vector","keyword","hybrid"],"hybrid");class LyraRetrievalSearch extends LyraElement{constructor(){super(...arguments),this.query="",this._mode="hybrid",this.filters={},this.scope=[],this.loading=!1,this.errorText="",this.empty=!1,this.announce=!1,this.placeholder="",this.accessibleLabel=null,this.isMounting=!0,this.initialStateAnnounced=!1,this.connectionGeneration=0,this.wasEmptyPresented=!1,this.chipFocusGeneration=0,this.onQueryInput=e=>{e.stopPropagation(),this.query=e.detail.value},this.onQueryKeyDown=e=>{e.key==="Enter"&&(e.isComposing||e.keyCode===229||(e.preventDefault(),this.submit()))},this.onModeChange=e=>{e.stopPropagation(),this.mode=e.detail.value},this.containModeEvent=e=>{e.stopPropagation()},this.onSubmitClick=()=>{if(this.loading){this.cancel();return}this.submit()}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,retrievalFilterChipLabel:LYRA_DEFAULT_retrievalFilterChipLabel,retrievalFiltersLabel:LYRA_DEFAULT_retrievalFiltersLabel,retrievalModeHybrid:LYRA_DEFAULT_retrievalModeHybrid,retrievalModeKeyword:LYRA_DEFAULT_retrievalModeKeyword,retrievalModeLabel:LYRA_DEFAULT_retrievalModeLabel,retrievalModeVector:LYRA_DEFAULT_retrievalModeVector,retrievalSearchEmptyDescription:LYRA_DEFAULT_retrievalSearchEmptyDescription,retrievalSearchLabel:LYRA_DEFAULT_retrievalSearchLabel,search:LYRA_DEFAULT_search,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["filters","scope"])}static{this.styles=[LyraElement.styles,contextualSizes,styles]}static{this.immutableEventDetails=Object.freeze(["lr-search","lr-filters-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get mode(){return this._mode}set mode(next){const normalized=RETRIEVAL_MODE.normalize(next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=this.empty&&!this.loading&&this.errorText==="";!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("noMatches"))),this.wasEmptyPresented=emptyPresented}announcePresentedState(){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}this.empty&&!this.loading&&this.emptyAnnouncementSink?.announce(this.localize("noMatches"))}modeItems(){return[{value:"vector",label:this.localize("retrievalModeVector")},{value:"keyword",label:this.localize("retrievalModeKeyword")},{value:"hybrid",label:this.localize("retrievalModeHybrid")}]}formatFilterValue(value){const sentinel=this.localize("valueInvalid");return formatBoundedRetrievalValue(value,{locale:this.effectiveLocale,invalid:sentinel,truncated:sentinel})}get normalizedFilters(){return isRecord(this.filters)?this.filters:{}}get normalizedScope(){return canonicalIdentityList(this.scope)}buildQuery(){return{text:this.query,mode:this.mode,filters:{...this.normalizedFilters},scope:[...this.normalizedScope]}}submit(){this.loading&&this.emit("lr-cancel",{reason:"superseded"}),this.emit("lr-search",this.buildQuery())}cancel(){this.emit("lr-cancel",{})}emitFiltersChange(){this.emit("lr-filters-change",{filters:{...this.normalizedFilters},scope:[...this.normalizedScope]})}repairFocusAfterChipRemoval(index,shouldRepair){const generation=++this.chipFocusGeneration;shouldRepair&&this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.chipFocusGeneration)return;const chips=this.renderRoot.querySelectorAll('[part="filters"] lr-chip'),target=chips[Math.min(index,chips.length-1)];if(target){target.focus();return}this.renderRoot.querySelector('[part="query"]')?.focus()})}removeScope(value,shouldRepairFocus=!1){const scope=this.normalizedScope,index=scope.indexOf(value);this.scope=scope.filter(s=>s!==value),this.emitFiltersChange(),this.repairFocusAfterChipRemoval(Math.max(0,index),shouldRepairFocus)}removeFilter(key,shouldRepairFocus=!1){const filters=this.normalizedFilters,index=this.normalizedScope.length+Object.keys(filters).indexOf(key),next={...filters};delete next[key],this.filters=next,this.emitFiltersChange(),this.repairFocusAfterChipRemoval(Math.max(0,index),shouldRepairFocus)}render(){const label=retrievalSemanticLabel(this,this.accessibleLabel??(this.label==null?this.localize("retrievalSearchLabel"):this.label)),searchRole=retrievalSemanticRole(this,"search"),filters=this.normalizedFilters,scope=this.normalizedScope,hasFilters=Object.keys(filters).length>0||scope.length>0;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../forms/input/input.class.js";import"../../layout/segmented/segmented.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import"../../overlays/spinner/spinner.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./retrieval-search.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{formatBoundedRetrievalValue}from"../retrieval-value-format.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{announceAfterFirstPaint}from"../retrieval-announcements.js";import{literalSetConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{canonicalIdentityList,isRecord}from"../retrieval-identity.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_retrievalFilterChipLabel,LYRA_DEFAULT_retrievalFiltersLabel,LYRA_DEFAULT_retrievalModeHybrid,LYRA_DEFAULT_retrievalModeKeyword,LYRA_DEFAULT_retrievalModeLabel,LYRA_DEFAULT_retrievalModeVector,LYRA_DEFAULT_retrievalSearchEmptyDescription,LYRA_DEFAULT_retrievalSearchLabel,LYRA_DEFAULT_search,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const RETRIEVAL_MODE=literalSetConverter(["vector","keyword","hybrid"],"hybrid");class LyraRetrievalSearch extends LyraElement{constructor(){super(...arguments),this.query="",this._mode="hybrid",this.filters={},this.scope=[],this.loading=!1,this.errorText="",this.empty=!1,this.announce=!1,this.accessibleLabel=null,this.isMounting=!0,this.initialStateAnnounced=!1,this.connectionGeneration=0,this.wasEmptyPresented=!1,this.chipFocusGeneration=0,this.onQueryInput=e=>{e.stopPropagation(),this.query=e.detail.value},this.onQueryKeyDown=e=>{e.key==="Enter"&&(e.isComposing||e.keyCode===229||(e.preventDefault(),this.submit()))},this.onModeChange=e=>{e.stopPropagation(),this.mode=e.detail.value},this.containModeEvent=e=>{e.stopPropagation()},this.onSubmitClick=()=>{if(this.loading){this.cancel();return}this.submit()}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,retrievalFilterChipLabel:LYRA_DEFAULT_retrievalFilterChipLabel,retrievalFiltersLabel:LYRA_DEFAULT_retrievalFiltersLabel,retrievalModeHybrid:LYRA_DEFAULT_retrievalModeHybrid,retrievalModeKeyword:LYRA_DEFAULT_retrievalModeKeyword,retrievalModeLabel:LYRA_DEFAULT_retrievalModeLabel,retrievalModeVector:LYRA_DEFAULT_retrievalModeVector,retrievalSearchEmptyDescription:LYRA_DEFAULT_retrievalSearchEmptyDescription,retrievalSearchLabel:LYRA_DEFAULT_retrievalSearchLabel,search:LYRA_DEFAULT_search,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["filters","scope"])}static{this.styles=[LyraElement.styles,contextualSizes,styles]}static{this.immutableEventDetails=Object.freeze(["lr-search","lr-filters-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get mode(){return this._mode}set mode(next){const normalized=RETRIEVAL_MODE.normalize(next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.emptyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});const generation=++this.connectionGeneration;announceAfterFirstPaint(this,()=>generation===this.connectionGeneration,()=>{!this.announce||this.initialStateAnnounced||(this.initialStateAnnounced=!0,this.announcePresentedState())})}disconnectedCallback(){this.isMounting=!0,this.connectionGeneration+=1,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.emptyAnnouncementSink?.release(),this.emptyAnnouncementSink=void 0,this.wasEmptyPresented=!1,super.disconnectedCallback()}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("errorText")&&this.errorText!==""&&this.isConnected&&(this.initialStateAnnounced=!0,this.errorAnnouncementSink?.announce(this.errorText));const emptyPresented=this.empty&&!this.loading&&this.errorText==="";!wasMounting&&!this.wasEmptyPresented&&emptyPresented&&this.isConnected&&(this.initialStateAnnounced=!0,this.emptyAnnouncementSink?.announce(this.localize("noMatches"))),this.wasEmptyPresented=emptyPresented}announcePresentedState(){if(this.errorText!==""){this.errorAnnouncementSink?.announce(this.errorText);return}this.empty&&!this.loading&&this.emptyAnnouncementSink?.announce(this.localize("noMatches"))}modeItems(){return[{value:"vector",label:this.localize("retrievalModeVector")},{value:"keyword",label:this.localize("retrievalModeKeyword")},{value:"hybrid",label:this.localize("retrievalModeHybrid")}]}formatFilterValue(value){const sentinel=this.localize("valueInvalid");return formatBoundedRetrievalValue(value,{locale:this.effectiveLocale,invalid:sentinel,truncated:sentinel})}get normalizedFilters(){return isRecord(this.filters)?this.filters:{}}get normalizedScope(){return canonicalIdentityList(this.scope)}buildQuery(){return{text:this.query,mode:this.mode,filters:{...this.normalizedFilters},scope:[...this.normalizedScope]}}submit(){this.loading&&this.emit("lr-cancel",{reason:"superseded"}),this.emit("lr-search",this.buildQuery())}cancel(){this.emit("lr-cancel",{})}emitFiltersChange(){this.emit("lr-filters-change",{filters:{...this.normalizedFilters},scope:[...this.normalizedScope]})}repairFocusAfterChipRemoval(index,shouldRepair){const generation=++this.chipFocusGeneration;shouldRepair&&this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.chipFocusGeneration)return;const chips=this.renderRoot.querySelectorAll('[part="filters"] lr-chip'),target=chips[Math.min(index,chips.length-1)];if(target){target.focus();return}this.renderRoot.querySelector('[part="query"]')?.focus()})}removeScope(value,shouldRepairFocus=!1){const scope=this.normalizedScope,index=scope.indexOf(value);this.scope=scope.filter(s=>s!==value),this.emitFiltersChange(),this.repairFocusAfterChipRemoval(Math.max(0,index),shouldRepairFocus)}removeFilter(key,shouldRepairFocus=!1){const filters=this.normalizedFilters,index=this.normalizedScope.length+Object.keys(filters).indexOf(key),next={...filters};delete next[key],this.filters=next,this.emitFiltersChange(),this.repairFocusAfterChipRemoval(Math.max(0,index),shouldRepairFocus)}render(){const label=retrievalSemanticLabel(this,this.accessibleLabel??(this.label==null?this.localize("retrievalSearchLabel"):this.label)),searchRole=retrievalSemanticRole(this,"search"),filters=this.normalizedFilters,scope=this.normalizedScope,hasFilters=Object.keys(filters).length>0||scope.length>0;return html`
2
2
  <div
3
3
  part="base"
4
4
  role=${searchRole??nothing}
@@ -10,7 +10,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
10
10
  type="search"
11
11
  clearable
12
12
  .size=${this.size??"m"}
13
- placeholder=${this.placeholder||this.localize("search")}
13
+ placeholder=${this.placeholder==null?this.localize("search"):this.placeholder}
14
14
  .value=${this.query}
15
15
  @lr-input=${this.onQueryInput}
16
16
  @keydown=${this.onQueryKeyDown}
@@ -85,12 +85,15 @@ value:string;
85
85
  /** Id-based source expression. Takes precedence over `value`; supports `id`, `id[attr]`, and
86
86
  * `id.property`. */
87
87
  from:string;
88
- /** Accessible name and resting tooltip text. Empty uses the localized Copy string. */
89
- copyLabel:string;
90
- /** Confirmation accessible name and tooltip text. Empty uses the localized Copied string. */
91
- successLabel:string;
92
- /** Failure accessible name and tooltip text. Empty uses the localized failure string. */
93
- errorLabel:string;
88
+ /** Accessible name and resting tooltip text. When omitted, uses localized Copy; an explicit
89
+ * empty string intentionally suppresses that fallback. */
90
+ copyLabel?:string;
91
+ /** Confirmation accessible name and tooltip text. When omitted, uses localized Copied; an
92
+ * explicit empty string intentionally suppresses that fallback. */
93
+ successLabel?:string;
94
+ /** Failure accessible name and tooltip text. When omitted, uses localized failure copy; an
95
+ * explicit empty string intentionally suppresses that fallback. */
96
+ errorLabel?:string;
94
97
  /** Tooltip behavior: normal hover/focus plus feedback, feedback only, or disabled. */
95
98
  tooltip:LyraCopyButtonTooltip;
96
99
  /** Side on which the tooltip appears. */
@@ -37,7 +37,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
37
37
  aria-hidden="true"
38
38
  focusable="false"
39
39
  ><circle cx="12" cy="12" r="9"></circle><path d="M12 7.25v5.5"></path><path d="M12 16.4v.01"></path></svg>
40
- `}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getAttribute=="function"}function isHtmlElementValue(value){if(!isElementValue(value))return!1;const candidate=value;return candidate.namespaceURI==="http://www.w3.org/1999/xhtml"&&typeof candidate.focus=="function"&&typeof candidate.blur=="function"&&typeof candidate.click=="function"}class CopySourceError extends Error{constructor(message){super(message),this.name="CopySourceError"}}class LyraCopyButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.styles=[LyraElement.styles,styles]}constructor(){super(),this.value="",this.from="",this.copyLabel="",this.successLabel="",this.errorLabel="",this.tooltip="full",this.tooltipPlacement="top",this.hoist=!1,this.accessibleLabel=null,this.disabled=!1,this.feedbackDuration=DEFAULT_FEEDBACK_DURATION,this.status="rest",this.hasCustomTrigger=!1,this.triggerCollected=!1,this.internals=attachInternalsSafely(this),this.toolbarAction=this.createToolbarAction(),this.copyGeneration=0,this.onClick=()=>{this.copy()},this.onDefaultSlotChange=event=>{this.onDefaultSlotChangeFromSlot(event.currentTarget)},this.onCustomTriggerClick=()=>{this.hasCustomTrigger&&this.copy()},this.stopInternalTooltipEvent=event=>{event.stopPropagation()},this.internals.role="group"}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("value")||changed.has("from"))&&this.resetFeedback()}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("hasCustomTrigger"))&&this.emit("lr-toolbar-actions-change")}firstUpdated(changed){super.firstUpdated(changed);const slot=this.defaultSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onDefaultSlotChangeFromSlot(s))})}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","group"),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),super.disconnectedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}cancelFeedbackTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetFeedback(){this.copyGeneration+=1,this.cancelFeedbackTimer(),this.setStatus("rest")}setStatus(status){this.status=status,setCustomState(this.internals,"success",status==="success"),setCustomState(this.internals,"error",status==="error")}customTrigger(){return this.defaultSlot?.assignedElements({flatten:!0}).find(isHtmlElementValue)}activeTrigger(){return this.hasCustomTrigger?this.customTrigger():this.buttonEl}composedTriggerAction(){if(this.hasCustomTrigger)return;const[action]=this.buttonEl?.getToolbarActions()??[];return action}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1,delegated;const releaseDelegated=()=>{const previous=delegated;delegated=void 0,previous?.releaseTabIndex?.()},releaseTabIndex=()=>{releaseDelegated();const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"copy",get disabled(){const trigger=host.activeTrigger();return!trigger||host.disabled||trigger.disabled===!0},focus(options){host.activeTrigger()?.focus(options)},setTabIndex(tabIndex){const composed=host.composedTriggerAction();if(composed){delegated!==composed&&(releaseTabIndex(),delegated=composed),composed.setTabIndex(tabIndex);return}releaseDelegated();const trigger=host.activeTrigger();if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const trigger=host.activeTrigger();return trigger!=null&&path.includes(trigger)}}}getToolbarActions(){return[this.toolbarAction]}focus(options){this.activeTrigger()?.focus(options)}blur(){this.activeTrigger()?.blur()}click(){this.activeTrigger()?.click()}sourceById(id){const root=this.getRootNode();if((root.nodeType===9||root.nodeType===11)&&typeof root.getElementById=="function"){const source=root.getElementById(id);if(isElementValue(source))return source}const documentSource=this.ownerDocument.getElementById(id);return isElementValue(documentSource)?documentSource:null}resolveCopyText(){if(!this.from){if(!this.value)throw new CopySourceError("The copy value is empty.");return this.value}const expression=this.from.trim(),attributeMatch=/^(.*?)\[([^\]]+)\]$/.exec(expression),propertyMatch=attributeMatch?null:/^(.*?)\.([^.]*)$/.exec(expression),id=(attributeMatch?.[1]??propertyMatch?.[1]??expression).trim(),source=id?this.sourceById(id):null;if(!source)throw new CopySourceError(`The copy source "${id}" was not found.`);let resolved;if(attributeMatch){const attribute=attributeMatch[2].trim();resolved=attribute?source.getAttribute(attribute):null}else if(propertyMatch){const propertyName=propertyMatch[2].trim();resolved=propertyName?source[propertyName]:void 0}else resolved=source.textContent;const text=resolved==null?"":String(resolved);if(!text)throw new CopySourceError(`The copy source "${expression}" resolved to an empty value.`);return text}showStatus(status){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner)return;this.setStatus(status),this.sink?.announce(this.statusLabel(status)),this.cancelFeedbackTimer();const duration=finiteDuration(this.feedbackDuration,DEFAULT_FEEDBACK_DURATION,0),generation=this.copyGeneration;let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.setStatus("rest"))},duration),this.copyTimer={owner,handle,generation}}reportFailure(outcome){this.showStatus("error"),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}async copy(){if(this.disabled)return;const generation=++this.copyGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;let text="";try{text=this.resolveCopyText()}catch(error){this.isCurrentCopy(generation)&&this.reportFailure(Object.freeze({ok:!1,text,reason:"failed",error}));return}if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.reportFailure(outcome);return}this.showStatus("success"),this.emit("lr-copy",outcome)}}isCurrentCopy(generation,owner){return this.isConnected&&generation===this.copyGeneration&&(owner===void 0||this.ownerDocument.defaultView===owner)}onDefaultSlotChangeFromSlot(slot){const trigger=slot.assignedElements({flatten:!0}).find(isHtmlElementValue);if(this.triggerCollected&&trigger===this.lastObservedTrigger)return;this.triggerCollected=!0,this.lastObservedTrigger=trigger;const hasCustomTrigger=trigger!==void 0;if(hasCustomTrigger!==this.hasCustomTrigger){this.hasCustomTrigger=hasCustomTrigger;return}this.emit("lr-toolbar-actions-change")}statusLabel(status){return status==="success"?this.successLabel||this.localize("copied"):status==="error"?this.errorLabel||this.localize("copyFailed"):this.copyLabel||this.localize("copy")}renderIcon(){return this.status==="error"?html`<span part="error-icon" aria-hidden="true"><slot name="error-icon">${errorIcon()}</slot></span>`:this.status==="success"?html`<span part="success-icon" aria-hidden="true"><slot name="success-icon">${checkIcon()}</slot></span>`:html`<span part="copy-icon" aria-hidden="true"><slot name="copy-icon">${copyIcon()}</slot></span>`}render(){const statusLabel=this.statusLabel(this.status),feedback=this.status==="rest"?"":statusLabel,part=this.status==="success"?"base button base-success":this.status==="error"?"base button base-error":"base button",tooltipDisabled=this.tooltip==="none",tooltipOpen=!tooltipDisabled&&this.status!=="rest",buttonLabel=this.accessibleLabel?.trim()?this.accessibleLabel:statusLabel;return html`
40
+ `}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getAttribute=="function"}function isHtmlElementValue(value){if(!isElementValue(value))return!1;const candidate=value;return candidate.namespaceURI==="http://www.w3.org/1999/xhtml"&&typeof candidate.focus=="function"&&typeof candidate.blur=="function"&&typeof candidate.click=="function"}class CopySourceError extends Error{constructor(message){super(message),this.name="CopySourceError"}}class LyraCopyButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.styles=[LyraElement.styles,styles]}constructor(){super(),this.value="",this.from="",this.tooltip="full",this.tooltipPlacement="top",this.hoist=!1,this.accessibleLabel=null,this.disabled=!1,this.feedbackDuration=DEFAULT_FEEDBACK_DURATION,this.status="rest",this.hasCustomTrigger=!1,this.triggerCollected=!1,this.internals=attachInternalsSafely(this),this.toolbarAction=this.createToolbarAction(),this.copyGeneration=0,this.onClick=()=>{this.copy()},this.onDefaultSlotChange=event=>{this.onDefaultSlotChangeFromSlot(event.currentTarget)},this.onCustomTriggerClick=()=>{this.hasCustomTrigger&&this.copy()},this.stopInternalTooltipEvent=event=>{event.stopPropagation()},this.internals.role="group"}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("value")||changed.has("from"))&&this.resetFeedback()}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("hasCustomTrigger"))&&this.emit("lr-toolbar-actions-change")}firstUpdated(changed){super.firstUpdated(changed);const slot=this.defaultSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onDefaultSlotChangeFromSlot(s))})}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","group"),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),super.disconnectedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.resetFeedback(),this.sink?.release(),this.sink=void 0}cancelFeedbackTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetFeedback(){this.copyGeneration+=1,this.cancelFeedbackTimer(),this.setStatus("rest")}setStatus(status){this.status=status,setCustomState(this.internals,"success",status==="success"),setCustomState(this.internals,"error",status==="error")}customTrigger(){return this.defaultSlot?.assignedElements({flatten:!0}).find(isHtmlElementValue)}activeTrigger(){return this.hasCustomTrigger?this.customTrigger():this.buttonEl}composedTriggerAction(){if(this.hasCustomTrigger)return;const[action]=this.buttonEl?.getToolbarActions()??[];return action}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1,delegated;const releaseDelegated=()=>{const previous=delegated;delegated=void 0,previous?.releaseTabIndex?.()},releaseTabIndex=()=>{releaseDelegated();const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"copy",get disabled(){const trigger=host.activeTrigger();return!trigger||host.disabled||trigger.disabled===!0},focus(options){host.activeTrigger()?.focus(options)},setTabIndex(tabIndex){const composed=host.composedTriggerAction();if(composed){delegated!==composed&&(releaseTabIndex(),delegated=composed),composed.setTabIndex(tabIndex);return}releaseDelegated();const trigger=host.activeTrigger();if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const trigger=host.activeTrigger();return trigger!=null&&path.includes(trigger)}}}getToolbarActions(){return[this.toolbarAction]}focus(options){this.activeTrigger()?.focus(options)}blur(){this.activeTrigger()?.blur()}click(){this.activeTrigger()?.click()}sourceById(id){const root=this.getRootNode();if((root.nodeType===9||root.nodeType===11)&&typeof root.getElementById=="function"){const source=root.getElementById(id);if(isElementValue(source))return source}const documentSource=this.ownerDocument.getElementById(id);return isElementValue(documentSource)?documentSource:null}resolveCopyText(){if(!this.from){if(!this.value)throw new CopySourceError("The copy value is empty.");return this.value}const expression=this.from.trim(),attributeMatch=/^(.*?)\[([^\]]+)\]$/.exec(expression),propertyMatch=attributeMatch?null:/^(.*?)\.([^.]*)$/.exec(expression),id=(attributeMatch?.[1]??propertyMatch?.[1]??expression).trim(),source=id?this.sourceById(id):null;if(!source)throw new CopySourceError(`The copy source "${id}" was not found.`);let resolved;if(attributeMatch){const attribute=attributeMatch[2].trim();resolved=attribute?source.getAttribute(attribute):null}else if(propertyMatch){const propertyName=propertyMatch[2].trim();resolved=propertyName?source[propertyName]:void 0}else resolved=source.textContent;const text=resolved==null?"":String(resolved);if(!text)throw new CopySourceError(`The copy source "${expression}" resolved to an empty value.`);return text}showStatus(status){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner)return;this.setStatus(status),this.sink?.announce(this.statusLabel(status)),this.cancelFeedbackTimer();const duration=finiteDuration(this.feedbackDuration,DEFAULT_FEEDBACK_DURATION,0),generation=this.copyGeneration;let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.setStatus("rest"))},duration),this.copyTimer={owner,handle,generation}}reportFailure(outcome){this.showStatus("error"),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}async copy(){if(this.disabled)return;const generation=++this.copyGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;let text="";try{text=this.resolveCopyText()}catch(error){this.isCurrentCopy(generation)&&this.reportFailure(Object.freeze({ok:!1,text,reason:"failed",error}));return}if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.reportFailure(outcome);return}this.showStatus("success"),this.emit("lr-copy",outcome)}}isCurrentCopy(generation,owner){return this.isConnected&&generation===this.copyGeneration&&(owner===void 0||this.ownerDocument.defaultView===owner)}onDefaultSlotChangeFromSlot(slot){const trigger=slot.assignedElements({flatten:!0}).find(isHtmlElementValue);if(this.triggerCollected&&trigger===this.lastObservedTrigger)return;this.triggerCollected=!0,this.lastObservedTrigger=trigger;const hasCustomTrigger=trigger!==void 0;if(hasCustomTrigger!==this.hasCustomTrigger){this.hasCustomTrigger=hasCustomTrigger;return}this.emit("lr-toolbar-actions-change")}statusLabel(status){return status==="success"?this.successLabel==null?this.localize("copied"):this.successLabel:status==="error"?this.errorLabel==null?this.localize("copyFailed"):this.errorLabel:this.copyLabel==null?this.localize("copy"):this.copyLabel}renderIcon(){return this.status==="error"?html`<span part="error-icon" aria-hidden="true"><slot name="error-icon">${errorIcon()}</slot></span>`:this.status==="success"?html`<span part="success-icon" aria-hidden="true"><slot name="success-icon">${checkIcon()}</slot></span>`:html`<span part="copy-icon" aria-hidden="true"><slot name="copy-icon">${copyIcon()}</slot></span>`}render(){const statusLabel=this.statusLabel(this.status),feedback=this.status==="rest"?"":statusLabel,part=this.status==="success"?"base button base-success":this.status==="error"?"base button base-error":"base button",tooltipDisabled=this.tooltip==="none",tooltipOpen=!tooltipDisabled&&this.status!=="rest",buttonLabel=this.accessibleLabel?.trim()?this.accessibleLabel:statusLabel;return html`
41
41
  <lr-tooltip
42
42
  .content=${statusLabel}
43
43
  .trigger=${this.tooltip==="full"?"hover focus":"manual"}
@@ -118,8 +118,9 @@ fixedWidth:boolean;private fetchState;private svgEl?;private customSlot?;private
118
118
  private generation;connectedCallback():void;disconnectedCallback():void;protected updated(changed:PropertyValues):void;private onCustomSlotChange;
119
119
  /**
120
120
  * SVG geometry distributed through a shadow-DOM slot does not paint reliably in Chromium when
121
- * the slot itself is inside an SVG. Keep the public custom-content slot, but clone its trusted
122
- * SVG nodes into the component-owned SVG so path/circle/group content has a real SVG parent.
121
+ * the slot itself is inside an SVG. Keep the public custom-content slot, but clone its
122
+ * consumer-supplied SVG nodes into the component-owned SVG so path/circle/group content has a
123
+ * real SVG parent; the clone boundary applies the shared SVG safety filters first.
123
124
  */
124
125
  private syncCustomNodes;private observeCustomContent;private cloneSvgNode;private accessibleLabel;private hasRemoteSource;private releaseResourceLease;private load;private fail;private errorMessage;
125
126
  /** Applies presentation semantics to the fetched node. The stable wrapper rendered by
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fixedWidth=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-"))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name)||copy.setAttribute(attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fixedWidth=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value)||copy.setAttribute(attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
2
2
  part="svg"
3
3
  viewBox="0 0 24 24"
4
4
  fill="none"
@@ -1 +1 @@
1
- import{composedParentElement}from"./active-element.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element)){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden"))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType===1&&observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}function bindAccessibleTextObserver(observer,host,extraAttributes=[]){if(!observer)return;observer.disconnect(),observeAccessibleTextNode(observer,host,extraAttributes);let ancestor=composedParentElement(host);for(;ancestor;)observer.observe(ancestor,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0}))observeAccessibleTextNode(observer,assigned,extraAttributes)}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){const slottable=node;let branch=node.nodeType===1?node:slottable.assignedSlot??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function inheritedVisibilityHidden(context,node){const slottable=node,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement;return ancestor?cachedElementState(context,ancestor).visibilityHidden:!1}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&node.assignedSlot===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden||context.visibilityBaselineHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,labelReferenceRoots:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visibilityBaselineHidden:!1,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const validated=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root),ignoreInheritedVisibility=resolved.skipRootAncestorValidation===!0||resolved.ignoreInheritedVisibility===!0;context.visibilityBaselineHidden=ignoreInheritedVisibility&&inheritedVisibilityHidden(context,root);const ancestorState=context.visibilityBaselineHidden?{available:validated.available,inheritedTextVisible:!0}:validated;if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue};
1
+ import{composedParentElement}from"./active-element.js";import{asciiWhitespaceTokens}from"./ascii-whitespace.js";import{imageMapImageFor}from"./dom-guards.js";import{composedParentElement as composedParentElement2}from"./active-element.js";const NON_CONTENT_ELEMENTS=new Set(["script","style","template"]),DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS=4096,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH=256,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES=4096,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES=512,MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT=1e5;function isAriaTrue(value){return value?.trim().toLowerCase()==="true"}function accessibilityElementState(element,imageMapImage=imageMapImageFor(element)){let rendered;try{rendered=element.ownerDocument.defaultView?.getComputedStyle(element)}catch{}const visibility=rendered?.visibility;return{display:rendered?.display,subtreeExcluded:element.hasAttribute("hidden")||element.hasAttribute("inert")||isAriaTrue(element.getAttribute("aria-hidden"))||!imageMapImage&&(rendered?.display==="none"||rendered?.contentVisibility==="hidden"),visibilityHidden:visibility==="hidden"||visibility==="collapse"}}function isAccessibilitySubtreeExcluded(element){return accessibilityElementState(element).subtreeExcluded}function isAccessibilityVisibilityHidden(element){return accessibilityElementState(element).visibilityHidden}function isAccessibilityExcluded(element){return isAccessibilitySubtreeExcluded(element)||isAccessibilityVisibilityHidden(element)}const CONTENT_NODE_ATTRIBUTES=["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","id","inert","open","style"],ANCESTOR_ATTRIBUTES=["aria-hidden","class","hidden","inert","open","style"];function observeAccessibleTextNode(observer,node,extraAttributes){if(node.nodeType===3){observer.observe(node,{characterData:!0});return}node.nodeType===1&&observer.observe(node,{attributes:!0,attributeFilter:[...new Set([...CONTENT_NODE_ATTRIBUTES,...extraAttributes])],childList:!0,characterData:!0,subtree:!0})}function bindAccessibleTextObserver(observer,host,extraAttributes=[]){if(!observer)return;observer.disconnect(),observeAccessibleTextNode(observer,host,extraAttributes);let ancestor=composedParentElement(host);for(;ancestor;)observer.observe(ancestor,{attributes:!0,attributeFilter:ANCESTOR_ATTRIBUTES}),ancestor=composedParentElement(ancestor);for(const slot of host.querySelectorAll("slot"))for(const assigned of slot.assignedNodes({flatten:!0}))observeAccessibleTextNode(observer,assigned,extraAttributes)}function finiteTextLimit(value,fallback){return Number.isFinite(value)?Math.min(MAX_CONFIGURED_ACCESSIBILITY_TEXT_LIMIT,Math.max(0,Math.floor(value))):fallback}function isNodeValue(value){if(typeof value!="object"&&typeof value!="function"||value===null)return!1;try{return typeof value.nodeType=="number"&&typeof value.getRootNode=="function"}catch{return!1}}function consumeNodeWork(context){return context.workUnits>=context.maxNodes?(context.reasons.add("nodes"),!1):(context.workUnits+=1,!0)}function cachedElementState(context,element){let state=context.elementStates.get(element);return state||(state=accessibilityElementState(element,cachedImageMapImage(context,element)),context.elementStates.set(element,state)),state}function cachedImageMapImage(context,element){if(context.imageMapImages.has(element))return context.imageMapImages.get(element);const image=imageMapImageFor(element,{consume:()=>consumeNodeWork(context)});return context.imageMapImages.set(element,image),image}function cachedSubtreeExcluded(context,element){if(context.excludedElements.has(element))return context.excludedElements.get(element);const excluded=context.isSubtreeExcluded?context.isSubtreeExcluded(element):cachedElementState(context,element).subtreeExcluded;return context.excludedElements.set(element,excluded),excluded}function addLabelReferenceRoot(context,node){const root=node.getRootNode();(root.nodeType===9||root.nodeType===11&&"host"in root)&&context.labelReferenceRoots.add(root)}function appendBoundedText(context,value){if(value==="")return;if(context.outputLength>=context.maxCharacters){context.reasons.add("characters"),context.stack.length=0;return}const remaining=context.maxCharacters-context.outputLength;if(value.length>remaining){context.output.push(value.slice(0,remaining)),context.outputLength+=remaining,context.reasons.add("characters"),context.stack.length=0;return}context.output.push(value),context.outputLength+=value.length}function composedAncestorState(context,node){const slottable=node;let branch=node.nodeType===1?node:slottable.assignedSlot??node.parentElement,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement,depth=0,inheritedTextVisible=!0,firstAncestor=!0;for(;ancestor;){if(!consumeNodeWork(context))return{available:!1,inheritedTextVisible};const state=cachedElementState(context,ancestor);if(firstAncestor&&(inheritedTextVisible=!state.visibilityHidden,firstAncestor=!1),cachedSubtreeExcluded(context,ancestor)||isClosedDetailsContentBranchBounded(context,ancestor,branch))return{available:!1,inheritedTextVisible};if(ancestor===context.ancestorBoundary)return{available:!0,inheritedTextVisible};if(depth+=1,depth>context.maxDepth)return context.reasons.add("ancestors"),{available:!1,inheritedTextVisible};branch=ancestor,ancestor=composedParentElement(ancestor)}return{available:!0,inheritedTextVisible}}function inheritedVisibilityHidden(context,node){const slottable=node,ancestor=node.nodeType===1?composedParentElement(node):slottable.assignedSlot??node.parentElement;return ancestor?cachedElementState(context,ancestor).visibilityHidden:!1}function scheduleNode(context,node,depth,inheritedTextVisible,referenced,available,workCharged=!1){return depth>context.maxDepth?(context.reasons.add("depth"),!1):(context.stack.push({available,depth,inheritedTextVisible,kind:"node",node,referenced,workCharged}),!0)}function scheduleNodeList(context,nodes,depth,inheritedTextVisible,referenced,available){if(nodes.length!==0){if(depth>context.maxDepth){context.reasons.add("depth");return}context.stack.push({available,depth,index:0,inheritedTextVisible,kind:"nodes",nodes,referenced})}}function scheduleRenderedChildNodes(context,element,depth,inheritedTextVisible,referenced,available){if(element.localName==="slot"){const slot=element,root=slot.getRootNode(),candidates=root.nodeType===11&&"host"in root?root.host.childNodes:[];if(depth>context.maxDepth){(candidates.length>0||slot.childNodes.length>0)&&context.reasons.add("depth");return}context.stack.push({available,candidates,depth,fallback:slot.childNodes,foundAssigned:!1,index:0,inheritedTextVisible,kind:"slot",referenced,slot});return}if(element.localName==="details"&&!element.hasAttribute("open")){for(const child of element.children){if(!consumeNodeWork(context))return;if(child.localName==="summary"){scheduleNode(context,child,depth,inheritedTextVisible,referenced,available,!0);return}}return}const shadowRoot=element.shadowRoot,childNodes=shadowRoot?.childNodes??element.childNodes;shadowRoot&&(childNodes.length===0||depth<=context.maxDepth)&&context.traversedShadowRoots.add(shadowRoot),scheduleNodeList(context,childNodes,depth,inheritedTextVisible,referenced,available)}function labelledByElements(context,element){const value=element.getAttribute("aria-labelledby");if(value===null)return{authoritative:!1,elements:[]};addLabelReferenceRoot(context,element);const root=element.getRootNode(),canResolveSerialized=typeof root.getElementById=="function",serializedReferences=[];let sawSerializedToken=!1;for(const id of asciiWhitespaceTokens(value,()=>consumeNodeWork(context))){if(sawSerializedToken=!0,!consumeNodeWork(context))return{authoritative:!0,elements:serializedReferences};const reference=canResolveSerialized?root.getElementById(id):null;reference&&serializedReferences.push(reference)}if(sawSerializedToken)return{authoritative:serializedReferences.length>0,elements:serializedReferences};if(context.workUnits>=context.maxNodes||!consumeNodeWork(context))return context.reasons.add("nodes"),{authoritative:!0,elements:[]};if(context.workUnits>=context.maxNodes)return context.reasons.add("nodes"),{authoritative:!0,elements:[]};try{const ElementConstructor=element.ownerDocument.defaultView?.Element,descriptor=ElementConstructor?Object.getOwnPropertyDescriptor(ElementConstructor.prototype,"ariaLabelledByElements"):void 0,reflected=typeof descriptor?.get=="function"?descriptor.get.call(element):void 0;if(reflected?.length){const result=[];for(let index=0;index<reflected.length&&consumeNodeWork(context);index+=1){const reference=reflected[index];!reference||reference.nodeType!==1||(result.push(reference),addLabelReferenceRoot(context,reference))}return{authoritative:!0,elements:result}}}catch{}return{authoritative:!1,elements:[]}}function isRenderedAccessibilityBranch(context,element,display){const imageMapImage=cachedImageMapImage(context,element);if(imageMapImage)return isRenderedAccessibilityBranch(context,imageMapImage,cachedElementState(context,imageMapImage).display);if(!element.isConnected||display==="contents")return!0;const candidate=element;if(typeof candidate.checkVisibility!="function")return!0;try{return candidate.checkVisibility({contentVisibilityAuto:!0})}catch{return!1}}function processAccessibilityTextWork(context){for(;context.stack.length>0;){const work=context.stack.pop();if(work.kind==="text"){appendBoundedText(context,work.value);continue}if(work.kind==="slot"){if(work.index>=work.candidates.length){work.foundAssigned||scheduleNodeList(context,work.fallback,work.depth,work.inheritedTextVisible,work.referenced,work.available);continue}if(!consumeNodeWork(context)){context.stack.length=0;break}const node=work.candidates[work.index],assigned=!!(node&&node.assignedSlot===work.slot);context.stack.push({...work,foundAssigned:work.foundAssigned||assigned,index:work.index+1}),node&&assigned&&(scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available,!0),work.foundAssigned&&context.stack.push({kind:"text",value:" "}));continue}if(work.kind==="nodes"){if(work.index>=work.nodes.length)continue;const node=work.nodes[work.index];if(!node)continue;context.stack.push({...work,index:work.index+1}),scheduleNode(context,node,work.depth,work.inheritedTextVisible,work.referenced,work.available),work.index>0&&context.stack.push({kind:"text",value:" "});continue}if(context.visited.has(work.node))continue;if(!work.workCharged&&!consumeNodeWork(context)){context.stack.length=0;break}if(context.visited.add(work.node),context.visitedNodes+=1,!work.referenced&&context.shouldPruneNode?.(work.node))continue;if(work.node.nodeType===3){(work.referenced||work.available&&work.inheritedTextVisible)&&appendBoundedText(context,work.node.textContent??"");continue}if(work.node.nodeType===11){"host"in work.node&&context.traversedShadowRoots.add(work.node),scheduleNodeList(context,work.node.childNodes,work.depth+1,work.inheritedTextVisible,work.referenced,work.available);continue}if(work.node.nodeType!==1)continue;const element=work.node;if(NON_CONTENT_ELEMENTS.has(element.localName)||context.shouldPrune?.(element))continue;const state=cachedElementState(context,element),excluded=cachedSubtreeExcluded(context,element),available=work.referenced||work.available&&!excluded;if(!available||!work.referenced&&context.requireRendered&&!isRenderedAccessibilityBranch(context,element,state.display))continue;const ownTextVisible=work.referenced||!state.visibilityHidden||context.visibilityBaselineHidden,labelledBy=ownTextVisible?labelledByElements(context,element):{authoritative:!1,elements:[]};if(labelledBy.elements.length>0){for(const reference of labelledBy.elements)context.referencedElements.add(reference);scheduleNodeList(context,labelledBy.elements,work.depth+1,!0,!0,!0);continue}if(labelledBy.authoritative)continue;const ariaLabel=ownTextVisible?element.getAttribute("aria-label"):null;if(ariaLabel?.trim()){appendBoundedText(context,ariaLabel.trim());continue}if(ownTextVisible&&(element.localName==="img"||element.localName==="area")){const alt=element.getAttribute("alt");if(alt?.trim()){appendBoundedText(context,alt.trim());continue}}scheduleRenderedChildNodes(context,element,work.depth+1,ownTextVisible,work.referenced,available)}}function normalizedTextOptions(options){const resolved=typeof options=="boolean"?{inheritedTextVisible:options}:options??{};return{...resolved,inheritedTextVisible:resolved.inheritedTextVisible??!0,maxCharacters:finiteTextLimit(resolved.maxCharacters,DEFAULT_ACCESSIBILITY_TEXT_MAX_CHARACTERS),maxDepth:finiteTextLimit(resolved.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes:finiteTextLimit(resolved.maxNodes,DEFAULT_ACCESSIBILITY_TEXT_MAX_NODES)}}function composedAccessibilityTextResult(input,options){const resolved=normalizedTextOptions(options),context={ancestorBoundary:resolved.ancestorBoundary??null,elementStates:new Map,excludedElements:new Map,imageMapImages:new Map,isSubtreeExcluded:resolved.isSubtreeExcluded,labelReferenceRoots:new Set,maxCharacters:resolved.maxCharacters,maxDepth:resolved.maxDepth,maxNodes:resolved.maxNodes,output:[],outputLength:0,reasons:new Set,referencedElements:new Set,requireRendered:resolved.requireRendered!==!1,shouldPrune:resolved.shouldPrune,shouldPruneNode:resolved.shouldPruneNode,stack:[],traversedShadowRoots:new Set,visibilityBaselineHidden:!1,visited:new Set,visitedNodes:0,workUnits:0};if(context.maxNodes===0)return context.reasons.add("nodes"),{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:"",traversedShadowRoots:context.traversedShadowRoots,truncated:!0,truncationReasons:[...context.reasons],visitedNodes:0};const roots=isNodeValue(input)?[input]:input;let rootCount=0;for(const root of roots){if(!isNodeValue(root))continue;if(context.workUnits>=context.maxNodes){context.reasons.add("nodes");break}if(rootCount>0&&appendBoundedText(context," "),context.reasons.has("characters"))break;const validated=resolved.skipRootAncestorValidation?{available:!0,inheritedTextVisible:!0}:composedAncestorState(context,root),ignoreInheritedVisibility=resolved.skipRootAncestorValidation===!0||resolved.ignoreInheritedVisibility===!0;context.visibilityBaselineHidden=(root.nodeType===1||!resolved.skipRootAncestorValidation)&&ignoreInheritedVisibility&&inheritedVisibilityHidden(context,root);const ancestorState=context.visibilityBaselineHidden?{available:validated.available,inheritedTextVisible:!0}:validated;if(scheduleNode(context,root,0,resolved.inheritedTextVisible&&ancestorState.inheritedTextVisible,!1,ancestorState.available),processAccessibilityTextWork(context),rootCount+=1,context.reasons.has("characters")||context.reasons.has("nodes")&&context.workUnits>=context.maxNodes)break}return{labelReferenceRoots:context.labelReferenceRoots,referencedElements:context.referencedElements,text:context.output.join(""),traversedShadowRoots:context.traversedShadowRoots,truncated:context.reasons.size>0,truncationReasons:[...context.reasons],visitedNodes:context.visitedNodes}}function composedAccessibilityText(input,options){return composedAccessibilityTextResult(input,options).text}function composedAccessibleVisibleText(node){return composedAccessibilityText(node)}function isClosedDetailsContentBranchWithin(details,branch,consume){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;let summary=null;for(const child of details.children){if(!consume())return!0;if(child.localName==="summary"){summary=child;break}}return branch!==summary}function isClosedDetailsContentBranchBounded(context,details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;for(const child of details.children){if(!consumeNodeWork(context))return!0;if(child.localName==="summary")return child!==branch}return!0}function isAccessibilityVisible(element,options={}){if(!element.isConnected)return!1;const maxDepth=finiteTextLimit(options.maxDepth,DEFAULT_ACCESSIBILITY_TEXT_MAX_DEPTH),maxNodes=finiteTextLimit(options.maxNodes,DEFAULT_ACCESSIBILITY_VISIBILITY_MAX_NODES);let workUnits=0;const consume=()=>workUnits>=maxNodes?!1:(workUnits+=1,!0);let current=element,composedChild=null,depth=0,targetState,renderedSource=element;for(;current;){if(depth>maxDepth||!consume())return!1;const imageMapImage=imageMapImageFor(current,{consume}),state=accessibilityElementState(current,imageMapImage);if(current===element&&(targetState=state,renderedSource=imageMapImage??element),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===element&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(renderedSource!==element)for(current=renderedSource,composedChild=null,depth=0;current;){if(depth>maxDepth||!consume())return!1;const state=accessibilityElementState(current,imageMapImageFor(current,{consume}));if(current===renderedSource&&(targetState=state),!options.ignorePresentation?.(current)&&(state.subtreeExcluded||isClosedDetailsContentBranchWithin(current,composedChild,consume)||current===renderedSource&&state.visibilityHidden))return!1;composedChild=current,current=composedParentElement(current),depth+=1}if(targetState?.display==="contents")return!0;const visibilityTarget=renderedSource;if(!consume())return!1;try{return typeof visibilityTarget.checkVisibility=="function"?visibilityTarget.checkVisibility({contentVisibilityAuto:!0}):!0}catch{return!1}}export{bindAccessibleTextObserver,composedAccessibilityText,composedAccessibilityTextResult,composedAccessibleVisibleText,composedParentElement2 as composedParentElement,isAccessibilityExcluded,isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,isAccessibilityVisible,isAriaTrue};
@@ -1 +1 @@
1
- import{takeOverlayOrder}from"./overlay-order.js";import{deepActiveElementIn}from"./active-element.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 composedParent(element){return element.assignedSlot?element.assignedSlot:element.parentElement?element.parentElement:element.getRootNode().host??null}function composedContains(container,candidate){let current=candidate;for(;current;){if(current===container)return!0;current=composedParent(current)}return!1}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 focusEntry(entry,preserveCurrent=!0){const panel=entry.options.panel();if(!panel)return;const active=deepActiveElement(entry.state.document);if(preserveCurrent&&composedContains(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=collectFocusableElements(panel);if(focusable.length===0){event.preventDefault(),panel.focus();return}const active=deepActiveElement(state.document),first=focusable[0],last=focusable[focusable.length-1];(active?focusable.indexOf(active):-1)===-1?(event.preventDefault(),(event.shiftKey?last:first).focus()):event.shiftKey&&active===first?(event.preventDefault(),last.focus()):!event.shiftKey&&active===last&&(event.preventDefault(),first.focus())}function snapshotFor(state){return{entries:state.stack.map(entry=>({host:entry.options.host,modal:entry.options.modal,modalRoot:entry.options.modalRoot}))}}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];entry&&(event.key==="Escape"?(event.preventDefault(),entry.options.onEscape()):event.key==="Tab"&&(entry.options.trapFocus===!1?entry.options.onTab?.():handleTab(state,entry,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;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&&focusEntry(next),deferredResourceRelease}function activateOverlayStack(options){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 composedContains(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{takeOverlayOrder}from"./overlay-order.js";import{deepActiveElementIn}from"./active-element.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 composedParent(element){return element.assignedSlot?element.assignedSlot:element.parentElement?element.parentElement:element.getRootNode().host??null}function composedContains(container,candidate){let current=candidate;for(;current;){if(current===container)return!0;current=composedParent(current)}return!1}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 focusEntry(entry,preserveCurrent=!0){const panel=entry.options.panel();if(!panel)return;const active=deepActiveElement(entry.state.document);if(preserveCurrent&&composedContains(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=collectFocusableElements(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)event.preventDefault(),(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&&(event.preventDefault(),next.focus())}}function snapshotFor(state){return{entries:state.stack.map(entry=>({host:entry.options.host,modal:entry.options.modal,modalRoot:entry.options.modalRoot}))}}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];entry&&(event.key==="Escape"?(event.preventDefault(),entry.options.onEscape()):event.key==="Tab"&&(entry.options.trapFocus===!1?entry.options.onTab?.():handleTab(state,entry,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;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&&focusEntry(next),deferredResourceRelease}function activateOverlayStack(options){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 composedContains(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};
@@ -2,4 +2,4 @@
2
2
  * Generated from package.json by scripts/generate-package-metadata.mjs.
3
3
  * Run `pnpm package-metadata` after changing package identity or version.
4
4
  */
5
- export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'18.4.0';
5
+ export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'19.0.1';
@@ -1 +1 @@
1
- const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="18.4.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
1
+ const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="19.0.1";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
@@ -1,13 +1,17 @@
1
1
  /**
2
- * Rejects an attribute name that should never survive a raw DOM clone of consumer-supplied SVG
3
- * content (`<lr-icon>`'s and `<lr-icon-button>`'s slotted custom-content path -- unlike a fetched
4
- * `src` document, which is sanitized through DOMPurify before it ever reaches the DOM, a slotted
5
- * clone has no sanitizer in the loop, so this predicate is that path's own trust boundary).
6
- * Event-handler content attributes (`on*`) execute as inline JS once connected; `href`/
7
- * `xlink:href` on an SVG `<a>`/`<use>`/`<image>` can carry a `javascript:` URI or reference an
8
- * external resource. Every other presentational attribute (`d`, `fill`, `stroke`, `viewBox`,
9
- * `transform`, gradient stops, …) is left untouched -- this is a denylist, not an allowlist,
10
- * because SVG's legitimate presentation-attribute vocabulary is too large to enumerate without
11
- * silently breaking real icon markup.
2
+ * Rejects an element that should never survive a raw DOM clone of consumer-supplied SVG content.
3
+ * Unlike a fetched `src` document, `<lr-icon>`'s and `<lr-icon-button>`'s slotted clone paths do
4
+ * not pass through DOMPurify, so this predicate is their own element trust boundary. The list is
5
+ * deliberately narrow enough to retain ordinary icon primitives, groups, definitions, gradients,
6
+ * masks, clipping paths, and `<use>` elements.
12
7
  */
13
- export declare function isUnsafeSvgCloneAttribute(name:string):boolean;
8
+ export declare function isUnsafeSvgCloneElement(name:string):boolean;
9
+ /**
10
+ * Rejects an attribute that should never survive a raw DOM clone of consumer-supplied SVG content.
11
+ * Event-handler attributes execute as inline JS once connected; style and secondary resource
12
+ * attributes can apply attacker-controlled CSS or initiate fetches; and href attributes can carry
13
+ * script URLs or external document references. URL-bearing presentation attributes retain only
14
+ * same-document fragment references, so ordinary icon geometry and local paint servers continue
15
+ * to work.
16
+ */
17
+ export declare function isUnsafeSvgCloneAttribute(name:string,value?:string):boolean;
@@ -1 +1 @@
1
- function isUnsafeSvgCloneAttribute(name){const lower=name.toLowerCase();return lower.startsWith("on")||lower==="href"||lower==="xlink:href"}export{isUnsafeSvgCloneAttribute};
1
+ const UNSAFE_SVG_CLONE_ELEMENTS=new Set(["script","style","foreignobject","animate","animatecolor","animatemotion","animatetransform","set","discard","mpath","feimage","image","iframe","object","embed"]),SVG_URL_PRESENTATION_ATTRIBUTES=new Set(["clip-path","cursor","fill","filter","marker","marker-end","marker-mid","marker-start","mask","stroke"]);function isLocalSvgFragment(value){return/^#[^\s"'()<>]+$/.test(value.trim())}function hasUnsafeCssResource(value){if(value.includes("\\"))return!0;const urls=[...value.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)];return urls.length===0?!1:value.replace(/url\(\s*(["']?)(.*?)\1\s*\)/gi,"").trim()!==""||urls.some(match=>!isLocalSvgFragment(match[2]??""))}function isUnsafeSvgCloneElement(name){return UNSAFE_SVG_CLONE_ELEMENTS.has(name.toLowerCase())}function isUnsafeSvgCloneAttribute(name,value=""){const lower=name.toLowerCase();return lower.startsWith("on")||lower==="style"||lower==="src"||lower==="srcset"||lower==="poster"||lower==="href"||lower==="xlink:href"?!0:SVG_URL_PRESENTATION_ATTRIBUTES.has(lower)&&hasUnsafeCssResource(value)}export{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement};