@aceshooting/lyra-ui 30.5.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 +93 -0
- package/README.md +1 -1
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +7 -4
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +5 -5
- package/dist/components/conversation/code-block/onig.provenance.json +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +11 -1
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +11 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +8 -1
- package/dist/components/conversation/model-select/model-select.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +5 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +6 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +9 -2
- package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -2
- package/dist/components/conversation/widget-renderer/default-registry.js +1 -1
- package/dist/components/conversation/widget-renderer/registry.d.ts +1 -27
- package/dist/components/conversation/widget-renderer/registry.js +1 -1
- package/dist/components/conversation/widget-renderer/resolve.d.ts +1 -29
- package/dist/components/conversation/widget-renderer/resolve.js +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.d.ts +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
- package/dist/components/forms/catalog-picker-base.d.ts +3 -1
- package/dist/components/forms/catalog-picker-base.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +9 -2
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.class.d.ts +9 -2
- package/dist/components/forms/date-picker/date-input.class.js +2 -2
- package/dist/components/forms/input/input-shared.d.ts +9 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/time-input.class.d.ts +9 -2
- package/dist/components/forms/input/time-input.class.js +2 -2
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +18 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
- package/dist/components/forms/phone-input/phone-input.class.d.ts +9 -2
- package/dist/components/forms/phone-input/phone-input.class.js +2 -2
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +9 -2
- package/dist/components/forms/select/select.class.js +2 -2
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -2
- package/dist/components/forms/textarea/textarea.class.js +2 -2
- package/dist/components/forms/token-input/token-input.class.d.ts +9 -2
- package/dist/components/forms/token-input/token-input.class.js +2 -2
- package/dist/components/forms/token-input/token-input.styles.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +35 -7
- package/dist/components/layout/dock-panel/dock-panel.class.js +8 -5
- package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
- package/dist/components/layout/menu/menu-item.class.d.ts +7 -4
- package/dist/components/layout/menu/menu-item.class.js +3 -2
- package/dist/components/layout/multi-split/multi-split.class.d.ts +73 -6
- package/dist/components/layout/multi-split/multi-split.class.js +4 -4
- package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +7 -0
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +1 -5
- package/dist/components/media/image-viewer/image-viewer-panorama.js +1 -8
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-control-options.d.ts +7 -3
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-feature-loader.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +10 -4
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map-scene-admission.js +1 -0
- package/dist/components/media/map/map-scene-completion-adapter.js +1 -0
- package/dist/components/media/map/map-scene-completion-camera.js +1 -0
- package/dist/components/media/map/map-scene-configuration-controller.js +1 -0
- package/dist/components/media/map/map-scene-configuration.d.ts +15 -0
- package/dist/components/media/map/map-scene-configuration.js +1 -0
- package/dist/components/media/map/map-scene-controls.js +1 -0
- package/dist/components/media/map/map-scene-elevated-lines.js +36 -0
- package/dist/components/media/map/map-scene-errors.js +1 -0
- package/dist/components/media/map/map-scene-line-encoding.js +1 -0
- package/dist/components/media/map/map-scene-line-layer.js +1 -0
- package/dist/components/media/map/map-scene-lines.js +1 -0
- package/dist/components/media/map/map-scene-owner.js +1 -0
- package/dist/components/media/map/map-scene-position-registry.js +1 -0
- package/dist/components/media/map/map-scene-render-controller.js +1 -0
- package/dist/components/media/map/map-scene-render-input.js +1 -0
- package/dist/components/media/map/map-scene-source-snapshot.js +1 -0
- package/dist/components/media/map/map-scene-status.js +1 -0
- package/dist/components/media/map/map-scene-types.d.ts +60 -0
- package/dist/components/media/map/map.class.d.ts +60 -12
- package/dist/components/media/map/map.class.js +23 -6
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video/video.class.d.ts +1 -1
- package/dist/components/media/video/video.class.js +1 -1
- package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-curvature.js +1 -0
- package/dist/components/retrieval/graph/graph-engine-columns.js +1 -1
- package/dist/components/retrieval/graph/graph-model.d.ts +4 -0
- package/dist/components/retrieval/graph/graph-node-renderer.d.ts +13 -0
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -0
- package/dist/components/retrieval/graph/graph-source-controller.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +3 -1
- package/dist/components/retrieval/graph/graph-spatial.js +1 -1
- package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +11 -3
- package/dist/components/retrieval/graph/graph.class.js +4 -4
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +8 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +4 -2
- package/dist/events.d.ts +36 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/collection-policy.js +1 -0
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/default-strings/media.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/engine-3d-loader.d.ts +8 -2
- package/dist/internal/engine-3d-loader.js +1 -1
- package/dist/internal/form-control.styles.js +1 -1
- package/dist/internal/locale-loaders.generated.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/map-camera-follow-controller.d.ts +9 -0
- package/dist/internal/map-camera-follow-controller.js +1 -0
- package/dist/internal/map-camera-follow-data.js +1 -0
- package/dist/internal/map-camera-follow-scene.js +1 -0
- package/dist/internal/map-camera-session-controller.d.ts +59 -0
- package/dist/internal/map-camera-session-controller.js +1 -0
- package/dist/internal/map-camera-session-data.d.ts +16 -0
- package/dist/internal/map-camera-session-data.js +1 -0
- package/dist/internal/map-camera-session.js +1 -0
- package/dist/internal/map-custom-layer-attachment.js +1 -0
- package/dist/internal/map-custom-layer-controller.js +1 -0
- package/dist/internal/map-custom-layer-types.d.ts +63 -0
- package/dist/internal/map-scene-layer-runtime.js +1 -0
- package/dist/internal/map-scene-session.js +1 -0
- package/dist/internal/media-panorama.d.ts +5 -0
- package/dist/internal/media-panorama.js +8 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/sequence-playback-binding.js +1 -0
- package/dist/internal/typed-columns.d.ts +3 -1
- package/dist/internal/typed-columns.js +1 -1
- package/dist/internal/variants.d.ts +7 -0
- package/dist/internal/widget-default-registry.js +1 -0
- package/dist/internal/widget-document.d.ts +29 -0
- package/dist/internal/widget-document.js +1 -0
- package/dist/internal/widget-type-registry.d.ts +27 -0
- package/dist/internal/widget-type-registry.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/map-camera-session.d.ts +10 -0
- package/dist/map-camera-session.js +1 -0
- package/dist/map-custom-layers.d.ts +16 -0
- package/dist/map-custom-layers.js +1 -0
- package/dist/sequence-time-binding.d.ts +3 -0
- package/dist/sequence-time-binding.js +1 -0
- package/dist/simulation-clock.d.ts +3 -0
- package/dist/simulation-clock.js +1 -0
- package/dist/time-index.d.ts +3 -0
- package/dist/time-index.js +1 -0
- package/llms/components/lr-artifact-panel.md +8 -3
- package/llms/components/lr-combobox.md +2 -0
- package/llms/components/lr-country-picker.md +2 -0
- package/llms/components/lr-currency-picker.md +2 -0
- package/llms/components/lr-date-picker.md +2 -0
- package/llms/components/lr-dock-panel.md +28 -10
- package/llms/components/lr-graph.md +121 -3
- package/llms/components/lr-input.md +2 -0
- package/llms/components/lr-knowledge-graph-explorer.md +6 -1
- package/llms/components/lr-locale-picker.md +8 -1
- package/llms/components/lr-map.md +401 -7
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +12 -1
- package/llms/components/lr-menu.md +5 -2
- package/llms/components/lr-model-select.md +2 -0
- package/llms/components/lr-multi-split.md +53 -4
- package/llms/components/lr-native-time-input.md +2 -0
- package/llms/components/lr-number-input.md +2 -0
- package/llms/components/lr-page.md +9 -1
- package/llms/components/lr-phone-input.md +2 -0
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-sequence-playback.md +44 -0
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +6 -2
- package/llms/components/lr-textarea.md +2 -0
- package/llms/components/lr-time-input.md +2 -0
- package/llms/components/lr-time-zone-picker.md +2 -0
- package/llms/components/lr-token-input.md +2 -0
- package/llms/components/lr-unit-picker.md +2 -0
- package/llms/components/lr-voice-picker.md +2 -0
- package/llms/peers.md +7 -7
- package/llms/shared/imports-and-registration.md +1 -1
- package/llms/shared/localization-and-rtl.md +15 -1
- package/llms/shared/testing-and-utilities.md +261 -0
- package/llms/shared.md +277 -2
- package/locales.json +1 -1
- package/package.json +41 -21
- package/registrations.json +1 -1
- package/skills/lyra-ui/lyra-gen.md +2 -0
- /package/dist/{components/media/image-viewer/image-viewer-panorama.styles.js → internal/media-panorama.styles.js} +0 -0
|
@@ -1,8 +1 @@
|
|
|
1
|
-
import{html,nothing}from"lit";import{literalSetConverter}from"../../../internal/converters.js";import{snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{isObjectValue,readOwnDataValue}from"../../../internal/data-descriptors.js";import{finiteRange}from"../../../internal/numbers.js";import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{Engine3dSelection,ENGINE_3D_REASON_MESSAGE,ENGINE_3D_SHOWING_MESSAGE,engine3dFailureReason,webgl2Available}from"../../../internal/engine-3d.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{isAccessibilityVisible}from"../../../internal/accessibility-visibility.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{tag}from"../../../internal/prefix.js";const PANORAMA_PROJECTION=literalSetConverter(["flat","equirectangular"],"flat"),PANORAMA_DEFAULT_CAMERA=Object.freeze({yaw:0,pitch:0,fieldOfView:75}),panoramaLoader=createEngine3dLoader({entry:"panorama",tag:tag("image-viewer"),load:()=>import("@aceshooting/lyra-3d/panorama")}),panoramaEnvironment={available:owner=>webgl2Available(()=>owner.createElement("canvas"))};function normalizePanoramaCamera(value){if(!isObjectValue(value))return PANORAMA_DEFAULT_CAMERA;const number=key=>{const entry=readOwnDataValue(value,key);return typeof entry=="number"?entry:NaN},yaw=finiteRange(number("yaw"),0);return Object.freeze({yaw:((yaw+Math.PI)%(Math.PI*2)+Math.PI*2)%(Math.PI*2)-Math.PI,pitch:finiteRange(number("pitch"),0,-Math.PI/2+.01,Math.PI/2-.01),fieldOfView:finiteRange(number("fieldOfView"),75,20,100)})}function snapshotPanoramaHotspots(value,owner){const source=snapshotPublicCollection(value,owner);if(!Array.isArray(source))return Object.freeze([]);const seen=new Set,result=[];for(const item of source){const id=readOwnDataValue(item,"id"),yaw=readOwnDataValue(item,"yaw"),pitch=readOwnDataValue(item,"pitch"),label=readOwnDataValue(item,"label");typeof id!="string"||!id.trim()||seen.has(id)||typeof yaw!="number"||!Number.isFinite(yaw)||typeof pitch!="number"||!Number.isFinite(pitch)||Math.abs(pitch)>Math.PI/2||(seen.add(id),result.push(Object.freeze({id,yaw:normalizePanoramaCamera({yaw}).yaw,pitch,...typeof label=="string"?{label}:{}})))}return Object.freeze(result)}class PanoramaController{constructor(host,options){this.host=host,this.options=options,this.selection=new Engine3dSelection(!0),this.ready=!1,this.loading=!1,this.notice=null,this.software=!1,this.enabled=!1,this.media=null,this.mediaRevision=-1,this.hotspots=[],this.camera=PANORAMA_DEFAULT_CAMERA,this.container=null,this.generation=0,this.revision=0,this.attempted=!1,this.pending=!1,this.intersecting=!1,this.cleanups=[],this.cursor=0,this.announcements=new AnnouncementSinkController(host,{eager:["assertive"]})}release(){this.generation++,this.intersection?.disconnect(),this.intersection=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.intersecting=!1,this.resize?.disconnect(),this.resize=void 0,this.theme?.disconnect(),this.theme=void 0;for(const cleanup of this.cleanups)cleanup();this.cleanups=[];const engine=this.engine;this.engine=void 0,this.ready=this.loading=this.pending=!1,engine?.dispose()}invalidate(){this.release(),this.attempted=!1,this.notice=null,this.software=!1,this.selection.prefer(this.enabled?"webgl":"builtin")}disconnect(){this.invalidate(),this.media=null,this.container=null}adopted(){this.disconnect(),this.announcements.adopted()}update(enabled,media,mediaRevision,hotspots,camera,container){(enabled!==this.enabled||media!==this.media||mediaRevision!==this.mediaRevision||hotspots!==this.hotspots||container!==this.container)&&(this.invalidate(),this.enabled=enabled,this.media=media,this.mediaRevision=mediaRevision,this.hotspots=hotspots,this.container=container,this.cursor=Math.min(this.cursor,Math.max(0,hotspots.length-1)),this.selection.prefer(enabled?"webgl":"builtin"),this.options.changed());const cameraChanged=camera!==this.camera;if(this.camera=camera,!enabled||!media||!container||!this.host.isConnected)return;if(this.ready){cameraChanged&&this.command(()=>this.engine?.setCamera(camera));return}if(this.pending||this.attempted||this.intersection||this.eligibility)return;const view=this.host.ownerDocument.defaultView,generation=this.generation;this.intersecting=view?.IntersectionObserver===void 0;const admit=()=>{generation!==this.generation||this.pending||this.attempted||!this.intersecting||!isAccessibilityVisible(this.host)||(this.intersection?.disconnect(),this.intersection=void 0,this.eligibility?.disconnect(),this.eligibility=void 0,this.start())};if(view?.IntersectionObserver&&(this.intersection=new view.IntersectionObserver(entries=>{if(generation===this.generation){for(const entry of entries)entry.target===container&&(this.intersecting=entry.isIntersecting);admit()}}),this.intersection.observe(container)),view?.MutationObserver){this.eligibility=new view.MutationObserver(admit);let ancestor=this.host,depth=0;for(;ancestor&&depth++<=256;){this.eligibility.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","inert","hidden","style","class","open"]});const root=ancestor.getRootNode();ancestor=ancestor.assignedSlot??ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}admit()}fail(reason){const detail=this.selection.renderer==="webgl"?this.selection.fail(reason):null;this.ready=this.loading=!1,reason!=="context-lost"&&(this.release(),this.attempted=!0),detail&&(this.notice=detail,this.options.changed(),this.announcements.announceAssertive(this.options.localize(ENGINE_3D_REASON_MESSAGE[detail.reason])),this.announcements.announcePolite(this.options.localize(ENGINE_3D_SHOWING_MESSAGE[detail.to])),this.options.fallback(detail))}command(run){const generation=this.generation,engine=this.engine;try{run()}catch{generation===this.generation&&engine===this.engine&&this.fail("error")}}async start(){const owner=this.host.ownerDocument,container=this.container,media=this.media,hotspots=this.hotspots;if(!this.enabled||!container||!media||!this.host.isConnected)return;const generation=this.generation,current=()=>generation===this.generation&&this.host.isConnected&&this.host.ownerDocument===owner;if(this.pending=this.attempted=!0,!panoramaEnvironment.available(owner)){this.fail("unsupported");return}this.loading=!0,this.options.changed();let engine=null,owned=!1;try{if(engine=await panoramaLoader.create(),!current()){engine?.dispose();return}if(!engine){this.fail("unavailable");return}if(this.engine=engine,owned=!0,await engine.mount(container,{hover:index=>{current()&&this.ready&&this.command(()=>engine.setState?.({selected:new Set,dimmed:new Set,hover:index??-1,focus:this.cursor}))},pick:index=>{current()&&this.ready&&index!==null&&this.activate(index)},camera:value=>{current()&&this.ready&&(this.camera=normalizePanoramaCamera(value),this.options.camera(this.camera))},lost:reason=>{current()&&this.fail(reason)},restored:()=>{!current()||!this.engine||!this.selection.restore()||this.command(()=>{engine.setStyle(this.style()),current()&&(engine.setCamera(this.camera),current()&&(engine.setState?.({selected:new Set,dimmed:new Set,hover:-1,focus:this.cursor}),current()&&(this.ready=!0,this.notice=null,this.options.changed())))})},rendering:value=>{current()&&(this.software=value.software,this.options.changed())}}),!current()||(engine.setStyle(this.style()),!current()))return;const angles=new Float32Array(hotspots.length*2);if(hotspots.forEach((hotspot,index)=>{angles[index*2]=hotspot.yaw,angles[index*2+1]=hotspot.pitch}),engine.setData({source:media.localName==="video"?{kind:"video",video:media}:{kind:"image",image:media},hotspotAngles:angles},++this.revision),!current()||(engine.setCamera(this.camera),!current()))return;const resize=()=>{if(!current())return;const box=container.getBoundingClientRect();engine.resize(Math.max(1,box.width),Math.max(1,box.height))};if(resize(),!current())return;const view=owner.defaultView;view?.ResizeObserver&&(this.resize=new view.ResizeObserver(()=>{current()&&this.ready&&this.command(resize)}),this.resize.observe(container));const restyle=()=>{current()&&this.ready&&this.command(()=>engine.setStyle(this.style()))};if(view?.MutationObserver){this.theme=new view.MutationObserver(restyle);let ancestor=this.host;for(;ancestor;){this.theme.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}}for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const mediaQuery=view?.matchMedia(query);mediaQuery?.addEventListener("change",restyle),mediaQuery&&this.cleanups.push(()=>mediaQuery.removeEventListener("change",restyle))}this.pending=this.loading=!1,this.ready=this.selection.renderer==="webgl",this.options.changed()}catch(error){if(!current()){owned||engine?.dispose();return}this.fail(engine3dFailureReason(error))}}style(){const view=this.host.ownerDocument.defaultView,computed=view.getComputedStyle(this.host),canvas=this.host.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=name=>{const value=resolveCanvasColor(this.host,`var(${name})`,computed.color);if(!context)return value;context.clearRect(0,0,1,1),context.fillStyle=value,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:24,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}activate(index){const hotspot=this.hotspots[index];!hotspot||!Number.isSafeInteger(index)||(this.cursor=index,this.options.changed(),this.options.pick({hotspot,id:hotspot.id,index}))}keydown(event,direction){if(!this.ready||event.target!==event.currentTarget)return;const sign=direction==="rtl"?-1:1;let{yaw,pitch,fieldOfView}=this.camera;switch(event.key){case"ArrowLeft":yaw-=sign*Math.PI/18;break;case"ArrowRight":yaw+=sign*Math.PI/18;break;case"ArrowUp":pitch+=Math.PI/18;break;case"ArrowDown":pitch-=Math.PI/18;break;case"+":case"=":fieldOfView-=5;break;case"-":case"_":fieldOfView+=5;break;case"Home":yaw=pitch=0,fieldOfView=75;break;default:return}event.preventDefault(),event.stopPropagation(),this.camera=normalizePanoramaCamera({yaw,pitch,fieldOfView});const generation=this.generation;this.command(()=>this.engine?.setCamera(this.camera)),generation===this.generation&&this.ready&&this.options.camera(this.camera)}renderViewport(label,enabled){return enabled?html`<div part="panorama" role="group" aria-label=${label} aria-description=${this.options.localize("panoramaInstructions")}
|
|
2
|
-
tabindex=${this.ready?"0":"-1"} ?data-ready=${this.ready} ?hidden=${this.notice!==null}
|
|
3
|
-
@keydown=${event=>this.keydown(event,this.options.direction())}><div part="panorama-engine" aria-hidden="true"></div></div>`:nothing}renderNotice(){const notice=this.notice;return notice?html`<div part="panorama-notice"><p>${this.options.localize(ENGINE_3D_REASON_MESSAGE[notice.reason])}</p><p>${this.options.localize(ENGINE_3D_SHOWING_MESSAGE[notice.to])}</p></div>`:!this.loading&&!this.software?nothing:html`<p part="panorama-notice">${this.options.localize(this.loading?"engine3dLoading":"engine3dSoftwareRendering")}</p>`}renderHotspots(enabled){if(!enabled||!this.hotspots.length)return nothing;const start=Math.floor(this.cursor/200)*200,end=Math.min(this.hotspots.length,start+200),generation=this.generation,current=()=>this.host.isConnected&&generation===this.generation,move=(index,focus=!1)=>{current()&&(this.cursor=Math.max(0,Math.min(this.hotspots.length-1,index)),this.options.changed(),this.ready&&this.command(()=>this.engine?.setState?.({selected:new Set,dimmed:new Set,hover:-1,focus:this.cursor})),focus&&this.options.updated().then(()=>{current()&&this.host.shadowRoot?.querySelector(`[data-panorama-index="${this.cursor}"]`)?.focus()}))};return html`<div part="panorama-hotspots" role="group" aria-label=${this.options.localize("panoramaHotspotsLabel")}>
|
|
4
|
-
${this.hotspots.slice(start,end).map((hotspot,offset)=>{const index=start+offset;return html`<button part="panorama-hotspot" type="button" data-panorama-index=${index} tabindex=${index===this.cursor?"0":"-1"}
|
|
5
|
-
@focus=${()=>move(index)} @click=${()=>{current()&&this.activate(index)}}
|
|
6
|
-
@keydown=${event=>{const forward=this.options.direction()==="rtl"?"ArrowLeft":"ArrowRight",backward=this.options.direction()==="rtl"?"ArrowRight":"ArrowLeft";let next=index;if(event.key===forward||event.key==="ArrowDown")next++;else if(event.key===backward||event.key==="ArrowUp")next--;else if(event.key==="Home")next=0;else if(event.key==="End")next=this.hotspots.length-1;else return;event.preventDefault(),move(next,!0)}}>${hotspot.label||hotspot.id}</button>`})}
|
|
7
|
-
${this.hotspots.length>200?html`<div role="group" aria-label=${this.options.localize("paginationLabel")}><button part="panorama-page" type="button" ?disabled=${start===0} @click=${()=>move(start-200)}>${this.options.localize("previous")}</button><button part="panorama-page" type="button" ?disabled=${end===this.hotspots.length} @click=${()=>move(start+200)}>${this.options.localize("next")}</button></div>`:nothing}
|
|
8
|
-
</div>`}}export{PANORAMA_DEFAULT_CAMERA,PANORAMA_PROJECTION,PanoramaController,normalizePanoramaCamera,panoramaEnvironment,panoramaLoader,snapshotPanoramaHotspots};
|
|
1
|
+
export*from"../../../internal/media-panorama.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{type Engine3dPreference,type Engine3dFallbackDetail}from'../../../internal/engine-3d.js';import{type LyraMediaProjection,type LyraPanoramaCamera,type LyraPanoramaHotspot,type LyraPanoramaHotspotSelectDetail}from'
|
|
1
|
+
import{type Engine3dPreference,type Engine3dFallbackDetail}from'../../../internal/engine-3d.js';import{type LyraMediaProjection,type LyraPanoramaCamera,type LyraPanoramaHotspot,type LyraPanoramaHotspotSelectDetail}from'../../../internal/media-panorama.js';export type{LyraMediaProjection,LyraPanoramaCamera,LyraPanoramaHotspot,LyraPanoramaHotspotSelectDetail}from'../../../internal/media-panorama.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAnchor,LyraAnchorKind,HighlightActivateDetail,AnchorResultDetail}from'../../viewers/document-viewer/anchors.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export type{LyraImageFit}from'../../../internal/image-fit.js';export type LyraImageRotation=0|90|180|270;
|
|
2
2
|
/** Finite percentage coordinates. Negative widths/heights are rejected when rendered.*/
|
|
3
3
|
export interface LyraImageRegionRect{x:number;y:number;width:number;height:number;}
|
|
4
4
|
/** Maximum region buttons projected at once. An active region beyond the leading window replaces
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{panoramaStyles}from"./image-viewer-panorama.styles.js";import{ENGINE_3D_PREFERENCE}from"../../../internal/engine-3d.js";import{PanoramaController,PANORAMA_PROJECTION,PANORAMA_DEFAULT_CAMERA,normalizePanoramaCamera,snapshotPanoramaHotspots}from"./image-viewer-panorama.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight,LYRA_DEFAULT_panoramaHotspotsLabel,LYRA_DEFAULT_panoramaInstructions}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dError,LYRA_DEFAULT_engine3dLoading,LYRA_DEFAULT_engine3dShowingBuiltin,LYRA_DEFAULT_engine3dShowingList,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_previous,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.panoramaRevision=0,this.panorama=new PanoramaController(this,{changed:()=>this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaState",void 0,{hasChanged:()=>!0}),"panorama-state"),updated:async()=>(await Promise.resolve(),this.updateComplete),localize:key=>this.localize(key),direction:()=>this.effectiveDirection,fallback:detail=>this.emit("lr-engine-fallback",detail),pick:detail=>this.emit("lr-panorama-hotspot-select",detail),camera:camera=>{const old=this._panoramaCamera;this._panoramaCamera=camera,this.requestUpdate("panoramaCamera",old),this.emit("lr-panorama-camera-change",{camera})}}),this._projection="flat",this._engine="builtin",this._panoramaCamera=PANORAMA_DEFAULT_CAMERA,this._hotspots=Object.freeze([]),this.hotspotSource=this._hotspots,this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.declarativeAnchorUpdate=!1,this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.panorama.invalidate(),this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationLabel:LYRA_DEFAULT_paginationLabel,panoramaHotspotsLabel:LYRA_DEFAULT_panoramaHotspotsLabel,panoramaInstructions:LYRA_DEFAULT_panoramaInstructions,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,panoramaStyles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get projection(){return this._projection}set projection(value){const next=PANORAMA_PROJECTION.normalize(value),old=this._projection;next!==old&&(this._projection=next,this.panorama?.invalidate(),this.requestUpdate("projection",old))}get engine(){return this._engine}set engine(value){const next=ENGINE_3D_PREFERENCE.normalize(value),old=this._engine;next!==old&&(this._engine=next,this.panorama?.invalidate(),this.requestUpdate("engine",old))}get panoramaCamera(){return this._panoramaCamera}set panoramaCamera(value){const next=normalizePanoramaCamera(value),old=this._panoramaCamera;next.yaw===old.yaw&&next.pitch===old.pitch&&next.fieldOfView===old.fieldOfView||(this._panoramaCamera=next,this.requestUpdate("panoramaCamera",old))}get hotspots(){return this._hotspots}set hotspots(value){if(value===this.hotspotSource||value===this._hotspots)return;const old=this._hotspots;this.hotspotSource=value,this._hotspots=snapshotPanoramaHotspots(value,this.ownerDocument?.defaultView??null),this.panorama?.invalidate(),this.requestUpdate("hotspots",old)}get panoramaEnabled(){return this.projection==="equirectangular"&&this.engine==="webgl"}requestUpdate(name,oldValue,options){name==="src"&&this.panorama&&!Object.is(this.src,oldValue)&&(this.panoramaRevision++,this.panorama.invalidate()),super.requestUpdate(name,oldValue,options)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){this.declarativeAnchorUpdate=!0;try{super.willUpdate(changed)}finally{this.declarativeAnchorUpdate=!1}if(changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver();const image=this.renderRoot.querySelector('[part="image"]');this.panorama.update(this.panoramaEnabled,this.hasOperableContent?image:null,this.panoramaRevision,this.hotspots,this.panoramaCamera,this.renderRoot.querySelector('[part="panorama-engine"]'))}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}scrollToAnchor(target){const anchor=typeof target=="string"?this.highlights.find(highlight=>highlight.id===target)?.anchor:target;return!this.declarativeAnchorUpdate&&anchor?.kind==="region"&&(this.projection="flat"),super.scrollToAnchor(target)}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),super.requestUpdate("panoramaReconnect",void 0,{hasChanged:()=>!0}),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.panorama.adopted(),super.requestUpdate("panoramaAdopted",void 0,{hasChanged:()=>!0}),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{panoramaStyles}from"../../../internal/media-panorama.styles.js";import{ENGINE_3D_PREFERENCE}from"../../../internal/engine-3d.js";import{PanoramaController,PANORAMA_PROJECTION,PANORAMA_DEFAULT_CAMERA,normalizePanoramaCamera,snapshotPanoramaHotspots}from"../../../internal/media-panorama.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{normalizeImageZoom}from"../../../internal/image-zoom.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./image-viewer.styles.js";import{sanitizePercentRect}from"../../../internal/safe-css.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{IMAGE_VIEWER_HIGHLIGHT_LIMIT}from"./image-viewer-limits.js";import{LYRA_DEFAULT_imageViewerAnnotate,LYRA_DEFAULT_imageViewerAnnotationAdded,LYRA_DEFAULT_imageViewerAnnotationBoxPosition,LYRA_DEFAULT_imageViewerAnnotationCancelled,LYRA_DEFAULT_imageViewerAnnotationHint,LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_imageViewerFitActual,LYRA_DEFAULT_imageViewerFitContain,LYRA_DEFAULT_imageViewerFitLabel,LYRA_DEFAULT_imageViewerFitWidth,LYRA_DEFAULT_imageViewerHighlightsLabel,LYRA_DEFAULT_imageViewerLabel,LYRA_DEFAULT_imageViewerRotate,LYRA_DEFAULT_imageViewerUnlabeledHighlight,LYRA_DEFAULT_panoramaHotspotsLabel,LYRA_DEFAULT_panoramaInstructions}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dError,LYRA_DEFAULT_engine3dLoading,LYRA_DEFAULT_engine3dShowingBuiltin,LYRA_DEFAULT_engine3dShowingList,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_previous,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const MIN_REGION_PERCENT=2,ARROW_STEP_PERCENT=2;import{IMAGE_VIEWER_HIGHLIGHT_LIMIT as IMAGE_VIEWER_HIGHLIGHT_LIMIT2}from"./image-viewer-limits.js";function normalizeImageRotation(value){const degrees=typeof value=="number"?finiteNumber(value,0):0;return(Math.round(degrees/90)%4+4)%4*90}function normalizeImageRegionRect(value){const rect=sanitizePercentRect(value);if(!(!rect||rect.x<0||rect.y<0||rect.width<=0||rect.height<=0||rect.x+rect.width>100||rect.y+rect.height>100))return rect}function normalizeHighlightTone(value){return value==="success"||value==="warning"||value==="danger"||value==="neutral"?value:"accent"}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function screenPercentToImagePercent(px,py,rotation){switch(rotation){case 90:return{x:py,y:100-px};case 180:return{x:100-px,y:100-py};case 270:return{x:100-py,y:px};default:return{x:px,y:py}}}class LyraImageViewerBase extends LyraElement{}class LyraImageViewer extends DocumentAnchorTarget(LyraImageViewerBase){constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.panoramaRevision=0,this.panorama=new PanoramaController(this,{changed:()=>this.scheduleAfterUpdate(()=>super.requestUpdate("panoramaState",void 0,{hasChanged:()=>!0}),"panorama-state"),updated:async()=>(await Promise.resolve(),this.updateComplete),localize:key=>this.localize(key),direction:()=>this.effectiveDirection,fallback:detail=>this.emit("lr-engine-fallback",detail),pick:detail=>this.emit("lr-panorama-hotspot-select",detail),camera:camera=>{const old=this._panoramaCamera;this._panoramaCamera=camera,this.requestUpdate("panoramaCamera",old),this.emit("lr-panorama-camera-change",{camera})}}),this._projection="flat",this._engine="builtin",this._panoramaCamera=PANORAMA_DEFAULT_CAMERA,this._hotspots=Object.freeze([]),this.hotspotSource=this._hotspots,this.src="",this.name="",this._fit="contain",this.zoom=1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this._rotation=0,this.annotatable=!1,this.anchorKinds=["region"],this.loadState={kind:"idle"},this.draft=null,this.revealTarget=null,this.highlightFocusId=null,this.mediaLayoutSize=null,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.declarativeAnchorUpdate=!1,this.onImgLoad=event=>{const img=event.target;img===this.shadowRoot?.querySelector('[part="image"]')&&(this.loadState={kind:"loaded"},this.emit("lr-load",{naturalWidth:img.naturalWidth,naturalHeight:img.naturalHeight}))},this.onImgError=event=>{event.target===this.shadowRoot?.querySelector('[part="image"]')&&(this.panorama.invalidate(),this.cancelPointerDraft(),this.revealTarget=null,this.loadState={kind:"error"},this.announceLoadError(),this.emit("lr-render-error",{error:new Error("The image failed to load.")}))},this.onFrameZoomChange=event=>{this.zoom=event.detail.zoom},this.toggleAnnotatable=()=>{this.hasOperableContent&&(this.annotatable=!this.annotatable,this.emit("lr-annotatable-change",{annotatable:this.annotatable}))},this.onFitChange=event=>{this.fit=event.target.value},this.onWrapperKeyDown=event=>{if(event.target===event.currentTarget&&!(!this.annotatable||!this.hasOperableContent)){if(!this.draft){event.key==="Enter"&&(event.preventDefault(),this.draft={x:37.5,y:37.5,width:25,height:25},this.announceDraftPosition());return}switch(event.key){case"ArrowLeft":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x-ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowRight":event.preventDefault(),event.shiftKey?this.draft={...this.draft,width:clamp(this.draft.width+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.x)}:this.draft={...this.draft,x:clamp(this.draft.x+ARROW_STEP_PERCENT,0,100-this.draft.width)};break;case"ArrowUp":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height-ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y-ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"ArrowDown":event.preventDefault(),event.shiftKey?this.draft={...this.draft,height:clamp(this.draft.height+ARROW_STEP_PERCENT,MIN_REGION_PERCENT,100-this.draft.y)}:this.draft={...this.draft,y:clamp(this.draft.y+ARROW_STEP_PERCENT,0,100-this.draft.height)};break;case"Enter":event.preventDefault(),this.commitDraft();return;case"Escape":event.preventDefault(),this.draft=null,this.liveRegion?.announce(this.localize("imageViewerAnnotationCancelled"),{force:!0});return;default:return}this.announceDraftPosition()}},this.pointerDraftId=null,this.pointerOrigin=null,this.onWrapperPointerDown=event=>{if(!this.annotatable||!this.hasOperableContent||!this.wrapperEl||!event.isPrimary||event.button!==0||this.pointerDraftId!==null)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),origin=screenPercentToImagePercent(px,py,this.rotation);this.pointerOrigin=origin,this.pointerDraftId=event.pointerId;try{this.wrapperEl.setPointerCapture(event.pointerId)}catch{}this.draft={x:origin.x,y:origin.y,width:0,height:0},event.preventDefault()},this.onWrapperPointerMove=event=>{if(this.pointerDraftId!==event.pointerId||!this.pointerOrigin||!this.wrapperEl)return;const rect=this.wrapperEl.getBoundingClientRect(),px=clamp((event.clientX-rect.left)/rect.width*100,0,100),py=clamp((event.clientY-rect.top)/rect.height*100,0,100),point=screenPercentToImagePercent(px,py,this.rotation),x=Math.min(this.pointerOrigin.x,point.x),y=Math.min(this.pointerOrigin.y,point.y),width=Math.abs(point.x-this.pointerOrigin.x),height=Math.abs(point.y-this.pointerOrigin.y);this.draft={x,y,width,height}},this.onWrapperPointerUp=event=>{if(this.pointerDraftId!==event.pointerId)return;const draft=this.draft;this.cancelPointerDraft(event.pointerId),draft&&draft.width>=MIN_REGION_PERCENT&&draft.height>=MIN_REGION_PERCENT&&(this.draft=draft,this.commitDraft())}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewTypeImage:LYRA_DEFAULT_documentPreviewTypeImage,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dError:LYRA_DEFAULT_engine3dError,engine3dLoading:LYRA_DEFAULT_engine3dLoading,engine3dShowingBuiltin:LYRA_DEFAULT_engine3dShowingBuiltin,engine3dShowingList:LYRA_DEFAULT_engine3dShowingList,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,imageViewerAnnotate:LYRA_DEFAULT_imageViewerAnnotate,imageViewerAnnotationAdded:LYRA_DEFAULT_imageViewerAnnotationAdded,imageViewerAnnotationBoxPosition:LYRA_DEFAULT_imageViewerAnnotationBoxPosition,imageViewerAnnotationCancelled:LYRA_DEFAULT_imageViewerAnnotationCancelled,imageViewerAnnotationHint:LYRA_DEFAULT_imageViewerAnnotationHint,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,imageViewerFitActual:LYRA_DEFAULT_imageViewerFitActual,imageViewerFitContain:LYRA_DEFAULT_imageViewerFitContain,imageViewerFitLabel:LYRA_DEFAULT_imageViewerFitLabel,imageViewerFitWidth:LYRA_DEFAULT_imageViewerFitWidth,imageViewerHighlightsLabel:LYRA_DEFAULT_imageViewerHighlightsLabel,imageViewerLabel:LYRA_DEFAULT_imageViewerLabel,imageViewerRotate:LYRA_DEFAULT_imageViewerRotate,imageViewerUnlabeledHighlight:LYRA_DEFAULT_imageViewerUnlabeledHighlight,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,model:LYRA_DEFAULT_model,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationLabel:LYRA_DEFAULT_paginationLabel,panoramaHotspotsLabel:LYRA_DEFAULT_panoramaHotspotsLabel,panoramaInstructions:LYRA_DEFAULT_panoramaInstructions,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,panoramaStyles,styles,srOnly]}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-annotation-create"])}get projection(){return this._projection}set projection(value){const next=PANORAMA_PROJECTION.normalize(value),old=this._projection;next!==old&&(this._projection=next,this.panorama?.invalidate(),this.requestUpdate("projection",old))}get engine(){return this._engine}set engine(value){const next=ENGINE_3D_PREFERENCE.normalize(value),old=this._engine;next!==old&&(this._engine=next,this.panorama?.invalidate(),this.requestUpdate("engine",old))}get panoramaCamera(){return this._panoramaCamera}set panoramaCamera(value){const next=normalizePanoramaCamera(value),old=this._panoramaCamera;next.yaw===old.yaw&&next.pitch===old.pitch&&next.fieldOfView===old.fieldOfView||(this._panoramaCamera=next,this.requestUpdate("panoramaCamera",old))}get hotspots(){return this._hotspots}set hotspots(value){if(value===this.hotspotSource||value===this._hotspots)return;const old=this._hotspots;this.hotspotSource=value,this._hotspots=snapshotPanoramaHotspots(value,this.ownerDocument?.defaultView??null),this.panorama?.invalidate(),this.requestUpdate("hotspots",old)}get panoramaEnabled(){return this.projection==="equirectangular"&&this.engine==="webgl"}requestUpdate(name,oldValue,options){name==="src"&&this.panorama&&!Object.is(this.src,oldValue)&&(this.panoramaRevision++,this.panorama.invalidate()),super.requestUpdate(name,oldValue,options)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value),this.requestUpdate("fit",old)}get rotation(){return this._rotation}set rotation(value){const old=this._rotation;this._rotation=normalizeImageRotation(value),this.requestUpdate("rotation",old)}get hasOperableContent(){return this.loadState.kind==="loaded"}willUpdate(changed){this.declarativeAnchorUpdate=!0;try{super.willUpdate(changed)}finally{this.declarativeAnchorUpdate=!1}if(changed.has("src")){this.cancelPointerDraft(),this.revealTarget=null,this.mediaLayoutSize=null;const safeSrc=this.src?safeMediaSrc(this.src):null;this.loadState=safeSrc?{kind:"loading"}:this.src?{kind:"error"}:{kind:"idle"},this.hasUpdated&&this.src&&!safeSrc&&this.announceLoadError()}changed.has("annotatable")&&(!this.annotatable||!this.hasOperableContent)&&this.cancelPointerDraft()}updated(changed){super.updated(changed),changed.has("rotation")&&changed.get("rotation")!==void 0&&this.emit("lr-rotation-change",{rotation:this.rotation}),changed.has("fit")&&changed.get("fit")!==void 0&&this.emit("lr-fit-change",{fit:this.fit}),(changed.has("annotatable")||changed.has("loadState"))&&this.annotatable&&this.hasOperableContent&&(changed.has("loadState")||changed.get("annotatable")!==void 0)&&this.liveRegion?.announce(this.localize("imageViewerAnnotationHint"),{force:!0}),this.syncGeometryObserver();const image=this.renderRoot.querySelector('[part="image"]');this.panorama.update(this.panoramaEnabled,this.hasOperableContent?image:null,this.panoramaRevision,this.hotspots,this.panoramaCamera,this.renderRoot.querySelector('[part="panorama-engine"]'))}zoomIn(){this.frameEl?.zoomIn()}zoomOut(){this.frameEl?.zoomOut()}resetZoom(){this.frameEl?.resetZoom()}rotate(){this.rotation=(this.rotation+90)%360}scrollToAnchor(target){const anchor=typeof target=="string"?this.highlights.find(highlight=>highlight.id===target)?.anchor:target;return!this.declarativeAnchorUpdate&&anchor?.kind==="region"&&(this.projection="flat"),super.scrollToAnchor(target)}async applyAnchor(anchor){if(anchor.kind!=="region"||!this.hasOperableContent)return!1;const rect=normalizeImageRegionRect(anchor.rect);if(!rect)return!1;this.revealTarget=rect,await this.updateComplete;const target=this.shadowRoot?.querySelector("[data-reveal-target]"),viewport=this.frameEl?.shadowRoot?.querySelector('[part="viewport"]');if(!target||!viewport||target.getClientRects().length===0)return!1;target.scrollIntoView({block:"center",inline:"center"}),await new Promise(resolve=>{const view=this.ownerDocument.defaultView;view?view.requestAnimationFrame(()=>resolve()):resolve()});const targetRect=target.getBoundingClientRect(),viewportRect=viewport.getBoundingClientRect();return targetRect.right>viewportRect.left&&targetRect.left<viewportRect.right&&targetRect.bottom>viewportRect.top&&targetRect.top<viewportRect.bottom}connectedCallback(){super.connectedCallback(),super.requestUpdate("panoramaReconnect",void 0,{hasChanged:()=>!0}),this.hasUpdated&&this.syncGeometryObserver()}adoptedCallback(){super.adoptedCallback(),this.panorama.adopted(),super.requestUpdate("panoramaAdopted",void 0,{hasChanged:()=>!0}),this.hostDescription.adopted(),this.disconnectGeometryObserver(),this.announcements.adopted(),this.scheduleAfterUpdate(()=>this.syncGeometryObserver())}disconnectGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.observedWrapper=void 0,this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrame=void 0,this.geometryFrameOwner=void 0}updateMediaLayoutSize(width,height){!Number.isFinite(width)||!Number.isFinite(height)||width<=0||height<=0||this.mediaLayoutSize?.width===width&&this.mediaLayoutSize.height===height||(this.mediaLayoutSize={width,height})}scheduleMediaLayoutSize(width,height){if(!this.isConnected)return;const view=this.ownerDocument.defaultView;if(!view){this.updateMediaLayoutSize(width,height);return}this.geometryFrame!==void 0&&this.geometryFrameOwner?.cancelAnimationFrame(this.geometryFrame),this.geometryFrameOwner=view;const frame=view.requestAnimationFrame(()=>{!this.isConnected||this.ownerDocument.defaultView!==view||this.geometryFrameOwner!==view||this.geometryFrame!==frame||(this.geometryFrame=void 0,this.geometryFrameOwner=void 0,this.updateMediaLayoutSize(Math.round(width*100)/100,Math.round(height*100)/100))});this.geometryFrame=frame}syncGeometryObserver(){if(!this.isConnected)return;const wrapper=this.wrapperEl;if(wrapper===this.observedWrapper||(this.disconnectGeometryObserver(),!wrapper))return;this.observedWrapper=wrapper,this.scheduleMediaLayoutSize(wrapper.offsetWidth,wrapper.offsetHeight);const owner=this.ownerDocument.defaultView,ResizeObserverConstructor=owner?.ResizeObserver;if(!ResizeObserverConstructor)return;const observer=new ResizeObserverConstructor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.geometryObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this.observedWrapper);entry&&this.scheduleMediaLayoutSize(entry.contentRect.width,entry.contentRect.height)});this.geometryObserver=observer,observer.observe(wrapper)}announceLoadError(){this.announcements.announceAssertive(this.localize("imageViewerFailedToLoad"))}onHighlightActivate(id){this.activeHighlightId=id,this.emit("lr-highlight-activate",{highlightId:id})}announceDraftPosition(){if(!this.draft)return;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveRegion?.announce(this.localize("imageViewerAnnotationBoxPosition",void 0,{x:formatter.format(Math.round(this.draft.x)),y:formatter.format(Math.round(this.draft.y)),width:formatter.format(Math.round(this.draft.width)),height:formatter.format(Math.round(this.draft.height))}))}commitDraft(){if(!this.draft)return;const rect={x:this.draft.x,y:this.draft.y,width:this.draft.width,height:this.draft.height};this.draft=null,this.emit("lr-annotation-create",{anchor:{kind:"region",rect}}),this.liveRegion?.announce(this.localize("imageViewerAnnotationAdded"),{force:!0})}cancelPointerDraft(pointerId=this.pointerDraftId,releaseCapture=!0){if(pointerId!=null&&this.pointerDraftId!==pointerId)return;const wrapper=this.wrapperEl,capturedPointerId=this.pointerDraftId;if(this.pointerDraftId=null,this.pointerOrigin=null,this.draft=null,releaseCapture&&wrapper&&capturedPointerId!=null)try{wrapper.releasePointerCapture(capturedPointerId)}catch{}}canonicalRegionHighlights(){const source=this.highlights;if(this.regionHighlights?.[0]===source)return this.regionHighlights[1];const ids=new Set,result=[];for(const highlight of this.highlights){if(!highlight||typeof highlight.id!="string"||highlight.id.trim().length===0||ids.has(highlight.id)||highlight.anchor.kind!=="region")continue;const rect=normalizeImageRegionRect(highlight.anchor.rect);rect&&(ids.add(highlight.id),result.push({highlight,rect}))}return this.regionHighlights=[source,result],result}boundedRegionHighlights(){const all=this.canonicalRegionHighlights();if(all.length<=IMAGE_VIEWER_HIGHLIGHT_LIMIT)return{all,visible:all};const visible=all.slice(0,IMAGE_VIEWER_HIGHLIGHT_LIMIT),active=this.activeHighlightId?all.find(entry=>entry.highlight.id===this.activeHighlightId):void 0;return active&&!visible.includes(active)&&(visible[visible.length-1]=active),{all,visible}}onHighlightFocus(id){this.highlightFocusId=id}onHighlightKeyDown(event,id){const buttons=[...this.shadowRoot.querySelectorAll('[part="highlight"]')];if(buttons.length<2)return;const current=buttons.findIndex(button=>button.dataset.highlightId===id),rtl=this.effectiveDirection==="rtl";let next=current;if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else if(event.key==="ArrowDown"||event.key===(rtl?"ArrowLeft":"ArrowRight"))next=(current+1)%buttons.length;else if(event.key==="ArrowUp"||event.key===(rtl?"ArrowRight":"ArrowLeft"))next=(current-1+buttons.length)%buttons.length;else return;event.preventDefault();const target=buttons[next];this.highlightFocusId=target.dataset.highlightId??null,target.focus()}renderHighlights(){if(!this.hasOperableContent)return nothing;const{all:regionHighlights,visible}=this.boundedRegionHighlights();if(!regionHighlights.length)return nothing;const formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),preferredFocusId=visible.some(({highlight})=>highlight.id===this.highlightFocusId)?this.highlightFocusId:visible.some(({highlight})=>highlight.id===this.activeHighlightId)?this.activeHighlightId:visible[0]?.highlight.id??null,zoom=normalizeImageZoom(this.zoom,this.minZoom,this.maxZoom),layout=this.mediaLayoutSize;return html`<div
|
|
2
2
|
part="highlight-layer"
|
|
3
3
|
role="group"
|
|
4
4
|
aria-label=${this.localize("imageViewerHighlightsLabel")}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type MapOwnedControlKind='navigation'|'scale'|'geolocate'|'attribution';
|
|
1
|
+
import{type LyraMapTerrain}from'./map-scene-configuration.js';export type MapOwnedControlKind='navigation'|'scale'|'geolocate'|'globe'|'terrain'|'attribution';
|
|
2
2
|
/** Corner a declarative control is added to. The corners follow text direction under RTL.*/
|
|
3
3
|
export type LyraMapControlPosition='top-left'|'top-right'|'bottom-left'|'bottom-right';
|
|
4
4
|
/** Unit system of the scale control.*/
|
|
@@ -7,13 +7,17 @@ export type LyraMapScaleUnit='metric'|'imperial';
|
|
|
7
7
|
export interface LyraMapNavigationControlOptions{
|
|
8
8
|
/** Corner to add the control to. Defaults to `'top-right'`.*/
|
|
9
9
|
readonly position?:LyraMapControlPosition;
|
|
10
|
-
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
|
|
10
|
+
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, globe, terrain, attribution.*/
|
|
11
11
|
readonly order?:number;}
|
|
12
|
+
/** Placement of the component-owned globe toggle; scene state follows the map projection.*/
|
|
13
|
+
export interface LyraMapGlobeControlOptions extends LyraMapNavigationControlOptions{}
|
|
14
|
+
/** Explicit elevation source requested when the component-owned terrain toggle enables terrain.*/
|
|
15
|
+
export interface LyraMapTerrainControlOptions extends LyraMapNavigationControlOptions,LyraMapTerrain{}
|
|
12
16
|
/** Options of the declarative scale control.*/
|
|
13
17
|
export interface LyraMapScaleControlOptions{
|
|
14
18
|
/** Corner to add the control to. Defaults to `'bottom-left'`.*/
|
|
15
19
|
readonly position?:LyraMapControlPosition;
|
|
16
|
-
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
|
|
20
|
+
/** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, globe, terrain, attribution.*/
|
|
17
21
|
readonly order?:number;
|
|
18
22
|
/** Unit system. Defaults to `'metric'`.*/
|
|
19
23
|
readonly unit?:LyraMapScaleUnit;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="
|
|
1
|
+
import{admitMapTerrain}from"./map-scene-configuration.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","globe","terrain","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}if(kind==="terrain"&&value===!0)throw new TypeError("Terrain control source is required");const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="attribution"?"bottom-right":"top-right");let options,attributionLabels,initialExpanded;if(kind==="globe")options=Object.freeze({});else if(kind==="terrain"){const terrain=admitMapTerrain(entry);if(!terrain)throw new TypeError("Terrain control source is required");options=Object.freeze({source:terrain.source,exaggeration:terrain.exaggeration})}else if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution"),seed=own(entry,"initialExpanded");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");if(seed!==void 0&&typeof seed!="boolean")throw new TypeError("Invalid attribution expansion");initialExpanded=seed;const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,order,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},...initialExpanded===void 0?{}:{initialExpanded},key:`${corner}:${order}:${JSON.stringify(options)}${initialExpanded===void 0?"":`:${initialExpanded}`}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&next.initialExpanded===entry.options.initialExpanded&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}pendingKinds(){return new Set([...this.entries].filter(([,entry])=>!entry.installed&&!entry.retired).map(([kind])=>kind))}ownedRoot(kind){const entry=this.entries.get(kind);return entry?.installed&&!entry.retired?entry.root:void 0}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}const seed=entry.options.initialExpanded;if(entry.options.kind==="attribution"&&seed!==void 0&&entry.root?.classList.contains("maplibregl-compact")&&(entry.root.classList.toggle("maplibregl-compact-show",seed),entry.root.toggleAttribute("open",seed)),!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
|
|
1
|
+
import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&next.initialExpanded===entry.options.initialExpanded&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next,context.scene&&entry.control?.setSceneContext?.(context.scene)):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","globe","terrain","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}pendingKinds(){return new Set([...this.entries].filter(([,entry])=>!entry.installed&&!entry.retired).map(([kind])=>kind))}ownedRoot(kind){const entry=this.entries.get(kind);return entry?.installed&&!entry.retired?entry.root:void 0}refreshSceneControls(){for(const entry of this.entries.values())this.current(entry)&&entry.control?.refreshSceneControl?.()}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="globe"||entry.options.kind==="terrain"){if(!entry.context.scene||typeof entry.control.setSceneContext!="function"||typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Scene control is unavailable");if(entry.control.setSceneContext(entry.context.scene),this.subscribe(entry,"activate",action=>{this.current(entry)&&entry.context.onEvent({kind:"scene-action",action})}),!this.current(entry)){this.release(entry);return}}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}const seed=entry.options.initialExpanded;if(entry.options.kind==="attribution"&&seed!==void 0&&entry.root?.classList.contains("maplibregl-compact")&&(entry.root.classList.toggle("maplibregl-compact-show",seed),entry.root.toggleAttribute("open",seed)),!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mapFeatureLoader,__setMapFeatureImporterForTesting as setImporter}from"./map-feature-loader-core.js";import{loadMapImageRuntime,loadMapStyleOverrideRuntime}from"./map-resource-feature-loaders.js";const loadMapAnchorRuntime=mapFeatureLoader(()=>import("./map-anchor-controller.js")),loadMapControlRuntime=mapFeatureLoader(()=>import("./map-controls-lifecycle.js")),loadMapDrawingRuntime=mapFeatureLoader(()=>import("./map-drawing-controller.js")),loadMapImageExportRuntime=mapFeatureLoader(()=>import("./map-image-export-controller.js")),loadMapHashRuntime=mapFeatureLoader(()=>import("./map-hash-owner.js")),loadMapFeatureStateRuntime=mapFeatureLoader(()=>import("./map-feature-state-routes.js")),loadMapOwnedFeatureRuntime=mapFeatureLoader(()=>import("./map-owned-features.js"));function __setMapFeatureImporterForTesting(loader,importer){setImporter(loader,importer)}export{__setMapFeatureImporterForTesting,loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapImageRuntime,loadMapOwnedFeatureRuntime,loadMapStyleOverrideRuntime};
|
|
1
|
+
import{resolveOptionalPeerCapability}from"../../../internal/optional-peer-capabilities.js";import{mapFeatureLoader,__setMapFeatureImporterForTesting as setImporter}from"./map-feature-loader-core.js";import{loadMapImageRuntime,loadMapStyleOverrideRuntime}from"./map-resource-feature-loaders.js";const loadMapAnchorRuntime=mapFeatureLoader(()=>import("./map-anchor-controller.js")),loadMapControlRuntime=mapFeatureLoader(()=>import("./map-controls-lifecycle.js")),loadMapDrawingRuntime=mapFeatureLoader(()=>import("./map-drawing-controller.js")),loadMapImageExportRuntime=mapFeatureLoader(()=>import("./map-image-export-controller.js")),loadMapHashRuntime=mapFeatureLoader(()=>import("./map-hash-owner.js")),loadMapFeatureStateRuntime=mapFeatureLoader(()=>import("./map-feature-state-routes.js")),loadMapOwnedFeatureRuntime=mapFeatureLoader(()=>import("./map-owned-features.js"));function __setMapFeatureImporterForTesting(loader,importer){setImporter(loader,importer)}const loadMapSceneRenderRuntime=mapFeatureLoader(()=>import("./map-scene-render-controller.js")),sceneBridgeImporter=()=>import("@aceshooting/lyra-map/scene");let importSceneBridge=sceneBridgeImporter;async function importSceneBridgeRuntime(){const runtime=resolveOptionalPeerCapability(await importSceneBridge(),value=>typeof value=="object"&&value!==null&&"createSceneBridge"in value&&typeof value.createSceneBridge=="function");if(!runtime)throw new TypeError("Map scene renderer unavailable");return runtime}const loadMapSceneBridge=mapFeatureLoader(importSceneBridgeRuntime);function __setMapSceneBridgeImporterForTesting(importer){importSceneBridge=importer??sceneBridgeImporter,setImporter(loadMapSceneBridge)}export{__setMapFeatureImporterForTesting,__setMapSceneBridgeImporterForTesting,loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapImageRuntime,loadMapOwnedFeatureRuntime,loadMapSceneBridge,loadMapSceneRenderRuntime,loadMapStyleOverrideRuntime};
|
|
@@ -17,7 +17,11 @@ prepareFeatures?(requirements:LyraMapFeatureRequirements,options?:{signal?:Abort
|
|
|
17
17
|
/** Required, unlike setMaxBounds below: the loader validates getCanvas is callable and rejects a
|
|
18
18
|
* peer without it, so holding this type already implies the method is present. Call sites still
|
|
19
19
|
* guard with `?.()` against a peer that satisfies the shape check and then lies at runtime. */
|
|
20
|
-
getCanvas():HTMLCanvasElement;
|
|
20
|
+
getCanvas():HTMLCanvasElement;
|
|
21
|
+
/** Optional native allocation capabilities, feature-detected by opted-in scene rendering.*/
|
|
22
|
+
getContainer?():HTMLElement;getPixelRatio?():number;getPadding?():{top:number;right:number;bottom:number;left:number;};getCenter():{lng:number;lat:number;};getZoom():number;getBearing?():number;getPitch?():number;
|
|
23
|
+
/** Optional cancellation, required only for session-owned animated camera commands.*/
|
|
24
|
+
stop?():unknown;setCenter(center:[number,number]):unknown;setZoom(zoom:number):unknown;resize():unknown;
|
|
21
25
|
/** Optional zoom limits; `minZoom`/`maxZoom` feature-detect them before a live update.*/
|
|
22
26
|
setMinZoom?(zoom:number):unknown;setMaxZoom?(zoom:number):unknown;getMaxZoom?():number;
|
|
23
27
|
/** Optional: absent on peers predating it, and the caller feature-detects before use.*/
|
|
@@ -42,9 +46,11 @@ project?(lngLat:[number,number]):{x:number;y:number;};unproject?(point:[number,n
|
|
|
42
46
|
/** Optional: standard peer controls. A control is the peer's own object (`onAdd`/`onRemove`).*/
|
|
43
47
|
addControl?(control:unknown,position?:string):unknown;removeControl?(control:unknown):unknown;
|
|
44
48
|
/** Optional: the geographic box of the whole canvas.*/
|
|
45
|
-
getBounds?():{getWest():number;getSouth():number;getEast():number;getNorth():number;};remove():void;on(type:'error',listener:(event:{error?:unknown;})=>void):this;on(type:'render'|'load'|'style.load'|'idle'|'dataloading'|'sourcedata'|'movestart'|'move'|'error',listener:()=>void):this;on(type:'moveend',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'move',listener:()=>void):this;on(type:'boxzoomend',listener:()=>void):this;on(type:'movestart'|'boxzoomstart',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'click',listener:(event:{point:unknown;lngLat:{lng:number;lat:number;};})=>void):this;once(type:'style.load',listener:()=>void):this;setStyle(style:unknown,options?:{diff?:boolean;}):this;
|
|
49
|
+
getBounds?():{getWest():number;getSouth():number;getEast():number;getNorth():number;};remove():void;on(type:'error',listener:(event:{error?:unknown;})=>void):this;on(type:'render'|'load'|'style.load'|'idle'|'dataloading'|'sourcedata'|'movestart'|'move'|'error',listener:()=>void):this;on(type:'moveend',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'move',listener:()=>void):this;on(type:'boxzoomend',listener:()=>void):this;on(type:'movestart'|'boxzoomstart'|'dragstart'|'zoomstart'|'rotatestart'|'pitchstart',listener:(event:Readonly<Record<string,unknown>> |undefined)=>void):this;on(type:'click',listener:(event:{point:unknown;lngLat:{lng:number;lat:number;};})=>void):this;once(type:'style.load',listener:()=>void):this;setStyle(style:unknown,options?:{diff?:boolean;}):this;
|
|
46
50
|
/** Optional native style capabilities, required only for declarative owned overlays/overrides.*/
|
|
47
|
-
getStyle?():{readonly layers?:readonly{readonly id:string;}[];};
|
|
51
|
+
getStyle?():{readonly layers?:readonly{readonly id:string;}[];};
|
|
52
|
+
/** Optional scene capabilities, required only for declarative projection/terrain overrides.*/
|
|
53
|
+
getProjection?():unknown;getTerrain?():unknown;setProjection?(value:unknown):unknown;setTerrain?(value:unknown):unknown;moveLayer?(id:string,before?:string):unknown;getPaintProperty?(id:string,property:string):unknown;getLayoutProperty?(id:string,property:string):unknown;setLayoutProperty?(id:string,property:string,value:unknown):unknown;setFilter?(id:string,filter:unknown):unknown;setLayerZoomRange?(id:string,min:number,max:number):unknown;setFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,state:import('./map-feature-state.js').LyraMapFeatureState):unknown;removeFeatureState?(target:import('./map-feature-state.js').LyraMapFeatureIdentifier,key:string):unknown;triggerRepaint?():unknown;getSource(id:string):MapLibreGeoJsonSource|undefined;addSource(id:string,source:unknown):this;removeSource(id:string):this;getLayer(id:string):unknown;addLayer(layer:unknown,before?:string):this;removeLayer(id:string):this;setPaintProperty(layerId:string,name:string,value:unknown):this;
|
|
48
54
|
/** Optional image-atlas capabilities; point circles remain usable when a partial peer lacks these.*/
|
|
49
55
|
hasImage?(id:string):boolean;addImage?(id:string,image:ImageData,options:{pixelRatio:number;sdf?:boolean;}):unknown;
|
|
50
56
|
/** Optional lazy image hook: the engine awaits it before treating a style image as missing.*/
|
|
@@ -68,4 +74,4 @@ export interface ModularMapModule extends MaplibreModule{Map:new(options:Record<
|
|
|
68
74
|
/** Lazily loads the modular companion once per page. A failed load never selects another engine.*/
|
|
69
75
|
export declare function loadModularMap():Promise<ModularMapModule|null>;
|
|
70
76
|
/** The standard peer controls `<lr-map controls>` can add, by kind.*/
|
|
71
|
-
export type MapControlKind='navigation'|'scale'|'geolocate'|'attribution';
|
|
77
|
+
export type MapControlKind='navigation'|'scale'|'geolocate'|'globe'|'terrain'|'attribution';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre,maplibreCapabilities;async function loadMaplibreModule(importer=()=>import("maplibre-gl").then(source=>maplibreCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup},get NavigationControl(){return source.NavigationControl},get ScaleControl(){return source.ScaleControl},get GeolocateControl(){return source.GeolocateControl},get AttributionControl(){return source.AttributionControl},get setWorkerUrl(){return source.setWorkerUrl},get getVersion(){return source.getVersion},get default(){return source.default}}))){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}function isModularMapModule(candidate){return isMaplibreModule(candidate)&&typeof candidate.Map.prototype.prepareFeatures=="function"}let modularMapCapabilities;async function loadModularMapModule(importer=()=>import("@aceshooting/lyra-map").then(source=>modularMapCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup}}))){try{const value=await importer(),module=resolveOptionalPeerCapability(value,isModularMapModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"Map.prototype.prepareFeatures";throw new Error(`Invalid optional peer \`@aceshooting/lyra-map\`: missing or invalid \`${missing}\` capability.`)}catch(error){return console.warn("<lr-map> needs the optional peer dependency `@aceshooting/lyra-map` — install it with `pnpm add @aceshooting/lyra-map`.",error),null}}let modularMap;function loadModularMap(){return modularMap??=loadModularMapModule()}async function loadMapControl(kind,engine,module){const name={navigation:"NavigationControl",scale:"ScaleControl",geolocate:"GeolocateControl",attribution:"AttributionControl"}[kind],provided=module?.[name];if(isConstructor(provided))return provided;if(engine!=="modular")return null;try{const source=kind==="navigation"?await import("@aceshooting/lyra-map/controls/navigation"):kind==="scale"?await import("@aceshooting/lyra-map/controls/scale"):kind==="geolocate"?await import("@aceshooting/lyra-map/controls/geolocate"):await import("@aceshooting/lyra-map/controls/attribution"),candidate=unwrapOptionalPeerDefault(source),control=isObjectLike(candidate)?candidate[name]:void 0;return isConstructor(control)?control:null}catch(error){return console.warn(`<lr-map> could not load the ${kind} control from \`@aceshooting/lyra-map\`.`,error),null}}export{loadMapControl,loadMaplibre,loadMaplibreModule,loadModularMap,loadModularMapModule};
|
|
1
|
+
import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre,maplibreCapabilities;async function loadMaplibreModule(importer=()=>import("maplibre-gl").then(source=>maplibreCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup},get NavigationControl(){return source.NavigationControl},get ScaleControl(){return source.ScaleControl},get GeolocateControl(){return source.GeolocateControl},get AttributionControl(){return source.AttributionControl},get setWorkerUrl(){return source.setWorkerUrl},get getVersion(){return source.getVersion},get default(){return source.default}}))){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}function isModularMapModule(candidate){return isMaplibreModule(candidate)&&typeof candidate.Map.prototype.prepareFeatures=="function"}let modularMapCapabilities;async function loadModularMapModule(importer=()=>import("@aceshooting/lyra-map").then(source=>modularMapCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup}}))){try{const value=await importer(),module=resolveOptionalPeerCapability(value,isModularMapModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"Map.prototype.prepareFeatures";throw new Error(`Invalid optional peer \`@aceshooting/lyra-map\`: missing or invalid \`${missing}\` capability.`)}catch(error){return console.warn("<lr-map> needs the optional peer dependency `@aceshooting/lyra-map` — install it with `pnpm add @aceshooting/lyra-map`.",error),null}}let modularMap;function loadModularMap(){return modularMap??=loadModularMapModule()}async function loadMapControl(kind,engine,module){if(kind==="globe"||kind==="terrain"){const runtime=await import("./map-scene-controls.js");return kind==="globe"?runtime.MapGlobeControl:runtime.MapTerrainControl}const name={navigation:"NavigationControl",scale:"ScaleControl",geolocate:"GeolocateControl",attribution:"AttributionControl"}[kind],provided=module?.[name];if(isConstructor(provided))return provided;if(engine!=="modular")return null;try{const source=kind==="navigation"?await import("@aceshooting/lyra-map/controls/navigation"):kind==="scale"?await import("@aceshooting/lyra-map/controls/scale"):kind==="geolocate"?await import("@aceshooting/lyra-map/controls/geolocate"):await import("@aceshooting/lyra-map/controls/attribution"),candidate=unwrapOptionalPeerDefault(source),control=isObjectLike(candidate)?candidate[name]:void 0;return isConstructor(control)?control:null}catch(error){return console.warn(`<lr-map> could not load the ${kind} control from \`@aceshooting/lyra-map\`.`,error),null}}export{loadMapControl,loadMaplibre,loadMaplibreModule,loadModularMap,loadModularMapModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{createMapSceneAdmissionError,mapSceneAdmissionErrorCode}from"./map-scene-errors.js";import{captureMapSceneSourceMetadata,readMapSceneSource}from"./map-scene-source-snapshot.js";const candidates=new WeakMap,baseFields=["id","label","kind","color","opacity","interactive","showLabel"],latitudeLimit=85.0511287798066,radians=Math.PI/180;function invalid(){throw createMapSceneAdmissionError("invalid")}function limit(){throw createMapSceneAdmissionError("limit")}function own(record2,key){const descriptor=getOwnDataDescriptor(record2,key);return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&invalid(),descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function record(value,fields){isPlainDataRecord(value)||invalid();const snapshot={};for(const key of Reflect.ownKeys(value))(typeof key!="string"||!fields.includes(key))&&invalid(),snapshot[key]=own(value,key);return snapshot}function arrayLength(value,minimum,maximum,capped=!1){Array.isArray(value)||invalid();const length=readOwnArrayLength(value);return(length===void 0||length<minimum)&&invalid(),length>maximum?capped?limit():invalid():length}function array(value,minimum,maximum,capped=!1){const length=arrayLength(value,minimum,maximum,capped);Array.isArray(value)||invalid(),Reflect.ownKeys(value).length!==length+1&&invalid();const result=[];for(let index=0;index<length;index++){const descriptor=getOwnDataDescriptor(value,String(index));(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)&&invalid(),result.push(descriptor.value)}return result}function number(value,minimum=-1/0,maximum=1/0){return(typeof value!="number"||!Number.isFinite(value)||value<minimum||value>maximum)&&invalid(),value===0?0:value}function positive(value,fallback){const result=number(value===void 0?fallback:value,0);return result===0&&invalid(),result}function boolean(value,fallback){return value===void 0?fallback:(typeof value!="boolean"&&invalid(),value)}function longitude(value){const finite=number(value);if(finite>=-180&&finite<180)return finite;const normalized=(finite%360+540)%360-180;return normalized===0?0:normalized}function position(value){const data=record(value,["lngLat","altitude","altitudeReference"]),coordinates=array(own(data,"lngLat"),2,2),lngLat=Object.freeze([longitude(coordinates[0]),number(coordinates[1],-latitudeLimit,latitudeLimit)]),altitude=own(data,"altitude"),authoredReference=own(data,"altitudeReference"),reference=authoredReference===void 0?"sea-level":authoredReference;return reference!=="sea-level"&&reference!=="terrain"&&invalid(),Object.freeze({lngLat,altitude:number(altitude===void 0?0:altitude,-12e3,1e8),altitudeReference:reference})}function orientation(value){const entries=value===void 0?[0,0,0,1]:array(value,4,4).map(entry=>number(entry)),maximum=Math.max(...entries.map(Math.abs));maximum===0&&invalid();const scaled=entries.map(entry=>entry/maximum),magnitude=Math.hypot(...scaled),normalized=scaled.map(entry=>entry===0?0:entry/magnitude);return Object.freeze([normalized[0],normalized[1],normalized[2],normalized[3]])}function segment(start,end){start.altitudeReference!==end.altitudeReference&&invalid();const unit=point=>{const lng=point.lngLat[0]*radians,lat=point.lngLat[1]*radians;return[Math.cos(lat)*Math.cos(lng),Math.cos(lat)*Math.sin(lng),Math.sin(lat)]},a=unit(start),b=unit(end),sine=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 a[0]*b[0]+a[1]*b[1]+a[2]*b[2]<0&&sine<1e-8&&invalid(),start.lngLat[0]!==end.lngLat[0]||start.lngLat[1]!==end.lngLat[1]}function objectDescriptor(value){isPlainDataRecord(value)||invalid();const kind=own(value,"kind");let fields;switch(kind){case"marker":fields=["position","radius"];break;case"path":fields=["positions","interpolation","width"];break;case"arc":fields=["start","end","height","width"];break;case"model":fields=["position","source","metersPerUnit","orientation"];break;default:return invalid()}const snapshot=record(value,[...baseFields,...fields]);return own(snapshot,"kind")!==kind&&invalid(),snapshot}function preflight(values,sourceMetadata){const descriptors=values.map(objectDescriptor),pathLengths=new Map;let positions=0,text=0,models=0;for(const data of descriptors){const kind=own(data,"kind");if(kind==="path"){const length=arrayLength(own(data,"positions"),2,4096,!0);pathLengths.set(data,length),positions+=length}else positions+=kind==="arc"?2:1;positions>65536&&limit();for(const[key,maximum]of[["id",1024],["label",16384],["color",1024]]){const value=own(data,key);value===void 0&&key==="color"||(typeof value!="string"&&invalid(),value.length>maximum&&limit(),text+=value.length)}if(kind==="model"){++models>32&&limit();const source=captureMapSceneSourceMetadata(own(data,"source")),prior=sourceMetadata.get(source.record);prior&&(prior.kind!==source.kind||prior.format!==source.format||(prior.kind==="url"&&source.kind==="url"?prior.src!==source.src:prior.kind==="bytes"&&source.kind==="bytes"&&prior.bytes!==source.bytes))&&invalid(),sourceMetadata.set(source.record,source),source.kind==="url"&&(text+=source.src.length)}text>4194304&&limit()}for(const[data,length]of pathLengths){const positions2=array(own(data,"positions"),2,4096,!0);positions2.length!==length&&invalid(),data.positions=Object.freeze(positions2)}return descriptors}function object(data){const kind=own(data,"kind"),id=own(data,"id"),label=own(data,"label");(typeof id!="string"||id.length===0||id.length>1024||id.trim().length===0||typeof label!="string"||label.trim().length===0)&&invalid();const authoredColor=own(data,"color"),color=authoredColor===void 0?void 0:sanitizeCssColor(authoredColor);authoredColor!==void 0&&color===void 0&&invalid();const opacity=own(data,"opacity"),base={id,label,...color===void 0?{}:{color},opacity:number(opacity===void 0?1:opacity,0,1),interactive:boolean(own(data,"interactive"),!0),showLabel:boolean(own(data,"showLabel"),!1)};switch(kind){case"marker":return Object.freeze({...base,kind,position:position(own(data,"position")),radius:positive(own(data,"radius"),6)});case"path":{const positions=Object.freeze(array(own(data,"positions"),2,4096).map(position)),authoredInterpolation=own(data,"interpolation"),interpolation=authoredInterpolation===void 0?"great-circle":authoredInterpolation;interpolation!=="linear"&&interpolation!=="great-circle"&&invalid();let hasLength=!1;for(let index=1;index<positions.length;index++)hasLength=segment(positions[index-1],positions[index])||hasLength;return hasLength||invalid(),Object.freeze({...base,kind,positions,interpolation,width:positive(own(data,"width"),2)})}case"arc":{const start=position(own(data,"start")),end=position(own(data,"end"));return segment(start,end)||invalid(),Object.freeze({...base,kind,start,end,height:number(own(data,"height"),0),width:positive(own(data,"width"),2)})}case"model":return Object.freeze({...base,kind,position:position(own(data,"position")),source:readMapSceneSource(own(data,"source")),metersPerUnit:positive(own(data,"metersPerUnit"),1),orientation:orientation(own(data,"orientation"))});default:return invalid()}}function snapshotMapSceneRequest(value){try{const data=record(value,["connection","revision"]),connection=own(data,"connection"),revision=own(data,"revision");return(connection===null||typeof connection!="object"||typeof revision!="number"||!Number.isSafeInteger(revision)||revision<1)&&invalid(),Object.freeze({connection,revision})}catch{return invalid()}}function stageMapSceneAdmission(value,options){let sourceStage;try{const request=snapshotMapSceneRequest(options.request),scene=record(value,["objects"]),sourceMetadata=new Map,objects=preflight(array(own(scene,"objects"),0,2e3,!0),sourceMetadata).map(object),ids=new Set,sources=[],sourceIndices=new Map;for(const admitted2 of objects)ids.has(admitted2.id)&&invalid(),ids.add(admitted2.id),admitted2.kind==="model"&&(sourceIndices.has(admitted2.source)||(sourceIndices.set(admitted2.source,sources.length),sources.push(admitted2.source)));sourceStage=options.sources.stage(sources,request,sources.map(source=>sourceMetadata.get(source)));const stage=sourceStage,admitted=Object.freeze(objects.map(entry=>{if(entry.kind!=="model")return entry;const receipt=stage.receipts[sourceIndices.get(entry.source)];return receipt||invalid(),Object.freeze({...entry,source:receipt})})),state={sources:options.sources,consumed:!1},candidate=Object.freeze({request,objects:admitted,sourceStage:stage,dispose(){state.consumed=!0,stage.dispose()}});return candidates.set(candidate,state),candidate}catch(error){if(sourceStage?.dispose(),mapSceneAdmissionErrorCode(error)!==void 0)throw error;return invalid()}}function consumeMapSceneAdmission(candidate,sources,connection){const state=candidates.get(candidate);(!state||state.consumed||state.sources!==sources||candidate.request.connection!==connection)&&invalid(),state.consumed=!0}export{consumeMapSceneAdmission,snapshotMapSceneRequest,stageMapSceneAdmission};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const hostBindings=new WeakMap,noop=()=>{};function createMapSceneCompletionHost(options){const{owner}=options,tokens=new WeakMap;let input;function token(value){let result=tokens.get(value);return result||(result=Object.freeze({}),tokens.set(value,result)),result}function captureInput(){const next=owner.captureRenderPublication(),publicationToken=token(next);if(input?.publicationToken===publicationToken)return input;const targets=new Map(next.state.targets.map(target=>[target.id,target])),members=next.accepted.objects.map(row=>{const fact=targets.get(row.id);let target;if(fact&&(fact.kind==="marker"||fact.kind==="model")){const position=Object.freeze({lngLat:Object.freeze([fact.position.lngLat[0],fact.position.lngLat[1]]),altitude:fact.position.altitude,altitudeReference:fact.position.altitudeReference});target=Object.freeze({token:token(fact),acceptedPositionRevision:fact.acceptedPositionRevision,position})}return Object.freeze({id:row.id,kind:row.kind,rowToken:token(row),target})}),result=Object.freeze({publicationToken,stateToken:token(next.state),phase:next.phase,acceptedSceneRevision:next.accepted.acceptedSceneRevision,renderInput:next.input,members:Object.freeze(members)});return input=result,result}function current(expected){if(captureInput()!==expected||expected.phase!=="resolved")return!1;try{return options.isCurrent()&&captureInput()===expected}catch{return!1}}const host=Object.freeze({captureInput,subscribeInput:listener=>owner.subscribeRenderPublication(listener),claimPaintSerial(expected){if(current(expected))return owner.claimPaintFrameSerial(owner.captureRenderPublication())},captureCameraFacts(expected){if(current(expected))try{const facts=options.captureCameraFacts(owner.captureRenderPublication());return current(expected)?facts:void 0}catch{return}}});return hostBindings.set(host,{owner,current}),host}function createMapSceneCompletionAdapter(options){const{connection,state,owner,host,port}=options,binding=hostBindings.get(host);if(!binding||binding.owner!==owner||state!==owner.state||state.connection!==connection)throw new TypeError("Invalid map scene completion adapter");let disposed=!1;const releases=new Set,frames=new WeakMap;function live(input){return!disposed&&binding.current(input)&&!disposed&&host.captureInput()===input&&state.capture()===owner.captureRenderPublication().state}function retain(acquire){if(disposed)return noop;const release=acquire();let active=!0;const retire=()=>{if(active){active=!1,releases.delete(retire);try{release()}catch{}}};return disposed?retire():releases.add(retire),retire}function targetFor(input,id){if(!live(input))return;const fact=state.capture().targets.find(target=>target.id===id);return fact&&(fact.kind==="marker"||fact.kind==="model")?fact:void 0}function current(frame,target){const input=frames.get(frame);if(!input||targetFor(input,target.id)!==target)return!1;const member=input.members.find(row=>row.id===target.id);if(!member?.target)return!1;try{return port.current(frame,target.id,member.target.token)&&live(input)&&targetFor(input,target.id)===target}catch{return!1}}const backing=Object.freeze({connection,state,watchTarget(id){return retain(()=>port.watchTarget(id))},subscribeCompletedFrames(listener){let active=!0;return retain(()=>{const release=port.subscribeCompletedFrames(frame=>{if(disposed||!active)return;const input=host.captureInput();if(!live(input)||!active)return;const previous=frames.get(frame);previous&&previous!==input||(frames.set(frame,input),listener(frame))});return()=>{active=!1,release()}})},current,projectTarget(frame,id){const input=frames.get(frame),target=input&&targetFor(input,id);if(!(!target||!current(frame,target)))try{const projection=port.projectTarget(frame,id);return current(frame,target)?projection:void 0}catch{return}},requestFrame(){!disposed&&live(host.captureInput())&&port.requestFrame()}});return Object.freeze({backing,dispose(){if(!disposed){disposed=!0;for(const release of[...releases])release()}}})}export{createMapSceneCompletionAdapter,createMapSceneCompletionHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function captureMapSceneCompletionCamera(options){try{const{expected}=options;if(expected.phase!=="resolved"||!options.isCurrent()||options.capturePublication()!==expected)return;const map=options.captureMap();if(!map||typeof map.getCenter!="function"||typeof map.getZoom!="function"||typeof map.getPitch!="function"||typeof map.getMaxBounds!="function"||typeof map.getMinZoom!="function"||typeof map.getMaxZoom!="function"||typeof map.getTerrain!="function"||typeof map.isMoving!="function"||typeof map.getProjection!="function")return;const latitude=map.getCenter().lat,zoom=map.getZoom(),pitch=map.getPitch(),bounds=map.getMaxBounds(),nativeMinZoom=map.getMinZoom(),nativeMaxZoom=map.getMaxZoom(),terrain=map.getTerrain(),moving=map.isMoving(),projection=map.getProjection();if(!projection||typeof projection!="object"||!("type"in projection))return;const projectionType=projection.type,intent=options.captureIntent(),explicitBounds=intent.explicitBounds,explicitZoomLimits=intent.explicitZoomLimits,canPan=typeof map.panBy=="function",canStop=typeof map.stop=="function",canObserveMotion=typeof map.on=="function"&&typeof map.off=="function";if(![latitude,zoom,pitch,nativeMinZoom,nativeMaxZoom].every(Number.isFinite)||latitude<-90||latitude>90||nativeMinZoom>nativeMaxZoom||typeof moving!="boolean"||typeof explicitBounds!="boolean"||typeof explicitZoomLimits!="boolean"||projectionType!=="mercator"&&projectionType!=="globe")return;const facts=Object.freeze({latitude,zoom,pitch,explicitBounds,explicitZoomLimits,nativeBounds:bounds!=null,nativeMinZoom,nativeMaxZoom,terrain:terrain!=null,canPan,canObserveMotion,canStop,moving,hasProjection:!0});return!options.isCurrent()||options.captureMap()!==map||options.capturePublication()!==expected?void 0:facts}catch{return}}export{captureMapSceneCompletionCamera};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{admitMapTerrain,mapScenePreparation,mapSceneValueEqual,snapshotMapSceneBaseline}from"./map-scene-configuration.js";class MapSceneConfigurationController{constructor(options){this.options=options,this.projectionOwned=!1,this.terrainOwned=!1,this.revision=0,this.pending=!1,this.work=Promise.resolve()}cancel(){this.revision++,this.abort?.abort(),this.abort=void 0,this.pending=!1,this.peer=void 0,this.generation=void 0,this.baseline=void 0,this.applied=void 0,this.projectionOwned=!1,this.terrainOwned=!1}sync(peer,generation,current,projection,terrain){if((peer!==this.peer||generation!==this.generation)&&(this.cancel(),this.peer=peer,this.generation=generation),!this.baseline&&projection===void 0&&terrain===void 0)return;this.abort?.abort();const abort=new AbortController;this.abort=abort;const revision=++this.revision,live=()=>!abort.signal.aborted&&this.revision===revision&&this.peer===peer&¤t();try{if(!live())return;const admittedTerrain=admitMapTerrain(terrain);for(const key of["getStyle","getProjection","getTerrain"])if(typeof peer[key]!="function")throw new TypeError("Map scene reader unavailable");const style=peer.getStyle();if(!live())return;if(style===null||typeof style!="object"||Array.isArray(style))throw new TypeError("Map style unavailable");const originalProjection=peer.getProjection();if(!live())return;const originalTerrain=peer.getTerrain();if(!live())return;const observed=snapshotMapSceneBaseline(originalProjection,originalTerrain);if(!live())return;if(!this.baseline){for(const key of["projection","terrain"]){const descriptor=Object.getOwnPropertyDescriptor(style,key);if(descriptor&&!("value"in descriptor))throw new TypeError("Invalid map scene descriptor");if(!live())return}const baseline=observed,styleBaseline=snapshotMapSceneBaseline(Object.getOwnPropertyDescriptor(style,"projection")?.value,Object.getOwnPropertyDescriptor(style,"terrain")?.value);if(!mapSceneValueEqual(baseline,styleBaseline))throw new TypeError("Inconsistent map scene readers");if(!live())return;this.baseline=baseline,this.applied=baseline}const next={projection:projection===void 0?this.projectionOwned?this.baseline.projection:observed.projection:Object.freeze({type:projection}),terrain:admittedTerrain===void 0?this.terrainOwned?this.baseline.terrain:observed.terrain:admittedTerrain},projectionOwned=projection!==void 0,terrainOwned=admittedTerrain!==void 0,participatesProjection=projectionOwned||this.projectionOwned,participatesTerrain=terrainOwned||this.terrainOwned,writeProjection=participatesProjection&&!mapSceneValueEqual(next.projection,observed.projection),writeTerrain=participatesTerrain&&!mapSceneValueEqual(next.terrain,observed.terrain);if(participatesProjection&&typeof peer.setProjection!="function"||participatesTerrain&&typeof peer.setTerrain!="function")throw new TypeError("Map scene writer unavailable");const preparation=mapScenePreparation(participatesProjection?next.projection:void 0,participatesTerrain?next.terrain:void 0,style);if(!live())return;if(!writeProjection&&!writeTerrain){this.projectionOwned=projectionOwned,this.terrainOwned=terrainOwned,this.pending=!1,this.work=Promise.resolve(),this.options.changed();return}if(typeof peer.on!="function"||typeof peer.off!="function")throw new TypeError("Map error subscription unavailable");this.pending=!0,this.options.changed(),this.work=this.apply(peer,preparation,next,writeProjection,writeTerrain,participatesProjection,participatesTerrain,abort.signal,live).then(()=>{live()&&(this.projectionOwned=projectionOwned,this.terrainOwned=terrainOwned)}).catch(()=>{live()&&this.options.failed()}).finally(()=>{this.revision===revision&&(this.pending=!1,this.options.changed())})}catch{live()&&(this.pending=!1,this.options.failed()),this.work=Promise.resolve()}}async apply(peer,preparation,next,projection,terrain,participatesProjection,participatesTerrain,signal,live){let release=()=>{};const cancelled=new Promise(resolve=>{const cancel=()=>resolve();signal.addEventListener("abort",cancel,{once:!0}),release=()=>{signal.removeEventListener("abort",cancel)}});try{if(await Promise.race([peer.prepareFeatures?.(preparation,{signal})??Promise.resolve(),cancelled]),!live())return;const projectionNow=peer.getProjection();if(!live())return;const terrainNow=peer.getTerrain();if(!live())return;const observed=snapshotMapSceneBaseline(projectionNow,terrainNow);if(!live())return;const style=peer.getStyle();if(!live()||(mapScenePreparation(participatesProjection?next.projection:void 0,participatesTerrain?next.terrain:void 0,style),!live()))return;this.applied=observed;let nativeError=!1;const error=()=>{nativeError=!0};peer.on("error",error);try{if(!live())return;if(projection&&(this.applied={projection:next.projection,terrain:this.applied.terrain},this.projectionOwned=!0,peer.setProjection(next.projection)),nativeError)throw new Error("Map projection application failed");if(!live())return;if(terrain&&(this.applied={projection:this.applied.projection,terrain:next.terrain},this.terrainOwned=!0,peer.setTerrain(next.terrain)),nativeError)throw new Error("Map terrain application failed")}finally{peer.off("error",error)}}finally{release()}}}export{MapSceneConfigurationController};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type{LyraMapFeatureRequirements}from'./map-loader.js';import{type LyraMapStyleValue}from'./map-style-value.js';
|
|
2
|
+
/** Declarative shorthand projection override.*/
|
|
3
|
+
export type LyraMapProjection='mercator'|'globe';
|
|
4
|
+
/** A current-style raster elevation source and its nonnegative vertical scale.*/
|
|
5
|
+
export interface LyraMapTerrain{readonly source:string;readonly exaggeration?:number;}
|
|
6
|
+
/** Complete detached native projection specification, retained for replay.*/
|
|
7
|
+
export type LyraMapSceneProjection={readonly[key:string]:LyraMapStyleValue;};export interface LyraMapSceneBaseline{readonly projection:LyraMapSceneProjection;readonly terrain:LyraMapTerrain|null;}export declare function normalizeMapProjection(value:unknown):LyraMapProjection|undefined;
|
|
8
|
+
/** Admit a detached bounded terrain value without executing caller accessors.*/
|
|
9
|
+
export declare function admitMapTerrain(input:unknown):LyraMapTerrain|null|undefined;
|
|
10
|
+
/** Snapshot complete replay data independently of modular preparation requirements.*/
|
|
11
|
+
export declare function snapshotMapSceneBaseline(projection:unknown,terrain:unknown):LyraMapSceneBaseline;
|
|
12
|
+
/** Reduced activation metadata; never pass this object to the native projection setter.*/
|
|
13
|
+
export declare function mapScenePreparation(projection:LyraMapSceneProjection|undefined,terrain:LyraMapTerrain|null|undefined,style:unknown):LyraMapFeatureRequirements;
|
|
14
|
+
/** Compare admitted plain data independent of record insertion order.*/
|
|
15
|
+
export declare function mapSceneValueEqual(first:unknown,second:unknown):boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{safeValue}from"./map-style-value.js";function normalizeMapProjection(value){return value==="mercator"||value==="globe"?value:void 0}function own(record,key){const descriptor=getOwnDataDescriptor(record,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid map scene descriptor");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function admitMapTerrain(input){if(input==null)return input;if(!isPlainDataRecord(input))throw new TypeError("Invalid map terrain");const source=own(input,"source"),scale=own(input,"exaggeration");if(typeof source!="string"||source.trim().length===0||source.length>4096||scale!==void 0&&(typeof scale!="number"||!Number.isFinite(scale)||scale<0))throw new TypeError("Invalid map terrain");return Object.freeze({source,exaggeration:scale===void 0?1:scale})}function snapshotMapSceneBaseline(projection,terrain){const snapshot=safeValue(projection===void 0?{type:"mercator"}:projection)?.value;if(!isPlainDataRecord(snapshot))throw new TypeError("Invalid map projection");const type=own(snapshot,"type");if((typeof type!="string"||type.length===0)&&!Array.isArray(type))throw new TypeError("Invalid map projection");if(Array.isArray(type)&&type.length===0)throw new TypeError("Invalid map projection");return Object.freeze({projection:snapshot,terrain:admitMapTerrain(terrain)??null})}function terrainSource(style,source){if(!isPlainDataRecord(style))throw new TypeError("Invalid current map style");const sources=own(style,"sources");if(!isPlainDataRecord(sources))throw new TypeError("Invalid map terrain source");const descriptor=own(sources,source);if(!isPlainDataRecord(descriptor)||own(descriptor,"type")!=="raster-dem")throw new TypeError("Invalid map terrain source");const result=Object.create(null);return Object.defineProperty(result,source,{value:Object.freeze({type:"raster-dem"}),enumerable:!0}),Object.freeze(result)}function mapScenePreparation(projection,terrain,style){let projectionMetadata;if(projection!==void 0){const type=own(projection,"type");if(typeof type=="string"&&type!=="mercator"&&type!=="globe")throw new TypeError("Unsupported map projection");if(typeof type!="string"&&!Array.isArray(type))throw new TypeError("Invalid map projection");projectionMetadata=Object.freeze({type:type==="mercator"?"mercator":"globe"})}return Object.freeze({...projectionMetadata===void 0?{}:{projection:projectionMetadata},...terrain===void 0?{}:{terrain:terrain!==null},...terrain==null?{}:{sources:terrainSource(style,terrain.source)}})}function mapSceneValueEqual(first,second){if(first===second)return!0;if(Array.isArray(first)||Array.isArray(second))return Array.isArray(first)&&Array.isArray(second)&&first.length===second.length&&first.every((value,index)=>mapSceneValueEqual(value,second[index]));if(!isPlainDataRecord(first)||!isPlainDataRecord(second))return!1;const keys=Object.keys(first);return keys.length===Object.keys(second).length&&keys.every(key=>Object.hasOwn(second,key)&&mapSceneValueEqual(own(first,key),own(second,key)))}export{admitMapTerrain,mapScenePreparation,mapSceneValueEqual,normalizeMapProjection,snapshotMapSceneBaseline};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{admitMapTerrain,mapScenePreparation}from"./map-scene-configuration.js";class SceneControl{constructor(kind,options){this.kind=kind,this.pressed=!1,this.queued=!1,this.generation=0,this.listeners=new Set,this.events=["terrain","projectiontransition","style.load","sourcedata","idle"],this.schedule=()=>{if(this.queued||!this.current())return;this.queued=!0;const generation=this.generation;queueMicrotask(()=>{generation===this.generation&&(this.queued=!1,this.refreshSceneControl())})},this.activate=()=>{if(this.refreshSceneControl(),!this.current()||!this.button||this.button.disabled)return;this.button.disabled=!0,this.button.setAttribute("aria-busy","true");const event=Object.freeze({kind:this.kind,pressed:this.pressed,...this.terrain?{terrain:this.terrain}:{}});for(const listener of[...this.listeners]){if(!this.current())break;listener(event)}this.schedule()},kind==="terrain"&&(this.terrain=admitMapTerrain(options)??void 0)}setSceneContext(context){this.context=context,this.refreshSceneControl()}on(type,listener){type==="activate"&&this.listeners.add(listener)}off(type,listener){type==="activate"&&this.listeners.delete(listener)}onAdd(value){const peer=value;for(const name of["getCanvas","getStyle","getProjection","getTerrain","on","off",this.kind==="globe"?"setProjection":"setTerrain"])if(typeof peer?.[name]!="function")throw new TypeError("Scene control capability is unavailable");this.peer=peer;const document=peer.getCanvas().ownerDocument,root=document.createElement("div");root.className=`maplibregl-ctrl maplibregl-ctrl-group map-scene-${this.kind}-control`,root.part.add(`${this.kind}-control`);const button=document.createElement("button");button.type="button",button.part.add(`${this.kind}-button`);const icon=document.createElementNS("http://www.w3.org/2000/svg","svg");icon.setAttribute("viewBox","0 0 24 24"),icon.setAttribute("aria-hidden","true"),icon.setAttribute("focusable","false"),icon.setAttribute("part",`${this.kind}-icon`),icon.setAttribute("class","map-scene-control-icon");const path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d",this.kind==="globe"?"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM3 12h18M12 3c-5 5-5 13 0 18M12 3c5 5 5 13 0 18":"m2 20 7-13 4 7 3-5 6 11ZM6 13l3 2 2-2"),icon.append(path),button.append(icon),root.append(button),this.root=root,this.button=button,button.addEventListener("click",this.activate);try{for(const event of this.events)peer.on(event,this.schedule)}catch(error){throw this.onRemove(),error}return this.refreshSceneControl(),root}onRemove(){const peer=this.peer;this.peer=void 0,this.generation++,this.button?.removeEventListener("click",this.activate);for(const event of this.events)try{peer?.off(event,this.schedule)}catch{}this.root?.remove(),this.root=void 0,this.button=void 0,this.queued=!1}current(){return!!this.peer&&!!this.context?.isCurrent()}refreshSceneControl(){const context=this.context,button=this.button,peer=this.peer;if(!context||!button||!peer||!this.current())return;const state=context.state(this.kind);if(!this.current())return;let unavailable=!1;if(state.ready&&!state.busy)try{if(this.kind==="globe"){const type=peer.getProjection()?.type;this.pressed=type==="globe"?!0:type==="mercator"||type===void 0?!1:"mixed"}else this.pressed=peer.getTerrain()!=null,this.pressed||(this.terrain?mapScenePreparation(void 0,this.terrain,peer.getStyle()):unavailable=!0)}catch{unavailable=!0}this.current()&&(button.setAttribute("aria-label",state.label),button.title=state.label,button.setAttribute("aria-pressed",String(this.pressed)),button.setAttribute("aria-busy",String(state.busy)),button.disabled=!state.ready||state.busy||unavailable,context.unavailable(this.kind,unavailable))}}class MapGlobeControl extends SceneControl{constructor(options){super("globe",options)}}class MapTerrainControl extends SceneControl{constructor(options){super("terrain",options)}}export{MapGlobeControl,MapTerrainControl};
|
|
@@ -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 codes=new WeakMap;function createMapSceneAdmissionError(code){const error=new TypeError(code==="limit"?"Map scene input limit exceeded":"Invalid map scene descriptor");return codes.set(error,code),Object.freeze(error)}function mapSceneAdmissionErrorCode(error){return error!==null&&(typeof error=="object"||typeof error=="function")?codes.get(error):void 0}export{createMapSceneAdmissionError,mapSceneAdmissionErrorCode};
|
|
@@ -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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sceneLineGrounded}from"./map-scene-lines.js";const EMPTY_DATA=Object.freeze({type:"FeatureCollection",features:Object.freeze([])}),LAYOUT=Object.freeze({"line-join":"round","line-cap":"round"}),PAINT=Object.freeze({"line-color":["get","color"],"line-width":["get","width"],"line-opacity":["get","opacity"]}),MARKER_LAYER=/^scene-markers-\d+$/;let sequence=0;function terrainActive(map){try{const terrain=map.getTerrain?.();return terrain!=null}catch{return!1}}function createMapSceneLineLayer(options){const{map}=options,canvas=(()=>{try{return map.getCanvas()}catch{return}})();let request,ids,phase="pending",failure="engine",epoch=0,disposed=!1,awaitingStyle=!1,contextLost=!1,abort;const current=()=>!disposed&&options.isCurrent();function notify(){if(current())try{options.changed()}catch{}}function cancel(){epoch++,abort?.abort(),abort=void 0}function remove(){const owned=ids;if(owned){try{map.getLayer(owned.layer)&&map.removeLayer(owned.layer)}catch{}try{map.getSource(owned.source)&&map.removeSource(owned.source)}catch{}}}function allocate(){for(let attempt=0;attempt<512;attempt++){const source=`lr-scene-lines-${++sequence}`,layer=`${source}-line`;if(!map.getSource(source)&&!map.getLayer(source)&&!map.getLayer(layer))return Object.freeze({source,layer})}throw new Error("Scene line identifiers are unavailable.")}function before(){const layers=map.getStyle?.()?.layers;return Array.isArray(layers)?layers.find(layer=>typeof layer?.id=="string"&&MARKER_LAYER.test(layer.id))?.id:void 0}function fail(){disposed||(cancel(),remove(),phase="failed",failure="engine",notify())}async function install(data,attempt,signal){const live=()=>current()&&attempt===epoch&&!signal.aborted&&!awaitingStyle&&options.styleLoaded();try{if(typeof map.prepareFeatures=="function"){const owned2=ids??{source:"lr-scene-lines",layer:"lr-scene-lines-line"};await map.prepareFeatures({sources:{[owned2.source]:{type:"geojson",data:EMPTY_DATA}},layers:[{id:owned2.layer,type:"line",source:owned2.source}]},{signal})}if(!live())return;remove();const owned=ids=allocate();if(map.addSource(owned.source,{type:"geojson",data}),!live()){remove();return}if(map.addLayer({id:owned.layer,type:"line",source:owned.source,layout:LAYOUT,paint:PAINT},before()),!live()){remove();return}if(!map.getSource(owned.source)||!map.getLayer(owned.layer))throw new Error("Scene lines were not installed.");phase="installed",abort=void 0,notify()}catch{current()&&attempt===epoch&&!signal.aborted&&fail()}}function apply(){if(!current())return;const next=request;if(cancel(),!next){remove(),ids=void 0,phase="pending",notify();return}if("failure"in next){remove(),phase="failed",failure=next.failure,notify();return}if(awaitingStyle||!options.styleLoaded()){phase="pending",notify();return}const owned=ids;if(owned&&phase!=="failed")try{const source=map.getSource(owned.source);if(source&&map.getLayer(owned.layer)&&typeof source.setData=="function"){if(source.setData(next.data),!current()||request!==next)return;phase="installed",notify();return}}catch{fail();return}phase="pending",notify();const controller=abort=new AbortController,attempt=epoch;install(next.data,attempt,controller.signal)}const terrainChanged=()=>{current()&&phase==="installed"&¬ify()},lost=()=>{current()&&(contextLost=!0,notify())},restored=()=>{current()&&(contextLost=!1,apply())};try{Reflect.apply(map.on,map,["terrain",terrainChanged])}catch{}return canvas?.addEventListener("webglcontextlost",lost),canvas?.addEventListener("webglcontextrestored",restored),{update(value){disposed||(request=value,apply())},styleReady(){disposed||(awaitingStyle=!1,request&&apply())},invalidateStyle(){disposed||(cancel(),awaitingStyle=!0,phase==="installed"&&(phase="pending",notify()))},capture(){const revision=request?.revision;if(!request)return{revision,outcome:{state:"none"}};if(phase==="failed")return{revision,outcome:{state:"failed",code:failure}};if(contextLost)return{revision,outcome:{state:"failed",code:"context-lost"}};if(phase!=="installed"||"failure"in request)return{revision,outcome:{state:"pending"}};const terrain=terrainActive(map);return{revision,outcome:{state:"drawn",approximate:request.objects.some(object=>!sceneLineGrounded(object,terrain))}}},dispose(){if(!disposed){cancel(),disposed=!0;try{map.off?.("terrain",terrainChanged)}catch{}canvas?.removeEventListener("webglcontextlost",lost),canvas?.removeEventListener("webglcontextrestored",restored),remove(),ids=void 0,request=void 0}}}}export{createMapSceneLineLayer};
|
|
@@ -0,0 +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]))}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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{stageMapSceneAdmission}from"./map-scene-admission.js";import{createMapSceneAdmissionError,mapSceneAdmissionErrorCode}from"./map-scene-errors.js";import{createMapScenePositionRegistry}from"./map-scene-position-registry.js";import{buildSceneRenderInput,emptySceneRenderInput,nextSceneRenderRevision,snapshotScenePresentation,snapshotSceneViewport}from"./map-scene-render-input.js";import{createMapSceneSourceOwner,isStaleMapSceneSourceError}from"./map-scene-source-snapshot.js";const MAX_ENCODED_BYTES=64*1024*1024,MAX_NOTIFICATION_PASSES=6144,RENDER_STATES=new Set(["loading","ready","partial","unavailable"]),RENDER_CODES=new Set(["limit","model","resource","engine","projection","terrain","context-lost","altitude"]);function nextPaintFrameSerial(previous){return Number.isSafeInteger(previous)&&previous>=0&&previous<Number.MAX_SAFE_INTEGER?previous+1:void 0}function createMapSceneOwner(options){const{element,connection}=options;let closed=!1,notifying=!1,requestRevision=0,liveBytes=0,accepted=Object.freeze({acceptedSceneRevision:0,objects:Object.freeze([])}),view=Object.freeze({active:!1,accepted,status:void 0}),changedBaseline=view;const acceptedObservers=new Set,stateObservers=new Set,renderObservers=new Set;function current(request){return closed||request.connection!==connection||request.revision!==requestRevision?!1:options.isCurrentConnection()&&!closed&&request.connection===connection&&request.revision===requestRevision&&nextSceneRenderRevision(renderPublication.input.presentationRevision)!==void 0}let resources,stateSnapshot=Object.freeze({acceptedSceneRevision:0,registryRevision:0,targets:Object.freeze([]),viewport:void 0}),allocationRevision=0,paintFrameSerial=0,resolvedPresentation,renderPublication=Object.freeze({accepted,state:stateSnapshot,phase:"resolved",input:emptySceneRenderInput(0,1,void 0)});function createResources(){const sources=createMapSceneSourceOwner({connection,maxEncodedBytes:MAX_ENCODED_BYTES,isCurrent:current,reserveBytes(byteLength){if(!Number.isSafeInteger(byteLength)||byteLength<0)throw createMapSceneAdmissionError("invalid");if(byteLength>MAX_ENCODED_BYTES-liveBytes)throw createMapSceneAdmissionError("limit");liveBytes+=byteLength;let released=!1;return Object.freeze({release(){released||(released=!0,liveBytes-=byteLength)}})},resolveUrl(source){const target=resolveOwnerFetchTarget(element,source);return target?Object.freeze({url:target.url,owner:target.view}):null}}),registry=createMapScenePositionRegistry({connection,sources,isCurrent:current});return{sources,registry}}function subscribe(observers,listener,baseline){if(typeof listener!="function")throw new TypeError("Invalid map scene listener");if(closed)return()=>{};const observer={listener,baseline};return observers.add(observer),()=>{observers.delete(observer)}}const state=Object.freeze({connection,capture:()=>stateSnapshot,subscribe:listener=>subscribe(stateObservers,listener,stateSnapshot)});function invoke(callback){try{callback()}catch{}}function notify(){if(!(closed||notifying)){notifying=!0;try{for(let pass=0;pass<MAX_NOTIFICATION_PASSES&&!closed;pass++){let delivered=!1;for(const observer of[...stateObservers]){if(closed)return;!stateObservers.has(observer)||observer.baseline===stateSnapshot||(observer.baseline=stateSnapshot,delivered=!0,invoke(observer.listener))}for(const observer of[...acceptedObservers]){if(closed)return;!acceptedObservers.has(observer)||observer.baseline===accepted||(observer.baseline=accepted,delivered=!0,invoke(observer.listener))}for(const observer of[...renderObservers]){if(closed)return;!renderObservers.has(observer)||observer.baseline===renderPublication||(observer.baseline=renderPublication,delivered=!0,invoke(observer.listener))}if(closed||(changedBaseline!==view&&(changedBaseline=view,delivered=!0,invoke(options.changed)),!delivered))return}}finally{notifying=!1}}}function publish(active,status){view=Object.freeze({active,accepted,status}),notify()}function currentPublication(expected){if(closed||renderPublication!==expected)return!1;try{return options.isCurrentConnection()&&!closed&&renderPublication===expected}catch{return!1}}function commitRender(expected,next,presentation,nextAllocation){return currentPublication(expected)?(stateSnapshot=next.state,renderPublication=next,resolvedPresentation=presentation,allocationRevision=nextAllocation,notify(),!0):!1}function publishAccepted(objects,active){const snapshot=resources.registry.capture(),nextAccepted=Object.freeze({acceptedSceneRevision:snapshot.acceptedSceneRevision,objects}),nextState=Object.freeze({...snapshot,viewport:stateSnapshot.viewport}),revision=nextSceneRenderRevision(renderPublication.input.presentationRevision),next=Object.freeze({accepted:nextAccepted,state:nextState,phase:objects.some(object=>object.kind==="marker")?"pending":"resolved",input:emptySceneRenderInput(nextAccepted.acceptedSceneRevision,revision,nextState.viewport)});accepted=nextAccepted,stateSnapshot=nextState,renderPublication=next,resolvedPresentation=void 0,publish(active,objects.length===0?Object.freeze({revision:accepted.acceptedSceneRevision,state:"empty"}):Object.freeze({revision:accepted.acceptedSceneRevision,state:"loading"}))}function sameViewport(first,second){return first===void 0?second===void 0:second!==void 0&&first.width===second.width&&first.height===second.height&&first.pixelRatio===second.pixelRatio&&first.padding.top===second.padding.top&&first.padding.right===second.padding.right&&first.padding.bottom===second.padding.bottom&&first.padding.left===second.padding.left}return Object.freeze({state,captureAccepted:()=>accepted,captureView:()=>view,subscribeAccepted:listener=>subscribe(acceptedObservers,listener,accepted),captureRenderPublication:()=>renderPublication,claimPaintFrameSerial(expected){if(expected!==renderPublication||expected.phase!=="resolved"||!currentPublication(expected))return;const next=nextPaintFrameSerial(paintFrameSerial);return next!==void 0&&(paintFrameSerial=next),next},subscribeRenderPublication:listener=>subscribe(renderObservers,listener,renderPublication),invalidatePresentation(){const expected=renderPublication;if(closed||!accepted.objects.some(object=>object.kind==="marker"))return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const next=Object.freeze({...expected,phase:"pending",input:emptySceneRenderInput(accepted.acceptedSceneRevision,revision,expected.state.viewport)});return commitRender(expected,next,void 0,allocationRevision)},commitPresentation(expected,value){if(closed||renderPublication!==expected||expected.phase!=="pending")return!1;const presentation=snapshotScenePresentation(value);if(!presentation)return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const input=buildSceneRenderInput({accepted:expected.accepted,state:expected.state,phase:"resolved",presentationRevision:revision,presentation});if(!input)return!1;const next=Object.freeze({...expected,phase:"resolved",input});return commitRender(expected,next,presentation,allocationRevision)},failPresentation(expected){if(closed||renderPublication!==expected||expected.phase!=="pending")return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision);if(revision===void 0)return!1;const next=Object.freeze({...expected,phase:"unavailable",input:emptySceneRenderInput(accepted.acceptedSceneRevision,revision,expected.state.viewport)});return commitRender(expected,next,void 0,allocationRevision)},setViewport(value){const expected=renderPublication;if(closed)return!1;const copied=value===void 0?void 0:snapshotSceneViewport(value);if(value!==void 0&&!copied||sameViewport(expected.state.viewport,copied))return!1;const revision=nextSceneRenderRevision(expected.input.presentationRevision),nextAllocation=copied===void 0?allocationRevision:nextSceneRenderRevision(allocationRevision);if(revision===void 0||nextAllocation===void 0)return!1;const viewport=copied===void 0?void 0:Object.freeze({...copied,allocationRevision:nextAllocation}),nextState=Object.freeze({...expected.state,viewport}),input=expected.phase==="resolved"&&resolvedPresentation!==void 0?buildSceneRenderInput({accepted:expected.accepted,state:nextState,phase:"resolved",presentationRevision:revision,presentation:resolvedPresentation}):emptySceneRenderInput(expected.accepted.acceptedSceneRevision,revision,viewport);if(!input)return!1;const next=Object.freeze({...expected,state:nextState,input});return commitRender(expected,next,resolvedPresentation,nextAllocation)},reportRenderStatus(revision,value){if(closed||!view.active||accepted.objects.length===0||revision!==accepted.acceptedSceneRevision||value===null||typeof value!="object")return!1;const{state:next,code}=value;if(!RENDER_STATES.has(next)||code!==void 0&&!RENDER_CODES.has(code))return!1;const previous=view.status;return previous?.state==="error"||previous?.revision===revision&&previous.state===next&&previous.code===code?!1:(publish(!0,Object.freeze({revision,state:next,...code===void 0?{}:{code}})),!0)},assign(value){if(closed)return;const before=requestRevision;if(!options.isCurrentConnection()||closed||before!==requestRevision||value===void 0&&!view.active&&accepted.acceptedSceneRevision===0||nextSceneRenderRevision(renderPublication.input.presentationRevision)===void 0||!Number.isSafeInteger(requestRevision+1))return;const request=Object.freeze({connection,revision:++requestRevision});let candidate;try{const{sources,registry}=resources??=createResources();if(value===void 0){if(!registry.clear(request))return;publishAccepted(Object.freeze([]),!1);return}if(candidate=stageMapSceneAdmission(value,{request,sources}),!registry.commit(candidate))return;publishAccepted(candidate.objects,!0)}catch(error){if(candidate?.dispose(),!current(request)||isStaleMapSceneSourceError(error))return;publish(!0,Object.freeze({revision:accepted.acceptedSceneRevision,state:"error",code:mapSceneAdmissionErrorCode(error)??"invalid"}))}},close(){closed||(closed=!0,acceptedObservers.clear(),stateObservers.clear(),renderObservers.clear(),resolvedPresentation=void 0,resources?.registry.dispose(),resources?.sources.dispose(),resources=void 0)}})}export{createMapSceneOwner,nextPaintFrameSerial};
|