@aceshooting/lyra-ui 30.2.0 → 30.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/dist/ai/adapters/a2ui.d.ts +10 -4
- package/dist/ai/adapters/a2ui.js +1 -1
- package/dist/ai/adapters/ag-ui.d.ts +17 -4
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/ai/adapters/ai-sdk.js +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
- package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +3 -3
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
- package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +4 -1
- package/dist/components/layout/multi-split/multi-split.class.js +6 -3
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.d.ts +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.d.ts +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/stepper/stepper.class.d.ts +1 -1
- package/dist/components/layout/stepper/stepper.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/map/map-control-chrome.js +1 -0
- package/dist/components/media/map/map-control-options.d.ts +6 -2
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-controls-readiness.js +1 -0
- package/dist/components/media/map/map.class.d.ts +39 -2
- package/dist/components/media/map/map.class.js +13 -7
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +2 -2
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +13 -15
- package/dist/components/utility/copy-button/copy-button.class.js +3 -3
- package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +2 -2
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/modal-host.styles.js +1 -0
- package/dist/internal/modal-surface-controller.js +1 -1
- package/dist/internal/overlay-stack.d.ts +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/style-property-lease.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-app-rail.md +4 -0
- package/llms/components/lr-badge.md +3 -0
- package/llms/components/lr-copy-button.md +15 -7
- package/llms/components/lr-file-input.md +5 -0
- package/llms/components/lr-map.md +80 -8
- package/llms/components/lr-mcp-app.md +94 -4
- package/llms/components/lr-message-parts.md +18 -0
- package/llms/components/lr-multi-split.md +4 -0
- package/llms/components/lr-page.md +5 -1
- package/llms/components/lr-responsive-panel.md +5 -1
- package/llms/components/lr-select.md +3 -2
- package/llms/components/lr-token-input.md +4 -3
- package/llms/components/lr-tooltip.md +4 -4
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +88 -3
- package/llms/shared/events-and-types.md +25 -1
- package/llms/shared/localization-and-rtl.md +29 -0
- package/llms/shared/styles-and-tokens.md +75 -14
- package/llms/shared.md +217 -18
- package/locales.json +1 -1
- package/package.json +8 -4
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +5 -3
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
- package/skills/lyra-ui/SKILL.md +17 -8
- package/skills/lyra-ui/lyra-gen.md +95 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{resolveCssLength}from"../../../internal/css-length.js";import{cancelDeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter}from"../../../internal/converters.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{activateOverlay,deepActiveElement}from"../../../internal/overlay-manager.js";import{styles}from"./responsive-panel.styles.js";import{resolveResponsivePanelEffectiveMode}from"./responsive-panel-mode.js";import{LYRA_DEFAULT_responsivePanel}from"../../../internal/default-strings/layout.generated.js";import{resolveResponsivePanelEffectiveMode as resolveResponsivePanelEffectiveMode2}from"./responsive-panel-mode.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]',DEFAULT_OVERLAY_BREAKPOINT="768px",RESPONSIVE_PANEL_MODE=literalSetConverter(["inline","overlay","auto"],"auto");class LyraResponsivePanel extends LyraElement{constructor(){super(...arguments),this.open=!1,this._mode="auto",this.shape="fullscreen",this.label="",this.overlayBreakpoint=DEFAULT_OVERLAY_BREAKPOINT,this.accessibleLabel=null,this.belowBreakpoint=!1,this.resolvedMode="inline",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.close("escape"),this.open&&this.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this.shadowRoot?.querySelector('[part="base"]')??null),this.headerObserverGeneration=0,this.ownerRealmGeneration=0,this.overlayChromeActive=!1,this.focusOverlayAfterUpdate=!1,this.isFirstUpdate=!0,this.onWindowResize=()=>this.measureAllocation(),this.onHeaderSlotChange=e=>{this.syncHeaderSlot(e.target.assignedElements({flatten:!0}))},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,responsivePanel:LYRA_DEFAULT_responsivePanel}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}get mode(){return this._mode}set mode(next){const normalized=RESPONSIVE_PANEL_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}get effectiveMode(){return this.resolvedMode}willUpdate(changed){if(super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,this.isFirstUpdate&&(this.headingText=this.detectHeadingText()),!this.isFirstUpdate&&(changed.has("overlayBreakpoint")||changed.has("mode"))&&this.isConnected&&this.measureAllocation(),(this.isFirstUpdate||changed.has("mode")||changed.has("belowBreakpoint"))&&(this.resolvedMode=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)),changed.has("open")&&this.open){const active=deepActiveElement(this.ownerDocument);this.lastTrigger=active&&typeof active.focus=="function"?active:void 0}const overlayOpen=this.resolvedMode==="overlay"&&this.open;if(overlayOpen!==this.overlayChromeActive)if(this.overlayChromeActive=overlayOpen,overlayOpen)this.activateOverlayChrome(),this.focusOverlayAfterUpdate=!0;else{const restoreFocus=changed.has("open")&&!this.open;this.deactivateOverlayChrome(restoreFocus)}changed.has("open")&&!this.open&&(this.lastTrigger=void 0)}updated(changed){super.updated(changed),this.showOverlaySurface(),!this.isFirstUpdate&&changed.has("resolvedMode")&&this.emit("lr-mode-change",{mode:this.resolvedMode}),this.focusOverlayAfterUpdate&&(this.focusOverlayAfterUpdate=!1,this.overlayHandle?.focusInitial())}connectedCallback(){super.connectedCallback(),this.measureAllocation(),this.observeAllocation();const overlayOpen=resolveResponsivePanelEffectiveMode(this.mode,this.belowBreakpoint)==="overlay"&&this.open;this.hasUpdated&&overlayOpen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateOverlayChrome(),this.queueOwnerMicrotask(()=>{this.showOverlaySurface(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="header"]');slot&&this.syncHeaderSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork();const resizeObserver=this.resizeObserver;this.resizeObserver=void 0;const resizeView=this.resizeView;this.resizeView=void 0,resizeObserver?.disconnect(),resizeView?.removeEventListener("resize",this.onWindowResize),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.modalSurface.disconnect(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetHeaderObserver()}queueOwnerMicrotask(callback,nextFrame=!1){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,run=()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()};nextFrame?ownerWindow.requestAnimationFrame(run):ownerWindow.queueMicrotask(run)}activateOverlayChrome(){this.modalSurface.prepare(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),restoreFocusTo:this.lastTrigger??null,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.lastTrigger;return opener?{candidates:()=>[opener],isCurrent:()=>!this.open}:void 0}})}deactivateOverlayChrome(restoreFocus=!0){this.modalSurface.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0}showOverlaySurface(){!this.isConnected||!this.open||this.effectiveMode!=="overlay"||(this.overlayHandle?.resume(),this.modalSurface.show())}observeAllocation(){if(!this.isConnected)return;this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver??=new ResizeObserverConstructor(entries=>{const entry=entries.find(candidate=>candidate.target===this)??entries[0],inlineSize=entry?.contentBoxSize?.[0]?.inlineSize??entry?.contentRect.width;inlineSize!==void 0&&this.queueOwnerMicrotask(()=>this.applyMeasuredInlineSize(inlineSize),!0)}),this.resizeObserver.observe(this);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}measureAllocation(){if(this.mode!=="auto")return;const inlineSize=this.getBoundingClientRect().width;inlineSize>0&&this.applyMeasuredInlineSize(inlineSize)}applyMeasuredInlineSize(inlineSize){if(!Number.isFinite(inlineSize)||inlineSize<0)return;const resolved=resolveCssLength(this.overlayBreakpoint,{host:this}),fallback=resolveCssLength(DEFAULT_OVERLAY_BREAKPOINT,{host:this})??768,breakpoint=Math.max(0,resolved!==void 0&&Number.isFinite(resolved)?resolved:fallback);this.belowBreakpoint=inlineSize<=breakpoint}syncHeaderSlot(assigned){if(this.headingText=this.detectHeadingText(),this.resetHeaderObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headerObserverGeneration,observer=new MutationObserverCtor(()=>{this.headerObserver!==observer||this.headerObserverDocument!==ownerDocument||this.headerObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.headingText=this.detectHeadingText())});this.headerObserver=observer,this.headerObserverDocument=ownerDocument;for(const element of assigned)observer.observe(element,{childList:!0,characterData:!0,subtree:!0})}resetHeaderObserver(){this.headerObserverGeneration+=1,this.headerObserver?.disconnect(),this.headerObserver=void 0,this.headerObserverDocument=void 0}detectHeadingText(){const headerChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="header");if(headerChildren.length===0)return;const heading=headerChildren.find(el=>el.matches(HEADING_SELECTOR));return heading?heading.textContent?.trim()||void 0:headerChildren.map(el=>el.textContent?.trim()).filter(Boolean).join(" ")||void 0}close(reason="api"){this.open&&(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-close",{reason})))}show(){this.open=!0}hide(){this.close()}render(){const overlay=this.effectiveMode==="overlay",accessibleName=this.accessibleLabel??(this.label||this.headingText||this.localize("responsivePanel"));return this.nativeModal.render(html`
|
|
2
2
|
<div part="base" class=${overlay?"overlay":"inline"}>
|
|
3
3
|
${overlay?html`<div part="backdrop" @click=${this.onBackdropClick}></div>`:nothing}
|
|
4
4
|
<div
|
|
@@ -44,4 +44,4 @@ export declare class LyraScroller extends LyraElement<LyraScrollerEventMap>{stat
|
|
|
44
44
|
/** Hides the native scrollbar while preserving scrolling.*/
|
|
45
45
|
withoutScrollbar:boolean;
|
|
46
46
|
/** Removes both visual edge cues while leaving native scrolling untouched.*/
|
|
47
|
-
withoutShadow:boolean;scrollStep:number;label:string;private atStart;private atEnd;private measured;private viewport?;private content?;private resizeObserver?;private resizeObserverDocument?;private ownerRealmGeneration;connectedCallback():void;firstUpdated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private armResizeObserver;private resetOwnerRealmWork;private scheduleEdgeUpdate;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private edgeDetail;private updateEdges;private syncEdges;private scrollFrame?;private scrollFrameWindow?;private cancelScrollFrame;private onScroll;private onSlotChange;private get safeScrollStep();private scrollByDirection;private scrollToEdge;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-scroller':LyraScroller;}}
|
|
47
|
+
withoutShadow:boolean;scrollStep:number;label:string;private atStart;private atEnd;private measured;private viewport?;private content?;private resizeObserver?;private resizeObserverDocument?;private ownerRealmGeneration;private edgeUpdatePending;connectedCallback():void;firstUpdated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private armResizeObserver;private resetOwnerRealmWork;private scheduleEdgeUpdate;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private edgeDetail;private updateEdges;private syncEdges;private scrollFrame?;private scrollFrameWindow?;private cancelScrollFrame;private onScroll;private onSlotChange;private get safeScrollStep();private scrollByDirection;private scrollToEdge;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-scroller':LyraScroller;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{styles}from"./scroller.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious,LYRA_DEFAULT_scrollerLabel}from"../../../internal/default-strings/layout.generated.js";class LyraScroller extends LyraElement{constructor(){super(...arguments),this.orientation="horizontal",this.controls=!1,this.withoutScrollbar=!1,this.withoutShadow=!1,this.scrollStep=0,this.label="",this.atStart=!1,this.atEnd=!1,this.measured=!1,this.ownerRealmGeneration=0,this.updateEdges=()=>this.syncEdges(!1),this.onScroll=()=>{if(this.scrollFrame!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollFrame!==handle||this.scrollFrameWindow!==ownerWindow||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollFrame=void 0,this.scrollFrameWindow=void 0,this.syncEdges(!0))});this.scrollFrame=handle,this.scrollFrameWindow=ownerWindow},this.onSlotChange=()=>{this.content&&this.resizeObserver?.observe(this.content),this.scheduleEdgeUpdate()}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious,scrollerLabel:LYRA_DEFAULT_scrollerLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.armResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver(),this.scheduleEdgeUpdate()}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}armResizeObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.resizeObserver&&this.resizeObserverDocument===ownerDocument){this.viewport&&this.resizeObserver.observe(this.viewport),this.content&&this.resizeObserver.observe(this.content);return}this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0;const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.updateEdges()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this),this.viewport&&observer.observe(this.viewport),this.content&&observer.observe(this.content)}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.cancelScrollFrame(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.measured=!1}scheduleEdgeUpdate(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.updateEdges()})}willUpdate(changed){super.willUpdate(changed);const active=this.hasUpdated?shadowFocusTarget(this):null;(active?.matches('[part~="previous"]')?this.atStart:active?.matches('[part~="next"]')&&this.atEnd)&&this.viewport?.focus()}updated(changed){super.updated(changed),(changed.has("orientation")||changed.has("controls"))&&this.scheduleEdgeUpdate()}edgeDetail(){const viewport=this.viewport;if(!viewport)return{scrollStart:!1,scrollEnd:!1,scrollLeft:0,scrollTop:0};const horizontal=this.orientation==="horizontal",max=horizontal?Math.max(0,viewport.scrollWidth-viewport.clientWidth):Math.max(0,viewport.scrollHeight-viewport.clientHeight),position=horizontal?viewport.scrollLeft:viewport.scrollTop,startPosition=horizontal&&this.effectiveDirection==="rtl"?-position:position;return{scrollStart:startPosition<=1,scrollEnd:startPosition>=max-1,scrollLeft:viewport.scrollLeft,scrollTop:viewport.scrollTop}}syncEdges(emitForPositionChange){const detail=this.edgeDetail(),changed=!this.measured||detail.scrollStart!==this.atStart||detail.scrollEnd!==this.atEnd;this.measured=!0,this.atStart=detail.scrollStart,this.atEnd=detail.scrollEnd,(changed||emitForPositionChange)&&this.emit("lr-scroll",detail)}cancelScrollFrame(){this.scrollFrame!==void 0&&this.scrollFrameWindow?.cancelAnimationFrame(this.scrollFrame),this.scrollFrame=void 0,this.scrollFrameWindow=void 0}get safeScrollStep(){return finiteRange(this.scrollStep,0,0)}scrollByDirection(direction){const viewport=this.viewport;if(!viewport)return;const horizontal=this.orientation==="horizontal",step=this.safeScrollStep,amount=step>0?step:horizontal?Math.max(1,viewport.clientWidth*.8):Math.max(1,viewport.clientHeight*.8),physicalDirection=horizontal&&this.effectiveDirection==="rtl"?-direction:direction;viewport.scrollBy(horizontal?{left:amount*physicalDirection}:{top:amount*direction})}scrollToEdge(edge){const viewport=this.viewport;if(!viewport)return;if(this.orientation==="horizontal"){const max=Math.max(0,viewport.scrollWidth-viewport.clientWidth),rtl=this.effectiveDirection==="rtl";viewport.scrollTo({left:edge==="start"?0:rtl?-max:max})}else viewport.scrollTo({top:edge==="start"?0:viewport.scrollHeight})}render(){const label=this.getAttribute("aria-label")??(this.label||this.localize("scrollerLabel")),vertical=this.orientation==="vertical";return html`<div part="base">
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{styles}from"./scroller.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_scrollNext,LYRA_DEFAULT_scrollPrevious,LYRA_DEFAULT_scrollerLabel}from"../../../internal/default-strings/layout.generated.js";class LyraScroller extends LyraElement{constructor(){super(...arguments),this.orientation="horizontal",this.controls=!1,this.withoutScrollbar=!1,this.withoutShadow=!1,this.scrollStep=0,this.label="",this.atStart=!1,this.atEnd=!1,this.measured=!1,this.ownerRealmGeneration=0,this.edgeUpdatePending=!1,this.updateEdges=()=>this.syncEdges(!1),this.onScroll=()=>{if(this.scrollFrame!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{this.scrollFrame!==handle||this.scrollFrameWindow!==ownerWindow||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.scrollFrame=void 0,this.scrollFrameWindow=void 0,this.syncEdges(!0))});this.scrollFrame=handle,this.scrollFrameWindow=ownerWindow},this.onSlotChange=()=>{this.content&&this.resizeObserver?.observe(this.content),this.scheduleEdgeUpdate()}}static{this.defaultStrings={...super.defaultStrings,scrollNext:LYRA_DEFAULT_scrollNext,scrollPrevious:LYRA_DEFAULT_scrollPrevious,scrollerLabel:LYRA_DEFAULT_scrollerLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.armResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver(),this.scheduleEdgeUpdate()}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}armResizeObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.resizeObserver&&this.resizeObserverDocument===ownerDocument){this.viewport&&this.resizeObserver.observe(this.viewport),this.content&&this.resizeObserver.observe(this.content);return}this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0;const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.resizeObserver!==observer||this.resizeObserverDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.updateEdges()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,observer.observe(this),this.viewport&&observer.observe(this.viewport),this.content&&observer.observe(this.content)}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.edgeUpdatePending=!1,this.cancelScrollFrame(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.measured=!1}scheduleEdgeUpdate(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected||this.edgeUpdatePending)return;this.edgeUpdatePending=!0;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.edgeUpdatePending=!1,this.updateEdges())})}willUpdate(changed){super.willUpdate(changed);const active=this.hasUpdated?shadowFocusTarget(this):null;(active?.matches('[part~="previous"]')?this.atStart:active?.matches('[part~="next"]')&&this.atEnd)&&this.viewport?.focus()}updated(changed){super.updated(changed),(changed.has("orientation")||changed.has("controls"))&&this.scheduleEdgeUpdate()}edgeDetail(){const viewport=this.viewport;if(!viewport)return{scrollStart:!1,scrollEnd:!1,scrollLeft:0,scrollTop:0};const horizontal=this.orientation==="horizontal",max=horizontal?Math.max(0,viewport.scrollWidth-viewport.clientWidth):Math.max(0,viewport.scrollHeight-viewport.clientHeight),position=horizontal?viewport.scrollLeft:viewport.scrollTop,startPosition=horizontal&&this.effectiveDirection==="rtl"?-position:position;return{scrollStart:startPosition<=1,scrollEnd:startPosition>=max-1,scrollLeft:viewport.scrollLeft,scrollTop:viewport.scrollTop}}syncEdges(emitForPositionChange){const detail=this.edgeDetail(),changed=!this.measured||detail.scrollStart!==this.atStart||detail.scrollEnd!==this.atEnd;this.measured=!0,this.atStart=detail.scrollStart,this.atEnd=detail.scrollEnd,(changed||emitForPositionChange)&&this.emit("lr-scroll",detail)}cancelScrollFrame(){this.scrollFrame!==void 0&&this.scrollFrameWindow?.cancelAnimationFrame(this.scrollFrame),this.scrollFrame=void 0,this.scrollFrameWindow=void 0}get safeScrollStep(){return finiteRange(this.scrollStep,0,0)}scrollByDirection(direction){const viewport=this.viewport;if(!viewport)return;const horizontal=this.orientation==="horizontal",step=this.safeScrollStep,amount=step>0?step:horizontal?Math.max(1,viewport.clientWidth*.8):Math.max(1,viewport.clientHeight*.8),physicalDirection=horizontal&&this.effectiveDirection==="rtl"?-direction:direction;viewport.scrollBy(horizontal?{left:amount*physicalDirection}:{top:amount*direction})}scrollToEdge(edge){const viewport=this.viewport;if(!viewport)return;if(this.orientation==="horizontal"){const max=Math.max(0,viewport.scrollWidth-viewport.clientWidth),rtl=this.effectiveDirection==="rtl";viewport.scrollTo({left:edge==="start"?0:rtl?-max:max})}else viewport.scrollTo({top:edge==="start"?0:viewport.scrollHeight})}render(){const label=this.getAttribute("aria-label")??(this.label||this.localize("scrollerLabel")),vertical=this.orientation==="vertical";return html`<div part="base">
|
|
2
2
|
${this.controls?html`<button
|
|
3
3
|
part="control previous"
|
|
4
4
|
type="button"
|
|
@@ -61,7 +61,7 @@ positionInPixels:number;}export interface LyraSplitPanelEventMap{
|
|
|
61
61
|
* @status stable
|
|
62
62
|
* @since 8.0.0
|
|
63
63
|
*/
|
|
64
|
-
export declare class LyraSplitPanel extends LyraElement<LyraSplitPanelEventMap>{static styles:import("lit").CSSResultGroup[];private _startPosition;private _orientation;private _primary?;private _snapThreshold;private availableSize;private measuredConstraintBounds;private readonly resizeWriteGuard;private resizeRequestSequence;private pendingPositionInPixels?;private preservedPrimaryPixels?;private resizeObserver?;private resizeView?;private drag?;private readonly dragController;private readonly dividerSourceSnapshots;private dividerSourceObserver?;private dividerSourceObserverDocument?;private dividerSourceObserverGeneration;private normalizedSnapSource?;private cachedNormalizedSnapTokens;private baseElement?;private dividerElement?;private dividerSlot?;private minProbe?;private maxProbe?;
|
|
64
|
+
export declare class LyraSplitPanel extends LyraElement<LyraSplitPanelEventMap>{static styles:import("lit").CSSResultGroup[];private _startPosition;private _orientation;private _primary?;private _snapThreshold;private availableSize;private initialUpdate;private measuredConstraintBounds;private readonly resizeWriteGuard;private resizeRequestSequence;private pendingPositionInPixels?;private preservedPrimaryPixels?;private resizeObserver?;private resizeView?;private drag?;private readonly dragController;private readonly dividerSourceSnapshots;private dividerSourceObserver?;private dividerSourceObserverDocument?;private dividerSourceObserverGeneration;private normalizedSnapSource?;private cachedNormalizedSnapTokens;private baseElement?;private dividerElement?;private dividerSlot?;private minProbe?;private maxProbe?;
|
|
65
65
|
/** Divider position as a percentage from the primary panel's edge.
|
|
66
66
|
* @default 50 */
|
|
67
67
|
get position():number;set position(value:number);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate,separatorDelta}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./split-panel.styles.js";import{LYRA_DEFAULT_resizeDivider,LYRA_DEFAULT_resizeValuePercent}from"../../../internal/default-strings/layout.generated.js";const DEFAULT_POSITION=50,DEFAULT_SNAP_THRESHOLD=12,KEYBOARD_STEP_PERCENT=1,MAX_SNAP_SOURCE_CODE_UNITS=16384,MAX_SNAP_TOKENS=256,POSITION_EPSILON=1e-4;import{SNAP_NONE}from"./split-panel-snap.js";const snapConverter={fromAttribute(value){return value??""},toAttribute(value){return typeof value=="string"&&value!==""?value:null}};function isAsciiDigit(code){return code>=48&&code<=57}function matchesAsciiToken(source,index,token){if(index+token.length>source.length)return!1;for(let offset=0;offset<token.length;offset+=1){const sourceCode=source.charCodeAt(index+offset);if((sourceCode>=65&&sourceCode<=90?sourceCode+32:sourceCode)!==token.charCodeAt(offset))return!1}return!0}function isSnapWhitespace(code){return code>=9&&code<=13||code===32||code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipSnapWhitespace(source,start){let cursor=start;for(;cursor<source.length&&isSnapWhitespace(source.charCodeAt(cursor));)cursor+=1;return cursor}function scanSnapLength(source,start){let cursor=start;if(isAsciiDigit(source.charCodeAt(cursor))){for(;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1}else if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;else return{end:start+1,recognized:!1};const numberEnd=cursor;let unit;if(source.charCodeAt(cursor)===37?(unit="%",cursor+=1):matchesAsciiToken(source,cursor,"px")&&(unit="px",cursor+=2),unit===void 0)return{end:Math.max(start+1,numberEnd),recognized:!1};const numericValue=Number(source.slice(start,numberEnd));return{end:cursor,recognized:!0,token:Number.isFinite(numericValue)?Object.freeze({value:numericValue,unit}):void 0}}function normalizeSnapTokens(value){const source=value.slice(0,MAX_SNAP_SOURCE_CODE_UNITS),tokens=[];let index=0;for(;index<source.length&&tokens.length<MAX_SNAP_TOKENS;){if(matchesAsciiToken(source,index,"repeat(")){const innerStart=skipSnapWhitespace(source,index+7),scanned2=scanSnapLength(source,innerStart);if(scanned2.recognized){const close=skipSnapWhitespace(source,scanned2.end);if(source.charCodeAt(close)===41){scanned2.token&&tokens.push(Object.freeze({repeated:!0,...scanned2.token})),index=close+1;continue}scanned2.token&&tokens.push(Object.freeze({repeated:!1,...scanned2.token}))}index=Math.max(index+7,scanned2.end);continue}const scanned=scanSnapLength(source,index);scanned.recognized&&scanned.token&&tokens.push(Object.freeze({repeated:!1,...scanned.token})),index=Math.max(index+1,scanned.end)}return Object.freeze(tokens)}function nearlyEqual(left,right){return left===right?!0:left==null||right==null?!1:Math.abs(left-right)<=POSITION_EPSILON}class LyraSplitPanel extends LyraElement{constructor(){super(...arguments),this._startPosition=DEFAULT_POSITION,this._orientation="horizontal",this._snapThreshold=DEFAULT_SNAP_THRESHOLD,this.availableSize=0,this.measuredConstraintBounds={min:0,max:0},this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>this.onPointerEnd(event)),this.dividerSourceSnapshots=new Map,this.dividerSourceObserverGeneration=0,this.cachedNormalizedSnapTokens=Object.freeze([]),this.disabled=!1,this._snap="",this.onWindowResize=()=>{this.measureAndSynchronize(!1)},this.onDividerSlotChange=()=>{this.syncDividerSources()},this.onPointerMove=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;if(this.disabled||this.effectiveDirection==="rtl"!==drag.rtl||this.effectiveOrientation!==drag.orientation||this.primary!==drag.primary||!nearlyEqual(this.availableSize,drag.size)){this.stopDragging();return}let delta=separatorDelta(drag.startCoordinate,event,this.effectiveOrientation==="vertical"?"block":"inline",drag.rtl);this.primary==="end"&&(delta*=-1),this.requestReposition(drag.startPrimaryPixels+delta,!0,drag.bounds)&&(drag.acceptedResize=!0)},this.onPointerEnd=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;const bounds=this.constraintBounds(),shouldSettle=event.type==="pointerup"&&drag.acceptedResize&&!this.disabled&&this.effectiveOrientation===drag.orientation&&this.primary===drag.primary&&this.effectiveDirection==="rtl"===drag.rtl&&nearlyEqual(this.availableSize,drag.size)&&nearlyEqual(bounds.min,drag.bounds.min)&&nearlyEqual(bounds.max,drag.bounds.max);this.stopDragging(),shouldSettle&&this.emitResizeChange()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider,resizeValuePercent:LYRA_DEFAULT_resizeValuePercent}}static{this.styles=[LyraElement.styles,styles]}get position(){const start=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);return this.primary==="end"?100-start:start}set position(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels,next=finiteRange(value,DEFAULT_POSITION,0,100);this.pendingPositionInPixels=void 0;const layoutSize=this.measuredLayoutSize();if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next/100*layoutSize,!1,oldPosition,oldPixels);return}this._startPosition=this.primary==="end"?100-next:next,this.preservedPrimaryPixels=void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get positionInPixels(){return this.pendingPositionInPixels!=null?this.pendingPositionInPixels:this.availableSize<=0?0:this.position/100*this.availableSize}set positionInPixels(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels;if(value==null){this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=this.availableSize>0?this.positionInPixels:void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels);return}const fallback=this.positionInPixels??DEFAULT_POSITION/100*this.availableSize,layoutSize=this.measuredLayoutSize(),next=finiteRange(value,fallback,0,layoutSize>0?layoutSize:Number.MAX_VALUE);if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next,!1,oldPosition,oldPixels);return}this.pendingPositionInPixels=next,this.preservedPrimaryPixels=next,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get orientation(){return this._orientation}set orientation(value){const next=value==="vertical"?"vertical":"horizontal";if(next===this._orientation)return;const old=this._orientation,oldVertical=this.vertical;this._orientation=next,this.requestUpdate("orientation",old),this.requestUpdate("vertical",oldVertical)}get vertical(){return this.orientation==="vertical"}set vertical(value){this.orientation=value?"vertical":"horizontal"}get primary(){return this._primary}set primary(value){const next=value==="start"||value==="end"?value:void 0;if(next===this._primary)return;this.stopDragging();const oldPrimary=this._primary,oldPosition=this.position,oldPixels=this.positionInPixels,layoutSize=this.measuredLayoutSize(),referencePixels=layoutSize>0&&!oldPrimary?oldPosition/100*layoutSize:oldPixels;this._primary=next,layoutSize>0?(this.availableSize=layoutSize,this.applyPrimaryPixels(referencePixels,!1,oldPosition,oldPixels)):(this._startPosition=next==="end"?100-oldPosition:oldPosition,this.preservedPrimaryPixels=this.pendingPositionInPixels??oldPixels),this.requestUpdate("primary",oldPrimary)}get snap(){return this._snap}set snap(value){const old=this._snap;this._snap=value??"",this.requestUpdate("snap",old)}get snapThreshold(){return this._snapThreshold}set snapThreshold(value){const old=this._snapThreshold;this._snapThreshold=finiteRange(value,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE),this.requestUpdate("snapThreshold",old)}get effectiveOrientation(){return this.orientation}measuredLayoutSize(){return this.isConnected?this.axisSize(this.baseElement):0}connectedCallback(){const authoredOrientation=this.getAttribute("orientation");super.connectedCallback(),authoredOrientation!==null&&(this.orientation=authoredOrientation==="vertical"?"vertical":"horizontal"),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&(this.syncDividerSources(),this.observeSize(),this.measureAndSynchronize(!1))})}disconnectedCallback(){this.stopDragging(),this.resetDividerSourceObserver(),this.restoreDividerSources(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.syncDividerSources(),this.measureAndSynchronize(!0),this.observeSize()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&this.stopDragging(),(changed.has("orientation")||changed.has("vertical"))&&(this.stopDragging(),this.measureAndSynchronize(!1))}requestSynchronizedUpdate(oldPosition,oldPixels){nearlyEqual(oldPosition,this.position)||this.requestUpdate("position",oldPosition),nearlyEqual(oldPixels,this.positionInPixels)||this.requestUpdate("positionInPixels",oldPixels)}axisSize(element){if(!element)return 0;const rect=element.getBoundingClientRect(),measured=this.effectiveOrientation==="vertical"?rect.height:rect.width;return finiteRange(measured,0,0,Number.MAX_VALUE)}constraintBounds(){const size=this.availableSize,min=finiteRange(this.axisSize(this.minProbe),0,0,size),rawMax=this.maxProbe?this.axisSize(this.maxProbe):size,max=finiteRange(rawMax,size,min,size);return{min,max}}resolvePrimaryPixels(requestedPixels,useSnap,fallbackPixels,bounds=this.constraintBounds()){const size=this.availableSize,proposed=finiteRange(requestedPixels,fallbackPixels??DEFAULT_POSITION/100*size,0,size),snapped=useSnap?this.applySnap(proposed,size):proposed,{min,max}=bounds;return finiteRange(snapped,proposed,min,max)}applyPrimaryPixels(requestedPixels,useSnap,oldPosition=this.position,oldPixels=this.positionInPixels,scheduleUpdate=!0,resolvedPrimaryPixels){const size=this.availableSize;if(size<=0)return this.pendingPositionInPixels=finiteRange(requestedPixels,0,0,Number.MAX_VALUE),this.preservedPrimaryPixels=this.pendingPositionInPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!1;const primaryPixels=resolvedPrimaryPixels??this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels),primaryPercent=primaryPixels/size*100;return this._startPosition=this.primary==="end"?100-primaryPercent:primaryPercent,this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=primaryPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!nearlyEqual(oldPosition,this.position)||!nearlyEqual(oldPixels,this.positionInPixels)}requestReposition(requestedPixels,useSnap,bounds=this.constraintBounds()){if(this.availableSize<=0)return!1;const oldPosition=this.position,oldPixels=this.positionInPixels,primaryPixels=this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels,bounds),position=primaryPixels/this.availableSize*100;if(nearlyEqual(oldPosition,position)&&nearlyEqual(oldPixels,primaryPixels))return!1;const detail=Object.freeze({position,positionInPixels:primaryPixels}),snapshot={drag:this.drag,disabled:this.disabled,primary:this.primary,orientation:this.effectiveOrientation,direction:this.effectiveDirection,size:this.availableSize,snap:this.snap,snapThreshold:this.snapThreshold},requestSequence=++this.resizeRequestSequence;this.resizeWriteGuard.open();const resizeRequest=this.emit("lr-resize-request",detail,{cancelable:!0}),request=this.emit("lr-reposition-request",detail,{cancelable:!0});if(resizeRequest.defaultPrevented||request.defaultPrevented||this.resizeWriteGuard.touched)return!1;const currentBounds=this.constraintBounds();return this.drag!==snapshot.drag||this.resizeRequestSequence!==requestSequence||this.disabled||this.disabled!==snapshot.disabled||this.primary!==snapshot.primary||this.effectiveOrientation!==snapshot.orientation||this.effectiveDirection!==snapshot.direction||!nearlyEqual(this.availableSize,snapshot.size)||this.snap!==snapshot.snap||this.snapThreshold!==snapshot.snapThreshold||!nearlyEqual(this.position,oldPosition)||!nearlyEqual(this.positionInPixels,oldPixels)||!nearlyEqual(currentBounds.min,bounds.min)||!nearlyEqual(currentBounds.max,bounds.max)?(snapshot.drag&&this.drag===snapshot.drag&&this.stopDragging(),!1):this.applyPrimaryPixels(requestedPixels,useSnap,oldPosition,oldPixels,!0,primaryPixels)?(this.emit("lr-resize",Object.freeze({position:this.position,positionInPixels:this.positionInPixels})),this.emit("lr-reposition",null),!0):!1}measureAndSynchronize(initial){const nextSize=this.axisSize(this.baseElement);if(nextSize<=0)return;const oldPosition=this.position,oldPixels=this.positionInPixels,pending=this.pendingPositionInPixels,preserved=this.preservedPrimaryPixels,sizeChanged=!nearlyEqual(this.availableSize,nextSize);this.availableSize=nextSize;const nextBounds=this.constraintBounds();this.drag&&(sizeChanged||!nearlyEqual(nextBounds.min,this.drag.bounds.min)||!nearlyEqual(nextBounds.max,this.drag.bounds.max))&&this.stopDragging(),this.measuredConstraintBounds=nextBounds,pending!=null?this.applyPrimaryPixels(pending,!1,oldPosition,oldPixels,!1):!initial&&sizeChanged&&this.primary&&preserved!=null?this.applyPrimaryPixels(preserved,!1,oldPosition,oldPixels,!1):this.applyPrimaryPixels(this.position/100*nextSize,!1,oldPosition,oldPixels,!1),this.synchronizeMeasuredDom()}synchronizeMeasuredDom(){const startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);if(this.baseElement?.style.setProperty("--_lr-split-panel-start-position",`${startPosition}%`),this.dividerElement){const bounds=this.ariaBounds,position=Math.round(this.position);this.dividerElement.setAttribute("aria-valuenow",String(position)),this.dividerElement.setAttribute("aria-valuetext",this.resizeValueText(position)),this.dividerElement.setAttribute("aria-valuemin",String(Math.round(bounds.min))),this.dividerElement.setAttribute("aria-valuemax",String(Math.round(bounds.max)))}const reflectedPosition=String(this.position);this.getAttribute("position")!==reflectedPosition&&this.setAttribute("position",reflectedPosition)}observeSize(){if(this.resizeObserver||this.resizeView||!this.isConnected)return;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver=new ResizeObserverConstructor(()=>this.measureAndSynchronize(!1)),this.baseElement&&this.resizeObserver.observe(this.baseElement),this.minProbe&&this.resizeObserver.observe(this.minProbe),this.maxProbe&&this.resizeObserver.observe(this.maxProbe);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}snapshotDividerSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert}}adoptDividerSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current)}makeDividerSourceInert(source,snapshot){source.hasAttribute("inert")||source.setAttribute("inert",""),snapshot.appliedInert=source.getAttribute("inert")}restoreDividerSource(source,snapshot){this.adoptDividerSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreDividerSources(){for(const[source,snapshot]of this.dividerSourceSnapshots)this.restoreDividerSource(source,snapshot);this.dividerSourceSnapshots.clear()}resetDividerSourceObserver(){this.dividerSourceObserverGeneration+=1,this.dividerSourceObserver?.disconnect(),this.dividerSourceObserver=void 0,this.dividerSourceObserverDocument=void 0}observeDividerSources(){this.resetDividerSourceObserver();const MutationObserverConstructor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.dividerSourceSnapshots.size===0)return;const generation=this.dividerSourceObserverGeneration,observer=new MutationObserverConstructor(records=>{this.dividerSourceObserver!==observer||this.dividerSourceObserverDocument!==this.ownerDocument||this.dividerSourceObserverGeneration!==generation||!this.isConnected||records.some(record=>this.dividerSourceSnapshots.has(record.target))&&this.syncDividerSources()});this.dividerSourceObserver=observer,this.dividerSourceObserverDocument=this.ownerDocument;for(const source of this.dividerSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}syncDividerSources(){const assigned=new Set(this.dividerSlot?.assignedElements({flatten:!0})??[]);for(const[source,snapshot]of this.dividerSourceSnapshots)this.adoptDividerSourceInert(source,snapshot),assigned.has(source)||(this.restoreDividerSource(source,snapshot),this.dividerSourceSnapshots.delete(source));for(const source of assigned){const snapshot=this.dividerSourceSnapshots.get(source)??this.snapshotDividerSource(source);this.dividerSourceSnapshots.set(source,snapshot),this.adoptDividerSourceInert(source,snapshot),this.makeDividerSourceInert(source,snapshot)}this.observeDividerSources()}resolveNormalizedSnapLength(token,size){const resolved=token.unit==="%"?token.value/100*size:token.value;return Number.isFinite(resolved)&&resolved>=0?resolved:void 0}get normalizedSnapTokens(){const source=typeof this.snap=="string"?this.snap:"";return source===this.normalizedSnapSource?this.cachedNormalizedSnapTokens:(this.normalizedSnapSource=source,this.cachedNormalizedSnapTokens=normalizeSnapTokens(source),this.cachedNormalizedSnapTokens)}applySnap(position,size){const threshold=finiteRange(this.snapThreshold,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE);if(typeof this.snap=="function")try{return finiteRange(this.snap({pos:position,size,snapThreshold:threshold}),position,0,size)}catch{return position}const tokens=this.normalizedSnapTokens;if(tokens.length===0)return position;let nearest=position,nearestDistance=Number.POSITIVE_INFINITY;for(const token of tokens){const point=this.resolveNormalizedSnapLength(token,size);if(point==null||point<0)continue;const candidates=token.repeated?[Math.floor(position/point)*point,Math.round(position/point)*point,Math.ceil(position/point)*point]:[point];for(const candidate of candidates){if(!Number.isFinite(candidate)||candidate<0||candidate>size)continue;const distance=Math.abs(position-candidate);distance<nearestDistance&&(nearest=candidate,nearestDistance=distance)}}return nearestDistance<=threshold?nearest:position}pointerCoordinate(event){return separatorCoordinate(event,this.effectiveOrientation==="vertical"?"block":"inline")}onPointerDown(event){if(this.disabled||this.drag||event.button!==0)return;const primaryPixels=this.positionInPixels;primaryPixels==null||this.availableSize<=0||this.dragController.start(event,event.currentTarget)&&(event.preventDefault(),this.drag={pointerId:event.pointerId,startCoordinate:this.pointerCoordinate(event),startPrimaryPixels:primaryPixels,bounds:this.constraintBounds(),rtl:this.effectiveDirection==="rtl",orientation:this.effectiveOrientation,primary:this.primary,size:this.availableSize,acceptedResize:!1},this.dividerElement?.setAttribute("data-dragging",""))}stopDragging(){const pointerId=this.drag?.pointerId;this.drag=void 0,this.dividerElement?.removeAttribute("data-dragging"),pointerId!=null&&this.dragController.end(pointerId)}emitResizeChange(){const positionInPixels=this.positionInPixels;positionInPixels!=null&&this.emit("lr-resize-change",Object.freeze({position:this.position,positionInPixels}))}onKeyDown(event){if(this.disabled||this.availableSize<=0||event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.positionInPixels;if(current==null)return;let next;const{min,max}=this.constraintBounds();if(event.key==="Home")next=min;else if(event.key==="End")next=max;else{const physicalDirection=separatorArrowDirection(event,this.effectiveOrientation==="vertical"?"block":"inline",this.effectiveDirection==="rtl");if(physicalDirection!==0){const primaryDirection=this.primary==="end"?-physicalDirection:physicalDirection;next=current+primaryDirection*KEYBOARD_STEP_PERCENT*this.availableSize/100}}next!=null&&(event.preventDefault(),this.requestReposition(next,!1)&&this.emitResizeChange())}get separatorLabel(){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;const number=getNumberFormat(this.effectiveLocale);return this.localize("resizeDivider",void 0,{a:number.format(1),b:number.format(2)})}resizeValueText(position){return this.localize("resizeValuePercent",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(position))})}get ariaBounds(){if(this.availableSize<=0)return{min:0,max:100};const bounds=this.measuredConstraintBounds;return{min:bounds.min/this.availableSize*100,max:bounds.max/this.availableSize*100}}render(){const orientation=this.effectiveOrientation,startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100),ariaBounds=this.ariaBounds,position=Math.round(this.position);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate,separatorDelta}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{styles}from"./split-panel.styles.js";import{LYRA_DEFAULT_resizeDivider,LYRA_DEFAULT_resizeValuePercent}from"../../../internal/default-strings/layout.generated.js";const DEFAULT_POSITION=50,DEFAULT_SNAP_THRESHOLD=12,KEYBOARD_STEP_PERCENT=1,MAX_SNAP_SOURCE_CODE_UNITS=16384,MAX_SNAP_TOKENS=256,POSITION_EPSILON=1e-4;import{SNAP_NONE}from"./split-panel-snap.js";const snapConverter={fromAttribute(value){return value??""},toAttribute(value){return typeof value=="string"&&value!==""?value:null}};function isAsciiDigit(code){return code>=48&&code<=57}function matchesAsciiToken(source,index,token){if(index+token.length>source.length)return!1;for(let offset=0;offset<token.length;offset+=1){const sourceCode=source.charCodeAt(index+offset);if((sourceCode>=65&&sourceCode<=90?sourceCode+32:sourceCode)!==token.charCodeAt(offset))return!1}return!0}function isSnapWhitespace(code){return code>=9&&code<=13||code===32||code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipSnapWhitespace(source,start){let cursor=start;for(;cursor<source.length&&isSnapWhitespace(source.charCodeAt(cursor));)cursor+=1;return cursor}function scanSnapLength(source,start){let cursor=start;if(isAsciiDigit(source.charCodeAt(cursor))){for(;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1}else if(source.charCodeAt(cursor)===46&&isAsciiDigit(source.charCodeAt(cursor+1)))for(cursor+=2;isAsciiDigit(source.charCodeAt(cursor));)cursor+=1;else return{end:start+1,recognized:!1};const numberEnd=cursor;let unit;if(source.charCodeAt(cursor)===37?(unit="%",cursor+=1):matchesAsciiToken(source,cursor,"px")&&(unit="px",cursor+=2),unit===void 0)return{end:Math.max(start+1,numberEnd),recognized:!1};const numericValue=Number(source.slice(start,numberEnd));return{end:cursor,recognized:!0,token:Number.isFinite(numericValue)?Object.freeze({value:numericValue,unit}):void 0}}function normalizeSnapTokens(value){const source=value.slice(0,MAX_SNAP_SOURCE_CODE_UNITS),tokens=[];let index=0;for(;index<source.length&&tokens.length<MAX_SNAP_TOKENS;){if(matchesAsciiToken(source,index,"repeat(")){const innerStart=skipSnapWhitespace(source,index+7),scanned2=scanSnapLength(source,innerStart);if(scanned2.recognized){const close=skipSnapWhitespace(source,scanned2.end);if(source.charCodeAt(close)===41){scanned2.token&&tokens.push(Object.freeze({repeated:!0,...scanned2.token})),index=close+1;continue}scanned2.token&&tokens.push(Object.freeze({repeated:!1,...scanned2.token}))}index=Math.max(index+7,scanned2.end);continue}const scanned=scanSnapLength(source,index);scanned.recognized&&scanned.token&&tokens.push(Object.freeze({repeated:!1,...scanned.token})),index=Math.max(index+1,scanned.end)}return Object.freeze(tokens)}function nearlyEqual(left,right){return left===right?!0:left==null||right==null?!1:Math.abs(left-right)<=POSITION_EPSILON}class LyraSplitPanel extends LyraElement{constructor(){super(...arguments),this._startPosition=DEFAULT_POSITION,this._orientation="horizontal",this._snapThreshold=DEFAULT_SNAP_THRESHOLD,this.availableSize=0,this.initialUpdate=!0,this.measuredConstraintBounds={min:0,max:0},this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>this.onPointerEnd(event)),this.dividerSourceSnapshots=new Map,this.dividerSourceObserverGeneration=0,this.cachedNormalizedSnapTokens=Object.freeze([]),this.disabled=!1,this._snap="",this.onWindowResize=()=>{this.measureAndSynchronize(!1)},this.onDividerSlotChange=()=>{this.syncDividerSources()},this.onPointerMove=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;if(this.disabled||this.effectiveDirection==="rtl"!==drag.rtl||this.effectiveOrientation!==drag.orientation||this.primary!==drag.primary||!nearlyEqual(this.availableSize,drag.size)){this.stopDragging();return}let delta=separatorDelta(drag.startCoordinate,event,this.effectiveOrientation==="vertical"?"block":"inline",drag.rtl);this.primary==="end"&&(delta*=-1),this.requestReposition(drag.startPrimaryPixels+delta,!0,drag.bounds)&&(drag.acceptedResize=!0)},this.onPointerEnd=event=>{const drag=this.drag;if(!drag||event.pointerId!==drag.pointerId)return;const bounds=this.constraintBounds(),shouldSettle=event.type==="pointerup"&&drag.acceptedResize&&!this.disabled&&this.effectiveOrientation===drag.orientation&&this.primary===drag.primary&&this.effectiveDirection==="rtl"===drag.rtl&&nearlyEqual(this.availableSize,drag.size)&&nearlyEqual(bounds.min,drag.bounds.min)&&nearlyEqual(bounds.max,drag.bounds.max);this.stopDragging(),shouldSettle&&this.emitResizeChange()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider,resizeValuePercent:LYRA_DEFAULT_resizeValuePercent}}static{this.styles=[LyraElement.styles,styles]}get position(){const start=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);return this.primary==="end"?100-start:start}set position(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels,next=finiteRange(value,DEFAULT_POSITION,0,100);this.pendingPositionInPixels=void 0;const layoutSize=this.measuredLayoutSize();if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next/100*layoutSize,!1,oldPosition,oldPixels);return}this._startPosition=this.primary==="end"?100-next:next,this.preservedPrimaryPixels=void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get positionInPixels(){return this.pendingPositionInPixels!=null?this.pendingPositionInPixels:this.availableSize<=0?0:this.position/100*this.availableSize}set positionInPixels(value){markVetoGuardWrite(this.resizeWriteGuard);const oldPosition=this.position,oldPixels=this.positionInPixels;if(value==null){this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=this.availableSize>0?this.positionInPixels:void 0,this.requestSynchronizedUpdate(oldPosition,oldPixels);return}const fallback=this.positionInPixels??DEFAULT_POSITION/100*this.availableSize,layoutSize=this.measuredLayoutSize(),next=finiteRange(value,fallback,0,layoutSize>0?layoutSize:Number.MAX_VALUE);if(layoutSize>0){this.availableSize=layoutSize,this.applyPrimaryPixels(next,!1,oldPosition,oldPixels);return}this.pendingPositionInPixels=next,this.preservedPrimaryPixels=next,this.requestSynchronizedUpdate(oldPosition,oldPixels)}get orientation(){return this._orientation}set orientation(value){const next=value==="vertical"?"vertical":"horizontal";if(next===this._orientation)return;const old=this._orientation,oldVertical=this.vertical;this._orientation=next,this.requestUpdate("orientation",old),this.requestUpdate("vertical",oldVertical)}get vertical(){return this.orientation==="vertical"}set vertical(value){this.orientation=value?"vertical":"horizontal"}get primary(){return this._primary}set primary(value){const next=value==="start"||value==="end"?value:void 0;if(next===this._primary)return;this.stopDragging();const oldPrimary=this._primary,oldPosition=this.position,oldPixels=this.positionInPixels,layoutSize=this.measuredLayoutSize(),referencePixels=layoutSize>0&&!oldPrimary?oldPosition/100*layoutSize:oldPixels;this._primary=next,layoutSize>0?(this.availableSize=layoutSize,this.applyPrimaryPixels(referencePixels,!1,oldPosition,oldPixels)):(this._startPosition=next==="end"?100-oldPosition:oldPosition,this.preservedPrimaryPixels=this.pendingPositionInPixels??oldPixels),this.requestUpdate("primary",oldPrimary)}get snap(){return this._snap}set snap(value){const old=this._snap;this._snap=value??"",this.requestUpdate("snap",old)}get snapThreshold(){return this._snapThreshold}set snapThreshold(value){const old=this._snapThreshold;this._snapThreshold=finiteRange(value,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE),this.requestUpdate("snapThreshold",old)}get effectiveOrientation(){return this.orientation}measuredLayoutSize(){return this.isConnected?this.axisSize(this.baseElement):0}connectedCallback(){const authoredOrientation=this.getAttribute("orientation");super.connectedCallback(),authoredOrientation!==null&&(this.orientation=authoredOrientation==="vertical"?"vertical":"horizontal"),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&(this.syncDividerSources(),this.observeSize(),this.measureAndSynchronize(!1))})}disconnectedCallback(){this.stopDragging(),this.resetDividerSourceObserver(),this.restoreDividerSources(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeView?.removeEventListener("resize",this.onWindowResize),this.resizeView=void 0,super.disconnectedCallback()}firstUpdated(changed){super.firstUpdated(changed),this.syncDividerSources(),this.measureAndSynchronize(!0),this.observeSize()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&this.stopDragging(),!this.initialUpdate&&(changed.has("orientation")||changed.has("vertical"))&&(this.stopDragging(),this.measureAndSynchronize(!1)),this.initialUpdate=!1}requestSynchronizedUpdate(oldPosition,oldPixels){nearlyEqual(oldPosition,this.position)||this.requestUpdate("position",oldPosition),nearlyEqual(oldPixels,this.positionInPixels)||this.requestUpdate("positionInPixels",oldPixels)}axisSize(element){if(!element)return 0;const rect=element.getBoundingClientRect(),measured=this.effectiveOrientation==="vertical"?rect.height:rect.width;return finiteRange(measured,0,0,Number.MAX_VALUE)}constraintBounds(){const size=this.availableSize,min=finiteRange(this.axisSize(this.minProbe),0,0,size),rawMax=this.maxProbe?this.axisSize(this.maxProbe):size,max=finiteRange(rawMax,size,min,size);return{min,max}}resolvePrimaryPixels(requestedPixels,useSnap,fallbackPixels,bounds=this.constraintBounds()){const size=this.availableSize,proposed=finiteRange(requestedPixels,fallbackPixels??DEFAULT_POSITION/100*size,0,size),snapped=useSnap?this.applySnap(proposed,size):proposed,{min,max}=bounds;return finiteRange(snapped,proposed,min,max)}applyPrimaryPixels(requestedPixels,useSnap,oldPosition=this.position,oldPixels=this.positionInPixels,scheduleUpdate=!0,resolvedPrimaryPixels){const size=this.availableSize;if(size<=0)return this.pendingPositionInPixels=finiteRange(requestedPixels,0,0,Number.MAX_VALUE),this.preservedPrimaryPixels=this.pendingPositionInPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!1;const primaryPixels=resolvedPrimaryPixels??this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels),primaryPercent=primaryPixels/size*100;return this._startPosition=this.primary==="end"?100-primaryPercent:primaryPercent,this.pendingPositionInPixels=void 0,this.preservedPrimaryPixels=primaryPixels,scheduleUpdate&&this.requestSynchronizedUpdate(oldPosition,oldPixels),!nearlyEqual(oldPosition,this.position)||!nearlyEqual(oldPixels,this.positionInPixels)}requestReposition(requestedPixels,useSnap,bounds=this.constraintBounds()){if(this.availableSize<=0)return!1;const oldPosition=this.position,oldPixels=this.positionInPixels,primaryPixels=this.resolvePrimaryPixels(requestedPixels,useSnap,oldPixels,bounds),position=primaryPixels/this.availableSize*100;if(nearlyEqual(oldPosition,position)&&nearlyEqual(oldPixels,primaryPixels))return!1;const detail=Object.freeze({position,positionInPixels:primaryPixels}),snapshot={drag:this.drag,disabled:this.disabled,primary:this.primary,orientation:this.effectiveOrientation,direction:this.effectiveDirection,size:this.availableSize,snap:this.snap,snapThreshold:this.snapThreshold},requestSequence=++this.resizeRequestSequence;this.resizeWriteGuard.open();const resizeRequest=this.emit("lr-resize-request",detail,{cancelable:!0}),request=this.emit("lr-reposition-request",detail,{cancelable:!0});if(resizeRequest.defaultPrevented||request.defaultPrevented||this.resizeWriteGuard.touched)return!1;const currentBounds=this.constraintBounds();return this.drag!==snapshot.drag||this.resizeRequestSequence!==requestSequence||this.disabled||this.disabled!==snapshot.disabled||this.primary!==snapshot.primary||this.effectiveOrientation!==snapshot.orientation||this.effectiveDirection!==snapshot.direction||!nearlyEqual(this.availableSize,snapshot.size)||this.snap!==snapshot.snap||this.snapThreshold!==snapshot.snapThreshold||!nearlyEqual(this.position,oldPosition)||!nearlyEqual(this.positionInPixels,oldPixels)||!nearlyEqual(currentBounds.min,bounds.min)||!nearlyEqual(currentBounds.max,bounds.max)?(snapshot.drag&&this.drag===snapshot.drag&&this.stopDragging(),!1):this.applyPrimaryPixels(requestedPixels,useSnap,oldPosition,oldPixels,!0,primaryPixels)?(this.emit("lr-resize",Object.freeze({position:this.position,positionInPixels:this.positionInPixels})),this.emit("lr-reposition",null),!0):!1}measureAndSynchronize(initial){const nextSize=this.axisSize(this.baseElement);if(nextSize<=0)return;const oldPosition=this.position,oldPixels=this.positionInPixels,pending=this.pendingPositionInPixels,preserved=this.preservedPrimaryPixels,sizeChanged=!nearlyEqual(this.availableSize,nextSize);this.availableSize=nextSize;const nextBounds=this.constraintBounds();this.drag&&(sizeChanged||!nearlyEqual(nextBounds.min,this.drag.bounds.min)||!nearlyEqual(nextBounds.max,this.drag.bounds.max))&&this.stopDragging(),this.measuredConstraintBounds=nextBounds,pending!=null?this.applyPrimaryPixels(pending,!1,oldPosition,oldPixels,!1):!initial&&sizeChanged&&this.primary&&preserved!=null?this.applyPrimaryPixels(preserved,!1,oldPosition,oldPixels,!1):this.applyPrimaryPixels(this.position/100*nextSize,!1,oldPosition,oldPixels,!1),this.synchronizeMeasuredDom()}synchronizeMeasuredDom(){const startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100);if(this.baseElement?.style.setProperty("--_lr-split-panel-start-position",`${startPosition}%`),this.dividerElement){const bounds=this.ariaBounds,position=Math.round(this.position);this.dividerElement.setAttribute("aria-valuenow",String(position)),this.dividerElement.setAttribute("aria-valuetext",this.resizeValueText(position)),this.dividerElement.setAttribute("aria-valuemin",String(Math.round(bounds.min))),this.dividerElement.setAttribute("aria-valuemax",String(Math.round(bounds.max)))}const reflectedPosition=String(this.position);this.getAttribute("position")!==reflectedPosition&&this.setAttribute("position",reflectedPosition)}observeSize(){if(this.resizeObserver||this.resizeView||!this.isConnected)return;const view=this.ownerDocument.defaultView,ResizeObserverConstructor=view?.ResizeObserver;if(ResizeObserverConstructor){this.resizeObserver=new ResizeObserverConstructor(()=>this.measureAndSynchronize(!1)),this.baseElement&&this.resizeObserver.observe(this.baseElement),this.minProbe&&this.resizeObserver.observe(this.minProbe),this.maxProbe&&this.resizeObserver.observe(this.maxProbe);return}view&&(this.resizeView=view,view.addEventListener("resize",this.onWindowResize))}snapshotDividerSource(source){const inert=source.getAttribute("inert");return{inert,appliedInert:inert}}adoptDividerSourceInert(source,snapshot){const current=source.getAttribute("inert");current!==snapshot.appliedInert&&(snapshot.inert=current)}makeDividerSourceInert(source,snapshot){source.hasAttribute("inert")||source.setAttribute("inert",""),snapshot.appliedInert=source.getAttribute("inert")}restoreDividerSource(source,snapshot){this.adoptDividerSourceInert(source,snapshot),snapshot.inert===null?source.removeAttribute("inert"):source.setAttribute("inert",snapshot.inert)}restoreDividerSources(){for(const[source,snapshot]of this.dividerSourceSnapshots)this.restoreDividerSource(source,snapshot);this.dividerSourceSnapshots.clear()}resetDividerSourceObserver(){this.dividerSourceObserverGeneration+=1,this.dividerSourceObserver?.disconnect(),this.dividerSourceObserver=void 0,this.dividerSourceObserverDocument=void 0}observeDividerSources(){this.resetDividerSourceObserver();const MutationObserverConstructor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.dividerSourceSnapshots.size===0)return;const generation=this.dividerSourceObserverGeneration,observer=new MutationObserverConstructor(records=>{this.dividerSourceObserver!==observer||this.dividerSourceObserverDocument!==this.ownerDocument||this.dividerSourceObserverGeneration!==generation||!this.isConnected||records.some(record=>this.dividerSourceSnapshots.has(record.target))&&this.syncDividerSources()});this.dividerSourceObserver=observer,this.dividerSourceObserverDocument=this.ownerDocument;for(const source of this.dividerSourceSnapshots.keys())observer.observe(source,{attributes:!0,attributeFilter:["inert"]})}syncDividerSources(){const assigned=new Set(this.dividerSlot?.assignedElements({flatten:!0})??[]);for(const[source,snapshot]of this.dividerSourceSnapshots)this.adoptDividerSourceInert(source,snapshot),assigned.has(source)||(this.restoreDividerSource(source,snapshot),this.dividerSourceSnapshots.delete(source));for(const source of assigned){const snapshot=this.dividerSourceSnapshots.get(source)??this.snapshotDividerSource(source);this.dividerSourceSnapshots.set(source,snapshot),this.adoptDividerSourceInert(source,snapshot),this.makeDividerSourceInert(source,snapshot)}this.observeDividerSources()}resolveNormalizedSnapLength(token,size){const resolved=token.unit==="%"?token.value/100*size:token.value;return Number.isFinite(resolved)&&resolved>=0?resolved:void 0}get normalizedSnapTokens(){const source=typeof this.snap=="string"?this.snap:"";return source===this.normalizedSnapSource?this.cachedNormalizedSnapTokens:(this.normalizedSnapSource=source,this.cachedNormalizedSnapTokens=normalizeSnapTokens(source),this.cachedNormalizedSnapTokens)}applySnap(position,size){const threshold=finiteRange(this.snapThreshold,DEFAULT_SNAP_THRESHOLD,0,Number.MAX_VALUE);if(typeof this.snap=="function")try{return finiteRange(this.snap({pos:position,size,snapThreshold:threshold}),position,0,size)}catch{return position}const tokens=this.normalizedSnapTokens;if(tokens.length===0)return position;let nearest=position,nearestDistance=Number.POSITIVE_INFINITY;for(const token of tokens){const point=this.resolveNormalizedSnapLength(token,size);if(point==null||point<0)continue;const candidates=token.repeated?[Math.floor(position/point)*point,Math.round(position/point)*point,Math.ceil(position/point)*point]:[point];for(const candidate of candidates){if(!Number.isFinite(candidate)||candidate<0||candidate>size)continue;const distance=Math.abs(position-candidate);distance<nearestDistance&&(nearest=candidate,nearestDistance=distance)}}return nearestDistance<=threshold?nearest:position}pointerCoordinate(event){return separatorCoordinate(event,this.effectiveOrientation==="vertical"?"block":"inline")}onPointerDown(event){if(this.disabled||this.drag||event.button!==0)return;const primaryPixels=this.positionInPixels;primaryPixels==null||this.availableSize<=0||this.dragController.start(event,event.currentTarget)&&(event.preventDefault(),this.drag={pointerId:event.pointerId,startCoordinate:this.pointerCoordinate(event),startPrimaryPixels:primaryPixels,bounds:this.constraintBounds(),rtl:this.effectiveDirection==="rtl",orientation:this.effectiveOrientation,primary:this.primary,size:this.availableSize,acceptedResize:!1},this.dividerElement?.setAttribute("data-dragging",""))}stopDragging(){const pointerId=this.drag?.pointerId;this.drag=void 0,this.dividerElement?.removeAttribute("data-dragging"),pointerId!=null&&this.dragController.end(pointerId)}emitResizeChange(){const positionInPixels=this.positionInPixels;positionInPixels!=null&&this.emit("lr-resize-change",Object.freeze({position:this.position,positionInPixels}))}onKeyDown(event){if(this.disabled||this.availableSize<=0||event.altKey||event.ctrlKey||event.metaKey||event.isComposing)return;const current=this.positionInPixels;if(current==null)return;let next;const{min,max}=this.constraintBounds();if(event.key==="Home")next=min;else if(event.key==="End")next=max;else{const physicalDirection=separatorArrowDirection(event,this.effectiveOrientation==="vertical"?"block":"inline",this.effectiveDirection==="rtl");if(physicalDirection!==0){const primaryDirection=this.primary==="end"?-physicalDirection:physicalDirection;next=current+primaryDirection*KEYBOARD_STEP_PERCENT*this.availableSize/100}}next!=null&&(event.preventDefault(),this.requestReposition(next,!1)&&this.emitResizeChange())}get separatorLabel(){const hostLabel=this.getAttribute("aria-label");if(hostLabel!==null)return hostLabel;const number=getNumberFormat(this.effectiveLocale);return this.localize("resizeDivider",void 0,{a:number.format(1),b:number.format(2)})}resizeValueText(position){return this.localize("resizeValuePercent",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(position))})}get ariaBounds(){if(this.availableSize<=0)return{min:0,max:100};const bounds=this.measuredConstraintBounds;return{min:bounds.min/this.availableSize*100,max:bounds.max/this.availableSize*100}}render(){const orientation=this.effectiveOrientation,startPosition=finiteRange(this._startPosition,DEFAULT_POSITION,0,100),ariaBounds=this.ariaBounds,position=Math.round(this.position);return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
data-orientation=${orientation}
|
|
@@ -162,4 +162,4 @@ readonly:boolean;
|
|
|
162
162
|
accessibleLabel:string|null;private _effectiveOrientation;private resizeObserver?;private resizeObservedElement?;private resizeObserverOwnerDocument?;private resizeObserverGeneration;private pendingStepFocus?;private baseEl?;private measuredInlineSize;private orientationBreakpoints;private scrollOverflow;
|
|
163
163
|
/** The live layout/navigation axis after applying `orientationBreakpoint` -- identical to
|
|
164
164
|
* `orientation` whenever that's unset. See the class doc. */
|
|
165
|
-
get effectiveOrientation():LyraOrientation;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private updateEffectiveOrientation;private armResizeObserver;private resetResizeObserver;private selectStep;private focusStep;private onKeyDown;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-stepper':LyraStepper;}}
|
|
165
|
+
get effectiveOrientation():LyraOrientation;connectedCallback():void;private seedInlineSize;private orientationInlineSize;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncScrollTabStop;private updateEffectiveOrientation;private armResizeObserver;private resetResizeObserver;private selectStep;private focusStep;private onKeyDown;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-stepper':LyraStepper;}}
|
|
@@ -12,7 +12,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
12
12
|
focusable="false"
|
|
13
13
|
>
|
|
14
14
|
<polyline points="5 12.5 10 17.5 19 6.5"></polyline>
|
|
15
|
-
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.readonly=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.
|
|
15
|
+
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.readonly=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.orientationInlineSize(),!0)),this.scrollOverflow=observeScrollOverflow(this,()=>this.baseEl,()=>this.syncScrollTabStop()),this.onKeyDown=e=>{if(this.readonly||e.isComposing||e.keyCode===229||e.altKey||e.ctrlKey||e.metaKey)return;const navigable=this.steps.map((step,index)=>({step,index})).filter(({step})=>!step.disabled);if(navigable.length===0)return;const focused=shadowFocusTarget(this),focusedIndex=Number(focused?.dataset.index),currentIndex=navigable.findIndex(item=>item.index===focusedIndex);if(e.key==="Enter"||e.key===" "){if(e.preventDefault(),currentIndex>=0){const target=navigable[currentIndex];this.selectStep(target.step,target.index)}return}const targetIndex=resolveListMove(e,{count:navigable.length,current:currentIndex,orientation:this.effectiveOrientation==="vertical"?"vertical":"horizontal",direction:this.effectiveDirection,wrap:!1,clamp:!0,backwardFromMissing:"first"});targetIndex!==null&&(e.preventDefault(),this.focusStep(navigable[targetIndex].index))}}static{this.styles=[LyraElement.styles,scrollOverflowFadeStyles,styles]}get steps(){return this.effectiveSteps}set steps(value){if(value===this.stepsSource||value===this.effectiveSteps)return;this.stepsSource=value;const previous=this.effectiveSteps;this.effectiveSteps=snapshotSteps(value),this.requestUpdate("steps",previous)}get effectiveOrientation(){return this._effectiveOrientation}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.orientationBreakpoints.containerObservationEnabled&&this.seedInlineSize(),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}seedInlineSize(){const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth)}orientationInlineSize(){return this.orientationBreakpoints.containerObservationEnabled?this.baseEl?.clientWidth??this.measuredInlineSize:this.measuredInlineSize}disconnectedCallback(){super.disconnectedCallback(),this.resetResizeObserver()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),changed.has("steps")){const focusedStep=shadowFocusTarget(this);focusedStep?.getAttribute("part")==="step"&&(this.pendingStepFocus={stepId:focusedStep.dataset.stepId??"",index:Number(focusedStep.dataset.index)})}(changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.orientationBreakpoints.configure(this.orientationBreakpoint,this.orientationBreakpointBasis),!this.hasUpdated&&this.isConnected&&this.orientationBreakpoints.containerObservationEnabled&&this.seedInlineSize(),(changed.has("orientation")||changed.has("narrowOrientation")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.updateEffectiveOrientation(this.orientationInlineSize(),this.hasUpdated&&this.orientationBreakpointBasis==="viewport")}updated(changed){super.updated(changed);const base=this.renderRoot.querySelector('[part~="base"]')??void 0;if(syncAriaDescribedByElements(this,base,this.getAttribute("aria-describedby")),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="step"]')),this.syncScrollTabStop(),this.pendingStepFocus!==void 0){const focusedOccurrence=this.pendingStepFocus;this.pendingStepFocus=void 0;const enabledIdentityMatches=[...this.renderRoot.querySelectorAll('[part="step"]')].filter(step=>step.dataset.stepId===focusedOccurrence.stepId&&step.getAttribute("aria-disabled")!=="true");(enabledIdentityMatches.find(step=>Number(step.dataset.index)===focusedOccurrence.index)??(enabledIdentityMatches.length===1?enabledIdentityMatches[0]:void 0)??this.renderRoot.querySelector('[part="step"][tabindex="0"]'))?.focus()}(changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&(this.orientationBreakpoints.containerObservationEnabled?this.armResizeObserver():this.resetResizeObserver())}syncScrollTabStop(){const base=this.baseEl;if(!base)return;const scrollable=this.effectiveOrientation==="horizontal"&&base.hasAttribute(SCROLL_OVERFLOW_ATTRIBUTE);this.readonly&&scrollable?base.setAttribute("tabindex","0"):base.removeAttribute("tabindex")}updateEffectiveOrientation(width,emitOnChange){const next=this.orientationBreakpoints.isBelow(width)?this.narrowOrientation:this.orientation;this.orientationBreakpoints.active?this.setAttribute("data-effective-orientation",next):this.removeAttribute("data-effective-orientation"),next!==this._effectiveOrientation&&(this._effectiveOrientation=next,this.requestUpdate(),emitOnChange&&this.emit("lr-stepper-orientation-change",{orientation:next}))}armResizeObserver(){const observedElement=this.baseEl;if(!this.isConnected||!observedElement)return;const ownerDocument=this.ownerDocument;if(this.resizeObserver&&this.resizeObservedElement===observedElement&&this.resizeObserverOwnerDocument===ownerDocument)return;this.resetResizeObserver();const ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverConstructor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverConstructor(entries=>{const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:observedElement.getBoundingClientRect().width;ownerDocument.defaultView?.requestAnimationFrame(()=>{this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.baseEl!==observedElement||(this.measuredInlineSize=width,this.updateEffectiveOrientation(width,!0))})});this.resizeObserver=observer,this.resizeObservedElement=observedElement,this.resizeObserverOwnerDocument=ownerDocument,observer.observe(observedElement)}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObservedElement=void 0,this.resizeObserverOwnerDocument=void 0}selectStep(step,index){this.readonly||step.disabled||this.emit("lr-step-select",{stepId:step.stepId,index})}focusStep(index){this.renderRoot.querySelector(`[part="step"][data-index="${index}"]`)?.focus()}render(){const currentIndex=this.steps.findIndex(step=>step.state==="current"),rovingIndex=this.readonly?-1:currentIndex>=0&&!this.steps[currentIndex].disabled?currentIndex:this.steps.findIndex(step=>!step.disabled),numberFormat=getNumberFormat(this.effectiveLocale),stepGlyphs=(step,index)=>html`${step.icon!==void 0?html`<span part="step-icon" aria-hidden="true" inert
|
|
16
16
|
>${step.icon}</span
|
|
17
17
|
>`:nothing}
|
|
18
18
|
${step.state==="completed"?checkmarkGlyph():html`<span part="step-index"
|
|
@@ -168,4 +168,4 @@ get views():readonly LyraWidgetView[];set views(value:readonly LyraWidgetView[])
|
|
|
168
168
|
/** The currently active view's `viewId` -- defaults to the first entry of `views` (or `''` when
|
|
169
169
|
* `views` is empty). Settable directly by a consumer wanting to control the active view
|
|
170
170
|
* externally; also updated internally when a view toggle is clicked. */
|
|
171
|
-
activeViewId:string;private readonly slotPresence;private labelSlotText?;private overlayHandle?;private readonly nativeModal;private explicitTrigger?;private fullscreenOpener?;private readonly labelTextObserver;private ownerRealmGeneration;private readonly bodyId;private focusedViewIdBeforeUpdate?;private get storageFullKey();private persistReady;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateFullscreenOverlay;private deactivateFullscreenOverlay;private onLabelSlotChange;private syncLabelSlot;private readLabelSlotText;private setActiveView;private dispatchingCollapse;private requestCollapse;private toggleCollapsed;private requestFullscreenChange;private toggleFullscreen;private dismissFullscreen;private onBackdropClick;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-widget':LyraWidget;}}
|
|
171
|
+
activeViewId:string;private readonly slotPresence;private labelSlotText?;private overlayHandle?;private readonly nativeModal;private readonly modalSurface;private explicitTrigger?;private fullscreenOpener?;private readonly labelTextObserver;private ownerRealmGeneration;private readonly bodyId;private focusedViewIdBeforeUpdate?;private get storageFullKey();private persistReady;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private resetOwnerRealmWork;private queueOwnerMicrotask;private activateFullscreenOverlay;private deactivateFullscreenOverlay;private onLabelSlotChange;private syncLabelSlot;private readLabelSlotText;private setActiveView;private dispatchingCollapse;private requestCollapse;private toggleCollapsed;private requestFullscreenChange;private toggleFullscreen;private dismissFullscreen;private onBackdropClick;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-widget':LyraWidget;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.nativeModal.show()}}),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&this.nativeModal.show();const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.nativeModal.show(),this.overlayHandle?.focusInitial()})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork(),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.nativeModal.hide(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.nativeModal.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.nativeModal.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>this.emit("lr-toggle-request",proposal,init),guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{modalHostStyles}from"../../../internal/modal-host.styles.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{cancelDeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings/layout.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}const collapseWriteGuards=new WeakMap;function collapseWriteGuardFor(widget){let guard=collapseWriteGuards.get(widget);return guard||(guard=new VetoWriteGuard,collapseWriteGuards.set(widget,guard)),guard}function installSynchronousCollapsedReflection(prototype){const installed=Object.getOwnPropertyDescriptor(prototype,"collapsed"),installedSet=installed.set;Object.defineProperty(prototype,"collapsed",{...installed,set(next){installedSet.call(this,next),markVetoGuardWrite(collapseWriteGuardFor(this)),this.toggleAttribute("collapsed",this.collapsed)}})}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.size="m",this.effectiveViews=Object.freeze([]),this.activeViewId="",this.slotPresence=new SlotPresenceController(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen()},onUnexpectedClose:()=>{this.overlayHandle?.isTopmost()&&this.dismissFullscreen(),this.fullscreen&&this.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal),this.labelTextObserver=new AccessibleTextController(this,[],()=>{const assigned=this.shadowRoot?.querySelector('slot[name="label"]')?.assignedElements({flatten:!0})??[];this.syncLabelSlot(assigned)},["alt","aria-labelledby","slot"],!1),this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.setActiveView=viewId=>{if(viewId!==this.activeViewId){if(this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented)return;this.activeViewId=viewId,this.emit("lr-view-change",{viewId})}this.emit("lr-activate",{value:viewId})},this.dispatchingCollapse=!1,this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,modalHostStyles,scrollOverflowFadeStyles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}static{definePersistedProperty(this.prototype,"collapsed",{initial:!1,attribute:!0,type:Boolean,reflect:!0,coerce:next=>!!next}),installSynchronousCollapsedReflection(this.prototype)}get views(){return this.effectiveViews}set views(value){if(value===this.viewsSource||value===this.effectiveViews)return;this.viewsSource=value;const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.labelSlotText=this.readLabelSlotText(labelChildren);const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!isPersistedPropertyExplicitlySet(this,"collapsed")&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;if(!views.some(view=>view.viewId===this.activeViewId)){const forcedBySibling=this.hasUpdated&&changed.has("views")&&!changed.has("activeViewId");this.activeViewId=views[0]?.viewId??"",forcedBySibling&&this.emit("lr-view-change",{viewId:this.activeViewId})}}}updated(changed){super.updated(changed),this.fullscreen&&(this.overlayHandle?.resume(),this.modalSurface.show());const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>{this.fullscreen&&(this.modalSurface.show(),this.overlayHandle?.focusInitial())})),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){this.resetOwnerRealmWork(),cancelDeferredFocusReturn(this),super.disconnectedCallback(),this.modalSurface.disconnect(),this.overlayHandle?.suspend()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork();const slot=this.shadowRoot?.querySelector('slot[name="label"]');this.isConnected&&slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0})),this.labelTextObserver.adopted()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.labelTextObserver.setEnabled(!1)}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.modalSurface.prepare(),this.fullscreenOpener=this.explicitTrigger??captureFocusReturnOpener(this),this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0,deferredReturn:()=>{const opener=this.fullscreenOpener;return opener?{candidates:()=>[opener],isCurrent:()=>!this.fullscreen}:void 0}}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.modalSurface.hide(),this.nativeModal.prepare(!1),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.fullscreenOpener=void 0}syncLabelSlot(assigned){this.labelSlotText=this.readLabelSlotText(assigned),this.labelTextObserver.setEnabled(assigned.length>0),this.labelTextObserver.bind()}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}requestCollapse(next){if(this.dispatchingCollapse)return;const previous=this.collapsed;this.dispatchingCollapse=!0;try{requestThenCommit({requestDetail:{expanded:!next},emitRequest:(proposal,init)=>this.emit("lr-toggle-request",proposal,init),guard:collapseWriteGuardFor(this),commit:()=>{this.collapsed===previous&&(this.collapsed=next,this.emit("lr-toggle",{expanded:!next}))}})}finally{this.dispatchingCollapse=!1}}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return this.nativeModal.render(html`
|
|
2
2
|
${this.fullscreen?html`<div
|
|
3
3
|
part="backdrop"
|
|
4
4
|
style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display:
|
|
1
|
+
import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: flex; flex-direction: column; min-inline-size: 0; max-inline-size: 100%; --_lr-file-input-font-size: var(--lr-form-control-font-size); --_lr-file-input-dropzone-font-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-padding: var(--lr-space-l); --_lr-file-input-detail-font-size: var(--lr-font-size-sm); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([size="2xs"]), :host([size="xs"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xs); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-padding: var(--lr-space-s); --_lr-file-input-detail-font-size: var(--lr-font-size-2xs); } :host([size="s"]), :host([size="small"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-padding: var(--lr-space-m); --_lr-file-input-detail-font-size: var(--lr-font-size-xs); } :host([size="l"]), :host([size="large"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-2xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-md-sm); } :host([size="xl"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-3xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-m); } [part="form-control"] { display: flex; flex-direction: column; flex: 1; min-inline-size: 0; max-inline-size: 100%; } [part~="form-control-label"] { display: block; min-inline-size: 0; margin-block-end: var(--lr-space-xs); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); font-weight: var(--lr-font-weight-semibold); overflow-wrap: anywhere; } [part~="form-control-label"][hidden], [part="hint"][hidden], [part="error"][hidden] { display: none; } ${formControlRequiredMarker} .dropzone { position: relative; display: grid; flex: 1; min-inline-size: 0; } [part~="file-input"] { grid-area: 1 / 1; inline-size: 100%; ${iconHitTarget} box-sizing: border-box; font: inherit; cursor: pointer; appearance: none; padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); border: var(--lr-border-width-medium) dashed var(--lr-file-input-dropzone-border-color, var(--lr-color-border)); border-radius: var(--lr-file-input-radius, var(--lr-radius)); background: var(--lr-file-input-dropzone-fill, var(--lr-color-surface)); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); transition: border-color var(--lr-transition-fast), background-color var(--lr-transition-fast); } .dropzone-content { grid-area: 1 / 1; z-index: var(--lr-layer-content); min-inline-size: 0; max-inline-size: 100%; box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--lr-file-input-gap, var(--lr-space-xs)); padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); color: var(--lr-color-text-quiet); text-align: center; font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); overflow-wrap: anywhere; pointer-events: none; } [part="dropzone-icon"] { display: inline-flex; align-items: center; justify-content: center; font-size: var( --lr-file-input-dropzone-icon-size, var(--_lr-file-input-dropzone-icon-size) ); } [part="dropzone-text"] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } ::slotted(*) { max-inline-size: 100%; min-inline-size: 0; pointer-events: auto; } :host(:is([size='s'], [size='small'])) [part~='file-input'], :host(:is([size='s'], [size='small'])) .dropzone-content { padding: var(--lr-file-input-compact-padding, var(--lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding))); font-size: var(--lr-file-input-compact-font-size, var(--lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size))); } :host(:is([size='s'], [size='small'])) .dropzone-content { gap: var(--lr-file-input-compact-gap, var(--lr-file-input-gap, var(--lr-space-xs))); } [part~="file-input"][data-drag-state="accept"] { border-color: var( --lr-file-input-accept-border-color, var(--lr-color-success) ); background: var( --lr-file-input-accept-bg, color-mix(in srgb, var(--lr-color-success) 8%, transparent) ); } [part~="file-input"][data-drag-state="reject"] { border-color: var( --lr-file-input-reject-border-color, var(--lr-color-danger) ); background: var( --lr-file-input-reject-bg, color-mix(in srgb, var(--lr-color-danger) 8%, transparent) ); } @media (forced-colors: active) { [part~="file-input"][data-drag-state="accept"] { border-color: Highlight; border-style: double; outline: var(--lr-border-width-thin) solid Highlight; outline-offset: calc(-1 * var(--lr-border-width-medium)); } [part~="file-input"][data-drag-state="reject"] { border-color: CanvasText; border-style: dotted; outline: var(--lr-border-width-medium) double CanvasText; outline-offset: calc(-1 * var(--lr-border-width-medium)); } } :host(:not(:disabled)) [part~="file-input"]:hover { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) .dropzone:hover [part~="file-input"] { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) [part~="file-input"]:active { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } :host(:not(:disabled)) .dropzone:active [part~="file-input"] { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part~="file-input"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part~="file-input"]:focus { ${formControlFocusHalo} } :host(:disabled) [part~="file-input"] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="rejection"] { min-inline-size: 0; max-inline-size: 100%; margin-block: var(--lr-space-2xs) 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); text-align: start; overflow-wrap: anywhere; } [part="rejection"] ul { margin: 0; padding-inline-start: var(--lr-space-m); } [part="file-list"] { display: grid; gap: var(--lr-space-xs); margin-block-start: var(--lr-space-xs); } [part="file"] { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--lr-space-s); min-inline-size: 0; padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface-raised); } [part="file-thumbnail"] { display: inline-flex; align-items: center; justify-content: center; inline-size: var(--lr-icon-button-size); block-size: var(--lr-icon-button-size); overflow: hidden; border-radius: var(--lr-radius-xs); color: var(--lr-color-text-quiet); } [part="file-image"] { inline-size: 100%; block-size: 100%; object-fit: cover; } [part="file-icon"] { display: inline-flex; font-size: var(--lr-font-size-xl); } [part="file-details"] { display: flex; flex-direction: column; min-inline-size: 0; } [part="file-name"] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--lr-color-text); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); } [part="file-size"] { color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); } [part="remove-button"] { display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} padding: 0; border: none; border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-text-quiet); font: inherit; cursor: pointer; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="remove-button"]:hover:where(:not(:disabled)) { background: var(--lr-color-brand-quiet); color: var(--lr-color-text); } [part="remove-button"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="remove-button"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part="remove-button"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="hint"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } [part="error"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-danger); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } `;export{styles};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{deepActiveElementIn}from"../../../internal/active-element.js";function syncMapControlRows(container,isCurrent){for(const controls of container.querySelectorAll(".maplibregl-control-container")){const current=()=>isCurrent()&&container.contains(controls);for(const edge of["top","bottom"]){if(!current())return;let row=controls.querySelector(`:scope > .map-control-row-${edge}`);row||(row=container.ownerDocument.createElement("div"),row.className=`map-control-row map-control-row-${edge}`,row.part.add(edge==="top"?"controls-top":"controls-bottom"),controls.append(row));for(const side of["right","left"]){if(!current())return;const corner=controls.querySelector(`.maplibregl-ctrl-${edge}-${side}`);if(!corner)continue;const before=side==="left"?row.querySelector(`.maplibregl-ctrl-${edge}-right`):null;if(corner.parentNode===row&&corner.nextSibling===before)continue;const document=corner.ownerDocument,active=deepActiveElementIn(document),focus=active instanceof HTMLElement&&corner.contains(active)?active:void 0;let transferred=!1;const trackFocus=()=>{transferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{typeof row.moveBefore=="function"?row.moveBefore(corner,before):row.insertBefore(corner,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(!current())return;const remaining=deepActiveElementIn(document),lost=!remaining||remaining===document.body||remaining===document.documentElement;focus?.isConnected&&corner.contains(focus)&&focus.ownerDocument===document&&!transferred&&lost&&focus.focus({preventScroll:!0})}}}}export{syncMapControlRows};
|
|
@@ -6,11 +6,15 @@ export type LyraMapScaleUnit='metric'|'imperial';
|
|
|
6
6
|
/** Options of the declarative navigation control (zoom buttons and compass).*/
|
|
7
7
|
export interface LyraMapNavigationControlOptions{
|
|
8
8
|
/** Corner to add the control to. Defaults to `'top-right'`.*/
|
|
9
|
-
readonly position?:LyraMapControlPosition;
|
|
9
|
+
readonly position?:LyraMapControlPosition;
|
|
10
|
+
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
|
|
11
|
+
readonly order?:number;}
|
|
10
12
|
/** Options of the declarative scale control.*/
|
|
11
13
|
export interface LyraMapScaleControlOptions{
|
|
12
14
|
/** Corner to add the control to. Defaults to `'bottom-left'`.*/
|
|
13
15
|
readonly position?:LyraMapControlPosition;
|
|
16
|
+
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
|
|
17
|
+
readonly order?:number;
|
|
14
18
|
/** Unit system. Defaults to `'metric'`.*/
|
|
15
19
|
readonly unit?:LyraMapScaleUnit;}
|
|
16
20
|
/** Options of the declarative geolocation control.*/
|
|
@@ -26,7 +30,7 @@ export interface LyraMapAttributionControlOptions extends LyraMapNavigationContr
|
|
|
26
30
|
/** Omission retains the peer's automatic compact layout.*/
|
|
27
31
|
readonly compact?:boolean;
|
|
28
32
|
/** Text or guarded links; at most 32 items and 16 KiB of labels and URLs. Caller HTML is never interpreted.*/
|
|
29
|
-
readonly customAttribution?:string|LyraMapAttributionLink|readonly(string|LyraMapAttributionLink)[];}export interface NormalizedMapControlOptions{readonly kind:MapOwnedControlKind;readonly position:LyraMapControlPosition;readonly unit:LyraMapScaleUnit|undefined;readonly options:Readonly<Record<string,unknown>>;readonly key:string;
|
|
33
|
+
readonly customAttribution?:string|LyraMapAttributionLink|readonly(string|LyraMapAttributionLink)[];}export interface NormalizedMapControlOptions{readonly kind:MapOwnedControlKind;readonly position:LyraMapControlPosition;readonly order:number;readonly unit:LyraMapScaleUnit|undefined;readonly options:Readonly<Record<string,unknown>>;readonly key:string;
|
|
30
34
|
/** Escaped labels only, for text export without URLs or link markup.*/
|
|
31
35
|
readonly attributionText?:readonly string[];}export interface MapControlOptionsResult{readonly controls:ReadonlyMap<MapOwnedControlKind,NormalizedMapControlOptions>;readonly diagnostics:readonly{readonly kind:MapOwnedControlKind;readonly code:'invalid-options';}[];}
|
|
32
36
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},key:`${corner}:${JSON.stringify(options)}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
|
|
1
|
+
import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,order,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},key:`${corner}:${order}:${JSON.stringify(options)}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const order=corner.startsWith("bottom")?
|
|
1
|
+
import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function aborted(){return new DOMException("Map controls readiness was cancelled.","AbortError")}class MapControlsReadiness{reset(){this.cancel();let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes,reject=no});promise.catch(()=>{}),this.generation={promise,resolve,reject,run:0}}whenReady(){const generation=this.generation;return generation?.error?Promise.reject(generation.error):generation?.promise??Promise.reject(aborted())}begin(){const generation=this.generation;generation?.stop?.();const cancelled=new Promise(resolve=>{generation?generation.stop=resolve:resolve()}),run=generation?++generation.run:0,isCurrent=()=>generation!==void 0&&this.generation===generation&&generation.run===run;return{isCurrent,cancelled,resolve:()=>{isCurrent()&&!generation.error&&generation.resolve()},fail:()=>{isCurrent()&&this.fail()}}}fail(){const generation=this.generation;if(!generation||generation.error)return;const error=new Error("Map controls readiness failed.");error.name="MapReadinessError",generation.error=error,generation.reject(error)}cancel(){const previous=this.generation;this.generation=void 0,previous?.stop?.(),previous?.reject(aborted())}}export{MapControlsReadiness};
|