forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLivePreviewTransportRemote.js
More file actions
1 lines (1 loc) · 8 KB
/
LivePreviewTransportRemote.js
File metadata and controls
1 lines (1 loc) · 8 KB
1
!function(global){const TRANSPORT_CONFIG={};function _debugLog(...args){window.LIVE_PREVIEW_DEBUG_ENABLED&&console.log(...args)}function createLRU(max=100){const map=new Map;return{set:function(key,value=!0){if(map.has(key)&&map.delete(key),map.set(key,value),map.size>max){const oldestKey=map.keys().next().value;map.delete(oldestKey)}},has:function(key){if(!map.has(key))return!1;const val=map.get(key);return map.delete(key),map.set(key,val),!0},size:function(){return map.size}}}const processedMessageIDs=createLRU(1e3),clientID=""+Math.round(1e9*Math.random()),worker=new Worker(TRANSPORT_CONFIG.LIVE_DEV_REMOTE_WORKER_SCRIPTS_FILE_NAME);let _workerMessageProcessor,sentTitle,sentFavIconURL;function _postLivePreviewMessage(message){worker.postMessage({type:"livePreview",message:message})}function convertImgToBase64(url,callback){if(!url)return void callback(null);let canvas=document.createElement("CANVAS");const ctx=canvas.getContext("2d"),img=new Image;img.crossOrigin="Anonymous",img.onload=function(){canvas.height=img.height,canvas.width=img.width,ctx.drawImage(img,0,0);const dataURL=canvas.toDataURL();callback(dataURL),canvas=null},img.src=url}worker.onmessage=(event=>{const type=event.data.type;switch(type){case"REDIRECT_PAGE":location.href=event.data.URL;break;default:if(_workerMessageProcessor)return _workerMessageProcessor(event);console.error("Live Preview page loader: received unknown message from worker:",event)}}),worker.postMessage({type:"setupPhoenixComm",livePreviewDebugModeEnabled:TRANSPORT_CONFIG.LIVE_PREVIEW_DEBUG_ENABLED,broadcastChannel:TRANSPORT_CONFIG.LIVE_PREVIEW_BROADCAST_CHANNEL_ID,websocketChannelURL:TRANSPORT_CONFIG.LIVE_PREVIEW_WEBSOCKET_CHANNEL_URL,clientID:clientID}),setInterval(()=>{const favIcon=document.querySelector("link[rel~='icon']"),faviconUrl=favIcon&&favIcon.href;sentFavIconURL!==faviconUrl&&(sentFavIconURL=faviconUrl,convertImgToBase64(faviconUrl,function(base64){base64||(base64="favicon.ico"),worker.postMessage({type:"updateTitleIcon",faviconBase64:base64})})),sentTitle!==document.title&&(sentTitle=document.title,worker.postMessage({type:"updateTitleIcon",title:document.title}))},1e3),global._Brackets_LiveDev_Transport={_channelOpen:!1,_callbacks:null,setCallbacks:function(callbacks){this._callbacks=callbacks},connect:function(){const self=this;_workerMessageProcessor=(event=>{_debugLog("Live Preview: Browser received event from Phoenix: ",JSON.stringify(event.data));const type=event.data.type;switch(type){case"BROWSER_CONNECT":case"BROWSER_MESSAGE":case"BROWSER_CLOSE":break;case"MESSAGE_FROM_PHOENIX":if(self._callbacks&&self._callbacks.message){const clientIDs=event.data.clientIDs,message=event.data.message,messageID=event.data.messageID;if(messageID&&processedMessageIDs.has(messageID))return;processedMessageIDs.set(messageID,!0),(clientIDs.includes(clientID)||0===clientIDs.length)&&self._callbacks.message(message)}break;case"PHOENIX_CLOSE":self._channelOpen=!1,self._callbacks&&self._callbacks.close&&self._callbacks.close()}}),_postLivePreviewMessage({type:"BROWSER_CONNECT",url:global.location.href,clientID:clientID}),self._channelOpen=!0,self._callbacks&&self._callbacks.connect&&self._callbacks.connect(),addEventListener("beforeunload",function(){self._channelOpen&&(self._channelOpen=!1,_postLivePreviewMessage({type:"BROWSER_CLOSE",clientID:clientID}))})},send:function(msgStr){_postLivePreviewMessage({type:"BROWSER_MESSAGE",clientID:clientID,messageID:crypto.randomUUID(),message:msgStr})},enable:function(){this.connect()}};const ABS_REGEX=new RegExp("^(?:[a-z]+:)?\\/\\/","i");function getAbsoluteUrl(url){if(ABS_REGEX.test(url))return url;const absoluteUrl=new URL(url,window.location.href);return absoluteUrl.href}function alertPatch(message,titleText){const modal=document.createElement("div");modal.style.position="fixed",modal.style.top="0",modal.style.left="0",modal.style.width="100%",modal.style.height="100vh",modal.style.backgroundColor="rgba(0,0,0,0.5)",modal.style.display="flex",modal.style.justifyContent="center",modal.style.alignItems="center",modal.style.zIndex="1000000000";const modalContent=document.createElement("div");modalContent.style.backgroundColor="white",modalContent.style.padding="20px",modalContent.style.borderRadius="5px",modalContent.style.minWidth="300px",modalContent.style.margin="auto",modalContent.style.textAlign="center";const title=document.createElement("h3");title.textContent=titleText||"alert",title.style.marginBottom="10px";const text=document.createElement("p");text.textContent=message,text.style.marginBottom="20px";const button=document.createElement("button");button.textContent="OK",button.style.padding="10px 20px",button.style.border="none",button.style.backgroundColor="#007BFF",button.style.color="white",button.style.borderRadius="5px",button.style.cursor="pointer",button.onclick=function(){document.body.removeChild(modal)},modalContent.appendChild(title),modalContent.appendChild(text),modalContent.appendChild(button),modal.appendChild(modalContent),document.body.appendChild(modal)}function unsupportedConfirm(){alertPatch(TRANSPORT_CONFIG.STRINGS.UNSUPPORTED_DOM_APIS_CONFIRM,"window.confirm")}function unsupportedPrompt(){alertPatch(TRANSPORT_CONFIG.STRINGS.UNSUPPORTED_DOM_APIS_CONFIRM,"window.prompt")}document.addEventListener("click",function(event){let targetElement=event.target;if(null!==targetElement&&"A"!==targetElement.tagName&&(targetElement=targetElement.parentElement),window.__PHOENIX_EMBED_INFO&&window.__PHOENIX_EMBED_INFO.isTauri&&targetElement&&"A"===targetElement.tagName&&"_blank"===targetElement.target){const href=getAbsoluteUrl(targetElement.getAttribute("href"));event.defaultPrevented||(window.parent.postMessage({handlerName:"ph-liveServer",eventName:"embeddedIframeHrefClick",href:href},"*"),event.stopImmediatePropagation(),event.preventDefault())}}),document.addEventListener("contextmenu",function(event){(document.activeElement||document.body).focus()}),document.addEventListener("keydown",function(event){!window.__PHOENIX_EMBED_INFO||"Escape"!==event.key&&"Esc"!==event.key||window.parent.postMessage({handlerName:"ph-liveServer",eventName:"embeddedEscapeKeyPressed"},"*")});const currentUrl=new URL(window.location.href),queryParams=new URLSearchParams(currentUrl.search),isExternalBrowser="true"===queryParams.get("phcodeLivePreview"),isTauri=TRANSPORT_CONFIG.IS_NATIVE_APP,platform=TRANSPORT_CONFIG.PLATFORM;let alertQueue=[],confirmCalled=!1,promptCalled=!1,addToQueue=!0;window.__PHOENIX_APP_INFO={isTauri:isTauri,platform:platform};const _embeddedInfoCallbacks=[];if(!isExternalBrowser){window.__PHOENIX_EMBED_INFO={isTauri:isTauri,platform:platform,isPhoenixEmbeddedIframe:void 0},window.__PHOENIX_EMBED_INFO.onPhoenixEmbeddedInfoAvailable=function(callback){void 0!==window.__PHOENIX_EMBED_INFO.isPhoenixEmbeddedIframe?callback(window.__PHOENIX_EMBED_INFO.isPhoenixEmbeddedIframe):_embeddedInfoCallbacks.push(callback)};const shouldPatchAlert=isTauri&&"mac"===platform;if(shouldPatchAlert){function drainAlertQueues(){addToQueue=!1,confirmCalled&&unsupportedConfirm(),promptCalled&&unsupportedPrompt();for(let i=0;i<alertQueue.length;i++)alertPatch(alertQueue[i]);alertQueue=[],window.alert=alertPatch,window.confirm=unsupportedConfirm,window.prompt=unsupportedPrompt}window.alert=function(...args){addToQueue&&alertQueue.push(...args)},window.confirm=function(){confirmCalled=!0},window.prompt=function(){promptCalled=!0},document.addEventListener("DOMContentLoaded",function(){drainAlertQueues()})}}window.addEventListener("message",function(event){if(TRANSPORT_CONFIG.TRUSTED_ORIGINS_EMBED[event.origin]&&"WHO_AM_I_RESPONSE"===event.data.type){window.__PHOENIX_EMBED_INFO||console.error("Expected window.__PHOENIX_EMBED_INFO to be set, but not???");const isPhoenixEmbeddedIframe=!!event.data.isPhoenixEmbeddedIframe;window.__PHOENIX_EMBED_INFO.isPhoenixEmbeddedIframe=isPhoenixEmbeddedIframe;for(let i=0;i<_embeddedInfoCallbacks.length;i++)_embeddedInfoCallbacks[i](isPhoenixEmbeddedIframe);_embeddedInfoCallbacks.length=0}}),window.self!==window.parent&&window.parent.postMessage({handlerName:"ph-liveServer",eventName:"whoAmIframePhoenix",href:location.href},"*")}(this);