UNPKG

@onirix/embed-sdk

Version:

Onirix helper library for iframe event communication.

2 lines (1 loc) 13.9 kB
function t(){return t=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},t.apply(this,arguments)}let e;const i=new Uint8Array(16);function r(){if(!e&&(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(i)}const n=[];for(let t=0;t<256;++t)n.push((t+256).toString(16).slice(1));var E={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function o(t,e,i){if(E.randomUUID&&!e&&!t)return E.randomUUID();const o=(t=t||{}).random||(t.rng||r)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e){i=i||0;for(let t=0;t<16;++t)e[i+t]=o[t];return e}return function(t,e=0){return n[t[e+0]]+n[t[e+1]]+n[t[e+2]]+n[t[e+3]]+"-"+n[t[e+4]]+n[t[e+5]]+"-"+n[t[e+6]]+n[t[e+7]]+"-"+n[t[e+8]]+n[t[e+9]]+"-"+n[t[e+10]]+n[t[e+11]]+n[t[e+12]]+n[t[e+13]]+n[t[e+14]]+n[t[e+15]]}(o)}const s={READY:"READY",SCENE_LOAD_START:"SCENE_LOAD_START",SCENE_LOAD_END:"SCENE_LOAD_END",SCENE_LOST:"SCENE_LOST",SCENE_RADIUS_ENTER:"SCENE_RADIUS_ENTER",SCENE_RADIUS_EXIT:"SCENE_RADIUS_EXIT",ELEMENT_CLICK:"ELEMENT_CLICK",OPEN_MARKERS_PANEL:"OPEN_MARKERS_PANEL",CLOSE_MARKERS_PANEL:"CLOSE_MARKERS_PANEL",MAP_READY:"MAP_READY",SCENE_LOCATION_CLICK:"SCENE_LOCATION_CLICK",BACK_TO_MAP:"BACK_TO_MAP",ON_TOUCH_START:"ON_TOUCH_START",ON_TOUCH_END:"ON_TOUCH_END",ON_POSE:"ON_POSE",SCENE_CLICK:"SCENE_CLICK",ON_SCENE_TOUCH_START:"ON_SCENE_TOUCH_START",ON_SCENE_TOUCH_END:"ON_SCENE_TOUCH_END",SESSION_ENDED:"SESSION_ENDED",SCENE_DETECTED:"SCENE_DETECTED",LAZY_LOAD_END:"LAZY_LOAD_END",NAVIGATION_STARTED:"NAVIGATION_STARTED",NAVIGATION_COMPLETED:"NAVIGATION_COMPLETED",NAVIGATION_CANCELLED:"NAVIGATION_CANCELLED"},A={ENABLE_ELEMENT:"ENABLE_ELEMENT",DISABLE_ELEMENT:"DISABLE_ELEMENT",TOGGLE_ELEMENT:"TOGGLE_ELEMENT",ENABLE_ALL:"ENABLE_ALL",DISABLE_ALL:"DISABLE_ALL",PLAY:"PLAY",PAUSE:"PAUSE",STOP:"STOP",TRANSLATE_ELEMENT:"TRANSLATE_ELEMENT",ROTATE_ELEMENT:"ROTATE_ELEMENT",SCALE_ELEMENT:"SCALE_ELEMENT",SET_ELEMENT_POSITION:"SET_ELEMENT_POSITION",SET_ELEMENT_ROTATION:"SET_ELEMENT_ROTATION",SET_ELEMENT_SCALE:"SET_ELEMENT_SCALE",PLAY_ANIMATION:"PLAY_ANIMATION",STOP_ANIMATION:"STOP_ANIMATION",SET_LABEL_TEXT:"SET_LABEL_TEXT",RESET_SCENES:"RESET_SCENES",PLAY_PAUSE:"PLAY_PAUSE",SET_CAMERA_RIG_TRANSFORM:"SET_CAMERA_RIG_TRANSFORM",SET_CAMERA_RIG_POSITION:"SET_CAMERA_RIG_POSITION",SET_CAMERA_RIG_ROTATION:"SET_CAMERA_RIG_ROTATION",SET_CAMERA_RIG_QUATERNION:"SET_CAMERA_RIG_QUATERNION",DISABLE_CAMERA_CONTROLS:"DISABLE_CAMERA_CONTROLS",LOAD_ELEMENT:"LOAD_ELEMENT",CREATE_ELEMENT:"CREATE_ELEMENT",SET_VARIANT:"SET_VARIANT",CAPTURE_SCREEN_FRAME:"CAPTURE_SCREEN_FRAME",START_SCREEN_CAPTURE:"START_SCREEN_CAPTURE",STOP_SCREEN_CAPTURE:"STOP_SCREEN_CAPTURE",GET_ASSET_IMAGE:"GET_ASSET_IMAGE",LOAD_SURFACE_PLACEHOLDER:"LOAD_SURFACE_PLACEHOLDER",SET_TRANSFORM_CONTROLS_ALLOWLIST:"SET_TRANSFORM_CONTROLS_ALLOWLIST",SET_TRANSFORM_CONTROLS_BLOCKLIST:"SET_TRANSFORM_CONTROLS_BLOCKLIST",SET_SCREEN_CAPTURE_OVERLAY:"SET_SCREEN_CAPTURE_OVERLAY",CLEAR_SCREEN_CAPTURE_OVERLAY:"CLEAR_SCREEN_CAPTURE_OVERLAY",GET_METADATA:"GET_METADATA",LOAD_SCENE:"LOAD_SCENE",HIGHTLIGHT_PIECE:"HIGHTLIGHT_PIECE",SET_OPACITY:"SET_OPACITY",INIT_NAVIGATION:"INIT_NAVIGATION",CANCEL_NAVIGATION:"CANCEL_NAVIGATION",HIGHLIGHT_NODES:"HIGHLIGHT_NODES",HIGHLIGHT_ELEMENT_NODE:"HIGHLIGHT_ELEMENT_NODE",CLEAR_HIGHLIGHT_NODES:"CLEAR_HIGHLIGHT_NODES",SET_PROPERTIES:"SET_PROPERTIES"},a={NONE:0,FADE:1,GROW:2,GROW_X:3,GROW_Y:4,GROW_Z:5,BOUNCE:6,TRANSLATION:7},T="v1",_="studio";class N{constructor(){this.eventListeners={},this.eventListenersCount=0}addEventListener(t,e){this.eventListeners[t]||(this.eventListeners[t]=[]);const i=this.eventListenersCount++;return this.eventListeners[t].push({id:i,func:e}),i}triggerEvent(t,e){this.eventListeners[t]&&this.eventListeners[t].map(t=>t.func(e))}removeEventListener(t){for(let e of Object.keys(this.eventListeners))for(let i=0;i<e.length;i++)if(e[i].id===t){e.splice(i,1);break}}}class S{constructor(t){this.iframe=t,this.targetWindow=t?t.contentWindow:window,this.id=o(),this.eventManager=new N,this.onMessageReceived=this.onMessageReceived.bind(this),this.pendingActions=new Map}async connect(){try{this.origin=this.targetWindow.location.origin}catch(t){this.origin=new URL(this.iframe.src).origin}"null"===this.origin&&(await new Promise(t=>this.iframe.addEventListener("load",t,{once:!0})),this.origin=new URL(this.iframe.src).origin),this.origin.match(/\.onirix\.com$/)||(this.iframe?console.warn(`The Onirix Embed SDK is trying to connect to the origin \`${this.origin}\`, but that is not a recognised Onirix origin. The iframe provided to the Onirix Embed SDK constructor is not pointing to an Onirix Experience.`):console.warn(`The Onirix Embed SDK is trying to connect to the origin \`${this.origin}\`, but that is not a recognised Onirix origin. You may need to provide an iframe in the Onirix Embed SDK constructor.`));const t=new Promise((t,e)=>{this.onConnect=t});window.addEventListener("message",this.onMessageReceived),this.sendHandshake(),await t}async disconnect(){this.sendDisconnect(),window.removeEventListener("message",this.onMessageReceived),this.pendingActions.clear()}sendMessage(e,i){e=t({oxEmbedSdk:T,source:this.id,destination:_},e),this.targetWindow.postMessage(e,this.origin,null!=i?i:[])}sendHandshake(){this.targetWindow.postMessage({oxEmbedSdk:T,source:this.id,destination:_,type:"HANDSHAKE"},this.origin)}sendDisconnect(){this.sendMessage({type:"DISCONNECT"})}triggerAction(t,e,i){const r=o(),n=new Error,E=new Promise((t,e)=>{this.pendingActions.set(r,{resolve:t,reject(t){var i;const r=null!=(i=null==t?void 0:t.message)?i:t;n.message=r,e(t)}})});return this.sendMessage({type:"TRIGGER_ACTION",thread:r,action:t,args:e},i),E}onMessageReceived(t){var e;if(t.origin!==this.origin)return;const i=t.data;if(i.oxEmbedSdk===T&&i.destination===this.id)switch(i.type){case"CONNECT":null==(e=this.onConnect)||e.call(this),this.onConnect=void 0;break;case"RAISE_EVENT":this.eventManager.triggerEvent(i.event,i.args);break;case"REJECT_ACTION":this.onActionRejected(i.thread,i.error);break;case"RESOLVE_ACTION":this.onActionResolved(i.thread,i.value)}}onActionResolved(t,e){const i=this.pendingActions.get(t);i?(i.resolve(e),this.pendingActions.delete(t)):console.warn(`[Embed SDK] Resolving an already resolved action: ${t}`)}onActionRejected(t,e){const i=this.pendingActions.get(t);i?(i.reject(new Error(e)),this.pendingActions.delete(t)):console.warn(`[Embed SDK] Rejecting an already resolved action: ${t}`)}subscribe(t,e){if(!(t in s))throw new Error(`event "${t}" does not exists`);return this.eventManager.addEventListener(t,e)}unsubscribe(t){this.eventManager.removeEventListener(t)}enable(e,i=a.NONE,r=void 0){const{type:n,params:E}=this._buildTransitionParamsForEnableDisableOrToggle(i,r);return this.triggerAction(A.ENABLE_ELEMENT,t({oid:e,transition:n},E))}disable(e,i=a.NONE,r=void 0){const{type:n,params:E}=this._buildTransitionParamsForEnableDisableOrToggle(i,r);return this.triggerAction(A.DISABLE_ELEMENT,t({oid:e,transition:n},E))}toggle(e,i=a.NONE,r=void 0){const{type:n,params:E}=this._buildTransitionParamsForEnableDisableOrToggle(i,r);return this.triggerAction(A.TOGGLE_ELEMENT,t({oid:e,transition:n},E))}_buildTransitionParams(t,e=void 0){var i,r,n;return"number"==typeof t&&(t={type:t}),t.type=null!=(i=t.type)?i:a.NONE,t.time=null!=(r=null!=(n=t.time)?n:e)?r:1,t}_buildTransitionParamsForEnableDisableOrToggle(e,i){let r=this._buildTransitionParams(e,i);const n=r.type;return r=t({},r),delete r.type,{type:n,params:r}}enableAll(){return this.triggerAction(A.ENABLE_ALL)}disableAll(){return this.triggerAction(A.DISABLE_ALL)}play(t){return this.triggerAction(A.PLAY,{oid:t})}pause(t){return this.triggerAction(A.PAUSE,{oid:t})}stop(t){return this.triggerAction(A.STOP,{oid:t})}playPause(t){return this.triggerAction(A.PLAY_PAUSE,{oid:t})}translate(t,e,i,r,n,E){return this.triggerAction(A.TRANSLATE_ELEMENT,{oid:t,x:e,y:i,z:r,time:n,loop:E})}translateToPosition(t,e,i,r,n,E){return this.triggerAction(A.SET_ELEMENT_POSITION,{oid:t,target:{x:e,y:i,z:r},time:n,lookAt:E})}translateToElement(t,e,i,r,n){return this.triggerAction(A.SET_ELEMENT_POSITION,{oid:t,target:e,time:i,lookAt:r,loop:n})}rotate(t,e,i,r,n,E){return this.triggerAction(A.ROTATE_ELEMENT,{oid:t,x:e,y:i,z:r,time:n,loop:E})}rotateTo(t,e,i,r,n){return this.triggerAction(A.SET_ELEMENT_ROTATION,{oid:t,x:e,y:i,z:r,time:n})}rotateToQuaternion(t,e,i,r,n,E){return this.triggerAction(A.SET_ELEMENT_ROTATION,{oid:t,x:e,y:i,z:r,w:n,time:E})}scale(t,e,i,r,n,E){return this.triggerAction(A.SCALE_ELEMENT,{oid:t,x:e,y:i,z:r,time:n,loop:E})}playAnimation(t,e,i,r=!1,n=void 0){return this.triggerAction(A.PLAY_ANIMATION,{oid:t,animation:e,time:n,loop:i,autoStop:r})}stopAnimation(t,e){return this.triggerAction(A.STOP_ANIMATION,{oid:t,animation:e})}setLabelText(t,e){return this.triggerAction(A.SET_LABEL_TEXT,{oid:t,text:e})}resetScenes(){return this.triggerAction(A.RESET_SCENES,{})}setCameraRigTransform(t){return this.triggerAction(A.SET_CAMERA_RIG_TRANSFORM,{matrix:t.flat()})}setCameraRigPosition(t,e,i){return this.triggerAction(A.SET_CAMERA_RIG_POSITION,{x:t,y:e,z:i})}setCameraRigRotation(t,e,i){return this.triggerAction(A.SET_CAMERA_RIG_ROTATION,{x:t,y:e,z:i})}setCameraRigQuaternion(t,e,i,r){return this.triggerAction(A.SET_CAMERA_RIG_QUATERNION,{x:t,y:e,z:i,w:r})}disableCameraControls(){return this.triggerAction(A.DISABLE_CAMERA_CONTROLS,{})}loadElement(e,i,r={}){const n=this._buildTransitionParamsForCreateElementOrLoadElement(r,i);return this.triggerAction(A.LOAD_ELEMENT,t({},i,{transition:n,oid:e}))}createElement(e,i,r={}){const n=this._buildTransitionParamsForCreateElementOrLoadElement(r,i);return this.triggerAction(A.CREATE_ELEMENT,t({},i,{transition:n,newOid:e}))}_buildTransitionParamsForCreateElementOrLoadElement(e,i){var r;const n=this._buildTransitionParams(null!=(r=null==i?void 0:i.transition)?r:{});null!=i&&i.sound&&(n.sound=i.sound),null!=i&&i.time&&(n.time=i.time);const E=this._buildTransitionParams(e),o=t({},n,E);return o.type=E.type!==a.NONE?E.type:n.type,o}setVariant(t,e){return this.triggerAction(A.SET_VARIANT,{oid:t,variant:e})}captureScreenFrame(){return this.triggerAction(A.CAPTURE_SCREEN_FRAME,{})}startScreenCapture(){return this.triggerAction(A.START_SCREEN_CAPTURE,{})}stopScreenCapture(){return this.triggerAction(A.STOP_SCREEN_CAPTURE,{})}async setScreenCaptureOverlay(t,e,i,r,n,E,o,s,a){let T,_,N,S;if(void 0===E&&void 0===o?(T=0,_=0,E=e,o=i):(T=e,_=i),void 0===s&&void 0===a){if(t instanceof VideoFrame)N=t.displayWidth-T,S=t.displayHeight-_;else if(t instanceof Blob){const e=await createImageBitmap(t);N=e.width-T,S=e.height-_}else N=t.width-T,S=t.height-_;a=n,void 0!==(s=r)&&void 0!==a||(s=N,a=S)}else N=r,S=n;const c=await createImageBitmap(t,T,_,N,S);return this.triggerAction(A.SET_SCREEN_CAPTURE_OVERLAY,{source:c,x:E,y:o,width:s,height:a},[c])}clearScreenCaptureOverlay(){return this.triggerAction(A.CLEAR_SCREEN_CAPTURE_OVERLAY,{})}getAssetImage(t,e=!0){return this.triggerAction(A.GET_ASSET_IMAGE,{assetOid:t,thumb:e})}loadSurfacePlaceholder(t){return this.triggerAction(A.LOAD_SURFACE_PLACEHOLDER,{placeholderUrl:t})}setTransformControlsAllowlist(t){if(!(t&&t[Symbol.iterator]||void 0===t))throw new Error("`allowlist` must be an iterable or `undefined`.");return void 0===t||t instanceof Set||(t=new Set(t)),this.triggerAction(A.SET_TRANSFORM_CONTROLS_ALLOWLIST,{allowlist:t})}setTransformControlsBlocklist(t){if(!(t&&t[Symbol.iterator]||void 0===t))throw new Error("`blocklist` must be an iterable or `undefined`.");return void 0===t||t instanceof Set||(t=new Set(t)),this.triggerAction(A.SET_TRANSFORM_CONTROLS_BLOCKLIST,{blocklist:t})}getMetadata(t,e){if("string"!=typeof t)throw new Error(`expected OID to be a \`string\`, but got a \`${typeof t}\` instead`);if(!("number"==typeof e||"string"==typeof e||Array.isArray(e)||"object"==typeof e&&e instanceof RegExp))throw new Error(`expected metadata query to be an \`Array\`, \`string\`, \`number\` or \`RegExp\`, but got a \`${typeof e}\` instead`);if(Array.isArray(e)&&e.some(t=>"number"==typeof e||"string"!=typeof t&&!("object"==typeof t&&t instanceof RegExp))){const t=e.map(t=>typeof t).filter(t=>"string"!==t),i="["+Array.from(new Set(t)).join(", ")+"]";throw new Error(`expected metadata query to be an \`Array\` of \`string\`, \`number\` or \`RegExp\`, but got types such as \`${i}\``)}return this.triggerAction(A.GET_METADATA,{oid:t,query:e})}loadScene(t){if("string"!=typeof t)throw new Error(`expected the scene OID to be a \`string\`, but got a \`${typeof t}\``);return this.triggerAction(A.LOAD_SCENE,{sceneOid:t})}highlightBIMPieces(t,e){return this.triggerAction(A.HIGHTLIGHT_PIECE,{enable:t,params:e})}setOpacity(t,e,i=0){if(e<0||e>1)throw new Error("Opacity must be between 0 and 1.");return this.triggerAction(A.SET_OPACITY,{oid:t,opacity:e,time:i})}initNavigation(t,e,i=!1){return this.triggerAction(A.INIT_NAVIGATION,{destination:t,origin:e,fullRoute:i})}cancelNavigation(){return this.triggerAction(A.CANCEL_NAVIGATION)}enableHighlightNodes(t,e){return this.triggerAction(A.HIGHLIGHT_NODES,{enable:t,params:e})}highlightElementNode(t,e){return this.triggerAction(A.HIGHLIGHT_ELEMENT_NODE,{oid:t,name:e})}clearHighlightNodes(){return this.triggerAction(A.CLEAR_HIGHLIGHT_NODES)}setProperties(t,e){return this.triggerAction(A.SET_PROPERTIES,{oid:t,params:e})}}S.Events=s,S.Actions=A,S.Transitions=a,S.Sounds={SUCCESS:"success",SCORE:"score",SWEEP:"sweep",INTERFACE_ZOOM:"interface zoom",SWIPE:"swipe",FINGER_TAP:"finger_tap",SPRINT_JUMP:"sprint_jump",CINEMATIC_HIT:"cinematic_hit",POP:"pop",GLITCH:"glitch",BLOOP:"bloop",IMPACT:"impact"};export{S as default};