@aceshooting/lyra-ui 30.7.0 → 30.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 30.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - fddd9e7: `lr-dock-panel` gains a `rail` slot shown only while `collapsed`: its items (typically one icon button per section) stack after the collapse toggle, in a column on `start`/`end` and a row on `top`/`bottom`, and the rail grows past `--lr-dock-panel-collapsed-size` to fit them. New `collapse-icon` and `expand-icon` slots replace the toggle's chevron with consumer glyphs while keeping its localized name. New `expand()`, `collapse()` and `toggle()` methods drive the fold through the same cancelable `lr-toggle-request`/`lr-toggle` pair as the built-in toggle, so a consumer-owned control can replace it; collapsing moves focus to the built-in toggle, else the first focusable rail item, else the host.
8
+ - c8efd9b: Add `addMapCustomLayer(map, layer, options?)` from the new `@aceshooting/lyra-ui/map-custom-layers.js` entry for trusted custom WebGL2 layers on `lr-map`, such as beams, coverage cones, clouds or particles. A layer's `create(context)` receives the map's own WebGL2 context and geographic services; each frame provides the shared camera as a Mercator/globe shader prelude with projection uniforms, tile-local encoding, CSS projection and sea-level or terrain-relative altitude resolution. Layers are reinstalled with a fresh instance after a `mapStyle` replacement and after WebGL context restoration, disposed on `remove()` or map disconnection, and report `loading`, `ready`, `unavailable` and `removed` states. A pointer click that the layer's `pick()` hits emits `lr-map-scene-activate` with `kind: 'custom'` and `layerId`. The bridge loads from the optional `@aceshooting/lyra-map/scene` entry on first use; ordinary `lr-map` imports do not load it.
9
+
10
+ Scene paths and arcs with a nonzero altitude, a nonzero arc `height` or `sea-level` geometry over displayed terrain are now drawn in 3D at their authored altitude through that bridge, so the scene reports `ready` instead of `partial` with code `altitude`. Lines keep their CSS pixel width, depth-test against the map and hide behind the globe horizon; `terrain` altitude adds displayed terrain height, blending linearly along a segment between `terrain` and `sea-level` endpoints. When the bridge is unavailable or fails, those lines keep the ground-track fallback and the `partial`/`altitude` report.
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [e93aebb]
15
+ - @aceshooting/lyra-map@1.5.0
16
+ - @aceshooting/lyra-translations@30.8.0
17
+
3
18
  ## 30.7.0
4
19
 
5
20
  ### Minor Changes
