@aceshooting/lyra-ui 30.5.0 → 30.7.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 +78 -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 +5 -2
- 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-errors.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 +55 -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-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/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 +5 -2
- 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 +315 -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 +184 -0
- package/llms/shared.md +200 -2
- package/locales.json +1 -1
- package/package.json +37 -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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{admitMapCameraFollowOptions,admitMapCameraFollowProfile,createMapCameraFollowAttempt,observeMapCameraFollowAttempt}from"./map-camera-follow-data.js";import{admitMapViewpoint}from"./map-camera-session-data.js";const plans=new WeakMap,unavailable=()=>{throw new Error("Camera follow unavailable")};function prepareMapCameraFollow(input,dependencies){const options=admitMapCameraFollowOptions(input);if(options.mode==="geographic-visual"&&(options.zoom!==void 0||options.bearing!==void 0||options.pitch!==void 0))throw new TypeError("Explicit camera axes are unavailable for screen following");const check=()=>{dependencies.current()||unavailable()};check();const target=dependencies.scene?.target(options.objectId);if(check(),target?.kind==="unsupported")throw new TypeError("Unsupported camera follow target");const view=admitMapViewpoint(dependencies.capture());check();const reduced=dependencies.reducedMotion();check();const plan=Object.freeze({});return plans.set(plan,{options,dependencies,view,reduced}),plan}function sameView(first,second){return first!==void 0&&first.center[0]===second.center[0]&&first.center[1]===second.center[1]&&first.zoom===second.zoom&&first.bearing===second.bearing&&first.pitch===second.pitch}function startMapCameraFollow(plan,owner){const admitted=plans.get(plan);if(!admitted)throw new TypeError("Invalid camera follow plan");const{options,dependencies,view}=admitted,scene=dependencies.scene;let disposed=!1,failed=!1,starting=!0,draining=!1,revision=0,pendingTarget=!1,queuedFrame,target={kind:"absent"},positionRevision,viewportRevision=-1,lastSerial=-1,lastObservedSerial=-1,writes=0,highestPositionRevision=-1,restricted=admitted.reduced,profileRefused=!1,limitedByMotion=!1,attempt=createMapCameraFollowAttempt({reducedMotion:restricted}),applied,snapshot=Object.freeze({status:"pending",corrections:0});const releases=new Set,live=()=>!disposed&&owner.current(),releaseAll=()=>{for(const release of[...releases]){releases.delete(release);try{release()}catch{}}},dispose=()=>{disposed||(disposed=!0,revision++,pendingTarget=!1,queuedFrame=void 0,releaseAll())},publish=next=>{if(!live()){dispose();return}snapshot.status===next.status&&snapshot.reason===next.reason&&snapshot.corrections===next.corrections||(snapshot=Object.freeze(next),owner.publish(snapshot),live()||dispose())},fail=()=>{disposed||(failed=!0,revision++,pendingTarget=!1,queuedFrame=void 0,releaseAll(),live()?publish({status:"unavailable",reason:"engine",corrections:attempt.corrections}):dispose())},guard=delivery=>live()?!failed&&revision===delivery:(dispose(),!1),add=release=>{if(live()&&!failed)releases.add(release);else try{release()}finally{dispose()}},reset=()=>{attempt=createMapCameraFollowAttempt({reducedMotion:restricted}),profileRefused=!1,limitedByMotion=!1},request=()=>{!live()||failed||!scene||options.mode!=="geographic-visual"||(scene.requestFrame(options.objectId),live()||dispose())},targetCurrent=(expected,delivery)=>{if(!guard(delivery)||!scene)return!1;const latest=scene.target(options.objectId);return guard(delivery)?latest.kind==="eligible"&&latest.positionRevision===expected:!1},deliverTarget=()=>{const delivery=revision;if(!guard(delivery)||!scene)return;const next=scene.target(options.objectId);if(!guard(delivery)||next.kind==="eligible"&&(next.positionRevision<highestPositionRevision||target.kind!=="eligible"&&next.positionRevision<=highestPositionRevision))return;if(target=next,next.kind!=="eligible"){positionRevision=void 0,publish(next.kind==="absent"?{status:"missing",corrections:attempt.corrections}:{status:"unavailable",reason:"kind",corrections:attempt.corrections});return}const changed=positionRevision!==next.positionRevision;if(positionRevision=next.positionRevision,highestPositionRevision=Math.max(highestPositionRevision,next.positionRevision),options.mode==="geographic-visual"){changed&&(reset(),publish({status:"pending",corrections:0}),guard(delivery)&&request());return}const destination=admitMapViewpoint({center:next.center,zoom:options.zoom??view.zoom,bearing:options.bearing??view.bearing,pitch:options.pitch??view.pitch});if(sameView(applied,destination)||restricted&&writes>0){publish({status:"ground",corrections:0});return}const prepared=owner.prepareGround(destination);if(!targetCurrent(next.positionRevision,delivery))return;const accepted=owner.commitGround(prepared);if(accepted&&(writes++,applied=destination),!!guard(delivery)){if(!accepted){fail();return}publish({status:"ground",corrections:0})}},deliverFrame=frame=>{const delivery=revision;if(!guard(delivery)||!scene||options.mode!=="geographic-visual"||target.kind!=="eligible"||profileRefused||limitedByMotion||attempt.status!=="centering"||frame.serial<=lastSerial||frame.serial<=lastObservedSerial||frame.stamp.position!==target.positionRevision||!scene.current(frame.stamp)||!guard(delivery)||!targetCurrent(target.positionRevision,delivery)||!Number.isSafeInteger(frame.serial)||frame.serial<0)return;lastObservedSerial=frame.serial;const profile=admitMapCameraFollowProfile(frame.profile);if(profile.status==="unavailable"){profileRefused=!0,publish({status:"unavailable",reason:profile.reason,corrections:attempt.corrections});return}if(frame.result.status!=="visible"){publish(frame.result.status==="pending"?{status:"pending",corrections:attempt.corrections}:{status:"unavailable",reason:"placement",corrections:attempt.corrections});return}const observedAttempt=attempt,step=observeMapCameraFollowAttempt(observedAttempt,{frame:frame.serial,point:frame.result.point,width:frame.width,height:frame.height});if(!step.correction){attempt=step.attempt,publish({status:step.status,corrections:attempt.corrections});return}if(restricted&&writes>0){limitedByMotion=!0,publish({status:"limited",corrections:attempt.corrections});return}const prepared=owner.preparePan(step.correction,frame.stamp);if(!guard(delivery)||!targetCurrent(frame.stamp.position,delivery)||!scene.current(frame.stamp)||!guard(delivery))return;const accepted=owner.commitPan(prepared);if(accepted&&(writes++,lastSerial=Math.max(lastSerial,frame.serial),attempt===observedAttempt&&(attempt=step.attempt)),!!guard(delivery)){if(!accepted){fail();return}publish({status:step.status,corrections:attempt.corrections})}},drain=()=>{if(!(starting||draining||disposed||failed)){draining=!0;try{for(;!disposed&&!failed&&(pendingTarget||queuedFrame);)if(pendingTarget)pendingTarget=!1,deliverTarget();else{const frame=queuedFrame;queuedFrame=void 0,frame&&deliverFrame(frame)}}catch{fail()}finally{draining=!1}}},applyNotice=value=>{if(!live()||failed){live()||dispose();return}if(value.kind==="target"){if(value.objectId!==options.objectId)return;revision++,pendingTarget=!0}else{if(!Number.isSafeInteger(value.revision)||value.revision<=viewportRevision)return;viewportRevision=value.revision,revision++,options.mode==="geographic-visual"&&(reset(),request())}drain()},applyFrame=frame=>{if(!live()||failed){live()||dispose();return}(!queuedFrame||frame.serial>queuedFrame.serial)&&(queuedFrame=frame),drain()},notice=value=>{try{applyNotice(value)}catch{fail()}},receiveFrame=frame=>{try{applyFrame(frame)}catch{fail()}},runner={get snapshot(){return snapshot},refreshMotion:reduced=>{disposed||failed||!reduced||restricted||(restricted=!0,revision++)},dispose};try{if(!live()||(restricted=dependencies.reducedMotion(),!live())||(attempt=createMapCameraFollowAttempt({reducedMotion:restricted}),owner.ready?.(runner),!live()))return dispose(),runner;if(!scene)return publish({status:"unavailable",reason:"scene",corrections:0}),runner;if(add(scene.subscribeTargets(notice)),!live()||options.mode==="geographic-visual"&&(add(scene.watchTarget(options.objectId)),!live()||(add(scene.subscribeFrames(options.objectId,receiveFrame)),!live())))return runner;pendingTarget=!0,starting=!1,drain()}catch{fail()}finally{starting=!1}return runner}export{prepareMapCameraFollow,startMapCameraFollow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"./data-descriptors.js";const attempts=new WeakMap,invalid=()=>{throw new TypeError("Invalid camera follow data")};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(input,keys){if(!isPlainDataRecord(input))return invalid();for(const key of Reflect.ownKeys(input)){if(typeof key!="string"||!keys.includes(key))return invalid();own(input,key)}return input}function finite(value){return typeof value!="number"||!Number.isFinite(value)?invalid():value}function ranged(value,lower,upper){const result=finite(value);return result<lower||result>upper?invalid():result}function boolean(value){return typeof value!="boolean"?invalid():value}function angle(value){const reduced=value%360,result=reduced>=180?reduced-360:reduced<-180?reduced+360:reduced;return result===0?0:result}function admitMapCameraFollowOptions(input){const source=record(input,["objectId","mode","zoom","bearing","pitch"]),objectId=own(source,"objectId"),mode=own(source,"mode");if(typeof objectId!="string"||objectId.length<1||objectId.length>1024||objectId.trim().length===0||mode!=="ground"&&mode!=="geographic-visual")return invalid();const zoom=own(source,"zoom"),bearing=own(source,"bearing"),pitch=own(source,"pitch");return Object.freeze({objectId,mode,...zoom===void 0?{}:{zoom:finite(zoom)},...bearing===void 0?{}:{bearing:angle(finite(bearing))},...pitch===void 0?{}:{pitch:ranged(pitch,0,85)}})}const profileKeys=["latitude","zoom","pitch","width","height","projectionTransition","padding","explicitBounds","explicitZoomLimits","nativeBounds","nativeMinZoom","nativeMaxZoom","terrain","canPan","canObserveMotion","canStop","moving","hasProjection"],unavailable=reason=>Object.freeze({status:"unavailable",reason});function admitMapCameraFollowProfile(input){try{const source=record(input,profileKeys),explicitBounds=boolean(own(source,"explicitBounds")),explicitZoomLimits=boolean(own(source,"explicitZoomLimits")),nativeBounds=boolean(own(source,"nativeBounds")),nativeMinZoom=finite(own(source,"nativeMinZoom")),nativeMaxZoom=finite(own(source,"nativeMaxZoom"));if(explicitBounds||explicitZoomLimits||nativeBounds||nativeMinZoom!==-2||nativeMaxZoom!==22)return unavailable("camera-constraints");if(boolean(own(source,"terrain")))return unavailable("terrain");const canPan=boolean(own(source,"canPan")),canObserveMotion=boolean(own(source,"canObserveMotion")),canStop=boolean(own(source,"canStop")),moving=boolean(own(source,"moving")),hasProjection=boolean(own(source,"hasProjection"));if(!canPan||!canObserveMotion||!hasProjection||moving&&!canStop)return unavailable("camera-capability");const latitude=ranged(own(source,"latitude"),-90,90),zoom=finite(own(source,"zoom"));ranged(own(source,"pitch"),0,60),ranged(own(source,"width"),64,4096),ranged(own(source,"height"),64,4096);const padding=record(own(source,"padding"),["top","bottom","left","right"]);if(["top","bottom","left","right"].some(side=>finite(own(padding,side))!==0))return unavailable("camera-domain");const transition=ranged(own(source,"projectionTransition"),0,1),adjustment=Math.log2(Math.cos(Math.min(Math.abs(latitude),85.051129)*Math.PI/180)),domain=transition>0?zoom-adjustment:zoom;return!Number.isFinite(domain)||domain<4||domain>20?unavailable("camera-domain"):Object.freeze({status:"admitted",helper:transition>0?"globe":"mercator"})}catch{return unavailable("camera-domain")}}function makeAttempt(value,state){const result=Object.freeze(value);return attempts.set(result,state),result}function createMapCameraFollowAttempt(options){const source=record(options===void 0?{}:options,["reducedMotion"]),requested=own(source,"reducedMotion"),reduced=requested===void 0?!1:boolean(requested);return makeAttempt({corrections:0,nonImproving:0,status:"centering"},{maximum:reduced?1:4})}function point(input){return!Array.isArray(input)||own(input,"length")!==2||Reflect.ownKeys(input).length!==3?invalid():[finite(own(input,"0")),finite(own(input,"1"))]}function magnitude(x,y){const scale=Math.max(Math.abs(x),Math.abs(y));return{scale,normalized:scale===0?0:Math.hypot(x/scale,y/scale)}}function improves(next,previous){const scale=Math.max(next.scale,previous.scale);return scale===0?!1:next.scale/scale*next.normalized<previous.scale/scale*previous.normalized}function step(attempt,correction){return Object.freeze({attempt,status:attempt.status,...correction===void 0?{}:{correction:Object.freeze(correction)}})}function observeMapCameraFollowAttempt(attempt,input){const state=attempts.get(attempt);if(!state)return invalid();const source=record(input,["frame","point","width","height"]),frame=ranged(own(source,"frame"),0,Number.MAX_SAFE_INTEGER);if(!Number.isSafeInteger(frame))return invalid();const width=ranged(own(source,"width"),64,4096),height=ranged(own(source,"height"),64,4096),[x,y]=point(own(source,"point"));if(attempt.status!=="centering"||attempt.lastFrame!==void 0&&frame<=attempt.lastFrame)return step(attempt);const dx=x-width/2,dy=y-height/2,distance=magnitude(dx,dy),residual=Math.min(Number.MAX_VALUE,distance.scale*distance.normalized),centered=distance.scale<=2&&distance.scale*distance.normalized<=2,nonImproving=state.magnitude&&!improves(distance,state.magnitude)?attempt.nonImproving+1:0,limited=!centered&&(attempt.corrections>=state.maximum||nonImproving>=2),status=centered?"centered":limited?"limited":"centering",next=makeAttempt({corrections:attempt.corrections+(status==="centering"?1:0),nonImproving,lastFrame:frame,lastResidual:residual,status},{maximum:state.maximum,magnitude:distance});return status==="centering"?step(next,[Math.max(-width/2,Math.min(width/2,dx)),Math.max(-height/2,Math.min(height/2,dy))]):step(next)}export{admitMapCameraFollowOptions,admitMapCameraFollowProfile,createMapCameraFollowAttempt,observeMapCameraFollowAttempt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function once(release){let active=!0;return()=>{active&&(active=!1,release())}}function cameraProfile(profile){if(profile)return Object.freeze({latitude:profile.latitude,zoom:profile.zoom,pitch:profile.pitch,width:profile.width,height:profile.height,projectionTransition:profile.nativeControlTransition,padding:Object.freeze({top:profile.padding.top,bottom:profile.padding.bottom,left:profile.padding.left,right:profile.padding.right}),explicitBounds:profile.explicitBounds,explicitZoomLimits:profile.explicitZoomLimits,nativeBounds:profile.nativeBounds,nativeMinZoom:profile.nativeMinZoom,nativeMaxZoom:profile.nativeMaxZoom,terrain:profile.terrain,canPan:profile.canPan,canObserveMotion:profile.canObserveMotion,canStop:profile.canStop,moving:profile.moving,hasProjection:profile.hasProjection})}function projectionResult(projection,revision){if(!projection||projection.acceptedPositionRevision!==revision)return Object.freeze({status:"unavailable"});switch(projection.status){case"resolved":{const point=projection.point;return projection.visible!==!0||!Array.isArray(point)||point.length!==2||!Number.isFinite(point[0])||!Number.isFinite(point[1])?Object.freeze({status:"unavailable"}):Object.freeze({status:"visible",point:Object.freeze([point[0],point[1]])})}case"terrain-pending":case"model-pending":case"visibility-pending":return Object.freeze({status:"pending"});case"clipped":return Object.freeze({status:"clipped"});case"occluded":return Object.freeze({status:"occluded"});default:return Object.freeze({status:"unavailable"})}}function createMapCameraFollowScene(attachment){const receipts=new WeakMap;return Object.freeze({target(objectId){const lookup=attachment.target(objectId);if(lookup.status==="absent")return Object.freeze({kind:"absent"});if(lookup.status==="unsupported-kind")return Object.freeze({kind:"unsupported",objectKind:lookup.kind});const{target}=lookup;return Object.freeze({kind:"eligible",objectKind:target.kind,positionRevision:target.acceptedPositionRevision,center:Object.freeze([target.position.lngLat[0],target.position.lngLat[1]]),altitude:target.position.altitude,altitudeReference:target.position.altitudeReference})},subscribeTargets(listener){let active=!0;const releases=[],release=()=>{if(active){active=!1;for(const stop of releases.splice(0))try{stop()}catch{}}};try{releases.push(attachment.subscribeTargets(notice=>{for(const objectId of notice.changedIds){if(!active)return;listener(Object.freeze({kind:"target",objectId}))}})),releases.push(attachment.subscribeViewport(notice=>{active&&listener(Object.freeze({kind:"viewport",revision:notice.allocationRevision}))}))}catch(error){throw release(),error}return release},watchTarget(objectId){return once(attachment.watchTarget(objectId))},subscribeFrames(objectId,listener){let active=!0;const stop=attachment.subscribeCompletedFrames(frame=>{if(!active)return;const lookup=attachment.target(objectId);if(!active||lookup.status!=="accepted")return;const target=lookup.target;if(!attachment.current(frame,target)||!active)return;const projected=attachment.projectTarget(frame,objectId);if(!active||!attachment.current(frame,target)||!active)return;const stamp=Object.freeze({owner:frame.stamp.ownerToken,context:frame.stamp.contextEpoch,style:frame.stamp.styleRevision,view:frame.stamp.samplingViewRevision,position:target.acceptedPositionRevision,placement:frame.stamp.placementRevision});receipts.set(stamp,{frame,target}),listener(Object.freeze({serial:frame.stamp.paintFrameSerial,stamp,profile:cameraProfile(frame.cameraProfile),width:frame.width,height:frame.height,result:projectionResult(projected,target.acceptedPositionRevision)}))});return()=>{active&&(active=!1,stop())}},current(stamp){const receipt=receipts.get(stamp);return receipt!==void 0&&attachment.current(receipt.frame,receipt.target)},requestFrame(){attachment.requestFrame()}})}export{createMapCameraFollowScene};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import{type SimulationClock}from'../simulation-clock.js';import{type MapViewpoint}from'./map-camera-session-data.js';import{type MapCameraFollowSnapshot}from'./map-camera-follow-controller.js';export type{MapViewpoint}from'./map-camera-session-data.js';
|
|
2
|
+
/** Why a camera-session call failed. Every failure leaves the previous action unchanged.*/
|
|
3
|
+
export type MapCameraSessionErrorCode='invalid-options'|'invalid-viewpoint'|'invalid-tour'|'invalid-follow'|'invalid-clock'|'unsupported-map'|'inactive-map'|'already-bound'|'unavailable'|'disposed';
|
|
4
|
+
/** Thrown synchronously by `createMapCameraSession()` and the session methods; read `code`.*/
|
|
5
|
+
export declare class MapCameraSessionError extends Error{readonly code:MapCameraSessionErrorCode;constructor(code:MapCameraSessionErrorCode);}
|
|
6
|
+
/** Why the session snapshot last changed.*/
|
|
7
|
+
export type MapCameraSessionReason='initial'|'start'|'complete'|'stop'|'user'|'external'|'style'|'disconnect'|'engine'|'disposed';
|
|
8
|
+
/** The camera action a session currently owns, or `idle`.*/
|
|
9
|
+
export type MapCameraSessionMode='idle'|'viewpoint'|'tour'|'follow';
|
|
10
|
+
/** Tracking progress of a follow action. Ground following reports `pending`, `ground`, `missing` or `unavailable`.*/
|
|
11
|
+
export type MapCameraTrackingStatus=MapCameraFollowSnapshot['status'];
|
|
12
|
+
/** Why tracking is unavailable: `kind` for an unfollowable path or arc, `engine` for a refused camera command.*/
|
|
13
|
+
export type MapCameraTrackingIssue=NonNullable<MapCameraFollowSnapshot['reason']>;interface SnapshotBase{
|
|
14
|
+
/** `true` while the session owns a running or tracking camera action.*/
|
|
15
|
+
readonly active:boolean;readonly reason:MapCameraSessionReason;}
|
|
16
|
+
/** Immutable session state delivered to `subscribe()` listeners and read from `snapshot`.*/
|
|
17
|
+
export type MapCameraSessionSnapshot=SnapshotBase&({readonly mode:'idle'|'viewpoint'|'tour';}|{readonly mode:'follow';readonly objectId:string;readonly followMode:MapCameraFollowOptions['mode'];readonly trackingStatus:MapCameraTrackingStatus;readonly corrections:number;readonly unavailableReason?:MapCameraTrackingIssue;});
|
|
18
|
+
/** How `restore()` moves the camera. Under reduced motion every transition is a jump.*/
|
|
19
|
+
export interface MapCameraTransition{
|
|
20
|
+
/** `'jump'` (default) moves at once; `'ease'` and `'fly'` animate.*/
|
|
21
|
+
readonly kind?:'jump'|'ease'|'fly';
|
|
22
|
+
/** Animation length in milliseconds; finite and at least 0. The engine default applies when omitted.*/
|
|
23
|
+
readonly duration?:number;}
|
|
24
|
+
/** One tour keyframe. The gap to the next keyframe's `instant` is that segment's duration.*/
|
|
25
|
+
export interface MapCameraKeyframe{
|
|
26
|
+
/** Clock instant in epoch milliseconds; keyframes must strictly increase.*/
|
|
27
|
+
readonly instant:number;readonly view:MapViewpoint;
|
|
28
|
+
/** `'linear'` (default) interpolates toward the next keyframe; `'hold'` keeps this view until it.*/
|
|
29
|
+
readonly interpolation?:'linear'|'hold';}
|
|
30
|
+
/** An ordered camera tour of 1 to 1,024 keyframes, sampled from a shared simulation clock.*/
|
|
31
|
+
export interface MapCameraTour{readonly keyframes:readonly MapCameraKeyframe[];}
|
|
32
|
+
/** Follows one accepted `lr-map` scene marker or model by its exact `id`.*/
|
|
33
|
+
export interface MapCameraFollowOptions{readonly objectId:string;
|
|
34
|
+
/** Moves the map centre to the object's accepted geographic position.*/
|
|
35
|
+
readonly mode:'ground';
|
|
36
|
+
/** Fixed zoom while following; omitted axes keep the camera's value when following starts.*/
|
|
37
|
+
readonly zoom?:number;readonly bearing?:number;
|
|
38
|
+
/** Degrees in `[0, 85]`.*/
|
|
39
|
+
readonly pitch?:number;}
|
|
40
|
+
/** Options for `createMapCameraSession()`. Aborting the signal disposes the session.*/
|
|
41
|
+
export interface MapCameraSessionOptions{readonly signal?:AbortSignal;}
|
|
42
|
+
/** One application's ownership of an `lr-map` camera. Methods throw `MapCameraSessionError`.*/
|
|
43
|
+
export interface MapCameraSession{readonly snapshot:MapCameraSessionSnapshot;
|
|
44
|
+
/** Returns the current camera as a detached, frozen viewpoint.*/
|
|
45
|
+
capture():MapViewpoint;
|
|
46
|
+
/** Moves to a saved viewpoint, replacing any running tour or follow.*/
|
|
47
|
+
restore(viewpoint:MapViewpoint,transition?:MapCameraTransition):void;
|
|
48
|
+
/** Drives the camera from `clock`'s delivered instants until stopped or interrupted.*/
|
|
49
|
+
tour(clock:SimulationClock,tour:MapCameraTour):void;
|
|
50
|
+
/** Keeps the camera on a scene object as the application updates its position.*/
|
|
51
|
+
follow(options:MapCameraFollowOptions):void;
|
|
52
|
+
/** Ends the current action; the camera stays where it is.*/
|
|
53
|
+
stop():void;
|
|
54
|
+
/** Calls `listener` now and on every snapshot change; returns its release function.*/
|
|
55
|
+
subscribe(listener:(snapshot:MapCameraSessionSnapshot)=>void,options?:MapCameraSessionOptions):()=>void;
|
|
56
|
+
/** Releases the camera permanently. Idempotent.*/
|
|
57
|
+
dispose():void;}
|
|
58
|
+
/** Internal saved-view and shared-clock owner. Native attachment and clock instances remain opaque.*/
|
|
59
|
+
export declare function createMapCameraSessionController(host:HTMLElement,options?:MapCameraSessionOptions):{readonly snapshot:MapCameraSessionSnapshot;capture():MapViewpoint;restore:(input:unknown,transition?:{readonly kind?:'jump'|'ease'|'fly';readonly duration?:number;})=>void;follow:(input:unknown)=>void;tour(clock:SimulationClock,input:unknown):void;stop():void;subscribe(listener:(state:MapCameraSessionSnapshot)=>void,options?:{readonly signal?:AbortSignal;}):()=>void;dispose():void;};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{simulationClockLifetime}from"../simulation-clock.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"./data-descriptors.js";import{admitMapCameraTour,admitMapViewpoint,sampleMapCameraTour}from"./map-camera-session-data.js";import{mapCameraSessionAttachment}from"./map-camera-session.js";import{admitMapCameraFollowOptions}from"./map-camera-follow-data.js";import{prepareMapCameraFollow,startMapCameraFollow}from"./map-camera-follow-controller.js";import{createMapCameraFollowScene}from"./map-camera-follow-scene.js";import{mapSceneSessionAttachment}from"./map-scene-session.js";class MapCameraSessionError extends Error{constructor(code){super(code),this.code=code,this.name="MapCameraSessionError"}}const fail=code=>{throw new MapCameraSessionError(code)};function report(error){try{typeof globalThis.reportError=="function"&&globalThis.reportError(error)}catch{}}function data(input,allowed){if(!isPlainDataRecord(input))return fail("invalid-options");let keys;try{keys=Reflect.ownKeys(input)}catch{return fail("invalid-options")}const result={};for(const key of keys){if(typeof key!="string"||!allowed.includes(key))return fail("invalid-options");const descriptor=getOwnDataDescriptor(input,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return fail("invalid-options");result[key]=descriptor.value}return result}function signalOption(input){const signal=data(input===void 0?{}:input,["signal"]).signal;try{if(signal!==void 0&&(!signal||typeof signal.aborted!="boolean"||typeof signal.addEventListener!="function"||typeof signal.removeEventListener!="function"))return fail("invalid-options")}catch{return fail("invalid-options")}return signal}function transitionOption(input){const record=data(input===void 0?{}:input,["kind","duration"]),kind=record.kind===void 0?"jump":record.kind,duration=record.duration;return kind!=="jump"&&kind!=="ease"&&kind!=="fly"||duration!==void 0&&(typeof duration!="number"||!Number.isFinite(duration)||duration<0)?fail("invalid-options"):Object.freeze({kind,...duration===void 0?{}:{duration}})}function sameView(first,second){return first!==void 0&&first.zoom===second.zoom&&first.bearing===second.bearing&&first.pitch===second.pitch&&first.center[0]===second.center[0]&&first.center[1]===second.center[1]}function createMapCameraSessionController(host,options){const signal=signalOption(options);let disposed=!1,generation=0,lease,action,startingFollow,scene,snapshot=Object.freeze({mode:"idle",active:!1,reason:"initial"});const subscriptions=new Set,active=()=>{disposed&&fail("disposed")},current=candidate=>!disposed&&action===candidate&&lease?.current()===!0,publish=next=>{if(snapshot.mode===next.mode&&snapshot.active===next.active&&snapshot.reason===next.reason&&(snapshot.mode!=="follow"||next.mode==="follow"&&snapshot.objectId===next.objectId&&snapshot.followMode===next.followMode&&snapshot.trackingStatus===next.trackingStatus&&snapshot.corrections===next.corrections&&snapshot.unavailableReason===next.unavailableReason))return;snapshot=Object.freeze(next);const delivered=snapshot;for(const subscription of[...subscriptions]){if(snapshot!==delivered)break;if(subscription.active)try{subscription.listener(delivered)}catch(error){report(error)}}},actionSnapshot=(candidate,reason,active2)=>{if(candidate.mode!=="follow")return{mode:candidate.mode,active:active2,reason};const tracking=candidate.follow.snapshot;return{mode:"follow",active:active2&&(tracking.status==="ground"||tracking.status==="centering"||tracking.status==="centered"),reason,objectId:candidate.follow.options.objectId,followMode:candidate.follow.options.mode,trackingStatus:tracking.status,corrections:tracking.corrections,...tracking.reason===void 0?{}:{unavailableReason:tracking.reason}}},cleanup=(candidate,stopAnimation)=>{for(const release of[...candidate.cleanups]){candidate.cleanups.delete(release);try{release()}catch(error){report(error)}}try{lease?.retire(candidate.token,stopAnimation&&candidate.animating)}catch(error){report(error)}candidate.animating=!1},prepare=(token,target,transition)=>{if(!lease?.current())return fail("unavailable");try{return lease.prepare(token,target,transition)}catch{return fail("unavailable")}},replace=next=>{const intent=++generation,previous=action;if(action=void 0,previous&&cleanup(previous,!0),disposed||generation!==intent)return!1;let started=!1;const pending=next.mode==="follow"?{action:next,generation:intent}:void 0;pending&&(startingFollow=pending);try{started=lease?.current()===!0&&lease.start(next.token)}catch{}finally{pending&&startingFollow===pending&&(startingFollow=void 0)}return disposed||generation!==intent?(started&&lease?.retire(next.token,!1),!1):started?(action=next,publish(actionSnapshot(next,"start",!0)),current(next)):(next.mode==="follow"&&(next.follow.snapshot={status:"unavailable",reason:"engine",corrections:0}),publish(actionSnapshot(next,"engine",!1)),fail("unavailable"))},unavailable=candidate=>{if(action!==candidate||disposed)return;candidate.mode==="follow"&&(candidate.follow.snapshot={status:"unavailable",reason:"engine",corrections:candidate.follow.snapshot.corrections});const intent=++generation;action=void 0,cleanup(candidate,!0),!disposed&&generation===intent&&publish(actionSnapshot(candidate,"engine",!1))},commit=(candidate,command)=>{if(!current(candidate))return!1;let accepted=!1;try{accepted=lease.commit(command)}catch{}return accepted?(current(candidate)&&(candidate.applied=command.view),!0):(unavailable(candidate),!1)},retire=(reason,stopAnimation)=>{const intent=++generation,previous=action;action=void 0,previous&&cleanup(previous,stopAnimation),!disposed&&generation===intent&&publish({mode:"idle",active:!1,reason})},dispose=(reason="disposed")=>{if(disposed)return;disposed=!0,generation++;const previous=action;action=void 0,previous&&cleanup(previous,!0),signal?.removeEventListener("abort",abort),lease?.release(),publish({mode:"idle",active:!1,reason});for(const subscription of[...subscriptions])subscription.release()},abort=()=>{dispose()},sample=(candidate,delivered,resample=!1)=>{if(!(!current(candidate)||!candidate.tour)&&!(!resample&&candidate.delivered&&delivered.revision<=candidate.delivered.revision)){candidate.delivered=delivered;try{const target=sampleMapCameraTour(candidate.tour,delivered.instant,{reducedMotion:lease.reducedMotion()});if(!current(candidate))return;const command=prepare(candidate.token,target,{kind:"jump"});if(!current(candidate)||sameView(candidate.applied,command.view))return;commit(candidate,command)}catch{unavailable(candidate)}}},restore=(input,transition)=>{active();const intent=generation;let target;try{target=admitMapViewpoint(input)}catch{return fail("invalid-viewpoint")}const accepted=transitionOption(transition),token=Object.freeze({}),command=prepare(token,target,accepted);if(disposed||generation!==intent)return;const next={token,mode:"viewpoint",view:command.view,cleanups:new Set,animating:command.kind!=="jump"};replace(next)&&!commit(next,command)&&!disposed&&action===void 0&&snapshot.reason==="engine"&&fail("unavailable")},follow=input=>{active();const intent=generation;let accepted;try{accepted=admitMapCameraFollowOptions(input)}catch{return fail("invalid-follow")}if(accepted.mode!=="ground")return fail("unavailable");if(!scene){const attachment=mapSceneSessionAttachment(host);if(!attachment)return fail("unavailable");scene=createMapCameraFollowScene(attachment)}const preflightCurrent=()=>lease?.current()===!0&&!disposed&&generation===intent;let unsupported;try{unsupported=scene.target(accepted.objectId).kind==="unsupported"}catch{return fail("unavailable")}if(!preflightCurrent())return;if(unsupported)return fail("invalid-follow");const capture={};let plan;try{plan=prepareMapCameraFollow(accepted,{current:preflightCurrent,scene,capture(){return capture.view=admitMapViewpoint(lease.capture()),capture.view},reducedMotion:()=>lease.reducedMotion()})}catch{return fail("unavailable")}const captured=capture.view;if(!captured||!preflightCurrent())return;const token=Object.freeze({});if(prepare(token,{center:captured.center,zoom:accepted.zoom??captured.zoom,bearing:accepted.bearing??captured.bearing,pitch:accepted.pitch??captured.pitch},{kind:"jump"}),!preflightCurrent())return;const next={token,mode:"follow",cleanups:new Set,animating:!1,follow:{options:{...accepted,mode:"ground"},restricted:!1,snapshot:{status:"pending",corrections:0}}};if(!replace(next))return;const commands=new WeakMap;try{const runner=startMapCameraFollow(plan,{current:()=>current(next),ready(value){if(!current(next)){value.dispose();return}next.follow.runner=value,next.cleanups.add(()=>value.dispose()),next.follow.restricted&&value.refreshMotion(!0)},prepareGround(target){const command=prepare(next.token,target,{kind:"jump"});return commands.set(command,command),command},commitGround(receipt){const command=commands.get(receipt);return commands.delete(receipt),!!command&¤t(next)&&lease.commit(command)},preparePan(){return fail("unavailable")},commitPan(){return!1},publish(tracking){current(next)&&(next.follow.snapshot=tracking,tracking.status==="unavailable"&&tracking.reason==="engine"?unavailable(next):publish(actionSnapshot(next,"start",!0)))}});current(next)||runner.dispose(),!disposed&&action===void 0&&snapshot.reason==="engine"&&fail("unavailable")}catch{return unavailable(next),fail("unavailable")}};if(signal?.aborted)disposed=!0,snapshot=Object.freeze({mode:"idle",active:!1,reason:"disposed"});else{const attachment=mapCameraSessionAttachment(host);if(!attachment)return fail(host.isConnected?"unsupported-map":"inactive-map");let acquired;try{acquired=attachment.acquire({complete(token){const completed=action;!completed||completed.token!==token||!current(completed)||completed.mode!=="viewpoint"||(completed.animating=!1,publish({mode:"viewpoint",active:!1,reason:"complete"}))},interrupt(reason){if(disposed)return!1;if(reason==="disconnect")return dispose("disconnect"),!1;const retired=action!==void 0;return retire(reason,!1),retired},motion(reduced){const pending=startingFollow;if(pending&&pending.generation===generation&&!disposed&&pending.action.mode==="follow"){pending.action.follow.restricted||=reduced;return}const previous=action;if(!(!previous||!current(previous))){if(previous.mode==="follow")previous.follow.restricted||=reduced,previous.follow.runner?.refreshMotion(reduced);else if(previous.mode==="tour")previous.delivered&&sample(previous,previous.delivered,!0);else if(reduced&&previous.animating&&previous.view)try{restore(previous.view,{kind:"jump"})}catch{current(previous)&&unavailable(previous)}}}})}catch(error){const code=error?.code;return fail(code==="already-bound"?"already-bound":host.isConnected?"unavailable":"inactive-map")}if(lease=acquired,disposed)lease.release();else{try{signal?.addEventListener("abort",abort,{once:!0})}catch{return lease.release(),fail("invalid-options")}signal?.aborted&&dispose()}}return{get snapshot(){return snapshot},capture(){if(active(),!lease?.current())return fail("unavailable");try{return admitMapViewpoint(lease.capture())}catch{return fail("unavailable")}},restore,follow,tour(clock,input){active();const intent=generation;let admitted;try{admitted=admitMapCameraTour(input)}catch{return fail("invalid-tour")}const lifetime=simulationClockLifetime(clock);if(!lifetime||lifetime.disposed())return fail("invalid-clock");const token=Object.freeze({});if(prepare(token,sampleMapCameraTour(admitted,clock.snapshot.instant),{kind:"jump"}),lifetime.disposed())return fail("invalid-clock");if(disposed||generation!==intent)return;const next={token,mode:"tour",tour:admitted,cleanups:new Set,animating:!1};if(!replace(next))return;const addCleanup=release=>{current(next)?next.cleanups.add(release):release()};try{if(addCleanup(lifetime.onDispose(()=>{current(next)&&retire("engine",!1)})),!current(next))return;const release=clock.subscribe(delivered=>{sample(next,delivered)});addCleanup(release),!disposed&&action===void 0&&snapshot.reason==="engine"&&fail("unavailable")}catch{return unavailable(next),fail("unavailable")}},stop(){active(),retire("stop",!0)},subscribe(listener,options2){if(active(),typeof listener!="function")return fail("invalid-options");const signal2=signalOption(options2);if(signal2?.aborted)return()=>{};const subscription={active:!0,listener,release(){subscription.active&&(subscription.active=!1,subscriptions.delete(subscription),signal2?.removeEventListener("abort",subscription.release))}};try{signal2?.addEventListener("abort",subscription.release,{once:!0})}catch{return fail("invalid-options")}if(disposed||signal2?.aborted)return subscription.release(),subscription.release;subscriptions.add(subscription);try{listener(snapshot)}catch(error){report(error)}return subscription.release},dispose(){dispose()}}}export{MapCameraSessionError,createMapCameraSessionController};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** A complete saved camera. Admission rejects non-finite values and unknown or accessor fields.*/
|
|
2
|
+
export interface MapViewpoint{
|
|
3
|
+
/** `[longitude, latitude]`, within `[-180, 180]` and `[-90, 90]`.*/
|
|
4
|
+
readonly center:readonly[number,number];
|
|
5
|
+
/** Zoom level; the map's zoom limits clamp it when applied.*/
|
|
6
|
+
readonly zoom:number;
|
|
7
|
+
/** Degrees clockwise from north, normalized into `[-180, 180)`.*/
|
|
8
|
+
readonly bearing:number;
|
|
9
|
+
/** Degrees in `[0, 85]`.*/
|
|
10
|
+
readonly pitch:number;}interface MapCameraKeyframe{readonly instant:number;readonly view:MapViewpoint;readonly interpolation:'linear'|'hold';}declare const admittedTour:unique symbol;export interface AdmittedMapCameraTour{readonly keyframes:readonly MapCameraKeyframe[];readonly[admittedTour]:true;}
|
|
11
|
+
/** Strict, detached camera data; applying native camera limits is a separate operation.*/
|
|
12
|
+
export declare function admitMapViewpoint(input:unknown):MapViewpoint;
|
|
13
|
+
/** Admit once; the runtime brand keeps sampling independent of caller records and accessors.*/
|
|
14
|
+
export declare function admitMapCameraTour(input:unknown):AdmittedMapCameraTour;
|
|
15
|
+
/** Binary location over admitted immutable frames; results are detached frozen viewpoints.*/
|
|
16
|
+
export declare function sampleMapCameraTour(tour:AdmittedMapCameraTour,time:number,options?:{readonly reducedMotion?:boolean;}):MapViewpoint;export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"./data-descriptors.js";import{finiteInterpolate}from"./numbers.js";const tours=new WeakSet,MAX_INSTANT=864e13,MAX_KEYFRAMES=1024;function record(input,allowed){if(!isPlainDataRecord(input))throw new TypeError("Invalid camera data record");for(const key of Reflect.ownKeys(input)){if(typeof key!="string"||!allowed.includes(key))throw new TypeError("Unknown camera data field");own(input,key)}return input}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid camera data descriptor");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function finite(input){if(typeof input!="number"||!Number.isFinite(input))throw new TypeError("Expected finite camera value");return input}function range(input,minimum,maximum){const value=finite(input);if(value<minimum||value>maximum)throw new RangeError("Camera value outside supported range");return value}function instant(input){return range(input,-MAX_INSTANT,MAX_INSTANT)}function wrap(value){const remainder=value%360,normalized=remainder>=180?remainder-360:remainder<-180?remainder+360:remainder;return normalized===0?0:normalized}function array(input,minimum,maximum){if(!Array.isArray(input))throw new TypeError("Expected camera data array");const length=range(own(input,"length"),minimum,maximum);if(!Number.isInteger(length))throw new TypeError("Invalid camera data array length");const keys=Reflect.ownKeys(input);if(keys.length!==length+1||keys.some(key=>typeof key!="string"||key!=="length"&&(!/^(0|[1-9]\d*)$/.test(key)||Number(key)>=length)))throw new TypeError("Invalid camera data array fields");return{value:input,length}}function copyView(input){return Object.freeze({center:Object.freeze([input.center[0],input.center[1]]),zoom:input.zoom,bearing:input.bearing,pitch:input.pitch})}function admitMapViewpoint(input){const source=record(input,["center","zoom","bearing","pitch"]),center=array(own(source,"center"),2,2).value;return Object.freeze({center:Object.freeze([range(own(center,"0"),-180,180),range(own(center,"1"),-90,90)]),zoom:finite(own(source,"zoom")),bearing:wrap(finite(own(source,"bearing"))),pitch:range(own(source,"pitch"),0,85)})}function admitMapCameraTour(input){const source=record(input,["keyframes"]),frames=array(own(source,"keyframes"),1,MAX_KEYFRAMES),keyframes=[];let previous=-1/0;for(let index=0;index<frames.length;index++){const frame=record(own(frames.value,String(index)),["instant","view","interpolation"]),time=instant(own(frame,"instant"));if(time<=previous)throw new RangeError("Camera keyframes must be strictly increasing");previous=time;const requested=own(frame,"interpolation"),interpolation=requested===void 0?"linear":requested;if(interpolation!=="linear"&&interpolation!=="hold")throw new TypeError("Invalid camera interpolation");keyframes.push(Object.freeze({instant:time,view:admitMapViewpoint(own(frame,"view")),interpolation}))}const result=Object.freeze({keyframes:Object.freeze(keyframes)});return tours.add(result),result}function interpolateAngle(first,last,ratio){let difference=wrap(last-first);return difference===-180&&(difference=180),wrap(first+difference*ratio)}function sampleMapCameraTour(tour,time,options){if(!tours.has(tour))throw new TypeError("Expected admitted camera tour");const sample=instant(time),configuration=options===void 0?void 0:record(options,["reducedMotion"]),motion=configuration===void 0?void 0:own(configuration,"reducedMotion");if(motion!==void 0&&typeof motion!="boolean")throw new TypeError("Invalid camera sampling options");const frames=tour.keyframes;let low=0,high=frames.length;for(;low<high;){const middle=low+Math.floor((high-low)/2);frames[middle].instant<=sample?low=middle+1:high=middle}const index=Math.max(0,low-1),first=frames[index],last=frames[index+1];if(sample<=first.instant||!last||first.interpolation==="hold"||motion===!0)return copyView(first.view);const ratio=(sample-first.instant)/(last.instant-first.instant);return Object.freeze({center:Object.freeze([interpolateAngle(first.view.center[0],last.view.center[0],ratio),finiteInterpolate(first.view.center[1],last.view.center[1],ratio)]),zoom:finiteInterpolate(first.view.zoom,last.view.zoom,ratio),bearing:interpolateAngle(first.view.bearing,last.view.bearing,ratio),pitch:finiteInterpolate(first.view.pitch,last.view.pitch,ratio)})}export{admitMapCameraTour,admitMapViewpoint,sampleMapCameraTour};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const attachments=new WeakMap;function registerMapCameraSession(host,attachment){return attachments.set(host,attachment),()=>{attachments.get(host)===attachment&&attachments.delete(host)}}function mapCameraSessionAttachment(host){return attachments.get(host)}export{mapCameraSessionAttachment,registerMapCameraSession};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"./data-descriptors.js";const MAX_WATCHES=2e3,MAX_BACKEND_CALLS=6144,MAX_NOTIFICATION_PASSES=6144,MAX_CLEANUP_CALLS=2048,budgetExceeded=Object.freeze({}),absent=Object.freeze({status:"absent"}),emptyView={snapshot:Object.freeze({acceptedSceneRevision:0,registryRevision:0,targets:Object.freeze([]),viewport:void 0}),targets:new Map},attachments=new WeakMap;function invalid(){throw new TypeError("Invalid map scene capability")}function own(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?invalid():descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function data(value,keys,frozen=!0){if(!isPlainDataRecord(value)||frozen&&!Object.isFrozen(value))return invalid();for(const key of Reflect.ownKeys(value)){if(typeof key!="string"||!keys.includes(key))return invalid();own(value,key)}return value}function finite(value,minimum=-1/0,maximum=1/0){return typeof value!="number"||!Number.isFinite(value)||value<minimum||value>maximum?invalid():value}function counter(value,minimum=0){const result=finite(value,minimum);return Number.isSafeInteger(result)?result:invalid()}function identifier(value){return typeof value!="string"||value.length<1||value.length>1024||value.trim().length===0?invalid():value}function array(value,maximum,frozen=!0){if(!Array.isArray(value)||frozen&&!Object.isFrozen(value))return invalid();const length=readOwnArrayLength(value);if(length===void 0||length>maximum||Reflect.ownKeys(value).length!==length+1)return invalid();const result=[];for(let index=0;index<length;index++){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return invalid();result.push(descriptor.value)}return result}function padding(value,frozen=!0){const record=data(value,["top","bottom","left","right"],frozen);for(const side of["top","bottom","left","right"])finite(own(record,side),0);return value}function samePadding(a,b){return a.top===b.top&&a.bottom===b.bottom&&a.left===b.left&&a.right===b.right}function sameViewport(a,b){return a===b||a!==void 0&&b!==void 0&&a.width===b.width&&a.height===b.height&&a.pixelRatio===b.pixelRatio&&samePadding(a.padding,b.padding)}function viewport(value){if(value===void 0)return;const record=data(value,["allocationRevision","width","height","pixelRatio","padding"]);return counter(own(record,"allocationRevision")),finite(own(record,"width"),0),finite(own(record,"height"),0),finite(own(record,"pixelRatio"),0)===0?invalid():(padding(own(record,"padding")),value)}function eligible(value){return value!==void 0&&(value.kind==="marker"||value.kind==="model")}function sameTarget(a,b){return a===b?!0:!a||!b||a.kind!==b.kind?!1:!eligible(a)||!eligible(b)?!0:a.acceptedPositionRevision===b.acceptedPositionRevision&&a.position.lngLat[0]===b.position.lngLat[0]&&a.position.lngLat[1]===b.position.lngLat[1]&&a.position.altitude===b.position.altitude&&a.position.altitudeReference===b.position.altitudeReference}function targetEntry(value){const record=data(value,["id","kind","position","acceptedPositionRevision"]);identifier(own(record,"id"));const kind=own(record,"kind");if(kind==="path"||kind==="arc")return data(value,["id","kind"]),value;if(kind!=="marker"&&kind!=="model")return invalid();counter(own(record,"acceptedPositionRevision"),1);const position=data(own(record,"position"),["lngLat","altitude","altitudeReference"]),point=array(own(position,"lngLat"),2);if(point.length!==2||finite(point[0],-180,180)===180)return invalid();finite(point[1],-85.0511287798066,85.0511287798066),finite(own(position,"altitude"),-12e3,1e8);const reference=own(position,"altitudeReference");return reference!=="sea-level"&&reference!=="terrain"?invalid():value}function captureView(value){const record=data(value,["acceptedSceneRevision","registryRevision","targets","viewport"]);counter(own(record,"acceptedSceneRevision")),counter(own(record,"registryRevision")),viewport(own(record,"viewport"));const targets=new Map;for(const raw of array(own(record,"targets"),MAX_WATCHES)){const entry=targetEntry(raw);if(targets.has(entry.id))return invalid();targets.set(entry.id,entry)}return targets.size>0&&(own(record,"acceptedSceneRevision")===0||own(record,"registryRevision")===0)?invalid():{snapshot:value,targets}}function changedIds(first,second){const result=[];for(const[id,value]of second.targets)sameTarget(first.targets.get(id),value)||result.push(id);for(const id of first.targets.keys())second.targets.has(id)||result.push(id);return result}function validateFrame(frame){const record=data(frame,["stamp","width","height","pixelRatio","padding","projectionTransition","cameraProfile"]);if(finite(own(record,"width"),0),finite(own(record,"height"),0),finite(own(record,"pixelRatio"),0)===0)return invalid();const framePadding=padding(own(record,"padding")),transition=finite(own(record,"projectionTransition"),0,1);if(Math.fround(transition)!==transition)return invalid();const stampKeys=["ownerToken","contextEpoch","styleRevision","samplingViewRevision","layoutRevision","allocationRevision","acceptedSceneRevision","installedSceneRevision","placementRevision","paintRevision","paintFrameSerial"],stamp=data(own(record,"stamp"),stampKeys),owner=own(stamp,"ownerToken");if(owner===null||typeof owner!="object")return invalid();for(const key of stampKeys)key!=="ownerToken"&&counter(own(stamp,key));const rawProfile=own(record,"cameraProfile");if(rawProfile===void 0)return;const flags=["explicitBounds","explicitZoomLimits","nativeBounds","terrain","canPan","canObserveMotion","canStop","moving","hasProjection"],profile=data(rawProfile,["latitude","zoom","pitch","width","height","padding","nativeControlTransition","nativeMinZoom","nativeMaxZoom",...flags]);for(const flag of flags)if(typeof own(profile,flag)!="boolean")return invalid();finite(own(profile,"latitude"),-90,90);for(const key of["zoom","pitch","nativeMinZoom","nativeMaxZoom"])finite(own(profile,key));if(finite(own(profile,"nativeControlTransition"),0,1),own(profile,"width")!==own(record,"width")||own(profile,"height")!==own(record,"height")||!samePadding(padding(own(profile,"padding")),framePadding))return invalid()}function matchesState(frame,view){const allocation=view.snapshot.viewport;return allocation!==void 0&&frame.stamp.acceptedSceneRevision===view.snapshot.acceptedSceneRevision&&frame.stamp.installedSceneRevision===view.snapshot.acceptedSceneRevision&&frame.stamp.allocationRevision===allocation.allocationRevision&&frame.width===allocation.width&&frame.height===allocation.height&&frame.pixelRatio===allocation.pixelRatio&&samePadding(frame.padding,allocation.padding)}function copyProjection(value,revision){const record=data(value,["acceptedPositionRevision","status","point","visible"],!1);if(own(record,"acceptedPositionRevision")!==revision||typeof own(record,"visible")!="boolean")return invalid();const status=own(record,"status");if(status!=="resolved"&&status!=="terrain-pending"&&status!=="terrain-unavailable"&&status!=="model-pending"&&status!=="visibility-pending"&&status!=="clipped"&&status!=="occluded"&&status!=="unavailable")return invalid();const rawPoint=own(record,"point");let point;if(rawPoint!==void 0){const values=array(rawPoint,2,!1);if(values.length!==2)return invalid();point=Object.freeze([finite(values[0]),finite(values[1])])}const visible=own(record,"visible");return visible&&(status!=="resolved"||point===void 0)?invalid():Object.freeze({acceptedPositionRevision:revision,status,visible,...point?{point}:{}})}function registerMapSceneSession(host,attachment){return attachments.set(host,attachment),()=>{attachments.get(host)===attachment&&attachments.delete(host)}}function mapSceneSessionAttachment(host){return attachments.get(host)}function createMapSceneSessionFacade(options){const{connection}=options;if(connection===null||typeof connection!="object")return invalid();let closed=!1,running=!1,querying=!1,containing=!1,unavailable=!1,backendCalls=0,cleanupCalls=0,notificationPasses=0,generation=0,highestSerial=-1,greatestPositionRevision=0,state,wantedState,installingState,frameBinding,wantedFrame,view=emptyView,knownViewport,statePending=!1,watchesPending=!1,requestPending=!1,notificationsBlocked=!1,pendingFrame;const demands=new Map,targetObservers=new Set,viewportObservers=new Set,frameObservers=new Set,receipts=new WeakMap;function backendCall(callback){if(containing||backendCalls>=MAX_BACKEND_CALLS)throw budgetExceeded;return backendCalls++,callback()}function retire(release){if(backendCalls<MAX_BACKEND_CALLS&&!containing)backendCalls++;else if(containing=!0,cleanupCalls++,cleanupCalls>MAX_CLEANUP_CALLS)return invalid();try{release()}catch{}}function live(binding){return!closed&&frameBinding===binding&&binding.generation===generation&&!containing}function detachFrame(){const old=frameBinding;if(frameBinding=void 0,pendingFrame=void 0,!old)return;const releases=[...old.watches.values()];old.watches.clear(),old.release&&(releases.push(old.release),old.release=void 0);for(const release of releases)retire(release)}function containFrame(){containing=!0,generation++,wantedFrame=void 0,pendingFrame=void 0,detachFrame()}function failFrame(binding,error){error===budgetExceeded||containing||live(binding)?containFrame():frameBinding===binding&&detachFrame()}function readState(throwOnFailure=!1){if(closed||!state)return emptyView;try{const captured=state.capture.call(state.state);if(captured===view.snapshot)return unavailable=!1,view;const next=captureView(captured);if(next.snapshot.acceptedSceneRevision<view.snapshot.acceptedSceneRevision||next.snapshot.registryRevision<view.snapshot.registryRevision||changedIds(view,next).length&&(next.snapshot.acceptedSceneRevision===view.snapshot.acceptedSceneRevision||next.snapshot.registryRevision===view.snapshot.registryRevision))return invalid();let greatest=greatestPositionRevision;for(const[id,entry]of next.targets){if(!eligible(entry))continue;const previous=view.targets.get(id);if(sameTarget(previous,entry)){if(previous!==entry)return invalid()}else if(entry.acceptedPositionRevision<=greatestPositionRevision)return invalid();greatest=Math.max(greatest,entry.acceptedPositionRevision)}const allocation=next.snapshot.viewport;return allocation&&knownViewport&&(allocation.allocationRevision<knownViewport.allocationRevision||allocation.allocationRevision===knownViewport.allocationRevision&&!sameViewport(allocation,knownViewport))?invalid():(greatestPositionRevision=greatest,allocation&&(knownViewport=allocation),view=next,unavailable=!1,next)}catch{return unavailable=!0,throwOnFailure?invalid():void 0}}function owned(frame,target){const binding=receipts.get(frame);if(!binding||!binding.ready||!live(binding))return;const current=readState();if(!(!current||current.targets.get(target.id)!==target||!matchesState(frame,current)))return binding}function checkCurrent(frame,target){const binding=owned(frame,target);return binding?backendCall(()=>binding.current.call(binding.backing,frame,target))===!0&&owned(frame,target)===binding:!1}function query(fallback,callback){if(querying||containing)return fallback;running||(backendCalls=0,cleanupCalls=0,notificationPasses=0),querying=!0;try{return callback()}catch(error){return error===budgetExceeded&&run(containFrame),fallback}finally{querying=!1,running||(containing=!1)}}function queueFrame(binding,frame){if(live(binding))try{validateFrame(frame);const current=readState();if(!current||!matchesState(frame,current)||frame.stamp.paintFrameSerial<=highestSerial)return;const previousOwner=receipts.get(frame);if(previousOwner&&previousOwner!==binding)return;pendingFrame&&(!live(pendingFrame.binding)||!matchesState(pendingFrame.frame,current))&&(pendingFrame=void 0),(!pendingFrame||frame.stamp.paintFrameSerial>pendingFrame.frame.stamp.paintFrameSerial)&&(pendingFrame={binding,frame}),run()}catch{}}function bindPendingState(){const next=wantedState;if(wantedState=void 0,!next||closed)return;if(state){state.state===next.state&&(statePending=!0);return}let acquired;installingState=next;try{if(acquired=backendCall(()=>next.subscribe.call(next.state,()=>{closed||state!==next&&installingState!==next||(containing||(notificationsBlocked=!1),statePending=!0,run())})),typeof acquired!="function")return invalid();if(closed||state||wantedState){retire(acquired);return}const initial=captureView(next.capture.call(next.state));state=next,next.release=acquired,view=initial,greatestPositionRevision=Math.max(0,...[...initial.targets.values()].filter(eligible).map(entry=>entry.acceptedPositionRevision)),knownViewport=initial.snapshot.viewport,unavailable=!1,statePending=!0}catch{typeof acquired=="function"&&retire(acquired),state===next&&(state=void 0)}finally{installingState===next&&(installingState=void 0)}}function installFrame(){const next=wantedFrame;if(wantedFrame=void 0,!next||closed||(detachFrame(),closed||containing||wantedFrame||next.generation!==generation))return;frameBinding=next;let acquired;try{if(acquired=backendCall(()=>next.subscribe.call(next.backing,frame=>queueFrame(next,frame))),typeof acquired!="function")return invalid();if(!live(next)){retire(acquired);return}next.release=acquired,watchesPending=!0}catch(error){typeof acquired=="function"&&next.release!==acquired&&retire(acquired),failFrame(next,error)}}function reconcileWatches(){const binding=frameBinding;if(!(!binding||!live(binding)))try{for(;live(binding);){const removed=[...binding.watches.keys()].find(id=>!demands.has(id));if(removed!==void 0){const release2=binding.watches.get(removed);binding.watches.delete(removed),retire(release2);continue}const missing=[...demands.keys()].find(id=>!binding.watches.has(id));if(missing===void 0){binding.ready=!0,watchesPending=!1;return}const release=backendCall(()=>binding.watch.call(binding.backing,missing));if(typeof release!="function")return invalid();!live(binding)||!demands.has(missing)?retire(release):binding.watches.set(missing,release)}}catch(error){failFrame(binding,error)}}function deliverState(){statePending=!1;const next=readState();if(!next||closed)return;const stillCurrent=()=>{if(closed)return!1;const actual=readState();return actual!==next?(actual&&(statePending=!0),!1):!0};for(const observer of[...targetObservers]){if(!stillCurrent())return;if(!targetObservers.has(observer))continue;const changed=changedIds(observer.baseline,next);if(observer.baseline=next,!changed.length)continue;const notice=Object.freeze({acceptedSceneRevision:next.snapshot.acceptedSceneRevision,registryRevision:next.snapshot.registryRevision,changedIds:Object.freeze(changed)});try{observer.listener(notice)}catch{}}for(const observer of[...viewportObservers]){if(!stillCurrent())return;if(!viewportObservers.has(observer))continue;const allocation=next.snapshot.viewport;if(!allocation)continue;const changed=!sameViewport(observer.baseline,allocation);if(observer.baseline=allocation,changed)try{observer.listener(allocation)}catch{}}}function deliverFrame(){const candidate=pendingFrame;if(pendingFrame=void 0,!candidate||!live(candidate.binding)||!candidate.binding.ready)return;const current=readState();if(!(!current||!matchesState(candidate.frame,current)||candidate.frame.stamp.paintFrameSerial<=highestSerial)){highestSerial=candidate.frame.stamp.paintFrameSerial,receipts.set(candidate.frame,candidate.binding);for(const observer of[...frameObservers]){const latest=readState();if(!live(candidate.binding)||!latest||!matchesState(candidate.frame,latest))return;if(frameObservers.has(observer))try{observer.listener(candidate.frame)}catch{}}}}function run(action){if(running){action?.();return}running=!0,querying||(containing=!1,backendCalls=0,cleanupCalls=0,notificationPasses=0);try{for(action?.();!closed;){if(containing&&(frameBinding||wantedFrame)&&containFrame(),wantedState){bindPendingState();continue}if(wantedFrame&&!containing){installFrame();continue}if(watchesPending&&frameBinding&&live(frameBinding)){reconcileWatches();continue}if(!notificationsBlocked&&statePending||pendingFrame&&frameBinding?.ready){if(notificationPasses>=MAX_NOTIFICATION_PASSES){notificationsBlocked=!0,containFrame();break}notificationPasses++,statePending&&!notificationsBlocked?deliverState():deliverFrame();continue}if(requestPending&&frameBinding?.ready&&live(frameBinding)){const binding=frameBinding;requestPending=!1;try{backendCall(()=>binding.request.call(binding.backing))}catch(error){closed||(requestPending=!0),failFrame(binding,error)}continue}break}}finally{running=!1,querying||(containing=!1)}}function close(){closed||run(()=>{closed=!0,generation++,wantedState=void 0,wantedFrame=void 0,statePending=!1,requestPending=!1,pendingFrame=void 0,demands.clear(),targetObservers.clear(),viewportObservers.clear(),frameObservers.clear();const previous=state;if(state=void 0,view=emptyView,detachFrame(),previous?.release){const release=previous.release;previous.release=void 0,retire(release)}})}const attachment=Object.freeze({target(id){const entry=readState(!0)?.targets.get(id);return entry?eligible(entry)?Object.freeze({status:"accepted",target:entry}):Object.freeze({status:"unsupported-kind",kind:entry.kind}):absent},subscribeTargets(listener){if(typeof listener!="function")return invalid();if(closed)return()=>{};const observer={listener,baseline:readState()??view};return targetObservers.add(observer),()=>{targetObservers.delete(observer)}},subscribeViewport(listener){if(typeof listener!="function")return invalid();if(closed)return()=>{};const observer={listener,baseline:(readState()??view).snapshot.viewport};return viewportObservers.add(observer),()=>{viewportObservers.delete(observer)}},subscribeCompletedFrames(listener){if(typeof listener!="function")return invalid();if(closed)return()=>{};const observer={listener};return frameObservers.add(observer),()=>{frameObservers.delete(observer)}},watchTarget(value){if(closed)return()=>{};const id=identifier(value),count=demands.get(id)??0;if(!count&&demands.size>=MAX_WATCHES||!Number.isSafeInteger(count+1))return invalid();run(()=>{demands.set(id,count+1),watchesPending=!0});let released=!1;return()=>{released||(released=!0,!closed&&run(()=>{const remaining=(demands.get(id)??1)-1;remaining===0?demands.delete(id):demands.set(id,remaining),watchesPending=!0}))}},current(frame,target){return query(!1,()=>checkCurrent(frame,target))},projectTarget(frame,id){return query(void 0,()=>{const target=readState()?.targets.get(id);if(!eligible(target)||!checkCurrent(frame,target))return;const binding=owned(frame,target);if(!binding)return;const raw=backendCall(()=>binding.project.call(binding.backing,frame,id)),result=copyProjection(raw,target.acceptedPositionRevision);return checkCurrent(frame,target)&&owned(frame,target)===binding?result:void 0})},requestFrame(){closed||run(()=>{requestPending=!0})}});return Object.freeze({attachment,close,bindState(value){if(closed||state&&state.state!==value)return!1;try{if(own(value,"connection")!==connection)return!1;const capture=own(value,"capture"),subscribe=own(value,"subscribe");if(typeof capture!="function"||typeof subscribe!="function")return!1;const nested=running;return run(()=>{state?.state===value?(containing||(notificationsBlocked=!1),statePending=!0):wantedState={state:value,capture,subscribe}}),nested||!closed&&state?.state===value&&!unavailable}catch{return!1}},promote(backing){if(closed||containing||!state)return!1;try{if(own(backing,"connection")!==connection||own(backing,"state")!==state.state)return!1;const subscribe=own(backing,"subscribeCompletedFrames"),watch=own(backing,"watchTarget"),request=own(backing,"requestFrame"),project=own(backing,"projectTarget"),current=own(backing,"current");if([subscribe,watch,request,project,current].some(method=>typeof method!="function"))return!1;const next={backing,generation:++generation,ready:!1,watches:new Map,subscribe,watch,request,project,current},nested=running;return run(()=>{wantedFrame=next}),nested||!closed&&frameBinding===next&&next.ready}catch{return!1}}})}export{createMapSceneSessionFacade,mapSceneSessionAttachment,registerMapSceneSession};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{nothing,type TemplateResult}from'lit';import{type Engine3dFallbackDetail}from'./engine-3d.js';import type{LyraMessageKey}from'./localization.js';export type LyraMediaProjection='flat'|'equirectangular';export interface LyraPanoramaCamera{readonly yaw:number;readonly pitch:number;readonly fieldOfView:number;}export interface LyraPanoramaHotspot{readonly id:string;readonly yaw:number;readonly pitch:number;readonly label?:string;}export interface LyraPanoramaHotspotSelectDetail{readonly hotspot:LyraPanoramaHotspot;readonly id:string;readonly index:number;}export declare const PANORAMA_PROJECTION:import("./converters.js").LiteralSetConverter<LyraMediaProjection>;export declare const PANORAMA_DEFAULT_CAMERA:LyraPanoramaCamera;export declare const panoramaLoader:import("./engine-3d-loader.js").Engine3dLoader;export declare const panoramaEnvironment:{available:(owner:Document)=>boolean;};export declare function normalizePanoramaCamera(value:unknown):LyraPanoramaCamera;
|
|
2
|
+
/** First valid ID wins; invalid coordinates and blank IDs are omitted from the bounded snapshot.*/
|
|
3
|
+
export declare function snapshotPanoramaHotspots(value:unknown,owner:Window|null):readonly LyraPanoramaHotspot[];type Media=HTMLImageElement|HTMLVideoElement;interface PanoramaOptions{readonly changed:()=>void;readonly updated:()=>Promise<unknown>;readonly localize:(key:LyraMessageKey)=>string;readonly direction:()=>'ltr'|'rtl';readonly camera:(camera:LyraPanoramaCamera)=>void;readonly pick:(detail:LyraPanoramaHotspotSelectDetail)=>void;readonly fallback:(detail:Engine3dFallbackDetail)=>void;}
|
|
4
|
+
/** Optional spherical rendering around a caller-owned native image or video.*/
|
|
5
|
+
export declare class PanoramaController{private readonly host;private readonly options;private readonly selection;private readonly announcements;ready:boolean;loading:boolean;notice:Engine3dFallbackDetail|null;private software;private enabled;private media;private mediaRevision;private hotspots;private camera;private container;private engine?;private generation;private revision;private attempted;private pending;private intersection?;private eligibility?;private intersecting;private resize?;private theme?;private cleanups;private cursor;constructor(host:HTMLElement,options:PanoramaOptions);private release;invalidate():void;disconnect():void;adopted():void;update(enabled:boolean,media:Media|null,mediaRevision:number,hotspots:readonly LyraPanoramaHotspot[],camera:LyraPanoramaCamera,container:HTMLElement|null):void;private fail;private command;private start;private style;private activate;keydown(event:KeyboardEvent,direction:'ltr'|'rtl'):void;renderViewport(label:string,enabled:boolean):TemplateResult|typeof nothing;renderNotice():TemplateResult|typeof nothing;renderHotspots(enabled:boolean):TemplateResult|typeof nothing;}export{};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{html,nothing}from"lit";import{literalSetConverter}from"./converters.js";import{snapshotPublicCollection}from"./collection-snapshot.js";import{isObjectValue,readOwnDataValue}from"./data-descriptors.js";import{finiteRange}from"./numbers.js";import{createEngine3dLoader}from"./engine-3d-loader.js";import{Engine3dSelection,ENGINE_3D_REASON_MESSAGE,ENGINE_3D_SHOWING_MESSAGE,engine3dFailureReason,webgl2Available}from"./engine-3d.js";import{AnnouncementSinkController}from"./announcer.js";import{isAccessibilityVisible}from"./accessibility-visibility.js";import{resolveCanvasColor}from"./canvas-color.js";import{tag}from"./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 +1 @@
|
|
|
1
|
-
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="30.
|
|
1
|
+
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="30.7.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const controls=new WeakMap;function registerSequencePlayback(control,attachment){controls.set(control,attachment)}function sequencePlaybackAttachment(control){return controls.get(control)}export{registerSequencePlayback,sequencePlaybackAttachment};
|
|
@@ -6,7 +6,9 @@ import type{LyraMessage}from'./localization-types.js';
|
|
|
6
6
|
* assigning a new object, and validation runs once per assignment.
|
|
7
7
|
*/
|
|
8
8
|
/** Graph columns: row `i` of every node column describes node `i`; edges index into the nodes.*/
|
|
9
|
-
export interface LyraGraphColumns{readonly ids:readonly string[];readonly x?:Float32Array;readonly y?:Float32Array;readonly z?:Float32Array;readonly size?:Float32Array;readonly category?:Uint16Array;readonly categories?:readonly string[];readonly labels?:readonly string[];readonly source:Uint32Array;readonly target:Uint32Array;readonly edgeCategory?:Uint16Array;
|
|
9
|
+
export interface LyraGraphColumns{readonly ids:readonly string[];readonly x?:Float32Array;readonly y?:Float32Array;readonly z?:Float32Array;readonly size?:Float32Array;readonly category?:Uint16Array;readonly categories?:readonly string[];readonly labels?:readonly string[];readonly source:Uint32Array;readonly target:Uint32Array;readonly edgeCategory?:Uint16Array;
|
|
10
|
+
/** Finite signed 3D curvature per edge; render projections clamp to [-1, 1] without changing this borrowed array.*/
|
|
11
|
+
readonly edgeCurvature?:Float32Array;}
|
|
10
12
|
/** Point columns: row `i` of every column describes point `i`.*/
|
|
11
13
|
export interface LyraPointColumns{readonly ids:readonly string[];readonly x:Float32Array;readonly y:Float32Array;readonly z?:Float32Array;readonly cluster?:Uint16Array;readonly clusters?:readonly string[];readonly labels?:readonly string[];}export interface GraphColumnLimits{readonly nodes:number;readonly edges:number;}
|
|
12
14
|
/** Documented ceilings: 200,000 graph nodes, 1,000,000 graph edges and 1,000,000 points.*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LYRA_DEFAULT_largeDataInvalid,LYRA_DEFAULT_largeDataLimit}from"./default-strings/shared.generated.js";const GRAPH_COLUMN_LIMITS=Object.freeze({nodes:2e5,edges:1e6}),POINT_COLUMN_LIMIT=1e6,LARGE_DATA_PAGE_SIZE=200,typedArrayTag=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag)?.get;function typedArrayKind(value){if(!(typeof value!="object"||value===null||!typedArrayTag))return typedArrayTag.call(value)}class ColumnError extends Error{constructor(issue){super(issue.code),this.issue=issue}}function fail(issue){throw new ColumnError(Object.freeze(issue))}function snapshot(value,keys){(typeof value!="object"||value===null||Array.isArray(value))&&fail({code:"not-an-object",column:""});const copy={};for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(value,key);copy[key]=descriptor&&"value"in descriptor?descriptor.value:void 0}return copy}function typedColumn(columns,column,kind,required,length){const value=columns[column];return value===void 0?required?fail({code:"missing",column}):void 0:(typedArrayKind(value)!==kind&&fail({code:"wrong-type",column}),length!==void 0&&value.length!==length&&fail({code:"length-mismatch",column}),value)}const MAX_NAMES=65536;function stringColumn(columns,column,length){const value=columns[column];if(value!==void 0){if(!Array.isArray(value))return fail({code:"wrong-type",column});length!==void 0&&value.length!==length&&fail({code:"length-mismatch",column}),length===void 0&&value.length>MAX_NAMES&&fail({code:"too-many",column,limit:MAX_NAMES});for(let index=0;index<value.length;index+=1)typeof value[index]!="string"&&fail({code:"wrong-type",column,index});return value}}function finiteColumn(values,column,minimum=Number.NEGATIVE_INFINITY){if(values)for(let index=0;index<values.length;index+=1){const value=values[index];Number.isFinite(value)||fail({code:"not-finite",column,index}),value<minimum&&fail({code:"out-of-range",column,index})}}function indexColumn(values,column,size){if(!(!values||size===void 0))for(let index=0;index<values.length;index+=1)values[index]>=size&&fail({code:"out-of-range",column,index})}function idColumn(columns,limit,limitColumn){const value=columns.ids;if(value===void 0)return fail({code:"missing",column:"ids"});if(!Array.isArray(value))return fail({code:"wrong-type",column:"ids"});value.length>limit&&fail({code:"too-many",column:limitColumn,limit});const seen=new Set;for(let index=0;index<value.length;index+=1){const id=value[index];(typeof id!="string"||id.length===0)&&fail({code:"invalid-id",column:"ids",index}),seen.has(id)&&fail({code:"duplicate-id",column:"ids",index}),seen.add(id)}return value}function validate(build){try{const{columns,count}=build();return Object.freeze({ok:!0,columns,count})}catch(error){if(error instanceof ColumnError)return Object.freeze({ok:!1,issue:error.issue});throw error}}const GRAPH_KEYS=["ids","x","y","z","size","category","categories","labels","source","target","edgeCategory"],POINT_KEYS=["ids","x","y","z","cluster","clusters","labels"];function validateGraphColumns(value,limits=GRAPH_COLUMN_LIMITS){return validate(()=>{const columns=snapshot(value,GRAPH_KEYS),ids=idColumn(columns,limits.nodes,"ids"),nodes=ids.length,x=typedColumn(columns,"x","Float32Array",!1,nodes),y=typedColumn(columns,"y","Float32Array",!1,nodes),z=typedColumn(columns,"z","Float32Array",!1,nodes),size=typedColumn(columns,"size","Float32Array",!1,nodes),category=typedColumn(columns,"category","Uint16Array",!1,nodes),categories=stringColumn(columns,"categories"),labels=stringColumn(columns,"labels",nodes),source=typedColumn(columns,"source","Uint32Array",!0);source.length>limits.edges&&fail({code:"too-many",column:"source",limit:limits.edges});const target=typedColumn(columns,"target","Uint32Array",!0,source.length),edgeCategory=typedColumn(columns,"edgeCategory","Uint16Array",!1,source.length);for(const[name,values]of[["x",x],["y",y],["z",z]])finiteColumn(values,name);finiteColumn(size,"size",0),indexColumn(source,"source",nodes),indexColumn(target,"target",nodes),indexColumn(category,"category",categories?.length),indexColumn(edgeCategory,"edgeCategory",categories?.length);const admitted={ids,source,target};for(const[key,entry]of Object.entries({x,y,z,size,category,categories,labels,edgeCategory}))entry!==void 0&&(admitted[key]=entry);return{columns:Object.freeze(admitted),count:nodes}})}function validatePointColumns(value,limit=POINT_COLUMN_LIMIT){return validate(()=>{const columns=snapshot(value,POINT_KEYS),ids=idColumn(columns,limit,"ids"),points=ids.length,x=typedColumn(columns,"x","Float32Array",!0,points),y=typedColumn(columns,"y","Float32Array",!0,points),z=typedColumn(columns,"z","Float32Array",!1,points),cluster=typedColumn(columns,"cluster","Uint16Array",!1,points),clusters=stringColumn(columns,"clusters"),labels=stringColumn(columns,"labels",points);for(const[name,values]of[["x",x],["y",y],["z",z]])finiteColumn(values,name);indexColumn(cluster,"cluster",clusters?.length);const admitted={ids,x,y};for(const[key,entry]of Object.entries({z,cluster,clusters,labels}))entry!==void 0&&(admitted[key]=entry);return{columns:Object.freeze(admitted),count:points}})}function largeDataPage(total,page,pageSize=LARGE_DATA_PAGE_SIZE){const rows=Number.isFinite(total)?Math.max(0,Math.floor(total)):0,size=Number.isFinite(pageSize)?Math.max(1,Math.floor(pageSize)):LARGE_DATA_PAGE_SIZE,pageCount=Math.max(1,Math.ceil(rows/size)),current=Number.isFinite(page)?Math.min(pageCount-1,Math.max(0,Math.floor(page))):0;return Object.freeze({page:current,pageCount,start:current*size,end:Math.min(rows,(current+1)*size)})}const LARGE_DATA_DEFAULT_STRINGS=Object.freeze({largeDataInvalid:LYRA_DEFAULT_largeDataInvalid,largeDataLimit:LYRA_DEFAULT_largeDataLimit});function typedColumnIssueMessage(issue,property,formatNumber){return issue.code==="too-many"&&issue.limit!==void 0?{key:"largeDataLimit",values:{limit:formatNumber(issue.limit)}}:{key:"largeDataInvalid",values:{column:issue.column?`${property}.${issue.column}`:property}}}export{GRAPH_COLUMN_LIMITS,LARGE_DATA_DEFAULT_STRINGS,LARGE_DATA_PAGE_SIZE,POINT_COLUMN_LIMIT,largeDataPage,typedColumnIssueMessage,validateGraphColumns,validatePointColumns};
|
|
1
|
+
import{LYRA_DEFAULT_largeDataInvalid,LYRA_DEFAULT_largeDataLimit}from"./default-strings/shared.generated.js";const GRAPH_COLUMN_LIMITS=Object.freeze({nodes:2e5,edges:1e6}),POINT_COLUMN_LIMIT=1e6,LARGE_DATA_PAGE_SIZE=200,typedArrayTag=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag)?.get;function typedArrayKind(value){if(!(typeof value!="object"||value===null||!typedArrayTag))return typedArrayTag.call(value)}class ColumnError extends Error{constructor(issue){super(issue.code),this.issue=issue}}function fail(issue){throw new ColumnError(Object.freeze(issue))}function snapshot(value,keys){(typeof value!="object"||value===null||Array.isArray(value))&&fail({code:"not-an-object",column:""});const copy={};for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(value,key);copy[key]=descriptor&&"value"in descriptor?descriptor.value:void 0}return copy}function typedColumn(columns,column,kind,required,length){const value=columns[column];return value===void 0?required?fail({code:"missing",column}):void 0:(typedArrayKind(value)!==kind&&fail({code:"wrong-type",column}),length!==void 0&&value.length!==length&&fail({code:"length-mismatch",column}),value)}const MAX_NAMES=65536;function stringColumn(columns,column,length){const value=columns[column];if(value!==void 0){if(!Array.isArray(value))return fail({code:"wrong-type",column});length!==void 0&&value.length!==length&&fail({code:"length-mismatch",column}),length===void 0&&value.length>MAX_NAMES&&fail({code:"too-many",column,limit:MAX_NAMES});for(let index=0;index<value.length;index+=1)typeof value[index]!="string"&&fail({code:"wrong-type",column,index});return value}}function finiteColumn(values,column,minimum=Number.NEGATIVE_INFINITY){if(values)for(let index=0;index<values.length;index+=1){const value=values[index];Number.isFinite(value)||fail({code:"not-finite",column,index}),value<minimum&&fail({code:"out-of-range",column,index})}}function indexColumn(values,column,size){if(!(!values||size===void 0))for(let index=0;index<values.length;index+=1)values[index]>=size&&fail({code:"out-of-range",column,index})}function idColumn(columns,limit,limitColumn){const value=columns.ids;if(value===void 0)return fail({code:"missing",column:"ids"});if(!Array.isArray(value))return fail({code:"wrong-type",column:"ids"});value.length>limit&&fail({code:"too-many",column:limitColumn,limit});const seen=new Set;for(let index=0;index<value.length;index+=1){const id=value[index];(typeof id!="string"||id.length===0)&&fail({code:"invalid-id",column:"ids",index}),seen.has(id)&&fail({code:"duplicate-id",column:"ids",index}),seen.add(id)}return value}function validate(build){try{const{columns,count}=build();return Object.freeze({ok:!0,columns,count})}catch(error){if(error instanceof ColumnError)return Object.freeze({ok:!1,issue:error.issue});throw error}}const GRAPH_KEYS=["ids","x","y","z","size","category","categories","labels","source","target","edgeCategory","edgeCurvature"],POINT_KEYS=["ids","x","y","z","cluster","clusters","labels"];function validateGraphColumns(value,limits=GRAPH_COLUMN_LIMITS){return validate(()=>{const columns=snapshot(value,GRAPH_KEYS),ids=idColumn(columns,limits.nodes,"ids"),nodes=ids.length,x=typedColumn(columns,"x","Float32Array",!1,nodes),y=typedColumn(columns,"y","Float32Array",!1,nodes),z=typedColumn(columns,"z","Float32Array",!1,nodes),size=typedColumn(columns,"size","Float32Array",!1,nodes),category=typedColumn(columns,"category","Uint16Array",!1,nodes),categories=stringColumn(columns,"categories"),labels=stringColumn(columns,"labels",nodes),source=typedColumn(columns,"source","Uint32Array",!0);source.length>limits.edges&&fail({code:"too-many",column:"source",limit:limits.edges});const target=typedColumn(columns,"target","Uint32Array",!0,source.length),edgeCategory=typedColumn(columns,"edgeCategory","Uint16Array",!1,source.length),edgeCurvature=typedColumn(columns,"edgeCurvature","Float32Array",!1,source.length);finiteColumn(edgeCurvature,"edgeCurvature");for(const[name,values]of[["x",x],["y",y],["z",z]])finiteColumn(values,name);finiteColumn(size,"size",0),indexColumn(source,"source",nodes),indexColumn(target,"target",nodes),indexColumn(category,"category",categories?.length),indexColumn(edgeCategory,"edgeCategory",categories?.length);const admitted={ids,source,target};for(const[key,entry]of Object.entries({x,y,z,size,category,categories,labels,edgeCategory,edgeCurvature}))entry!==void 0&&(admitted[key]=entry);return{columns:Object.freeze(admitted),count:nodes}})}function validatePointColumns(value,limit=POINT_COLUMN_LIMIT){return validate(()=>{const columns=snapshot(value,POINT_KEYS),ids=idColumn(columns,limit,"ids"),points=ids.length,x=typedColumn(columns,"x","Float32Array",!0,points),y=typedColumn(columns,"y","Float32Array",!0,points),z=typedColumn(columns,"z","Float32Array",!1,points),cluster=typedColumn(columns,"cluster","Uint16Array",!1,points),clusters=stringColumn(columns,"clusters"),labels=stringColumn(columns,"labels",points);for(const[name,values]of[["x",x],["y",y],["z",z]])finiteColumn(values,name);indexColumn(cluster,"cluster",clusters?.length);const admitted={ids,x,y};for(const[key,entry]of Object.entries({z,cluster,clusters,labels}))entry!==void 0&&(admitted[key]=entry);return{columns:Object.freeze(admitted),count:points}})}function largeDataPage(total,page,pageSize=LARGE_DATA_PAGE_SIZE){const rows=Number.isFinite(total)?Math.max(0,Math.floor(total)):0,size=Number.isFinite(pageSize)?Math.max(1,Math.floor(pageSize)):LARGE_DATA_PAGE_SIZE,pageCount=Math.max(1,Math.ceil(rows/size)),current=Number.isFinite(page)?Math.min(pageCount-1,Math.max(0,Math.floor(page))):0;return Object.freeze({page:current,pageCount,start:current*size,end:Math.min(rows,(current+1)*size)})}const LARGE_DATA_DEFAULT_STRINGS=Object.freeze({largeDataInvalid:LYRA_DEFAULT_largeDataInvalid,largeDataLimit:LYRA_DEFAULT_largeDataLimit});function typedColumnIssueMessage(issue,property,formatNumber){return issue.code==="too-many"&&issue.limit!==void 0?{key:"largeDataLimit",values:{limit:formatNumber(issue.limit)}}:{key:"largeDataInvalid",values:{column:issue.column?`${property}.${issue.column}`:property}}}export{GRAPH_COLUMN_LIMITS,LARGE_DATA_DEFAULT_STRINGS,LARGE_DATA_PAGE_SIZE,POINT_COLUMN_LIMIT,largeDataPage,typedColumnIssueMessage,validateGraphColumns,validatePointColumns};
|
|
@@ -31,6 +31,13 @@ export type LyraAppearance='accent'|'filled'|'outlined'|'filled-outlined'|'plain
|
|
|
31
31
|
* Displaced from `appearance` in 8.0.0, where it collided with the fill vocabulary above.
|
|
32
32
|
*/
|
|
33
33
|
export type LyraFrame='card'|'plain';
|
|
34
|
+
/**
|
|
35
|
+
* Whether a labelled form control renders its `label` on screen. `hidden` keeps the label in the
|
|
36
|
+
* accessibility tree (it remains the accessible name) and removes it from the layout, for compact
|
|
37
|
+
* toolbars and table cells where the surrounding UI already shows what the field is. Hint and error
|
|
38
|
+
* text are unaffected. A closed literal union, never an `enum`.
|
|
39
|
+
*/
|
|
40
|
+
export type LyraLabelDisplay='visible'|'hidden';
|
|
34
41
|
/** The canonical six-step size ladder.*/
|
|
35
42
|
export type LyraSizeStep='2xs'|'xs'|'s'|'m'|'l'|'xl';
|
|
36
43
|
/**
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{tag}from"./prefix.js";import{createWidgetTypeRegistry}from"./widget-type-registry.js";const DEFAULT_WIDGET_TYPE_REGISTRY=createWidgetTypeRegistry([["card",{tag:tag("card"),interaction:"none",props:{appearance:"string"}}],["badge",{tag:tag("badge"),interaction:"none",props:{variant:"string"}}],["button",{tag:tag("button"),props:{variant:"string",appearance:"string",size:"string",disabled:"boolean",loading:"boolean"},interaction:"control",action:{event:"click"}}],["stat",{tag:tag("stat"),interaction:"none",props:{label:"string",value:"string",unit:"string",variant:"string",caption:"string",sub:"string"}}],["result-card",{tag:tag("result-card"),interaction:"none",props:{title:"string"}}],["result-field",{tag:tag("result-field"),interaction:"none",props:{label:"string",value:"string"}}],["markdown",{tag:tag("markdown"),interaction:"none",props:{content:"string"}}],["image",{tag:tag("media-card"),interaction:"none",props:{src:"string",alt:"string",filename:"string"},forcedProps:{kind:"image"}}]]);export{DEFAULT_WIDGET_TYPE_REGISTRY};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import{type LyraWidgetTypeRegistry}from'./widget-type-registry.js';export interface LyraWidgetNode{readonly type:string;readonly id?:string;readonly props?:Readonly<Record<string,unknown>>;readonly children?:readonly(LyraWidgetNode|string)[];readonly slot?:string;readonly actionId?:string;readonly payload?:unknown;}export interface LyraWidgetBinding{readonly $bind:string;readonly fallback?:string|number|boolean|null;}
|
|
2
|
+
/** Version-two document. Controlled binding state is supplied separately through `bindingState`.*/
|
|
3
|
+
export interface LyraWidgetDocument{readonly version:'2';readonly root:LyraWidgetNode;}
|
|
4
|
+
/**
|
|
5
|
+
* Creates an immediate, bounded, frozen version-two document snapshot. Widget-owned structure and
|
|
6
|
+
* prop records are copied; opaque prop values and action payloads intentionally retain identity.
|
|
7
|
+
* String children and string prop values are truncated to `WIDGET_MAX_STRING_LENGTH`, the same
|
|
8
|
+
* silent admission ceiling the depth/node/prop budgets apply here.
|
|
9
|
+
* Malformed, cyclic, duplicate-id, or hostile input throws `TypeError` before a document escapes.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createWidgetDocument(root:LyraWidgetNode):LyraWidgetDocument;export interface ResolvedText{
|
|
12
|
+
/** Collision-free deterministic reconciliation key.*/
|
|
13
|
+
nodeKey:string;nodePath:string;kind:'text';text:string;slot?:string;}export interface ResolvedElement{
|
|
14
|
+
/** Explicit public identity, when authored. Stateful/actionable mapped nodes always have one.*/
|
|
15
|
+
nodeId?:string;
|
|
16
|
+
/** Collision-free deterministic key: authored id when present, otherwise structural path.*/
|
|
17
|
+
nodeKey:string;
|
|
18
|
+
/** Deterministic occurrence path within this document.*/
|
|
19
|
+
nodePath:string;kind:'builtin-row'|'builtin-col'|'builtin-text'|'mapped';tag?:string;
|
|
20
|
+
/** Semantic control classification, independent of actions and bindings.*/
|
|
21
|
+
interactive:boolean;props:Record<string,unknown>;actionEvent?:string;actionId?:string;payload?:unknown;bindings:Array<{prop:string;path:string;event?:string;}>;children:ResolvedNode[];slot?:string;}export type ResolvedNode=ResolvedText|ResolvedElement;export interface ResolveContext{registry:LyraWidgetTypeRegistry;bindingState:unknown;
|
|
22
|
+
/** Warning keys retained for one renderer document/registry generation.*/
|
|
23
|
+
warned:Set<string>;
|
|
24
|
+
/** Explicit diagnostic callback, active in every runtime. Without one, authoring warnings
|
|
25
|
+
* are emitted only in development; keys and caps belong to this context generation. */
|
|
26
|
+
warn?:(message:string)=>void;}
|
|
27
|
+
/** Resolves one bounded immutable snapshot through `ctx.registry`. Structural invalidity returns
|
|
28
|
+
* `null`; throwing getters/registry access propagate so the renderer can emit one normalized error. */
|
|
29
|
+
export declare function resolveTree(root:LyraWidgetNode|null|undefined,ctx:ResolveContext):ResolvedNode|null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{devWarn}from"./dev-mode-attribute-warning.js";import{isWidgetTypeRegistry}from"./widget-type-registry.js";import{readWidgetPointer,WIDGET_MAX_DEPTH,WIDGET_MAX_NODES,WIDGET_MAX_PROPS_PER_NODE,WIDGET_MAX_WARNINGS}from"./widget-resolver.js";const WIDGET_MAX_STRING_LENGTH=16384;function truncateWidgetString(value){if(value.length<=WIDGET_MAX_STRING_LENGTH)return value;const capped=value.slice(0,WIDGET_MAX_STRING_LENGTH),last=capped.charCodeAt(capped.length-1);return last>=55296&&last<=56319?capped.slice(0,-1):capped}const DOCUMENT_INVALID=Symbol("invalid-widget-document"),DOCUMENT_MISSING=Symbol("missing-widget-document-field");function readDocumentField(input,key){try{return Object.hasOwn(input,key)?Reflect.get(input,key):DOCUMENT_MISSING}catch{return DOCUMENT_INVALID}}function snapshotDocumentProps(input){const output={};let admitted=0;try{for(const key in input){if(!Object.hasOwn(input,key))continue;if(admitted>=WIDGET_MAX_PROPS_PER_NODE)break;const value=Reflect.get(input,key);admitted+=1,output[key]=typeof value=="string"?truncateWidgetString(value):value}}catch{return DOCUMENT_INVALID}return Object.freeze(output)}function snapshotDocumentNode(input,depth,context){if(depth>WIDGET_MAX_DEPTH||context.remaining<=0)return null;if(context.remaining-=1,input===null||typeof input!="object"||Array.isArray(input)||context.ancestors.has(input))return DOCUMENT_INVALID;const type=readDocumentField(input,"type");if(typeof type!="string")return DOCUMENT_INVALID;const id=readDocumentField(input,"id"),slot=readDocumentField(input,"slot"),actionId=readDocumentField(input,"actionId"),propsInput=readDocumentField(input,"props"),childrenInput=readDocumentField(input,"children");if([id,slot,actionId,propsInput,childrenInput].includes(DOCUMENT_INVALID)||id!==DOCUMENT_MISSING&&(typeof id!="string"||id.length===0||id!==id.trim()))return DOCUMENT_INVALID;if(typeof id=="string"){if(context.ids.has(id))return DOCUMENT_INVALID;context.ids.add(id)}if(slot!==DOCUMENT_MISSING&&(typeof slot!="string"||slot.length===0||slot!==slot.trim())||actionId!==DOCUMENT_MISSING&&(typeof actionId!="string"||actionId.length===0||actionId!==actionId.trim())||propsInput!==DOCUMENT_MISSING&&(propsInput===null||typeof propsInput!="object"||Array.isArray(propsInput))||childrenInput!==DOCUMENT_MISSING&&!Array.isArray(childrenInput))return DOCUMENT_INVALID;const props=propsInput===DOCUMENT_MISSING?void 0:snapshotDocumentProps(propsInput);if(props===DOCUMENT_INVALID)return DOCUMENT_INVALID;let payload=DOCUMENT_MISSING;if(actionId!==DOCUMENT_MISSING&&(payload=readDocumentField(input,"payload"),payload===DOCUMENT_INVALID))return DOCUMENT_INVALID;const children=[];if(childrenInput!==DOCUMENT_MISSING&&depth<WIDGET_MAX_DEPTH){const length=readDocumentField(childrenInput,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0)return DOCUMENT_INVALID;context.ancestors.add(input);try{for(let index=0;index<length&&context.remaining>0;index++){const child=readDocumentField(childrenInput,index);if(child===DOCUMENT_INVALID||child===DOCUMENT_MISSING)return DOCUMENT_INVALID;if(typeof child=="string"){context.remaining-=1,children.push(truncateWidgetString(child));continue}const snapshot=snapshotDocumentNode(child,depth+1,context);if(snapshot===DOCUMENT_INVALID)return DOCUMENT_INVALID;snapshot&&children.push(snapshot)}}finally{context.ancestors.delete(input)}}return Object.freeze({type,...typeof id=="string"?{id}:{},...typeof slot=="string"?{slot}:{},...typeof actionId=="string"?{actionId,payload:payload===DOCUMENT_MISSING?void 0:payload}:{},...props===void 0?{}:{props},...children.length===0?{}:{children:Object.freeze(children)}})}function createWidgetDocument(root){const snapshot=snapshotDocumentNode(root,0,{ancestors:new Set,ids:new Set,remaining:WIDGET_MAX_NODES});if(snapshot===DOCUMENT_INVALID||snapshot===null)throw new TypeError("A widget document root must be a valid bounded widget node.");return Object.freeze({version:"2",root:snapshot})}const WARNING_SUPPRESSION_KEY="__warning-cap__",INVALID=Symbol("invalid-widget-input"),ROW_COL_PROP_ENUMS={gap:["s","m","l"],align:["start","center","end","stretch"],justify:["start","center","end","between"]};function warnOnce(ctx,key,message){if(!ctx.warned.has(key)){if(ctx.warned.size>=WIDGET_MAX_WARNINGS){if(ctx.warned.has(WARNING_SUPPRESSION_KEY))return;ctx.warned.add(WARNING_SUPPRESSION_KEY),(ctx.warn??devWarn)(`[lr-widget-renderer] suppressed further diagnostics after ${WIDGET_MAX_WARNINGS} unique warnings`);return}ctx.warned.add(key),(ctx.warn??devWarn)(`[lr-widget-renderer] ${message}`)}}function capResolvedString(value,ctx,key,subject){const capped=truncateWidgetString(value);return capped.length!==value.length&&warnOnce(ctx,`__string-cap__:${key}`,`truncated ${subject} after the ${WIDGET_MAX_STRING_LENGTH}-character string cap was reached`),capped}function isBinding(value){return!!(value&&typeof value=="object"&&!Array.isArray(value)&&typeof value.$bind=="string")}function resolveValue(value,ctx){if(!isBinding(value))return{value};const resolved=readWidgetPointer(ctx.bindingState,value.$bind);return{value:resolved===void 0?value.fallback:resolved,path:value.$bind}}function consumeNodeBudget(snapshot){return snapshot.remaining<=0?(warnOnce(snapshot.resolve,"__node-cap__",`stopped resolving after the ${WIDGET_MAX_NODES}-node cap was reached`),!1):(snapshot.remaining--,!0)}function snapshotProps(input,type,ctx){const out={};let visited=0;for(const key in input){if(visited>=WIDGET_MAX_PROPS_PER_NODE){warnOnce(ctx,`__prop-cap__:${type}`,`stopped reading props on type "${type}" after the ${WIDGET_MAX_PROPS_PER_NODE}-prop cap was reached`);break}visited++,Object.hasOwn(input,key)&&(out[key]=input[key])}return out}function definitionFor(type,registry){return registry.get(type)}function snapshotNode(input,depth,snapshot){if(!consumeNodeBudget(snapshot))return null;if(input===null||typeof input!="object"||Array.isArray(input)||snapshot.ancestors.has(input))return INVALID;const candidate=input,type=candidate.type;if(typeof type!="string")return INVALID;if(!(type==="row"||type==="col"||type==="text")&&!definitionFor(type,snapshot.resolve.registry))return{type};const id=candidate.id;if(id!==void 0&&(typeof id!="string"||id.length===0||id!==id.trim()))return INVALID;const slot=candidate.slot;if(slot!==void 0&&(typeof slot!="string"||slot.length===0||slot!==slot.trim()))return INVALID;const actionId=candidate.actionId;if(actionId!==void 0&&(typeof actionId!="string"||actionId.length===0||actionId!==actionId.trim()))return INVALID;const propsInput=candidate.props;if(propsInput!==void 0&&(propsInput===null||typeof propsInput!="object"||Array.isArray(propsInput)))return INVALID;const childrenInput=candidate.children;if(childrenInput!==void 0&&!Array.isArray(childrenInput))return INVALID;const node={type,...id!==void 0?{id}:{},...slot!==void 0?{slot}:{},...actionId!==void 0?{actionId,payload:candidate.payload}:{},...propsInput!==void 0?{props:snapshotProps(propsInput,type,snapshot.resolve)}:{}};if(childrenInput===void 0||depth===WIDGET_MAX_DEPTH)return childrenInput&&childrenInput.length>0&&warnOnce(snapshot.resolve,"__depth-cap__",`stopped resolving after the ${WIDGET_MAX_DEPTH}-level depth cap was reached`),node;const children=[];snapshot.ancestors.add(input);try{const childCount=childrenInput.length;for(let index=0;index<childCount;index++){if(snapshot.remaining<=0){consumeNodeBudget(snapshot);break}const child=childrenInput[index];if(typeof child=="string"){if(!consumeNodeBudget(snapshot))break;children.push(child);continue}const accepted=snapshotNode(child,depth+1,snapshot);if(accepted===INVALID)return INVALID;accepted&&children.push(accepted)}}finally{snapshot.ancestors.delete(input)}return children.length>0?{...node,children}:node}function filterRowColProps(props){const out={};if(!props)return out;for(const[key,allowed]of Object.entries(ROW_COL_PROP_ENUMS)){const value=props[key];typeof value=="string"&&allowed.includes(value)&&(out[key]=value)}return out}function filterMappedProps(props,def,ctx,type){const out={},bindings=[],allowlist=def.props??{};if(props)for(const[key,rawValue]of Object.entries(props)){const expectedType=allowlist[key],{value,path}=resolveValue(rawValue,ctx);if(expectedType===void 0||typeof value!==expectedType){warnOnce(ctx,`${type}:${key}`,`skipped disallowed or mistyped prop "${key}" on type "${type}"`);continue}out[key]=typeof value=="string"?capResolvedString(value,ctx,`${type}:${key}`,`string prop "${key}" on type "${type}"`):value,path&&bindings.push({prop:key,path,event:def.bindings?.[key]?.event})}return{props:{...out,...def.forcedProps??{}},bindings}}function containsInteractive(node){return node.kind==="text"?!1:node.interactive||node.children.some(containsInteractive)}function resolveChild(value,ctx,path){return typeof value=="string"?{nodeKey:`path:${path}`,nodePath:path,kind:"text",text:capResolvedString(value,ctx,"__text__","a text child")}:resolveNode(value,ctx,path)}function resolveNode(node,ctx,path){const authoredId=node.id,nodeKey=authoredId?`id:${authoredId}`:`path:${path}`;let kind,tag,interactive=!1,props,actionEvent,bindings=[],slots=[];if(node.type==="row"||node.type==="col")kind=node.type==="row"?"builtin-row":"builtin-col",props=filterRowColProps(node.props);else if(node.type==="text"){kind="builtin-text";const resolved=resolveValue(node.props?.value,ctx);if(props=typeof resolved.value=="string"||typeof resolved.value=="number"?{value:capResolvedString(String(resolved.value),ctx,"__text-value__",'the "value" of a built-in text node')}:{},resolved.path){if(!authoredId)throw warnOnce(ctx,`__required-id__:${path}`,"rejected bound text without a stable id"),new TypeError("A bound widget node requires a stable id.");bindings=[{prop:"value",path:resolved.path}]}}else{const def=definitionFor(node.type,ctx.registry);if(!def)return warnOnce(ctx,node.type,`skipped unknown widget type "${node.type}" (and its subtree)`),null;kind="mapped",tag=def.tag,interactive=def.interaction==="control";const filtered=filterMappedProps(node.props,def,ctx,node.type);if(props=filtered.props,bindings=filtered.bindings,slots=def.slots??[],node.actionId!==void 0&&def.action&&(actionEvent=def.action.event),(actionEvent||bindings.length>0)&&!authoredId)throw warnOnce(ctx,`__required-id__:${path}`,`rejected stateful or actionable type "${node.type}" without a stable id`),new TypeError("A stateful or actionable widget node requires a stable id.")}const children=[];for(let index=0;index<(node.children?.length??0);index++){const resolvedChild=resolveChild(node.children[index],ctx,`${path}.${index}`);if(resolvedChild){if(interactive&&containsInteractive(resolvedChild)){warnOnce(ctx,`__nested-interactive__:${node.type}`,`skipped a control descendant inside control type "${node.type}"`);continue}resolvedChild.slot!==void 0&&!slots.includes(resolvedChild.slot)&&(resolvedChild.slot=void 0),children.push(resolvedChild)}}return{nodeId:authoredId,nodeKey,nodePath:path,kind,tag,interactive,props,actionEvent,actionId:actionEvent?node.actionId:void 0,payload:actionEvent?node.payload:void 0,bindings,children,slot:node.slot}}function hasDuplicateAuthoredIds(root,ctx){const counts=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();node.id&&counts.set(node.id,(counts.get(node.id)??0)+1);for(const child of node.children??[])typeof child!="string"&&pending.push(child)}let duplicate=!1;for(const[id,count]of counts)count<2||(duplicate=!0,warnOnce(ctx,`__duplicate-id__:${id}`,`rejected duplicate widget id "${id}"`));return duplicate}function resolveTree(root,ctx){if(root==null)return null;if(!isWidgetTypeRegistry(ctx.registry))throw new TypeError("A widget renderer registry must be created with createWidgetTypeRegistry().");const snapshot=snapshotNode(root,0,{resolve:ctx,ancestors:new Set,remaining:WIDGET_MAX_NODES});return snapshot===INVALID||snapshot===null||hasDuplicateAuthoredIds(snapshot,ctx)?null:resolveNode(snapshot,ctx,"0")}export{WIDGET_MAX_STRING_LENGTH,createWidgetDocument,resolveTree};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** A primitive property type accepted from an authored widget document.*/
|
|
2
|
+
export type LyraWidgetPropType='string'|'number'|'boolean';
|
|
3
|
+
/** Semantic interaction classification, independent of event and binding plumbing.*/
|
|
4
|
+
export type LyraWidgetInteraction='none'|'control';
|
|
5
|
+
/** One allowlisted mapped widget type. Structural `text`/`row`/`col` nodes are not registered.*/
|
|
6
|
+
export interface LyraWidgetTypeDefinition{
|
|
7
|
+
/** Required custom-element render target.*/
|
|
8
|
+
readonly tag:string;
|
|
9
|
+
/** Prop allowlist: name -> required primitive type.*/
|
|
10
|
+
readonly props?:Readonly<Record<string,LyraWidgetPropType>>;
|
|
11
|
+
/** Always applied after the authored allowlist and never overridable by document input.*/
|
|
12
|
+
readonly forcedProps?:Readonly<Record<string,unknown>>;
|
|
13
|
+
/** Allowlisted child slot names.*/
|
|
14
|
+
readonly slots?:readonly string[];
|
|
15
|
+
/** Whether this element is semantically a control for nested-control content-model checks.*/
|
|
16
|
+
readonly interaction:LyraWidgetInteraction;
|
|
17
|
+
/** Event that emits `lr-widget-action` when a node also supplies `actionId`.*/
|
|
18
|
+
readonly action?:Readonly<{event:string;}>;
|
|
19
|
+
/** Controlled-state event mappings for allowlisted props.*/
|
|
20
|
+
readonly bindings?:Readonly<Record<string,Readonly<{event:string;}>>>;}declare const WIDGET_TYPE_REGISTRY_BRAND:unique symbol;
|
|
21
|
+
/** Immutable type-keyed registry snapshot accepted by each `<lr-widget-renderer>` instance.*/
|
|
22
|
+
export interface LyraWidgetTypeRegistry extends ReadonlyMap<string,Readonly<LyraWidgetTypeDefinition>>{readonly[WIDGET_TYPE_REGISTRY_BRAND]:true;}
|
|
23
|
+
/** Runtime guard for callers crossing an untyped boundary. Mutable structural `Map` values are
|
|
24
|
+
* rejected rather than retained by a renderer and allowed to leak mutations between instances. */
|
|
25
|
+
export declare function isWidgetTypeRegistry(value:unknown):value is LyraWidgetTypeRegistry;
|
|
26
|
+
/** Creates an immutable, validated registry snapshot owned by the assigning renderer/consumer.*/
|
|
27
|
+
export declare function createWidgetTypeRegistry(entries?:Iterable<readonly[string,LyraWidgetTypeDefinition]>):LyraWidgetTypeRegistry;export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var _a;const WIDGET_TYPE_REGISTRY_BRAND=Symbol("LyraWidgetTypeRegistry"),CUSTOM_ELEMENT_NAME=/^[a-z][.0-9_a-z]*-[-.0-9_a-z]*$/,RESERVED_CUSTOM_ELEMENT_NAMES=new Set(["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),SAFE_PROPERTY_NAME=/^[A-Za-z_$][\w$]*$/,FORBIDDEN_PROPERTIES=new Set(["__proto__","constructor","innerHTML","outerHTML","prototype"]),STRUCTURAL_WIDGET_TYPES=new Set(["col","row","text"]);function registryTypeKey(value){if(typeof value!="string"||value.length===0||value!==value.trim())throw new TypeError("A widget type key must be a nonempty string without surrounding whitespace.");if(STRUCTURAL_WIDGET_TYPES.has(value))throw new TypeError(`Structural widget type "${value}" cannot be registered.`);return value}function eventName(value,label){if(typeof value!="string"||value.length===0||value!==value.trim())throw new TypeError(`A widget ${label} must be a nonempty event name.`);return value}function propertyName(value){if(!SAFE_PROPERTY_NAME.test(value)||FORBIDDEN_PROPERTIES.has(value)||value.toLowerCase().startsWith("on"))throw new TypeError(`Widget property "${value}" is not a safe assignable property name.`);return value}function freezeProps(value){if(value===void 0)return;if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("A widget props allowlist must be an object.");const out={};for(const[key,type]of Object.entries(value)){if(propertyName(key),type!=="string"&&type!=="number"&&type!=="boolean")throw new TypeError(`Widget property "${key}" has an invalid primitive type.`);out[key]=type}return Object.freeze(out)}function freezeForcedProps(value){if(value===void 0)return;if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("Widget forcedProps must be an object.");const out={};for(const[key,forced]of Object.entries(value))propertyName(key),out[key]=forced;return Object.freeze(out)}function freezeBindings(value,props){if(value===void 0)return;if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("Widget bindings must be an object.");const out={};for(const[key,binding]of Object.entries(value)){if(propertyName(key),!props?.[key])throw new TypeError(`Widget binding "${key}" must name an allowlisted property.`);if(typeof binding!="object"||binding===null||Array.isArray(binding))throw new TypeError(`Widget binding "${key}" must be an object.`);out[key]=Object.freeze({event:eventName(binding.event,`binding for "${key}"`)})}return Object.freeze(out)}function validateWidgetTypeDefinition(value){if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError("A widget type definition must be an object.");const candidate=value;if(typeof candidate.tag!="string"||!CUSTOM_ELEMENT_NAME.test(candidate.tag)||RESERVED_CUSTOM_ELEMENT_NAMES.has(candidate.tag))throw new TypeError("A widget type definition requires a valid custom-element tag.");const props=freezeProps(candidate.props),forcedProps=freezeForcedProps(candidate.forcedProps),interaction=candidate.interaction;if(interaction!=="none"&&interaction!=="control")throw new TypeError("Widget interaction must be either 'none' or 'control'.");const action=candidate.action?Object.freeze({event:eventName(candidate.action.event,"action")}):void 0,bindings=freezeBindings(candidate.bindings,props);if((action||bindings)&&interaction!=="control")throw new TypeError("A widget definition with actions or bindings must declare interaction: 'control'.");let slots;if(candidate.slots!==void 0){if(!Array.isArray(candidate.slots))throw new TypeError("Widget slots must be an array.");const unique=new Set;for(const slot of candidate.slots){if(typeof slot!="string"||!slot||slot!==slot.trim())throw new TypeError("Widget slot names must be nonempty strings without surrounding whitespace.");if(unique.has(slot))throw new TypeError(`Duplicate widget slot name "${slot}".`);unique.add(slot)}slots=Object.freeze([...unique])}return Object.freeze({tag:candidate.tag,...props?{props}:{},...forcedProps?{forcedProps}:{},...slots?{slots}:{},interaction,...action?{action}:{},...bindings?{bindings}:{}})}class ImmutableWidgetTypeRegistry{#entries;constructor(entries){this[_a]=!0,this.#entries=new Map(entries),Object.freeze(this)}get size(){return this.#entries.size}get(key){return this.#entries.get(key)}has(key){return this.#entries.has(key)}entries(){return this.#entries.entries()}keys(){return this.#entries.keys()}values(){return this.#entries.values()}forEach(callbackfn,thisArg){for(const[key,value]of this.#entries)callbackfn.call(thisArg,value,key,this)}[(_a=WIDGET_TYPE_REGISTRY_BRAND,Symbol.iterator)](){return this.entries()}}function isWidgetTypeRegistry(value){return!!(value&&typeof value=="object"&&value[WIDGET_TYPE_REGISTRY_BRAND]===!0)}function createWidgetTypeRegistry(entries=[]){const validated=new Map;for(const[type,definition]of entries){const key=registryTypeKey(type);if(validated.has(key))throw new TypeError(`Duplicate widget type key "${key}".`);validated.set(key,validateWidgetTypeDefinition(definition))}return new ImmutableWidgetTypeRegistry(validated)}export{createWidgetTypeRegistry,isWidgetTypeRegistry};
|