@@ -49,8 +49,22 @@ readonly expanded:boolean;}export interface LyraDockPanelEventMap{'lr-resize-req
49
49
  * collapsed, so re-expanding restores what it was unless the live container
50
50
  * bounds now require a smaller or larger valid extent.
51
51
  *
52
+ * Elements in the `rail` slot show in that rail only while collapsed -- typically one icon button
53
+ * per section the panel holds -- stacked after the toggle (in a column on `start`/`end`, in a row
54
+ * on `top`/`bottom`), and the rail grows past `--lr-dock-panel-collapsed-size` to fit them. A rail
55
+ * item usually calls `expand()`; `expand()`, `collapse()` and `toggle()` drive the fold from any
56
+ * consumer-owned control through the same cancelable `lr-toggle-request`/`lr-toggle` pair as the
57
+ * built-in toggle, so a panel without `collapsible` can place its own control in its content.
58
+ * Collapsing while focus is inside moves it to the built-in toggle, else to the first focusable rail
59
+ * item, else to the host; expanding while focus is on a rail item moves it to the toggle or the host.
60
+ *
52
61
  * @customElement lr-dock-panel
53
62
  * @slot - The panel's own content.
63
+ * @slot rail - Shown in the collapsed rail only while `collapsed`, after the collapse toggle.
64
+ * @slot collapse-icon - Decorative glyph for the expanded panel's collapse toggle, replacing the
65
+ * chevron. The toggle keeps its localized accessible name and the glyph is not rotated.
66
+ * @slot expand-icon - Decorative glyph for the collapsed panel's expand toggle, replacing the
67
+ * chevron. The toggle keeps its localized accessible name and the glyph is not rotated.
54
68
  * @event lr-resize-request - Cancelable proposed `detail: { extent }` before each pointer or
55
69
  * keyboard resize step. Preventing it leaves the current extent unchanged.
56
70
  * @event lr-resize - Accepted pointer or keyboard step with frozen `detail: { extent }`.
@@ -60,16 +74,18 @@ readonly expanded:boolean;}export interface LyraDockPanelEventMap{'lr-resize-req
60
74
  * least one accepted value transition, and after each accepted keyboard step. Pointer
61
75
  * cancellation, lost capture, policy/geometry mutation, no-op attempts, and a prevented
62
76
  * `lr-resize-request` all emit nothing.
63
- * @event lr-toggle-request - Cancelable proposed `detail: { expanded }` before the built-in toggle commits.
64
- * Call `preventDefault()` to keep `collapsed` unchanged. Not fired when a consumer sets `collapsed` directly.
65
- * @event lr-toggle - Accepted built-in disclosure change with `detail: { expanded }`. Not fired when a
66
- * consumer sets `collapsed` directly.
77
+ * @event lr-toggle-request - Cancelable proposed `detail: { expanded }` before the built-in toggle,
78
+ * `expand()`, `collapse()` or `toggle()` commits. Call `preventDefault()` to keep `collapsed`
79
+ * unchanged. Not fired when a consumer sets `collapsed` directly.
80
+ * @event lr-toggle - Accepted disclosure change from the built-in toggle or one of those methods, with
81
+ * `detail: { expanded }`. Not fired when a consumer sets `collapsed` directly.
67
82
  * @csspart base - The panel root.
68
83
  * @csspart content - The wrapper around the default slot; hidden while `collapsed`.
69
84
  * @csspart handle - The draggable resize handle on the panel's inner edge. Its numeric ARIA range
70
85
  * remains in CSS pixels while `aria-valuetext` reports the current extent through the effective
71
86
  * locale. Only rendered when not `without-resize` and not `collapsed`.
72
87
  * @csspart collapse-toggle - The collapse/expand toggle button. Only rendered when `collapsible`.
88
+ * @csspart rail - The wrapper around the `rail` slot; hidden unless `collapsed`.
73
89
  * @cssprop [--lr-dock-panel-collapsed-size=var(--lr-icon-button-size)] - The extent the panel
74
90
  * keeps along its resize axis while `collapsed` -- enough to still host the toggle button that
75
91
  * re-expands it.
@@ -109,4 +125,13 @@ minExtent:string;
109
125
  * its container. */
110
126
  maxExtent:string;collapsible:boolean;private readonly toggleWriteGuard;private _collapsed;get collapsed():boolean;set collapsed(next:boolean);
111
127
  /** When set, no drag handle renders at all and the panel is a fixed size.*/
112
- withoutResize:boolean;private drag;private readonly resizeWriteGuard;private resizeRequestSequence;private renderBounds?;private renderSizePx?;private readonly dragController;private readonly contentId;private containerResizeObserver?;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private armContainerResizeObserver;private get container();private relocateFocus;protected willUpdate(changed:PropertyValues):void;private get axis();private get growSign();private applyHostSize;private containerPx;private resolveBoundsPx;private currentSizePx;private resizeValueText;private reconcileLiveExtent;private resolveProposal;private applyProposal;private requestResize;private emitResize;private dragSnapshotIsCurrent;private onPointerDown;private onPointerMove;private onPointerUp;private onPointerCancel;private endDrag;private onHandleKeyDown;private dispatchingToggle;private toggleCollapsed;private get topBottomChevronDeg();private handleTemplate;private collapseToggleTemplate;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dock-panel':LyraDockPanel;}}
128
+ withoutResize:boolean;private drag;private readonly resizeWriteGuard;private resizeRequestSequence;private renderBounds?;private renderSizePx?;private readonly dragController;private readonly contentId;private hasRail;private pendingRailFocus;private containerResizeObserver?;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private armContainerResizeObserver;private get container();private railElements;private onRailSlotChange;private focusRail;private relocateFocus;private focusHost;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private get axis();private get growSign();private applyHostSize;private collapsedFloor;private containerPx;private resolveBoundsPx;private currentSizePx;private resizeValueText;private reconcileLiveExtent;private resolveProposal;private applyProposal;private requestResize;private emitResize;private dragSnapshotIsCurrent;private onPointerDown;private onPointerMove;private onPointerUp;private onPointerCancel;private endDrag;private onHandleKeyDown;
129
+ /** Expands the panel through the cancelable `lr-toggle-request`/`lr-toggle` pair, exactly as the
130
+ * built-in toggle does. Returns whether the panel is expanded afterwards. */
131
+ expand():boolean;
132
+ /** Collapses the panel through the cancelable `lr-toggle-request`/`lr-toggle` pair, exactly as the
133
+ * built-in toggle does. Returns whether the panel is collapsed afterwards. */
134
+ collapse():boolean;
135
+ /** Flips the fold through the cancelable `lr-toggle-request`/`lr-toggle` pair, exactly as the
136
+ * built-in toggle does. Returns whether the panel is expanded afterwards. */
137
+ toggle():boolean;private dispatchingToggle;private toggleCollapsed;private get topBottomChevronDeg();private handleTemplate;private collapseToggleTemplate;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-dock-panel':LyraDockPanel;}}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{styles}from"./dock-panel.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dockPanelCollapse,LYRA_DEFAULT_dockPanelExpand,LYRA_DEFAULT_dockPanelResize}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_resizeValuePixels}from"../../../internal/default-strings/shared.generated.js";const KEYBOARD_STEP_PX=16;class LyraDockPanel extends LyraElement{constructor(){super(...arguments),this.placement="end",this._extent="280px",this.minExtent="160px",this.maxExtent="",this.collapsible=!1,this.toggleWriteGuard=new VetoWriteGuard,this._collapsed=!1,this.withoutResize=!1,this.drag=null,this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>event.type==="pointerup"?this.onPointerUp(event):this.onPointerCancel(event)),this.contentId=nextId("dock-panel-content"),this.onPointerDown=e=>{if(!e.isPrimary||e.button!==0||this.withoutResize||this.collapsed||this.drag)return;const handle=e.currentTarget;if(!this.dragController.start(e,handle))return;const axis=this.axis,growSign=this.growSign,containerPx=this.containerPx(),startSizePx=this.currentSizePx();this.drag={pointerId:e.pointerId,startPos:separatorCoordinate(e,axis),startSizePx,axis,growSign,placement:this.placement,minExtent:this.minExtent,maxExtent:this.maxExtent,containerPx,bounds:this.resolveBoundsPx(containerPx),currentSizePx:startSizePx,expectedExtent:this.extent,finalExtent:this.extent,acceptedResize:!1}},this.onPointerMove=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;if(this.withoutResize||this.collapsed||this.placement!==drag.placement||this.axis!==drag.axis||this.growSign!==drag.growSign||this.extent!==drag.expectedExtent||this.minExtent!==drag.minExtent||this.maxExtent!==drag.maxExtent){this.endDrag();return}const pos=separatorCoordinate(e,drag.axis),delta=drag.growSign*(pos-drag.startPos),proposal=this.resolveProposal(drag.startSizePx+delta,drag.bounds,drag.currentSizePx);if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);!extent||this.drag!==drag||(drag.expectedExtent=extent,drag.finalExtent=extent,drag.currentSizePx=parseFloat(extent),drag.acceptedResize=!0,this.emitResize("lr-resize",extent),!(this.drag!==drag||this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-input",extent))},this.onPointerUp=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;const shouldCommit=drag.acceptedResize&&this.dragSnapshotIsCurrent(drag),finalExtent=drag.finalExtent;this.endDrag(),shouldCommit&&this.emitResize("lr-resize-change",finalExtent)},this.onPointerCancel=e=>{!this.drag||e.pointerId!==this.drag.pointerId||this.endDrag()},this.onHandleKeyDown=e=>{if(this.withoutResize||this.collapsed||e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const arrowDirection=separatorArrowDirection(e,this.axis,!1);let proposal;if(e.key==="Home"||e.key==="End"){e.preventDefault();const{minPx,maxPx}=this.resolveBoundsPx();proposal=this.resolveProposal(e.key==="Home"?minPx:maxPx)}else arrowDirection===1?(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()+this.growSign*KEYBOARD_STEP_PX)):arrowDirection===-1&&(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()-this.growSign*KEYBOARD_STEP_PX));if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);extent&&(this.emitResize("lr-resize",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&(this.emitResize("lr-resize-input",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-change",extent)))},this.dispatchingToggle=!1,this.toggleCollapsed=()=>{if(this.dispatchingToggle)return;const previous=this.collapsed,detail=()=>Object.freeze({expanded:previous});this.dispatchingToggle=!0;try{requestThenCommit({requestDetail:detail(),emitRequest:(proposal,init)=>this.emit("lr-toggle-request",proposal,init),guard:this.toggleWriteGuard,commit:()=>{this.collapsed===previous&&(this.collapsed=!previous,this.emit("lr-toggle",detail()))}})}finally{this.dispatchingToggle=!1}}}static{this.defaultStrings={...super.defaultStrings,dockPanelCollapse:LYRA_DEFAULT_dockPanelCollapse,dockPanelExpand:LYRA_DEFAULT_dockPanelExpand,dockPanelResize:LYRA_DEFAULT_dockPanelResize,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels}}static{this.styles=[LyraElement.styles,styles]}get extent(){return this._extent}set extent(value){const old=this._extent;this._extent=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("extent",old)}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleWriteGuard),this.requestUpdate("collapsed",old)}connectedCallback(){super.connectedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.applyHostSize(),this.armContainerResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}adoptedCallback(){super.adoptedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}armContainerResizeObserver(){const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver,container=this.container;!container||!ResizeObserverCtor||(this.containerResizeObserver??=new ResizeObserverCtor(()=>{this.isConnected&&(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent(),this.requestUpdate())}),this.containerResizeObserver.observe(container),this.containerResizeObserver.observe(this))}get container(){let parent=flattenedParentElement(this);for(;parent?.localName==="slot";)parent=flattenedParentElement(parent);return parent}relocateFocus(){const toggle=this.renderRoot.querySelector('[part="collapse-toggle"]');if(toggle){toggle.focus();return}this.hasAttribute("tabindex")||(this.tabIndex=-1,this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("collapsed")&&this.collapsed&&this.matches(":focus-within")||changed.has("withoutResize")&&this.withoutResize&&shadowFocusTarget(this)?.matches('[part="handle"]'))&&this.relocateFocus(),changed.has("extent")||changed.has("minExtent")||changed.has("maxExtent")||changed.has("collapsed")||changed.has("placement")?(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent()):this.drag&&(changed.has("withoutResize")&&this.withoutResize||changed.has("collapsed")&&this.collapsed)&&this.endDrag()}get axis(){return this.placement==="start"||this.placement==="end"?"inline":"block"}get growSign(){if(this.placement==="top")return 1;if(this.placement==="bottom")return-1;const rtl=isRtl(this);return this.placement==="start"?rtl?-1:1:rtl?1:-1}applyHostSize(bounds=this.resolveBoundsPx()){const value=this.collapsed?"var(--lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size))":this.extent;this.axis==="inline"?(this.style.inlineSize=value,this.style.blockSize="",this.style.minBlockSize="",this.style.maxBlockSize="",this.style.minInlineSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxInlineSize=this.collapsed?"":`${bounds.maxPx}px`):(this.style.blockSize=value,this.style.inlineSize="",this.style.minInlineSize="",this.style.maxInlineSize="",this.style.minBlockSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxBlockSize=this.collapsed?"":`${bounds.maxPx}px`)}containerPx(){const rect=this.container?.getBoundingClientRect(),ownerWindow=this.ownerDocument.defaultView;return this.axis==="inline"?rect?.width??ownerWindow?.innerWidth??0:rect?.height??ownerWindow?.innerHeight??0}resolveBoundsPx(containerSize=this.containerPx()){const containerPx=Math.max(0,containerSize),lengthContext={host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0},authoredMax=Math.max(0,resolveCssLength(this.maxExtent,lengthContext)??containerPx),maxPx=Math.min(containerPx,authoredMax),authoredMin=Math.max(0,resolveCssLength(this.minExtent,lengthContext)??0);return{minPx:Math.min(authoredMin,maxPx),maxPx}}currentSizePx(){const rect=this.getBoundingClientRect();return this.axis==="inline"?rect.width:rect.height}resizeValueText(sizePx){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(sizePx))})}reconcileLiveExtent(){const containerPx=this.containerPx(),bounds=this.resolveBoundsPx(containerPx);if(this.applyHostSize(bounds),this.renderBounds=bounds,this.collapsed)return;const authoredPx=resolveCssLength(this.extent,{host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0}),renderedPx=this.currentSizePx();this.renderSizePx=renderedPx;const candidate=authoredPx??renderedPx;if(!Number.isFinite(candidate))return;const clamped=Math.min(Math.max(candidate,bounds.minPx),bounds.maxPx),renderedOutsideBounds=Number.isFinite(renderedPx)&&(renderedPx<bounds.minPx-.5||renderedPx>bounds.maxPx+.5);if(Math.abs(candidate-clamped)<=.5&&!renderedOutsideBounds)return;const nextExtent=`${Math.round(clamped)}px`;this.extent!==nextExtent&&(this.extent=nextExtent),this.applyHostSize(bounds),this.renderSizePx=this.currentSizePx()}resolveProposal(px,bounds=this.resolveBoundsPx(),currentSizePx=this.currentSizePx()){const clamped=Math.min(Math.max(px,bounds.minPx),bounds.maxPx),nextExtent=`${Math.round(clamped)}px`,currentExtent=`${Math.round(currentSizePx)}px`;if(nextExtent!==currentExtent)return{bounds,nextExtent}}applyProposal(bounds,nextExtent){this.extent=nextExtent,this.applyHostSize(bounds)}requestResize(bounds,extent){const requestSequence=++this.resizeRequestSequence,snapshot={drag:this.drag,extent:this.extent,placement:this.placement,collapsed:this.collapsed,withoutResize:this.withoutResize,minExtent:this.minExtent,maxExtent:this.maxExtent,growSign:this.growSign,containerPx:this.drag?.containerPx??this.containerPx()};let committed;return requestThenCommit({requestDetail:Object.freeze({extent}),emitRequest:(detail,init)=>this.emit("lr-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{const currentBounds=this.resolveBoundsPx(snapshot.containerPx);if(this.drag!==snapshot.drag||this.collapsed||this.collapsed!==snapshot.collapsed||this.resizeRequestSequence!==requestSequence||this.withoutResize||this.withoutResize!==snapshot.withoutResize||this.extent!==snapshot.extent||this.placement!==snapshot.placement||this.minExtent!==snapshot.minExtent||this.maxExtent!==snapshot.maxExtent||this.growSign!==snapshot.growSign||Math.abs(this.containerPx()-snapshot.containerPx)>.5||Math.abs(currentBounds.minPx-bounds.minPx)>.5||Math.abs(currentBounds.maxPx-bounds.maxPx)>.5){snapshot.drag&&this.drag===snapshot.drag&&this.endDrag();return}this.applyProposal(bounds,extent),committed=this.extent}}),committed}emitResize(type,extent){this.emit(type,Object.freeze({extent}))}dragSnapshotIsCurrent(drag){return!this.withoutResize&&!this.collapsed&&this.placement===drag.placement&&this.axis===drag.axis&&this.growSign===drag.growSign&&this.extent===drag.expectedExtent&&this.minExtent===drag.minExtent&&this.maxExtent===drag.maxExtent&&Math.abs(this.containerPx()-drag.containerPx)<=.5}endDrag(){const pointerId=this.drag?.pointerId;this.drag=null,pointerId!=null&&this.dragController.end(pointerId)}get topBottomChevronDeg(){if(this.placement==="top")return this.collapsed?90:-90;if(this.placement==="bottom")return this.collapsed?-90:90}handleTemplate(){if(this.withoutResize||this.collapsed)return nothing;const{minPx,maxPx}=this.renderBounds??this.resolveBoundsPx(),nowPx=Math.min(Math.max(this.renderSizePx??this.currentSizePx(),minPx),maxPx);return html`<div
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{styles}from"./dock-panel.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dockPanelCollapse,LYRA_DEFAULT_dockPanelExpand,LYRA_DEFAULT_dockPanelResize}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_resizeValuePixels}from"../../../internal/default-strings/shared.generated.js";const KEYBOARD_STEP_PX=16;class LyraDockPanel extends LyraElement{constructor(){super(...arguments),this.placement="end",this._extent="280px",this.minExtent="160px",this.maxExtent="",this.collapsible=!1,this.toggleWriteGuard=new VetoWriteGuard,this._collapsed=!1,this.withoutResize=!1,this.drag=null,this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>event.type==="pointerup"?this.onPointerUp(event):this.onPointerCancel(event)),this.contentId=nextId("dock-panel-content"),this.hasRail=!1,this.pendingRailFocus=!1,this.onRailSlotChange=()=>{const hasRail=this.railElements().length>0;hasRail!==this.hasRail&&(this.hasRail=hasRail,this.applyHostSize(),this.requestUpdate())},this.onPointerDown=e=>{if(!e.isPrimary||e.button!==0||this.withoutResize||this.collapsed||this.drag)return;const handle=e.currentTarget;if(!this.dragController.start(e,handle))return;const axis=this.axis,growSign=this.growSign,containerPx=this.containerPx(),startSizePx=this.currentSizePx();this.drag={pointerId:e.pointerId,startPos:separatorCoordinate(e,axis),startSizePx,axis,growSign,placement:this.placement,minExtent:this.minExtent,maxExtent:this.maxExtent,containerPx,bounds:this.resolveBoundsPx(containerPx),currentSizePx:startSizePx,expectedExtent:this.extent,finalExtent:this.extent,acceptedResize:!1}},this.onPointerMove=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;if(this.withoutResize||this.collapsed||this.placement!==drag.placement||this.axis!==drag.axis||this.growSign!==drag.growSign||this.extent!==drag.expectedExtent||this.minExtent!==drag.minExtent||this.maxExtent!==drag.maxExtent){this.endDrag();return}const pos=separatorCoordinate(e,drag.axis),delta=drag.growSign*(pos-drag.startPos),proposal=this.resolveProposal(drag.startSizePx+delta,drag.bounds,drag.currentSizePx);if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);!extent||this.drag!==drag||(drag.expectedExtent=extent,drag.finalExtent=extent,drag.currentSizePx=parseFloat(extent),drag.acceptedResize=!0,this.emitResize("lr-resize",extent),!(this.drag!==drag||this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-input",extent))},this.onPointerUp=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;const shouldCommit=drag.acceptedResize&&this.dragSnapshotIsCurrent(drag),finalExtent=drag.finalExtent;this.endDrag(),shouldCommit&&this.emitResize("lr-resize-change",finalExtent)},this.onPointerCancel=e=>{!this.drag||e.pointerId!==this.drag.pointerId||this.endDrag()},this.onHandleKeyDown=e=>{if(this.withoutResize||this.collapsed||e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const arrowDirection=separatorArrowDirection(e,this.axis,!1);let proposal;if(e.key==="Home"||e.key==="End"){e.preventDefault();const{minPx,maxPx}=this.resolveBoundsPx();proposal=this.resolveProposal(e.key==="Home"?minPx:maxPx)}else arrowDirection===1?(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()+this.growSign*KEYBOARD_STEP_PX)):arrowDirection===-1&&(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()-this.growSign*KEYBOARD_STEP_PX));if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);extent&&(this.emitResize("lr-resize",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&(this.emitResize("lr-resize-input",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-change",extent)))},this.dispatchingToggle=!1,this.toggleCollapsed=()=>{if(this.dispatchingToggle)return;const previous=this.collapsed,detail=()=>Object.freeze({expanded:previous});this.dispatchingToggle=!0;try{requestThenCommit({requestDetail:detail(),emitRequest:(proposal,init)=>this.emit("lr-toggle-request",proposal,init),guard:this.toggleWriteGuard,commit:()=>{this.collapsed===previous&&(this.collapsed=!previous,this.emit("lr-toggle",detail()))}})}finally{this.dispatchingToggle=!1}}}static{this.defaultStrings={...super.defaultStrings,dockPanelCollapse:LYRA_DEFAULT_dockPanelCollapse,dockPanelExpand:LYRA_DEFAULT_dockPanelExpand,dockPanelResize:LYRA_DEFAULT_dockPanelResize,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels}}static{this.styles=[LyraElement.styles,styles]}get extent(){return this._extent}set extent(value){const old=this._extent;this._extent=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("extent",old)}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleWriteGuard),this.requestUpdate("collapsed",old)}connectedCallback(){super.connectedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.applyHostSize(),this.armContainerResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}adoptedCallback(){super.adoptedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}armContainerResizeObserver(){const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver,container=this.container;!container||!ResizeObserverCtor||(this.containerResizeObserver??=new ResizeObserverCtor(()=>{this.isConnected&&(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent(),this.requestUpdate())}),this.containerResizeObserver.observe(container),this.containerResizeObserver.observe(this))}get container(){let parent=flattenedParentElement(this);for(;parent?.localName==="slot";)parent=flattenedParentElement(parent);return parent}railElements(){return this.renderRoot.querySelector('slot[name="rail"]')?.assignedElements({flatten:!0})??[]}focusRail(){for(const item of this.railElements())if(!(!("focus"in item)||typeof item.focus!="function")&&(item.focus(),item.matches(":focus-within")))return!0;return!1}relocateFocus(collapsing=!1){const toggle=this.renderRoot.querySelector('[part="collapse-toggle"]');if(toggle){toggle.focus();return}if(collapsing&&this.hasRail){this.pendingRailFocus=!0;return}this.focusHost()}focusHost(){this.hasAttribute("tabindex")||(this.tabIndex=-1,this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("collapsed")&&this.collapsed&&this.matches(":focus-within")||changed.has("withoutResize")&&this.withoutResize&&shadowFocusTarget(this)?.matches('[part="handle"]'))?this.relocateFocus(changed.has("collapsed")&&this.collapsed):this.hasUpdated&&changed.has("collapsed")&&!this.collapsed&&this.railElements().some(item=>item.matches(":focus-within"))&&this.relocateFocus(),changed.has("extent")||changed.has("minExtent")||changed.has("maxExtent")||changed.has("collapsed")||changed.has("placement")?(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent()):this.drag&&(changed.has("withoutResize")&&this.withoutResize||changed.has("collapsed")&&this.collapsed)&&this.endDrag()}updated(changed){super.updated(changed),this.pendingRailFocus&&(this.pendingRailFocus=!1,this.collapsed&&!this.focusRail()&&this.focusHost())}get axis(){return this.placement==="start"||this.placement==="end"?"inline":"block"}get growSign(){if(this.placement==="top")return 1;if(this.placement==="bottom")return-1;const rtl=isRtl(this);return this.placement==="start"?rtl?-1:1:rtl?1:-1}applyHostSize(bounds=this.resolveBoundsPx()){const value=this.collapsed?"var(--lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size))":this.extent;this.axis==="inline"?(this.style.inlineSize=value,this.style.blockSize="",this.style.minBlockSize="",this.style.maxBlockSize="",this.style.minInlineSize=this.collapsed?this.collapsedFloor():`${bounds.minPx}px`,this.style.maxInlineSize=this.collapsed?"":`${bounds.maxPx}px`):(this.style.blockSize=value,this.style.inlineSize="",this.style.minInlineSize="",this.style.maxInlineSize="",this.style.minBlockSize=this.collapsed?this.collapsedFloor():`${bounds.minPx}px`,this.style.maxBlockSize=this.collapsed?"":`${bounds.maxPx}px`)}collapsedFloor(){return this.hasRail?"max-content":""}containerPx(){const rect=this.container?.getBoundingClientRect(),ownerWindow=this.ownerDocument.defaultView;return this.axis==="inline"?rect?.width??ownerWindow?.innerWidth??0:rect?.height??ownerWindow?.innerHeight??0}resolveBoundsPx(containerSize=this.containerPx()){const containerPx=Math.max(0,containerSize),lengthContext={host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0},authoredMax=Math.max(0,resolveCssLength(this.maxExtent,lengthContext)??containerPx),maxPx=Math.min(containerPx,authoredMax),authoredMin=Math.max(0,resolveCssLength(this.minExtent,lengthContext)??0);return{minPx:Math.min(authoredMin,maxPx),maxPx}}currentSizePx(){const rect=this.getBoundingClientRect();return this.axis==="inline"?rect.width:rect.height}resizeValueText(sizePx){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(sizePx))})}reconcileLiveExtent(){const containerPx=this.containerPx(),bounds=this.resolveBoundsPx(containerPx);if(this.applyHostSize(bounds),this.renderBounds=bounds,this.collapsed)return;const authoredPx=resolveCssLength(this.extent,{host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0}),renderedPx=this.currentSizePx();this.renderSizePx=renderedPx;const candidate=authoredPx??renderedPx;if(!Number.isFinite(candidate))return;const clamped=Math.min(Math.max(candidate,bounds.minPx),bounds.maxPx),renderedOutsideBounds=Number.isFinite(renderedPx)&&(renderedPx<bounds.minPx-.5||renderedPx>bounds.maxPx+.5);if(Math.abs(candidate-clamped)<=.5&&!renderedOutsideBounds)return;const nextExtent=`${Math.round(clamped)}px`;this.extent!==nextExtent&&(this.extent=nextExtent),this.applyHostSize(bounds),this.renderSizePx=this.currentSizePx()}resolveProposal(px,bounds=this.resolveBoundsPx(),currentSizePx=this.currentSizePx()){const clamped=Math.min(Math.max(px,bounds.minPx),bounds.maxPx),nextExtent=`${Math.round(clamped)}px`,currentExtent=`${Math.round(currentSizePx)}px`;if(nextExtent!==currentExtent)return{bounds,nextExtent}}applyProposal(bounds,nextExtent){this.extent=nextExtent,this.applyHostSize(bounds)}requestResize(bounds,extent){const requestSequence=++this.resizeRequestSequence,snapshot={drag:this.drag,extent:this.extent,placement:this.placement,collapsed:this.collapsed,withoutResize:this.withoutResize,minExtent:this.minExtent,maxExtent:this.maxExtent,growSign:this.growSign,containerPx:this.drag?.containerPx??this.containerPx()};let committed;return requestThenCommit({requestDetail:Object.freeze({extent}),emitRequest:(detail,init)=>this.emit("lr-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{const currentBounds=this.resolveBoundsPx(snapshot.containerPx);if(this.drag!==snapshot.drag||this.collapsed||this.collapsed!==snapshot.collapsed||this.resizeRequestSequence!==requestSequence||this.withoutResize||this.withoutResize!==snapshot.withoutResize||this.extent!==snapshot.extent||this.placement!==snapshot.placement||this.minExtent!==snapshot.minExtent||this.maxExtent!==snapshot.maxExtent||this.growSign!==snapshot.growSign||Math.abs(this.containerPx()-snapshot.containerPx)>.5||Math.abs(currentBounds.minPx-bounds.minPx)>.5||Math.abs(currentBounds.maxPx-bounds.maxPx)>.5){snapshot.drag&&this.drag===snapshot.drag&&this.endDrag();return}this.applyProposal(bounds,extent),committed=this.extent}}),committed}emitResize(type,extent){this.emit(type,Object.freeze({extent}))}dragSnapshotIsCurrent(drag){return!this.withoutResize&&!this.collapsed&&this.placement===drag.placement&&this.axis===drag.axis&&this.growSign===drag.growSign&&this.extent===drag.expectedExtent&&this.minExtent===drag.minExtent&&this.maxExtent===drag.maxExtent&&Math.abs(this.containerPx()-drag.containerPx)<=.5}endDrag(){const pointerId=this.drag?.pointerId;this.drag=null,pointerId!=null&&this.dragController.end(pointerId)}expand(){return this.collapsed&&this.toggleCollapsed(),!this.collapsed}collapse(){return this.collapsed||this.toggleCollapsed(),this.collapsed}toggle(){return this.toggleCollapsed(),!this.collapsed}get topBottomChevronDeg(){if(this.placement==="top")return this.collapsed?90:-90;if(this.placement==="bottom")return this.collapsed?-90:90}handleTemplate(){if(this.withoutResize||this.collapsed)return nothing;const{minPx,maxPx}=this.renderBounds??this.resolveBoundsPx(),nowPx=Math.min(Math.max(this.renderSizePx??this.currentSizePx(),minPx),maxPx);return html`<div
2
2
  part="handle"
3
3
  role="separator"
4
4
  aria-label=${this.localize("dockPanelResize")}
@@ -18,15 +18,18 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from
18
18
  aria-label=${this.collapsed?this.localize("dockPanelExpand"):this.localize("dockPanelCollapse")}
19
19
  @click=${this.toggleCollapsed}
20
20
  >
21
- <span
22
- style=${this.topBottomChevronDeg===void 0?"display:inline-flex":`display:inline-flex;transform:rotate(${this.topBottomChevronDeg}deg)`}
23
- >${chevronIcon()}</span
21
+ <slot name=${this.collapsed?"expand-icon":"collapse-icon"}
22
+ ><span
23
+ style=${this.topBottomChevronDeg===void 0?"display:inline-flex":`display:inline-flex;transform:rotate(${this.topBottomChevronDeg}deg)`}
24
+ >${chevronIcon()}</span
25
+ ></slot
24
26
  >
25
27
  </button>`:nothing}render(){return html`
26
- <div part="base">
28
+ <div part="base" ?data-rail=${this.collapsed&&this.hasRail}>
27
29
  <div part="content" id=${this.contentId} ?hidden=${this.collapsed}>
28
30
  <slot></slot>
29
31
  </div>
30
32
  ${this.handleTemplate()} ${this.collapseToggleTemplate()}
33
+ <div part="rail" ?hidden=${!this.collapsed}><slot name="rail" @slotchange=${this.onRailSlotChange}></slot></div>
31
34
  </div>
32
35
  `}}__decorate([property({reflect:!0})],LyraDockPanel.prototype,"placement",void 0),__decorate([property()],LyraDockPanel.prototype,"extent",null),__decorate([property({attribute:"min-extent"})],LyraDockPanel.prototype,"minExtent",void 0),__decorate([property({attribute:"max-extent"})],LyraDockPanel.prototype,"maxExtent",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDockPanel.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDockPanel.prototype,"collapsed",null),__decorate([property({type:Boolean,reflect:!0,attribute:"without-resize"})],LyraDockPanel.prototype,"withoutResize",void 0);export{LyraDockPanel};
@@ -1 +1 @@
1
- import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; box-sizing: border-box; --_lr-dock-panel-collapsed-size: var(--lr-icon-button-size); position: relative; } :host([placement="start"]), :host([placement="end"]) { block-size: 100%; } :host([placement="top"]), :host([placement="bottom"]) { inline-size: 100%; } :host([placement="start"][collapsed]), :host([placement="end"][collapsed]) { min-inline-size: var( --lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size) ); } :host([placement="top"][collapsed]), :host([placement="bottom"][collapsed]) { min-block-size: var( --lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size) ); } [part="base"] { position: relative; inline-size: 100%; block-size: 100%; background: var(--lr-color-surface); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); overflow: hidden; } [part="content"] { inline-size: 100%; block-size: 100%; overflow: auto; } [part="content"][hidden] { display: none; } [part="handle"] { position: absolute; background: var(--lr-color-border); touch-action: none; transition: background var(--lr-transition-fast); } [part="handle"]:hover { background: var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)); } [part="handle"]:focus-visible { background: var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)); outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="handle"]:active { background: var( --lr-dock-panel-handle-active-color, color-mix( in oklab, var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part="handle"]::before { content: ""; position: absolute; --_lr-dock-panel-hit-area: var(--lr-dock-panel-handle-hit-area, var(--lr-space-m)); inline-size: var(--_lr-dock-panel-hit-area); block-size: 100%; inset-block-start: 0; inset-inline-start: 0; } :host([placement="start"]) [part="handle"]::before { inset-inline-start: auto; inset-inline-end: 0; } :host([placement="top"]) [part="handle"]::before, :host([placement="bottom"]) [part="handle"]::before { inline-size: 100%; block-size: var(--_lr-dock-panel-hit-area); inset-inline-start: 0; inset-block-start: 0; } :host([placement="top"]) [part="handle"]::before { inset-block-start: auto; inset-block-end: 0; } @media (hover: none), (pointer: coarse) { [part="handle"]::before { --_lr-dock-panel-hit-area: max( var(--lr-icon-button-size), var(--lr-dock-panel-handle-hit-area, var(--lr-space-m)) ); } } :host([placement="start"]) [part="handle"] { inset-block: 0; inset-inline-end: 0; inline-size: var(--lr-size-3px); cursor: col-resize; } :host([placement="end"]) [part="handle"] { inset-block: 0; inset-inline-start: 0; inline-size: var(--lr-size-3px); cursor: col-resize; } :host([placement="top"]) [part="handle"] { inset-inline: 0; inset-block-end: 0; block-size: var(--lr-size-3px); cursor: row-resize; } :host([placement="bottom"]) [part="handle"] { inset-inline: 0; inset-block-start: 0; block-size: var(--lr-size-3px); cursor: row-resize; } [part="collapse-toggle"] { position: absolute; display: inline-flex; align-items: center; justify-content: center; inline-size: var(--lr-icon-button-size); block-size: var(--lr-icon-button-size); ${iconHitTarget} padding: 0; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); cursor: pointer; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); transition: background var(--lr-transition-fast), color var(--lr-transition-fast); z-index: var(--lr-layer-content); } [part="collapse-toggle"]:hover { background: var( --lr-dock-panel-collapse-toggle-hover-bg, var(--lr-color-brand-quiet) ); color: var( --lr-dock-panel-collapse-toggle-hover-color, var(--lr-color-brand) ); } [part="collapse-toggle"]:active { background: color-mix( in oklab, var( --lr-dock-panel-collapse-toggle-hover-bg, var(--lr-color-brand-quiet) ), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var( --lr-dock-panel-collapse-toggle-hover-color, var(--lr-color-brand) ); } [part="collapse-toggle"]:focus-visible { ${focusRing} } :host([placement="start"]) [part="collapse-toggle"] { inset-inline-end: var(--lr-space-xs); inset-block-start: 50%; transform: translateY(-50%); } :host([placement="end"]) [part="collapse-toggle"] { inset-inline-start: var(--lr-space-xs); inset-block-start: 50%; transform: translateY(-50%); } :host([placement="top"]) [part="collapse-toggle"] { inset-block-end: var(--lr-space-xs); inset-inline-start: 50%; transform: translateX(-50%); } :host([placement="bottom"]) [part="collapse-toggle"] { inset-block-start: var(--lr-space-xs); inset-inline-start: 50%; transform: translateX(-50%); } :host(:dir(rtl)[placement="top"]) [part="collapse-toggle"], :host(:dir(rtl)[placement="bottom"]) [part="collapse-toggle"] { transform: translateX(50%); } :host([placement="start"]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host([placement="start"][collapsed]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host([placement="end"]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host([placement="end"][collapsed]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="start"]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host(:dir(rtl)[placement="start"][collapsed]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="end"]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="end"][collapsed]) [part="collapse-toggle"] span { transform: rotate(0deg); } @media (prefers-reduced-motion: reduce) { [part="collapse-toggle"], [part="handle"] { transition: none !important; } } `;export{styles};
1
+ import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; box-sizing: border-box; --_lr-dock-panel-collapsed-size: var(--lr-icon-button-size); position: relative; } :host([placement="start"]), :host([placement="end"]) { block-size: 100%; } :host([placement="top"]), :host([placement="bottom"]) { inline-size: 100%; } :host([placement="start"][collapsed]), :host([placement="end"][collapsed]) { min-inline-size: var( --lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size) ); } :host([placement="top"][collapsed]), :host([placement="bottom"][collapsed]) { min-block-size: var( --lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size) ); } [part="base"] { position: relative; inline-size: 100%; block-size: 100%; background: var(--lr-color-surface); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); overflow: hidden; } [part="content"] { inline-size: 100%; block-size: 100%; overflow: auto; } [part="content"][hidden] { display: none; } [part="handle"] { position: absolute; background: var(--lr-color-border); touch-action: none; transition: background var(--lr-transition-fast); } [part="handle"]:hover { background: var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)); } [part="handle"]:focus-visible { background: var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)); outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part="handle"]:active { background: var( --lr-dock-panel-handle-active-color, color-mix( in oklab, var(--lr-dock-panel-handle-hover-color, var(--lr-color-brand)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); } [part="handle"]::before { content: ""; position: absolute; --_lr-dock-panel-hit-area: var(--lr-dock-panel-handle-hit-area, var(--lr-space-m)); inline-size: var(--_lr-dock-panel-hit-area); block-size: 100%; inset-block-start: 0; inset-inline-start: 0; } :host([placement="start"]) [part="handle"]::before { inset-inline-start: auto; inset-inline-end: 0; } :host([placement="top"]) [part="handle"]::before, :host([placement="bottom"]) [part="handle"]::before { inline-size: 100%; block-size: var(--_lr-dock-panel-hit-area); inset-inline-start: 0; inset-block-start: 0; } :host([placement="top"]) [part="handle"]::before { inset-block-start: auto; inset-block-end: 0; } @media (hover: none), (pointer: coarse) { [part="handle"]::before { --_lr-dock-panel-hit-area: max( var(--lr-icon-button-size), var(--lr-dock-panel-handle-hit-area, var(--lr-space-m)) ); } } :host([placement="start"]) [part="handle"] { inset-block: 0; inset-inline-end: 0; inline-size: var(--lr-size-3px); cursor: col-resize; } :host([placement="end"]) [part="handle"] { inset-block: 0; inset-inline-start: 0; inline-size: var(--lr-size-3px); cursor: col-resize; } :host([placement="top"]) [part="handle"] { inset-inline: 0; inset-block-end: 0; block-size: var(--lr-size-3px); cursor: row-resize; } :host([placement="bottom"]) [part="handle"] { inset-inline: 0; inset-block-start: 0; block-size: var(--lr-size-3px); cursor: row-resize; } [part="collapse-toggle"] { position: absolute; display: inline-flex; align-items: center; justify-content: center; inline-size: var(--lr-icon-button-size); block-size: var(--lr-icon-button-size); ${iconHitTarget} padding: 0; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); cursor: pointer; font-size: var(--lr-font-size-xs); line-height: var(--lr-line-height-none); transition: background var(--lr-transition-fast), color var(--lr-transition-fast); z-index: var(--lr-layer-content); } [part="collapse-toggle"]:hover { background: var( --lr-dock-panel-collapse-toggle-hover-bg, var(--lr-color-brand-quiet) ); color: var( --lr-dock-panel-collapse-toggle-hover-color, var(--lr-color-brand) ); } [part="collapse-toggle"]:active { background: color-mix( in oklab, var( --lr-dock-panel-collapse-toggle-hover-bg, var(--lr-color-brand-quiet) ), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); color: var( --lr-dock-panel-collapse-toggle-hover-color, var(--lr-color-brand) ); } [part="collapse-toggle"]:focus-visible { ${focusRing} } :host([placement="start"]) [part="collapse-toggle"] { inset-inline-end: var(--lr-space-xs); inset-block-start: 50%; transform: translateY(-50%); } :host([placement="end"]) [part="collapse-toggle"] { inset-inline-start: var(--lr-space-xs); inset-block-start: 50%; transform: translateY(-50%); } :host([placement="top"]) [part="collapse-toggle"] { inset-block-end: var(--lr-space-xs); inset-inline-start: 50%; transform: translateX(-50%); } :host([placement="bottom"]) [part="collapse-toggle"] { inset-block-start: var(--lr-space-xs); inset-inline-start: 50%; transform: translateX(-50%); } :host(:dir(rtl)[placement="top"]) [part="collapse-toggle"], :host(:dir(rtl)[placement="bottom"]) [part="collapse-toggle"] { transform: translateX(50%); } :host([placement="start"]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host([placement="start"][collapsed]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host([placement="end"]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host([placement="end"][collapsed]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="start"]) [part="collapse-toggle"] span { transform: rotate(0deg); } :host(:dir(rtl)[placement="start"][collapsed]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="end"]) [part="collapse-toggle"] span { transform: rotate(180deg); } :host(:dir(rtl)[placement="end"][collapsed]) [part="collapse-toggle"] span { transform: rotate(0deg); } [part="collapse-toggle"] ::slotted(*) { display: inline-flex; } [part="rail"] { display: contents; } [part="rail"][hidden] { display: none; } [part="base"]:where([data-rail]) { box-sizing: border-box; display: flex; flex-direction: column; align-items: center; gap: var(--lr-space-xs); padding: var(--lr-space-xs); } :host([placement="top"]) [part="base"]:where([data-rail]), :host([placement="bottom"]) [part="base"]:where([data-rail]) { flex-direction: row; } :host([collapsed]) [part="base"]:where([data-rail]) [part="collapse-toggle"] { position: static; flex: none; order: -1; transform: none; } @media (prefers-reduced-motion: reduce) { [part="collapse-toggle"], [part="handle"] { transition: none !important; } } `;export{styles};
@@ -0,0 +1,36 @@
1
+ import{canonicalLongitude,encodeTileVertex,lineWorldShift,MERCATOR_LATITUDE_LIMIT}from"./map-scene-line-encoding.js";const FLOATS=13,mercatorLatitude=value=>Math.max(-MERCATOR_LATITUDE_LIMIT,Math.min(MERCATOR_LATITUDE_LIMIT,value)),vertexBody=`
2
+ in vec3 a_lr_position;
3
+ in vec3 a_lr_other;
4
+ in vec2 a_lr_side;
5
+ in vec4 a_lr_color;
6
+ in float a_lr_width;
7
+ uniform vec2 u_lr_viewport;
8
+ uniform float u_lr_pixel_ratio;
9
+ out vec4 v_lr_color;
10
+ out vec3 v_lr_sphere;
11
+ void main() {
12
+ vec4 here = lrProjectPosition(a_lr_position);
13
+ vec4 there = lrProjectPosition(a_lr_other);
14
+ v_lr_color = a_lr_color;
15
+ v_lr_sphere = lrHorizonPosition(a_lr_position);
16
+ if (here.w <= 0.0 || there.w <= 0.0) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
17
+ vec2 halfSize = u_lr_viewport * 0.5;
18
+ vec2 direction = (there.xy / there.w - here.xy / here.w) * halfSize * a_lr_side.y;
19
+ float run = length(direction);
20
+ vec2 normal = run > 0.0 ? vec2(-direction.y, direction.x) / run : vec2(0.0);
21
+ vec2 offset = normal * a_lr_side.x * a_lr_width * 0.5 * u_lr_pixel_ratio;
22
+ gl_Position = here + vec4(offset / halfSize * here.w, 0.0, 0.0);
23
+ }`,fragmentBody=`
24
+ in vec4 v_lr_color;
25
+ in vec3 v_lr_sphere;
26
+ out vec4 lr_color;
27
+ void main() {
28
+ if (lrHorizonOccluded(v_lr_sphere)) discard;
29
+ lr_color = vec4(v_lr_color.rgb * v_lr_color.a, v_lr_color.a);
30
+ }`,attributes=[["a_lr_position",3,0],["a_lr_other",3,3],["a_lr_side",2,6],["a_lr_color",4,8],["a_lr_width",1,12]];function elevatedLineVertices(line,tile,heights){const shift=lineWorldShift(line.coordinates[0][0]),encoded=line.coordinates.map((row,index)=>encodeTileVertex(row[0]+shift,row[1],row[2]+line.terrain[index]*heights[index],tile)),data=new Float32Array(Math.max(0,encoded.length-1)*6*FLOATS),[red,green,blue,alpha]=line.rgba;let offset=0;const push=(self,other,side,direction)=>{data.set([self[0],self[1],self[2],other[0],other[1],other[2],side,direction,red,green,blue,alpha,line.width],offset),offset+=FLOATS};for(let index=1;index<encoded.length;index++){const a=encoded[index-1],b=encoded[index];push(a,b,-1,1),push(a,b,1,1),push(b,a,-1,-1),push(b,a,-1,-1),push(a,b,1,1),push(b,a,1,-1)}return data}function createElevatedSceneLineLayer(id,lines){return Object.freeze({id,label:"Scene paths and arcs",create(context){const{gl}=context,programs=new Map,buffers=new Map;let disposed=!1;function compile(shader){const source=`${shader.defines}
31
+ ${shader.vertexPrelude}
32
+ ${shader.fragmentPrelude}`,cached=programs.get(source);if(cached)return cached;const shaders=[];for(const[type,prelude,body]of[[gl.VERTEX_SHADER,shader.vertexPrelude,vertexBody],[gl.FRAGMENT_SHADER,shader.fragmentPrelude,fragmentBody]]){const created=gl.createShader(type);if(!created)throw new Error("Scene line shader unavailable");if(shaders.push(created),gl.shaderSource(created,`#version 300 es
33
+ precision highp float;
34
+ ${shader.defines}
35
+ ${prelude}
36
+ ${body}`),gl.compileShader(created),!gl.getShaderParameter(created,gl.COMPILE_STATUS))throw new Error("Scene line shader failed to compile")}const program=gl.createProgram();if(!program)throw new Error("Scene line program unavailable");for(const created of shaders)gl.attachShader(program,created);if(attributes.forEach(([name],index)=>{gl.bindAttribLocation(program,index,name)}),gl.linkProgram(program),!gl.getProgramParameter(program,gl.LINK_STATUS))throw new Error("Scene line program failed to link");const value={program,shaders,locations:new Map};return programs.set(source,value),value}function location(program,name){return program.locations.has(name)||program.locations.set(name,gl.getUniformLocation(program.program,name)),program.locations.get(name)}function bufferFor(line){let owned=buffers.get(line.id);if(owned)return owned;const vao=gl.createVertexArray(),buffer=gl.createBuffer();if(!vao||!buffer)throw new Error("Scene line buffer unavailable");return gl.bindVertexArray(vao),gl.bindBuffer(gl.ARRAY_BUFFER,buffer),attributes.forEach(([,size,offset],index)=>{gl.enableVertexAttribArray(index),gl.vertexAttribPointer(index,size,gl.FLOAT,!1,FLOATS*4,offset*4)}),gl.bindVertexArray(null),owned={vao,buffer,key:"",count:0},buffers.set(line.id,owned),owned}function heights(frame,line){const result=[];for(let index=0;index<line.coordinates.length;index++){if(line.terrain[index]===0){result.push(0);continue}const row=line.coordinates[index],resolved=frame.geographic.resolve({lngLat:[canonicalLongitude(row[0]),mercatorLatitude(row[1])],altitudeReference:"terrain"});if(resolved.status==="terrain-pending")return;result.push(resolved.status==="resolved"?resolved.altitude:0)}return result}return{render(frame){if(disposed)return;const viewport=[frame.width*frame.pixelRatio,frame.height*frame.pixelRatio];gl.disable(gl.CULL_FACE),gl.enable(gl.BLEND),gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);for(const line of lines){if(line.coordinates.length<2||line.rgba[3]===0)continue;const first=line.coordinates[0],origin=context.geographic.frameFor({lngLat:[canonicalLongitude(first[0]),mercatorLatitude(first[1])]}),terrainDependent=line.terrain.some(weight=>weight!==0),key=`${origin.tile.z}/${origin.tile.x}/${origin.tile.y}/${origin.tile.wrap}/${terrainDependent?frame.revision:0}`,owned=bufferFor(line);if(owned.key!==key){const sampled=terrainDependent?heights(frame,line):line.coordinates.map(()=>0);if(!sampled)continue;const data=elevatedLineVertices(line,origin.tile,sampled);gl.bindBuffer(gl.ARRAY_BUFFER,owned.buffer),gl.bufferData(gl.ARRAY_BUFFER,data,gl.DYNAMIC_DRAW),owned.key=key,owned.count=data.length/FLOATS}const shader=frame.geographic.shader(origin),program=compile(shader);gl.useProgram(program.program);for(const uniform of shader.uniforms){const target=location(program,uniform.name);target&&(uniform.type==="float"?gl.uniform1f(target,uniform.value):uniform.type==="vec4"?gl.uniform4fv(target,uniform.value):gl.uniformMatrix4fv(target,!1,uniform.value))}gl.uniform2f(location(program,"u_lr_viewport"),viewport[0],viewport[1]),gl.uniform1f(location(program,"u_lr_pixel_ratio"),frame.pixelRatio),gl.bindVertexArray(owned.vao),gl.drawArrays(gl.TRIANGLES,0,owned.count)}gl.bindVertexArray(null)},dispose(){if(!disposed){if(disposed=!0,gl.isContextLost()){programs.clear(),buffers.clear();return}for(const owned of buffers.values())gl.deleteVertexArray(owned.vao),gl.deleteBuffer(owned.buffer);for(const program of programs.values()){gl.deleteProgram(program.program);for(const shader of program.shaders)gl.deleteShader(shader)}programs.clear(),buffers.clear()}}}}})}export{createElevatedSceneLineLayer,elevatedLineVertices};
@@ -0,0 +1 @@
1
+ const TILE_EXTENT=8192,MERCATOR_LATITUDE_LIMIT=85.0511287798066,radians=Math.PI/180;function canonicalLongitude(value){if(value>=-180&&value<180)return value===0?0:value;const result=(value%360+540)%360-180;return result===0?0:result}function encodeTileVertex(longitude,latitude,altitude,tile){const size=2**tile.z,clamped=Math.max(-MERCATOR_LATITUDE_LIMIT,Math.min(MERCATOR_LATITUDE_LIMIT,latitude)),worldX=(longitude+180)/360,worldY=clamped===0?.5:(1-Math.asinh(Math.tan(clamped*radians))/Math.PI)/2;return[(worldX*size-tile.x)*8192,(worldY*size-tile.y)*8192,altitude]}function decodeTileVertex(x,y,altitude,tile){const size=2**tile.z,worldX=(x/8192+tile.x)/size,worldY=(y/8192+tile.y)/size;return[worldX*360-180,Math.atan(Math.sinh(Math.PI*(1-2*worldY)))/radians,altitude]}function lineWorldShift(firstLongitude){return canonicalLongitude(firstLongitude)-firstLongitude}export{MERCATOR_LATITUDE_LIMIT,TILE_EXTENT,canonicalLongitude,decodeTileVertex,encodeTileVertex,lineWorldShift};
@@ -1 +1 @@
1
- const SCENE_LINE_VERTEX_LIMIT=262144,SCENE_ARC_MIN_SEGMENTS=32,radians=Math.PI/180,FINEST_STEP=radians;function unit(position){const lng=position.lngLat[0]*radians,lat=position.lngLat[1]*radians;return[Math.cos(lat)*Math.cos(lng),Math.cos(lat)*Math.sin(lng),Math.sin(lat)]}function angle(a,b){const cross=Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]);return Math.atan2(cross,a[0]*b[0]+a[1]*b[1]+a[2]*b[2])}function sceneArcAltitude(start,end,height,t){return start+(end-start)*t+height*4*t*(1-t)}function sceneLineGrounded(object,terrain){return object.kind==="arc"&&object.height!==0?!1:(object.kind==="arc"?[object.start,object.end]:object.positions).every(position=>position.altitude===0&&(!terrain||position.altitudeReference==="terrain"))}function segments(object){if(object.kind==="arc")return[{start:object.start,end:object.end,angle:angle(unit(object.start),unit(object.end)),greatCircle:!0,minimum:32,height:object.height}];const greatCircle=object.interpolation==="great-circle",result=[];for(let index=1;index<object.positions.length;index++){const start=object.positions[index-1],end=object.positions[index];result.push({start,end,angle:greatCircle?angle(unit(start),unit(end)):0,greatCircle,minimum:1,height:0})}return result}function steps(segment,step){return segment.greatCircle?Math.max(segment.minimum,Math.ceil(segment.angle/step)):1}function unwrap(longitude,previous){if(previous===void 0)return longitude;let value=longitude;for(;value-previous>180;)value-=360;for(;value-previous<-180;)value+=360;return value}function emit(target,longitude,latitude,altitude){const value=unwrap(longitude,target.at(-1)?.[0]);target.push(Object.freeze([value===0?0:value,latitude===0?0:latitude,altitude===0?0:altitude]))}function trace(object,rows,step){const coordinates=[],first=rows[0].start;emit(coordinates,first.lngLat[0],first.lngLat[1],first.altitude);for(const segment of rows){const count=steps(segment,step),{start,end}=segment,a=unit(start),b=unit(end),sine=Math.sin(segment.angle);for(let index=1;index<count;index++){const t=index/count,altitude=object.kind==="arc"?sceneArcAltitude(start.altitude,end.altitude,segment.height,t):start.altitude+(end.altitude-start.altitude)*t;if(sine<1e-12){emit(coordinates,start.lngLat[0]+(unwrap(end.lngLat[0],start.lngLat[0])-start.lngLat[0])*t,start.lngLat[1]+(end.lngLat[1]-start.lngLat[1])*t,altitude);continue}const wa=Math.sin((1-t)*segment.angle)/sine,wb=Math.sin(t*segment.angle)/sine,x=wa*a[0]+wb*b[0],y=wa*a[1]+wb*b[1],z=wa*a[2]+wb*b[2];emit(coordinates,Math.atan2(y,x)/radians,Math.atan2(z,Math.hypot(x,y))/radians,altitude)}emit(coordinates,end.lngLat[0],end.lngLat[1],end.altitude)}return Object.freeze(coordinates)}function tessellateSceneLines(objects,limit=262144){const rows=objects.map(segments),count=step2=>rows.reduce((total,row)=>total+1+row.reduce((sum,segment)=>sum+steps(segment,step2),0),0);let step=FINEST_STEP;for(;count(step)>limit;){if(step>=Math.PI)return;step*=2}return Object.freeze(objects.map((object,index)=>trace(object,rows[index],step)))}function buildSceneLineData(objects,colors,limit=262144){if(objects.some(object=>!colors.has(object.id)))return;const geometry=tessellateSceneLines(objects,limit);if(!geometry)return;const features=objects.map((object,index)=>Object.freeze({type:"Feature",properties:Object.freeze({id:object.id,kind:object.kind,color:colors.get(object.id),width:object.width,opacity:object.opacity}),geometry:Object.freeze({type:"LineString",coordinates:geometry[index]})}));return Object.freeze({type:"FeatureCollection",features:Object.freeze(features)})}export{SCENE_ARC_MIN_SEGMENTS,buildSceneLineData,sceneArcAltitude,sceneLineGrounded,tessellateSceneLines};
1
+ const SCENE_LINE_VERTEX_LIMIT=262144,SCENE_ARC_MIN_SEGMENTS=32,radians=Math.PI/180,FINEST_STEP=radians;function unit(position){const lng=position.lngLat[0]*radians,lat=position.lngLat[1]*radians;return[Math.cos(lat)*Math.cos(lng),Math.cos(lat)*Math.sin(lng),Math.sin(lat)]}function angle(a,b){const cross=Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]);return Math.atan2(cross,a[0]*b[0]+a[1]*b[1]+a[2]*b[2])}function sceneArcAltitude(start,end,height,t){return start+(end-start)*t+height*4*t*(1-t)}function sceneLineGrounded(object,terrain){return object.kind==="arc"&&object.height!==0?!1:(object.kind==="arc"?[object.start,object.end]:object.positions).every(position=>position.altitude===0&&(!terrain||position.altitudeReference==="terrain"))}function segments(object){if(object.kind==="arc")return[{start:object.start,end:object.end,angle:angle(unit(object.start),unit(object.end)),greatCircle:!0,minimum:32,height:object.height}];const greatCircle=object.interpolation==="great-circle",result=[];for(let index=1;index<object.positions.length;index++){const start=object.positions[index-1],end=object.positions[index];result.push({start,end,angle:greatCircle?angle(unit(start),unit(end)):0,greatCircle,minimum:1,height:0})}return result}function steps(segment,step){return segment.greatCircle?Math.max(segment.minimum,Math.ceil(segment.angle/step)):1}function unwrap(longitude,previous){if(previous===void 0)return longitude;let value=longitude;for(;value-previous>180;)value-=360;for(;value-previous<-180;)value+=360;return value}function emit(target,longitude,latitude,altitude){const value=unwrap(longitude,target.at(-1)?.[0]);target.push(Object.freeze([value===0?0:value,latitude===0?0:latitude,altitude===0?0:altitude]))}const terrainWeight=position=>position.altitudeReference==="terrain"?1:0;function trace(object,rows,step){const coordinates=[],terrain=[],first=rows[0].start;emit(coordinates,first.lngLat[0],first.lngLat[1],first.altitude),terrain.push(terrainWeight(first));for(const segment of rows){const count=steps(segment,step),{start,end}=segment,a=unit(start),b=unit(end),sine=Math.sin(segment.angle),startWeight=terrainWeight(start),endWeight=terrainWeight(end);for(let index=1;index<count;index++){const t=index/count,altitude=object.kind==="arc"?sceneArcAltitude(start.altitude,end.altitude,segment.height,t):start.altitude+(end.altitude-start.altitude)*t;if(terrain.push(startWeight+(endWeight-startWeight)*t),sine<1e-12){emit(coordinates,start.lngLat[0]+(unwrap(end.lngLat[0],start.lngLat[0])-start.lngLat[0])*t,start.lngLat[1]+(end.lngLat[1]-start.lngLat[1])*t,altitude);continue}const wa=Math.sin((1-t)*segment.angle)/sine,wb=Math.sin(t*segment.angle)/sine,x=wa*a[0]+wb*b[0],y=wa*a[1]+wb*b[1],z=wa*a[2]+wb*b[2];emit(coordinates,Math.atan2(y,x)/radians,Math.atan2(z,Math.hypot(x,y))/radians,altitude)}emit(coordinates,end.lngLat[0],end.lngLat[1],end.altitude),terrain.push(endWeight)}return Object.freeze({coordinates:Object.freeze(coordinates),terrain:Object.freeze(terrain)})}function traceSceneLines(objects,limit=262144){const rows=objects.map(segments),count=step2=>rows.reduce((total,row)=>total+1+row.reduce((sum,segment)=>sum+steps(segment,step2),0),0);let step=FINEST_STEP;for(;count(step)>limit;){if(step>=Math.PI)return;step*=2}return Object.freeze(objects.map((object,index)=>trace(object,rows[index],step)))}function tessellateSceneLines(objects,limit=262144){const geometry=traceSceneLines(objects,limit);return geometry&&Object.freeze(geometry.map(row=>row.coordinates))}function sceneLineDataFrom(objects,geometry,colors){if(objects.length!==geometry.length||objects.some(object=>!colors.has(object.id)))return;const features=objects.map((object,index)=>Object.freeze({type:"Feature",properties:Object.freeze({id:object.id,kind:object.kind,color:colors.get(object.id),width:object.width,opacity:object.opacity}),geometry:Object.freeze({type:"LineString",coordinates:geometry[index].coordinates})}));return Object.freeze({type:"FeatureCollection",features:Object.freeze(features)})}function buildSceneLineData(objects,colors,limit=262144){if(objects.some(object=>!colors.has(object.id)))return;const geometry=traceSceneLines(objects,limit);return geometry&&sceneLineDataFrom(objects,geometry,colors)}export{SCENE_ARC_MIN_SEGMENTS,buildSceneLineData,sceneArcAltitude,sceneLineDataFrom,sceneLineGrounded,tessellateSceneLines,traceSceneLines};
@@ -1 +1 @@
1
- import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createMapSceneLineLayer}from"./map-scene-line-layer.js";import{buildSceneLineData}from"./map-scene-lines.js";const isLine=row=>row.kind==="path"||row.kind==="arc";function channel(value){return Math.round(Math.min(1,Math.max(0,value))*255)}function bridgeReport(value){try{if(value===null||typeof value!="object")return;const state=Reflect.get(value,"state"),revision=Reflect.get(value,"acceptedSceneRevision"),code=Reflect.get(value,"code");if(typeof revision!="number"||!Number.isSafeInteger(revision)||revision<0)return;if(state==="installed")return{revision,outcome:{state:"drawn"}};if(state==="pending")return{revision,outcome:{state:"pending"}};if(state==="unavailable")return{revision,outcome:{state:"failed",code:code==="limit"?"limit":code==="context-lost"?"context-lost":"engine"}}}catch{}}function resolvedColor(element,expression){const color=resolveCanvasColor(element,expression,"");if(!color)return;const match=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/.exec(color);if(match){const channels=[Number(match[1])/255,Number(match[2])/255,Number(match[3])/255,match[4]===void 0?1:Number(match[4])];if(channels.every(value=>Number.isFinite(value)&&value>=0&&value<=1))return channels}const canvas=element.ownerDocument.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{colorSpace:"srgb",willReadFrequently:!0});if(!context)return;context.fillStyle=color,context.fillRect(0,0,1,1);const pixel=context.getImageData(0,0,1,1).data;return[pixel[0]/255,pixel[1]/255,pixel[2]/255,pixel[3]/255]}function createMapSceneRenderController(options){const{element,map,container,owner}=options,document=element.ownerDocument,view=document.defaultView,abort=new(view?.AbortController??AbortController),releases=[];let closed=!1,intersecting=!1,visibilityObserved=!1,intersectionObserved=!1,allocationRead={},bridge,visible,loading=!1,attemptedRevision,preparing=!1,bridgeFailure,report,markerContextLost=!1,linesFor,lineColorsStale=!0;function current(){return!closed&&view!==null&&element.isConnected&&element.ownerDocument===document&&options.isCurrent()}function demand(){return owner.captureAccepted().objects.some(row=>row.kind==="marker")}function statusChanged(){if(current())try{options.onStatusChange?.()}catch{}}const lines=createMapSceneLineLayer({map,isCurrent:()=>current(),styleLoaded:()=>{try{return options.styleLoaded?.()??map.isStyleLoaded?.()===!0}catch{return!1}},changed:statusChanged});function syncLines(){if(!current())return;const accepted=owner.captureAccepted();if(accepted===linesFor&&!lineColorsStale)return;const objects=accepted.objects.filter(isLine);if(objects.length===0){linesFor=accepted,lineColorsStale=!1,lines.update(void 0);return}const colors=new Map,resolved=new Map;let request;try{for(const row of objects){const expression=row.color??`var(${options.accentToken})`;if(resolved.has(expression)||resolved.set(expression,resolvedColor(element,expression)),!current()||owner.captureAccepted()!==accepted)return;const rgba=resolved.get(expression);if(!rgba){request={revision:accepted.acceptedSceneRevision,failure:"engine"};break}colors.set(row.id,`rgba(${channel(rgba[0])}, ${channel(rgba[1])}, ${channel(rgba[2])}, ${rgba[3]})`)}if(!request){const data=buildSceneLineData(objects,colors);request=data?{revision:accepted.acceptedSceneRevision,objects,data}:{revision:accepted.acceptedSceneRevision,failure:"limit"}}}catch{request={revision:accepted.acceptedSceneRevision,failure:"engine"}}!current()||owner.captureAccepted()!==accepted||(linesFor=accepted,lineColorsStale=!1,lines.update(request))}function markerOutcome(revision){return demand()?bridgeFailure===revision?{state:"failed",code:"engine"}:markerContextLost?{state:"failed",code:"context-lost"}:report?.revision===revision?report.outcome:{state:"pending"}:{state:"none"}}function keep(release){if(current())releases.push(release);else try{release()}catch{}}function syncVisibility(){if(!current()||!bridge)return;const publication=owner.captureRenderPublication(),next=visibilityObserved&&intersectionObserved&&intersecting&&document.visibilityState!=="hidden"&&!document.hidden&&publication.phase==="resolved"&&publication.input.allocation!==void 0&&demand();if(visible!==next){visible=next;try{bridge.setVisible(next)}catch{}}}function preparePublication(expected){try{const colors=new Map,markers=[];for(const row of expected.accepted.objects){if(row.kind!=="marker")continue;const expression=row.color??`var(${options.accentToken})`;let rgba=colors.get(expression);if(!rgba){if(rgba=resolvedColor(element,expression),!rgba){current()&&owner.failPresentation(expected);return}colors.set(expression,rgba)}if(!current()||owner.captureRenderPublication()!==expected)return;markers.push({id:row.id,rgba})}const presentation={markers,reducedMotion:prefersReducedMotion(element)};current()&&owner.commitPresentation(expected,presentation)}catch{current()&&owner.failPresentation(expected)}}function prepare(){if(!(!current()||preparing)){preparing=!0;try{for(let pass=0;pass<32&&current();pass++){const expected=owner.captureRenderPublication();if(expected.phase!=="pending"||(preparePublication(expected),owner.captureRenderPublication()===expected))return}current()&&owner.failPresentation(owner.captureRenderPublication())}finally{preparing=!1}}}function refreshAllocation(){if(!current()||!demand())return;const attempt={};allocationRead=attempt;const active=()=>current()&&allocationRead===attempt;let allocation;try{const getContainer=map.getContainer;if(!active())return;const getCanvas=map.getCanvas;if(!active())return;const getPixelRatio=map.getPixelRatio;if(!active())return;const getPadding=map.getPadding;if(!active())return;if(typeof getContainer=="function"&&typeof getCanvas=="function"&&typeof getPixelRatio=="function"&&typeof getPadding=="function"){const nativeContainer=getContainer.call(map);if(!active())return;const canvas=getCanvas.call(map);if(!active())return;const width=nativeContainer.clientWidth;if(!active())return;const height=nativeContainer.clientHeight;if(!active())return;const pixelRatio=getPixelRatio.call(map);if(!active())return;const padding=getPadding.call(map);if(!active())return;const top=padding.top;if(!active())return;const right=padding.right;if(!active())return;const bottom=padding.bottom;if(!active())return;const left=padding.left;if(!active())return;const backingWidth=canvas.width;if(!active())return;const backingHeight=canvas.height;if(!active())return;const sameContainer=map.getContainer?.()===nativeContainer;if(!active())return;const sameCanvas=map.getCanvas()===canvas;if(!active())return;const sameWidth=nativeContainer.clientWidth===width;if(!active())return;const sameHeight=nativeContainer.clientHeight===height;if(!active())return;const sameBackingWidth=canvas.width===backingWidth;if(!active())return;const sameBackingHeight=canvas.height===backingHeight;if(!active())return;sameContainer&&sameCanvas&&sameWidth&&sameHeight&&sameBackingWidth&&sameBackingHeight&&nativeContainer===container&&nativeContainer.ownerDocument===document&&canvas.ownerDocument===document&&Number.isSafeInteger(width)&&width>0&&Number.isSafeInteger(height)&&height>0&&Number.isFinite(pixelRatio)&&pixelRatio>0&&Number.isSafeInteger(backingWidth)&&backingWidth>0&&Number.isSafeInteger(backingHeight)&&backingHeight>0&&backingWidth===Math.round(width*pixelRatio)&&backingHeight===Math.round(height*pixelRatio)&&[top,right,bottom,left].every(value=>Number.isFinite(value)&&value>=0)&&(allocation={width,height,pixelRatio,padding:{top,right,bottom,left}})}}catch{}active()&&(owner.setViewport(allocation),active()&&syncVisibility())}function startBridge(){if(!current()||!demand()||bridge||loading)return;const revision=owner.captureAccepted().acceptedSceneRevision;attemptedRevision!==revision&&(attemptedRevision=revision,loading=!0,options.loadBridge().then(runtime=>{if(!current()||!demand())return;let candidate;try{const created=runtime.createSceneBridge(map,{signal:abort.signal,isCurrent:current,captureRenderInput:()=>owner.captureRenderPublication().input,subscribeRenderInput:listener=>owner.subscribeRenderPublication(listener),onState:value=>{const next=current()&&bridge===created?bridgeReport(value):void 0;next&&(report=next,next.outcome.state==="drawn"&&(markerContextLost=!1),statusChanged())},onError:code=>{!current()||bridge!==created||code!=="context-lost"||(markerContextLost=!0,statusChanged())}});if(candidate=created,!created||!["dispose","invalidateStyle","setVisible","requestFrame"].every(name=>typeof Reflect.get(created,name)=="function"))throw new TypeError("Map scene renderer unavailable");if(!current()||!demand()){created.dispose();return}bridge=created,visible=void 0,syncVisibility()}catch{try{candidate?.dispose()}catch{}current()&&(bridgeFailure=revision,statusChanged())}},()=>{current()&&(bridgeFailure=revision,statusChanged())}).finally(()=>{loading=!1,current()&&owner.captureAccepted().acceptedSceneRevision!==attemptedRevision&&startBridge()}))}function retireBridge(){const previous=bridge;if(!(!previous||demand())){bridge=void 0,visible=void 0,report=void 0,markerContextLost=!1,attemptedRevision=void 0;try{previous.dispose()}catch{}}}function sync(){current()&&(retireBridge(),prepare(),syncVisibility(),startBridge(),syncLines())}function refreshPresentation(){current()&&(lineColorsStale=!0,demand()&&owner.invalidatePresentation(),sync())}function dispose(){if(closed)return;closed=!0,allocationRead={};const previous=bridge;bridge=void 0;for(const release of releases.splice(0))try{release()}catch{}abort.abort();try{previous?.dispose()}catch{}lines.dispose()}keep(owner.subscribeRenderPublication(sync));for(const event of["move","resize"])try{keep(()=>{map.off?.(event,refreshAllocation)}),current()&&(Reflect.apply(map.on,map,[event,refreshAllocation]),current()||map.off?.(event,refreshAllocation))}catch{}try{const Observer=view?.IntersectionObserver;if(Observer){const observer=new Observer(entries=>{if(current()){for(const entry of entries)entry.target===container&&(intersecting=entry.isIntersecting);syncVisibility()}});keep(()=>observer.disconnect()),current()&&(observer.observe(container),intersectionObserved=current())}}catch{intersecting=!1}keep(()=>document.removeEventListener("visibilitychange",syncVisibility));try{current()&&(document.addEventListener("visibilitychange",syncVisibility),visibilityObserved=current())}catch{intersecting=!1}try{keep(observeReducedMotion(element,refreshPresentation))}catch{}return refreshAllocation(),sync(),{sync,refreshPresentation,refreshAllocation,invalidateStyle(){if(current()){try{bridge?.invalidateStyle()}catch{}lines.invalidateStyle()}},styleReady(){current()&&lines.styleReady()},captureOutcomes(){const revision=owner.captureAccepted().acceptedSceneRevision,captured=lines.capture();return{markers:markerOutcome(revision),lines:captured.revision===revision||captured.outcome.state==="none"?captured.outcome:{state:"pending"}}},dispose}}export{createMapSceneRenderController};
1
+ import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{isMapSceneLayerHandle,loadMapSceneLayerRuntime}from"../../../internal/map-scene-layer-runtime.js";import{createMapSceneLineLayer}from"./map-scene-line-layer.js";import{sceneLineDataFrom,sceneLineGrounded,traceSceneLines}from"./map-scene-lines.js";const SCENE_ELEVATED_LINE_LAYER="lr-scene-elevated-lines",isLine=row=>row.kind==="path"||row.kind==="arc";function channel(value){return Math.round(Math.min(1,Math.max(0,value))*255)}function terrainActive(map){try{const terrain=map.getTerrain?.();return terrain!=null}catch{return!1}}function combineLineOutcomes(flat,elevated){return flat.state==="none"?elevated:elevated.state==="none"?flat:flat.state==="pending"||elevated.state==="pending"?{state:"pending"}:flat.state==="failed"?flat:elevated.state==="failed"?elevated:{state:"drawn",approximate:!!(flat.approximate||elevated.approximate)}}function bridgeReport(value){try{if(value===null||typeof value!="object")return;const state=Reflect.get(value,"state"),revision=Reflect.get(value,"acceptedSceneRevision"),code=Reflect.get(value,"code");if(typeof revision!="number"||!Number.isSafeInteger(revision)||revision<0)return;if(state==="installed")return{revision,outcome:{state:"drawn"}};if(state==="pending")return{revision,outcome:{state:"pending"}};if(state==="unavailable")return{revision,outcome:{state:"failed",code:code==="limit"?"limit":code==="context-lost"?"context-lost":"engine"}}}catch{}}function resolvedColor(element,expression){const color=resolveCanvasColor(element,expression,"");if(!color)return;const match=/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/.exec(color);if(match){const channels=[Number(match[1])/255,Number(match[2])/255,Number(match[3])/255,match[4]===void 0?1:Number(match[4])];if(channels.every(value=>Number.isFinite(value)&&value>=0&&value<=1))return channels}const canvas=element.ownerDocument.createElement("canvas");canvas.width=1,canvas.height=1;const context=canvas.getContext("2d",{colorSpace:"srgb",willReadFrequently:!0});if(!context)return;context.fillStyle=color,context.fillRect(0,0,1,1);const pixel=context.getImageData(0,0,1,1).data;return[pixel[0]/255,pixel[1]/255,pixel[2]/255,pixel[3]/255]}function createMapSceneRenderController(options){const{element,map,container,owner}=options,document=element.ownerDocument,view=document.defaultView,abort=new(view?.AbortController??AbortController),releases=[];let closed=!1,intersecting=!1,visibilityObserved=!1,intersectionObserved=!1,allocationRead={},bridge,visible,loading=!1,attemptedRevision,preparing=!1,bridgeFailure,report,markerContextLost=!1,linesFor,lineColorsStale=!0,elevatedRuntime,elevatedLoading=!1,elevatedWanted=!1,elevated,elevatedFailed,linesTerrain;function current(){return!closed&&view!==null&&element.isConnected&&element.ownerDocument===document&&options.isCurrent()}function demand(){return owner.captureAccepted().objects.some(row=>row.kind==="marker")}function statusChanged(){if(current())try{options.onStatusChange?.()}catch{}}const lines=createMapSceneLineLayer({map,isCurrent:()=>current(),styleLoaded:()=>{try{return options.styleLoaded?.()??map.isStyleLoaded?.()===!0}catch{return!1}},changed:statusChanged});function retireElevated(){const previous=elevated;if(elevated=void 0,!!previous){previous.controller.abort();try{previous.handle?.dispose()}catch{}}}function linesInvalidated(){current()&&(lineColorsStale=!0,sync(),statusChanged())}function startElevatedRuntime(){elevatedLoading||elevatedRuntime!==void 0||(elevatedLoading=!0,Promise.all([loadMapSceneLayerRuntime(),import("./map-scene-elevated-lines.js")]).then(([layers,lines2])=>{elevatedRuntime={layers,lines:lines2}},()=>{elevatedRuntime=null}).finally(()=>{elevatedLoading=!1,linesInvalidated()}))}function installElevated(runtime,revision,data){retireElevated();const installation={revision,controller:new(view?.AbortController??AbortController),handle:void 0,outcome:{state:"pending"}};elevated=installation;const fail=()=>{elevated===installation&&(elevatedFailed=revision,retireElevated(),queueMicrotask(linesInvalidated))};try{const handle=runtime.layers.createSceneLayer(map,runtime.lines.createElevatedSceneLineLayer(SCENE_ELEVATED_LINE_LAYER,data),{signal:installation.controller.signal,reducedMotion:()=>prefersReducedMotion(element),onState:(state,code)=>{if(!(elevated!==installation||!current())){if(state==="ready")installation.outcome={state:"drawn"};else if(state==="loading")installation.outcome={state:"pending"};else if(code==="context-lost")installation.outcome={state:"failed",code:"context-lost"};else{fail();return}statusChanged()}}});if(!isMapSceneLayerHandle(handle))throw new TypeError("Map custom layers are unavailable");if(elevated!==installation){handle.dispose();return}installation.handle=handle}catch{fail()}}function syncLines(){if(!current())return;const accepted=owner.captureAccepted();if(accepted===linesFor&&!lineColorsStale)return;const objects=accepted.objects.filter(isLine),revision=accepted.acceptedSceneRevision;if(objects.length===0){linesFor=accepted,lineColorsStale=!1,elevatedWanted=!1,retireElevated(),lines.update(void 0);return}const colors=new Map,rgbas=new Map,resolved=new Map;let request,exact=[];const terrain=terrainActive(map);try{for(const row of objects){const expression=row.color??`var(${options.accentToken})`;if(resolved.has(expression)||resolved.set(expression,resolvedColor(element,expression)),!current()||owner.captureAccepted()!==accepted)return;const rgba=resolved.get(expression);if(!rgba){request={revision,failure:"engine"};break}colors.set(row.id,`rgba(${channel(rgba[0])}, ${channel(rgba[1])}, ${channel(rgba[2])}, ${rgba[3]})`),rgbas.set(row.id,rgba)}const geometry=request?void 0:traceSceneLines(objects);if(!request&&!geometry&&(request={revision,failure:"limit"}),!request&&geometry){const raised=objects.map(row=>!sceneLineGrounded(row,terrain));elevatedWanted=raised.some(Boolean);const runtime=elevatedWanted&&elevatedFailed!==revision?elevatedRuntime:void 0;elevatedWanted&&elevatedRuntime===void 0&&startElevatedRuntime();const flat=[],flatGeometry=[];if(objects.forEach((row,index)=>{if(runtime&&raised[index]){const rgba=rgbas.get(row.id);exact.push({id:row.id,coordinates:geometry[index].coordinates,terrain:geometry[index].terrain,rgba:[rgba[0],rgba[1],rgba[2],rgba[3]*row.opacity],width:row.width})}else flat.push(row),flatGeometry.push(geometry[index])}),flat.length){const data=sceneLineDataFrom(flat,flatGeometry,colors);request=data?{revision,objects:flat,data}:{revision,failure:"engine"}}}}catch{request={revision,failure:"engine"},exact=[]}!current()||owner.captureAccepted()!==accepted||(linesFor=accepted,lineColorsStale=!1,linesTerrain=terrain,request&&"failure"in request&&(exact=[]),exact.length&&elevatedRuntime?installElevated(elevatedRuntime,revision,exact):retireElevated(),lines.update(request))}function elevatedOutcome(revision){return elevatedWanted?elevated?elevated.revision===revision?elevated.outcome:{state:"pending"}:elevatedRuntime===void 0&&elevatedFailed!==revision?{state:"pending"}:{state:"none"}:{state:"none"}}function markerOutcome(revision){return demand()?bridgeFailure===revision?{state:"failed",code:"engine"}:markerContextLost?{state:"failed",code:"context-lost"}:report?.revision===revision?report.outcome:{state:"pending"}:{state:"none"}}function keep(release){if(current())releases.push(release);else try{release()}catch{}}function syncVisibility(){if(!current()||!bridge)return;const publication=owner.captureRenderPublication(),next=visibilityObserved&&intersectionObserved&&intersecting&&document.visibilityState!=="hidden"&&!document.hidden&&publication.phase==="resolved"&&publication.input.allocation!==void 0&&demand();if(visible!==next){visible=next;try{bridge.setVisible(next)}catch{}}}function preparePublication(expected){try{const colors=new Map,markers=[];for(const row of expected.accepted.objects){if(row.kind!=="marker")continue;const expression=row.color??`var(${options.accentToken})`;let rgba=colors.get(expression);if(!rgba){if(rgba=resolvedColor(element,expression),!rgba){current()&&owner.failPresentation(expected);return}colors.set(expression,rgba)}if(!current()||owner.captureRenderPublication()!==expected)return;markers.push({id:row.id,rgba})}const presentation={markers,reducedMotion:prefersReducedMotion(element)};current()&&owner.commitPresentation(expected,presentation)}catch{current()&&owner.failPresentation(expected)}}function prepare(){if(!(!current()||preparing)){preparing=!0;try{for(let pass=0;pass<32&&current();pass++){const expected=owner.captureRenderPublication();if(expected.phase!=="pending"||(preparePublication(expected),owner.captureRenderPublication()===expected))return}current()&&owner.failPresentation(owner.captureRenderPublication())}finally{preparing=!1}}}function refreshAllocation(){if(!current()||!demand())return;const attempt={};allocationRead=attempt;const active=()=>current()&&allocationRead===attempt;let allocation;try{const getContainer=map.getContainer;if(!active())return;const getCanvas=map.getCanvas;if(!active())return;const getPixelRatio=map.getPixelRatio;if(!active())return;const getPadding=map.getPadding;if(!active())return;if(typeof getContainer=="function"&&typeof getCanvas=="function"&&typeof getPixelRatio=="function"&&typeof getPadding=="function"){const nativeContainer=getContainer.call(map);if(!active())return;const canvas=getCanvas.call(map);if(!active())return;const width=nativeContainer.clientWidth;if(!active())return;const height=nativeContainer.clientHeight;if(!active())return;const pixelRatio=getPixelRatio.call(map);if(!active())return;const padding=getPadding.call(map);if(!active())return;const top=padding.top;if(!active())return;const right=padding.right;if(!active())return;const bottom=padding.bottom;if(!active())return;const left=padding.left;if(!active())return;const backingWidth=canvas.width;if(!active())return;const backingHeight=canvas.height;if(!active())return;const sameContainer=map.getContainer?.()===nativeContainer;if(!active())return;const sameCanvas=map.getCanvas()===canvas;if(!active())return;const sameWidth=nativeContainer.clientWidth===width;if(!active())return;const sameHeight=nativeContainer.clientHeight===height;if(!active())return;const sameBackingWidth=canvas.width===backingWidth;if(!active())return;const sameBackingHeight=canvas.height===backingHeight;if(!active())return;sameContainer&&sameCanvas&&sameWidth&&sameHeight&&sameBackingWidth&&sameBackingHeight&&nativeContainer===container&&nativeContainer.ownerDocument===document&&canvas.ownerDocument===document&&Number.isSafeInteger(width)&&width>0&&Number.isSafeInteger(height)&&height>0&&Number.isFinite(pixelRatio)&&pixelRatio>0&&Number.isSafeInteger(backingWidth)&&backingWidth>0&&Number.isSafeInteger(backingHeight)&&backingHeight>0&&backingWidth===Math.round(width*pixelRatio)&&backingHeight===Math.round(height*pixelRatio)&&[top,right,bottom,left].every(value=>Number.isFinite(value)&&value>=0)&&(allocation={width,height,pixelRatio,padding:{top,right,bottom,left}})}}catch{}active()&&(owner.setViewport(allocation),active()&&syncVisibility())}function startBridge(){if(!current()||!demand()||bridge||loading)return;const revision=owner.captureAccepted().acceptedSceneRevision;attemptedRevision!==revision&&(attemptedRevision=revision,loading=!0,options.loadBridge().then(runtime=>{if(!current()||!demand())return;let candidate;try{const created=runtime.createSceneBridge(map,{signal:abort.signal,isCurrent:current,captureRenderInput:()=>owner.captureRenderPublication().input,subscribeRenderInput:listener=>owner.subscribeRenderPublication(listener),onState:value=>{const next=current()&&bridge===created?bridgeReport(value):void 0;next&&(report=next,next.outcome.state==="drawn"&&(markerContextLost=!1),statusChanged())},onError:code=>{!current()||bridge!==created||code!=="context-lost"||(markerContextLost=!0,statusChanged())}});if(candidate=created,!created||!["dispose","invalidateStyle","setVisible","requestFrame"].every(name=>typeof Reflect.get(created,name)=="function"))throw new TypeError("Map scene renderer unavailable");if(!current()||!demand()){created.dispose();return}bridge=created,visible=void 0,syncVisibility()}catch{try{candidate?.dispose()}catch{}current()&&(bridgeFailure=revision,statusChanged())}},()=>{current()&&(bridgeFailure=revision,statusChanged())}).finally(()=>{loading=!1,current()&&owner.captureAccepted().acceptedSceneRevision!==attemptedRevision&&startBridge()}))}function retireBridge(){const previous=bridge;if(!(!previous||demand())){bridge=void 0,visible=void 0,report=void 0,markerContextLost=!1,attemptedRevision=void 0;try{previous.dispose()}catch{}}}function sync(){current()&&(retireBridge(),prepare(),syncVisibility(),startBridge(),syncLines())}function refreshPresentation(){current()&&(lineColorsStale=!0,demand()&&owner.invalidatePresentation(),sync())}function dispose(){if(closed)return;closed=!0,allocationRead={};const previous=bridge;bridge=void 0;for(const release of releases.splice(0))try{release()}catch{}abort.abort();try{previous?.dispose()}catch{}retireElevated(),lines.dispose()}keep(owner.subscribeRenderPublication(sync));for(const event of["move","resize"])try{keep(()=>{map.off?.(event,refreshAllocation)}),current()&&(Reflect.apply(map.on,map,[event,refreshAllocation]),current()||map.off?.(event,refreshAllocation))}catch{}try{const Observer=view?.IntersectionObserver;if(Observer){const observer=new Observer(entries=>{if(current()){for(const entry of entries)entry.target===container&&(intersecting=entry.isIntersecting);syncVisibility()}});keep(()=>observer.disconnect()),current()&&(observer.observe(container),intersectionObserved=current())}}catch{intersecting=!1}keep(()=>document.removeEventListener("visibilitychange",syncVisibility));try{current()&&(document.addEventListener("visibilitychange",syncVisibility),visibilityObserved=current())}catch{intersecting=!1}try{keep(observeReducedMotion(element,refreshPresentation))}catch{}const terrainChanged=()=>{current()&&linesTerrain!==void 0&&terrainActive(map)!==linesTerrain&&linesInvalidated()};try{keep(()=>{map.off?.("terrain",terrainChanged)}),current()&&Reflect.apply(map.on,map,["terrain",terrainChanged])}catch{}return refreshAllocation(),sync(),{sync,refreshPresentation,refreshAllocation,invalidateStyle(){if(current()){try{bridge?.invalidateStyle()}catch{}try{elevated?.handle?.invalidateStyle()}catch{}lines.invalidateStyle()}},styleReady(){if(current()){try{elevated?.handle?.styleReady()}catch{}lines.styleReady()}},captureOutcomes(){const revision=owner.captureAccepted().acceptedSceneRevision,captured=lines.capture(),flat=captured.revision===revision||captured.outcome.state==="none"?captured.outcome:{state:"pending"};return{markers:markerOutcome(revision),lines:combineLineOutcomes(flat,elevatedOutcome(revision))}},dispose}}export{SCENE_ELEVATED_LINE_LAYER,createMapSceneRenderController};
@@ -16,7 +16,11 @@ readonly interactive?:boolean;
16
16
  readonly showLabel?:boolean;}export interface LyraMapSceneMarker extends LyraMapSceneObjectBase{readonly kind:'marker';readonly position:LyraMapPosition;
17
17
  /** Requested positive marker radius. Defaults to 6.*/
18
18
  readonly radius?:number;}
19
- /** Drawn as a native line; altitude is carried in the data and reported as `partial`/`altitude` when not representable.*/
19
+ /**
20
+ * Drawn as a native line. A path at its draped surface uses a flat line layer; any other altitude is
21
+ * drawn in 3D through the optional `@aceshooting/lyra-map/scene` layer bridge, or as its ground
22
+ * track reported as `partial`/`altitude` when that bridge is unavailable.
23
+ */
20
24
  export interface LyraMapScenePath extends LyraMapSceneObjectBase{readonly kind:'path';readonly positions:readonly LyraMapPosition[];
21
25
  /**
22
26
  * Path interpolation. Defaults to 'great-circle', the shortest route on the globe; 'linear'
@@ -27,8 +31,9 @@ readonly interpolation?:'linear'|'great-circle';
27
31
  readonly width?:number;}
28
32
  /**
29
33
  * A great-circle ground track whose altitude interpolates linearly between the endpoints plus a
30
- * parabolic rise of `height` meters at the midpoint. A nonzero altitude or height is drawn as the
31
- * ground track and reported as `partial` with code `altitude`.
34
+ * parabolic rise of `height` meters at the midpoint. A nonzero altitude or height is drawn in 3D
35
+ * through the optional scene layer bridge, or as the ground track reported as `partial` with code
36
+ * `altitude` when that bridge is unavailable.
32
37
  */
33
38
  export interface LyraMapSceneArc extends LyraMapSceneObjectBase{readonly kind:'arc';readonly start:LyraMapPosition;readonly end:LyraMapPosition;
34
39
  /** Nonnegative midpoint rise in meters above the chord between endpoint altitudes.*/
@@ -42,8 +47,8 @@ readonly orientation?:LyraMapQuaternion;}export type LyraMapSceneObject=LyraMapS
42
47
  /** New assignments are admitted atomically; undefined clears accepted scene ownership.*/
43
48
  export interface LyraMapScene{readonly objects:readonly LyraMapSceneObject[];}
44
49
  /**
45
- * `altitude`: a path or arc is drawn as its ground track because the flat map cannot show its
46
- * authored altitude or arc height. `model`: model objects are not drawn.
50
+ * `altitude`: a path or arc is drawn as its ground track because the optional 3D layer bridge is
51
+ * unavailable or failed. `model`: model objects are not drawn.
47
52
  */
48
53
  export type LyraMapSceneErrorCode='invalid'|'limit'|'model'|'resource'|'engine'|'projection'|'terrain'|'context-lost'|'altitude';
49
54
  /**
@@ -854,7 +854,7 @@ readonly trigger?:'keyboard';}>;}
854
854
  * The legend material remains stationary while its public surface scrolls. Opaque accessibility
855
855
  * fallbacks preserve native peer controls and map data paint.
856
856
  * @event lr-map-scene-state - `detail: { revision, state, code? }`. Accepted scene status: `loading`, then `ready`, `partial` or `unavailable` with a code such as `altitude` or `model`; `empty` for an empty scene. Rejected updates report `error` and retain the preceding accepted revision.
857
- * @event lr-map-scene-activate - `detail: { id, kind, source, position? }`. A current interactive scene object was activated without moving the camera.
857
+ * @event lr-map-scene-activate - `detail: { id, kind, layerId?, source, position? }`. A current interactive scene object was activated without moving the camera, or a pointer click hit an `addMapCustomLayer()` layer (`kind: 'custom'` with its `layerId`).
858
858
  * @csspart scene-panel - Accessible accepted scene object panel.
859
859
  * @csspart scene-toggle - Expands or collapses the scene object list.
860
860
  * @csspart scene-list - The current page of accepted scene objects.
@@ -871,7 +871,7 @@ export declare class LyraMap extends LyraElement<LyraMapEventMap>{protected stat
871
871
  * `loading`, then `ready`, `partial` (for example code `altitude` when an elevated path or arc is
872
872
  * drawn as its ground track, or `model`) or `unavailable`.
873
873
  * The authored property remains caller-owned; mutate by assigning a new scene object. */
874
- get scene():LyraMapScene|undefined;set scene(value:LyraMapScene|undefined);private connectGeographicScene;private closeGeographicScene;private geographicSceneChanged;private stopGeographicSceneRender;private syncGeographicSceneStatus;private syncGeographicSceneRender;private syncGeographicSceneRenderer;private sceneStatusMessage;private sceneInteractionAllowed;private activateSceneObject;private renderGeographicScene;
874
+ get scene():LyraMapScene|undefined;set scene(value:LyraMapScene|undefined);private connectGeographicScene;private closeGeographicScene;private geographicSceneChanged;private stopGeographicSceneRender;private syncGeographicSceneStatus;private syncGeographicSceneRender;private syncGeographicSceneRenderer;private notifyCustomLayers;private acquireCustomLayer;private sceneStatusMessage;private sceneInteractionAllowed;private activateSceneObject;private renderGeographicScene;
875
875
  /** MapLibre features and admitted marker snapshots carry opaque peer values that the generic
876
876
  * event-detail snapshotter must not walk. The marker is already a frozen canonical record; its
877
877
  * `unsafeHtml` value therefore reaches both Popup and activation consumers by identity. */
@@ -1247,7 +1247,7 @@ label?:string;
1247
1247
  /** Optional engine. Set before connecting; changes take effect after disconnect/reconnect.
1248
1248
  * `modular` loads `@aceshooting/lyra-map`; `maplibre` explicitly selects the full `maplibre-gl`
1249
1249
  * peer. No engine is substituted when the selected peer is unavailable. */
1250
- engine:LyraMapEngine;private loading;private failure?;private readonly announcements;private loadLibrary;private visible;private constructionScheduler?;private constructionMode;private constructionDelay?;private containerEl?;private anchorEl?;private anchorBoundaryEl?;private _map?;private _styleLoaded;private _appliedChoroplethSourceId?;private _appliedFillLayerId?;private _appliedDataLayerIds;private _appliedDataLayerShapes;private _appliedGeoJson;private _nextDataLayerId;private nextPointIconId;private appliedPointPaint;private appliedPointMuting;private appliedPointIcons;private cameraSessionConfigurationRevision;private cameraSessionConfigurationApplied;private cameraSessionConfigurationApplying;private cameraSession?;private unregisterCameraSession?;private _maplibreModule?;private _webglReady;private _markerInstances;private _markerLabels;private _markerPopupIds;private readonly markerActivationDetails;private _configuredPopups;private _nextPopupId;private peerChromeObserver?;private observedPeerContainer?;private mapResizeObserver?;private observedMapContainer?;private _markerColors;private _markerSources;private _connectGeneration;private _styleGeneration;private readonly readiness;private readonly controlsReadiness;private ownedFeatures?;private externalFeatures?;private externalFeatureWorkStarted;private externalIdStyle;private externalIdCounter;private readonly externalSourceIds;private readonly appliedGeoLabels;private readonly peerEvents;private optionalFeatureWorkStarted;
1250
+ engine:LyraMapEngine;private loading;private failure?;private readonly announcements;private loadLibrary;private visible;private constructionScheduler?;private constructionMode;private constructionDelay?;private containerEl?;private anchorEl?;private anchorBoundaryEl?;private _map?;private _styleLoaded;private _appliedChoroplethSourceId?;private _appliedFillLayerId?;private _appliedDataLayerIds;private _appliedDataLayerShapes;private _appliedGeoJson;private _nextDataLayerId;private nextPointIconId;private appliedPointPaint;private appliedPointMuting;private appliedPointIcons;private cameraSessionConfigurationRevision;private cameraSessionConfigurationApplied;private cameraSessionConfigurationApplying;private cameraSession?;private unregisterCameraSession?;private unregisterCustomLayers?;private readonly customLayerCallbacks;private readonly customLayerActivations;private _maplibreModule?;private _webglReady;private _markerInstances;private _markerLabels;private _markerPopupIds;private readonly markerActivationDetails;private _configuredPopups;private _nextPopupId;private peerChromeObserver?;private observedPeerContainer?;private mapResizeObserver?;private observedMapContainer?;private _markerColors;private _markerSources;private _connectGeneration;private _styleGeneration;private readonly readiness;private readonly controlsReadiness;private ownedFeatures?;private externalFeatures?;private externalFeatureWorkStarted;private externalIdStyle;private externalIdCounter;private readonly externalSourceIds;private readonly appliedGeoLabels;private readonly peerEvents;private optionalFeatureWorkStarted;
1251
1251
  /** Explicit basemap layer opt-in; all other basemap features remain noninteractive. Each entry
1252
1252
  * names one layer by `layerId`, or selects every current style layer whose `source`,
1253
1253
  * `sourceLayer` and `layerType` match the fields it gives (for example