forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLiveDevMultiBrowser.js
More file actions
1 lines (1 loc) · 11.9 KB
/
LiveDevMultiBrowser.js
File metadata and controls
1 lines (1 loc) · 11.9 KB
1
define(function(require,exports,module){const STATUS_INACTIVE=exports.STATUS_INACTIVE=0,STATUS_CONNECTING=exports.STATUS_CONNECTING=1,STATUS_ACTIVE=exports.STATUS_ACTIVE=2,STATUS_OUT_OF_SYNC=exports.STATUS_OUT_OF_SYNC=3,STATUS_SYNC_ERROR=exports.STATUS_SYNC_ERROR=4,STATUS_RELOADING=exports.STATUS_RELOADING=5,STATUS_RESTARTING=exports.STATUS_RESTARTING=6,EVENT_OPEN_PREVIEW_URL="openPreviewURL",EVENT_CONNECTION_CLOSE="ConnectionClose",EVENT_STATUS_CHANGE="statusChange",Dialogs=require("widgets/Dialogs"),DefaultDialogs=require("widgets/DefaultDialogs"),DocumentManager=require("document/DocumentManager"),EditorManager=require("editor/EditorManager"),EventDispatcher=require("utils/EventDispatcher"),MainViewManager=require("view/MainViewManager"),ProjectManager=require("project/ProjectManager"),Strings=require("strings"),LiveDevelopmentUtils=require("LiveDevelopment/LiveDevelopmentUtils"),LiveDevServerManager=require("LiveDevelopment/LiveDevServerManager"),LivePreviewTransport=require("LiveDevelopment/MultiBrowserImpl/transports/LivePreviewTransport"),LiveDevProtocol=require("LiveDevelopment/MultiBrowserImpl/protocol/LiveDevProtocol"),Metrics=require("utils/Metrics"),WorkspaceManager=require("view/WorkspaceManager"),FileSystem=require("filesystem/FileSystem"),PageLoaderWorkerScript=require("text!LiveDevelopment/BrowserScripts/pageLoaderWorker.js"),LiveCSSDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveCSSDocument"),LiveHTMLDocument=require("LiveDevelopment/MultiBrowserImpl/documents/LiveHTMLDocument");var _liveDocument;let livePreviewUrlPinned=!1,currentPreviewFilePath;var _relatedDocuments={},_protocol=LiveDevProtocol,_server;let _config={},_lastPreviewedHTMLFilePath;function _classForDocument(doc){return"css"===doc.getLanguage().getId()?LiveCSSDocument:LiveDevelopmentUtils.isHtmlFileExt(doc.file.fullPath)?LiveHTMLDocument:null}function isActive(){return exports.status>STATUS_INACTIVE}function getLiveDocForPath(path){return _server?_server.get(path):null}function _closeDocument(liveDocument){liveDocument.off(".livedev"),_protocol.off(".livedev"),liveDocument.close()}function _handleRelatedDocumentDeleted(url){const liveDoc=_relatedDocuments[url];liveDoc&&(delete _relatedDocuments[url],_server&&_server.remove(liveDoc),_closeDocument(liveDoc))}function _setStatus(status,closeReason){if(status!==exports.status){exports.status=status;var reason=status===STATUS_INACTIVE?closeReason:null;exports.trigger(EVENT_STATUS_CHANGE,status,reason)}}function _closeDocuments(){_liveDocument&&(_closeDocument(_liveDocument),_liveDocument=void 0),Object.keys(_relatedDocuments).forEach(function(url){_closeDocument(_relatedDocuments[url]),delete _relatedDocuments[url]}),_server&&_server.clear()}function _resolveUrl(path){return _server&&_server.pathToUrl(path)}function _createLiveDocument(doc,editor,roots){var DocClass=_classForDocument(doc),liveDocument;return DocClass?((liveDocument=new DocClass(_protocol,_resolveUrl,doc,editor,roots)).on("errorStatusChanged.livedev",function(event,hasErrors){isActive()&&_setStatus(hasErrors?STATUS_SYNC_ERROR:STATUS_ACTIVE)}),liveDocument):null}function _docIsOutOfSync(doc){var liveDoc=_server&&_server.get(doc.file.fullPath),isLiveEditingEnabled=liveDoc&&liveDoc.isLiveEditingEnabled();return doc.isDirty&&!isLiveEditingEnabled}function _styleSheetAdded(event,url,roots){var path=_server&&_server.urlToPath(url),alreadyAdded=!!_relatedDocuments[url],docPromise;path&&!alreadyAdded&&DocumentManager.getDocumentForPath(path).done(function(doc){if(!(_relatedDocuments[url]||_classForDocument(doc)!==LiveCSSDocument||_liveDocument&&doc===_liveDocument.doc)){var liveDoc=_createLiveDocument(doc,doc._masterEditor,roots);liveDoc&&(_server.add(liveDoc),_relatedDocuments[url]=liveDoc,liveDoc.on("updateDoc",function(event,url){var path,doc;getLiveDocForPath(_server.urlToPath(url))._updateBrowser()}))}})}function _close(doCloseWindow,reason){exports.status!==STATUS_INACTIVE&&(_closeDocuments(),_protocol.closeAllConnections(),_server&&(_server.stop(),_server=null)),_setStatus(STATUS_INACTIVE,reason||"explicit_close")}function close(){return _close(!0),(new $.Deferred).resolve().promise()}function _showLiveDevServerNotReadyError(){Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR,Strings.LIVE_DEVELOPMENT_ERROR_TITLE,Strings.LIVE_DEV_SERVER_NOT_READY_MESSAGE)}function _updateVirtualServerScripts(){_server&&_liveDocument&&_liveDocument.doc&&(_server.addVirtualContentAtPath(`${_liveDocument.doc.file.parentPath}${LiveDevProtocol.LIVE_DEV_REMOTE_SCRIPTS_FILE_NAME}`,_protocol.getRemoteScriptContents()),_server.addVirtualContentAtPath(`${_liveDocument.doc.file.parentPath}${LiveDevProtocol.LIVE_DEV_REMOTE_WORKER_SCRIPTS_FILE_NAME}`,PageLoaderWorkerScript))}function _createLiveDocumentForFrame(doc){doc._ensureMasterEditor(),(_liveDocument=_createLiveDocument(doc,doc._masterEditor))&&(_server.add(_liveDocument),_updateVirtualServerScripts())}function _launch(url,fullPath){exports.trigger(EVENT_OPEN_PREVIEW_URL,{url:url,fullPath:fullPath})}function _open(doc){doc&&_liveDocument&&doc===_liveDocument.doc&&(_server?(exports.status<STATUS_ACTIVE&&_launch(_resolveUrl(doc.file.fullPath),doc.file.fullPath),_protocol.on("ConnectionConnect.livedev",function(event,msg){if(_protocol.getConnectionIds().length>=1){const url=new URL(msg.url),urlString=`${url.origin}${url.pathname}`;_liveDocument&&urlString===_resolveUrl(_liveDocument.doc.file.fullPath)&&_setStatus(STATUS_ACTIVE)}Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW,"connect",`${_protocol.getConnectionIds().length}-preview`)}).on("ConnectionClose.livedev",function(event,{clientId:clientId}){exports.trigger(EVENT_CONNECTION_CLOSE,{clientId:clientId}),window.logger.livePreview.log("Live Preview: Phoenix received ConnectionClose, live preview left: ",_protocol.getConnectionIds().length,clientId)}).on("DocumentRelated.livedev",function(event,msg){var relatedDocs=msg.related,docs;Object.keys(relatedDocs.stylesheets).forEach(function(url){_styleSheetAdded(null,url,relatedDocs.stylesheets[url])})}).on("StylesheetAdded.livedev",function(event,msg){_styleSheetAdded(null,msg.href,msg.roots)}).on("StylesheetRemoved.livedev",function(event,msg){_handleRelatedDocumentDeleted(msg.href)}).on(LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED+".livedev",function(event,msg){exports.trigger(LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED,msg)}).on(LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD+".livedev",function(event,clients){exports.trigger(LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD,clients)})):console.error("LiveDevelopment._open(): No server active"))}function _prepareServer(doc){const deferred=new $.Deferred;let initialServePath=doc&&doc.file.fullPath;initialServePath||(initialServePath=`${ProjectManager.getProjectRoot().fullPath}index.html`);const readyPromise=(_server=LiveDevServerManager.getServer(initialServePath)).readyToServe();return readyPromise?readyPromise.then(deferred.resolve,function(){_showLiveDevServerNotReadyError(),deferred.reject()}):(_showLiveDevServerNotReadyError(),deferred.reject()),deferred.promise()}function _onFileChange(){let doc=DocumentManager.getCurrentDocument();if(!isActive()||!doc||livePreviewUrlPinned)return;let docUrl=_resolveUrl(doc.file.fullPath),isViewable=_server&&_server.canServe(doc.file.fullPath);_liveDocument&&_liveDocument.doc.url!==docUrl&&isViewable&&open()}async function _resolveLivePreviewDocument(){let activeDocument=DocumentManager.getCurrentDocument(),fileExists;return livePreviewUrlPinned?jsPromise(DocumentManager.getDocumentForPath(currentPreviewFilePath)):activeDocument&&"html"===activeDocument.getLanguage().getId()?(_lastPreviewedHTMLFilePath=activeDocument.file.fullPath,activeDocument):await FileSystem.existsAsync(_lastPreviewedHTMLFilePath)?jsPromise(DocumentManager.getDocumentForPath(_lastPreviewedHTMLFilePath)):activeDocument}async function open(){let doc=await _resolveLivePreviewDocument();_prepareServer(doc).done(function(){_server&&(_setStatus(STATUS_CONNECTING),_closeDocuments(),doc&&_createLiveDocumentForFrame(doc),_server.isActive()?doc&&_open(doc):_server.start().then(()=>{doc&&_open(doc)}))}).fail(function(){console.log("Live preview: no document to preview.")})}function _onDocumentSaved(event,doc){if(isActive()&&_server&&_liveDocument){var absolutePath=doc.file.fullPath,liveDocument=absolutePath&&_server.get(absolutePath),liveEditingEnabled;liveDocument&&liveDocument.isLiveEditingEnabled&&liveDocument.isLiveEditingEnabled()||_liveDocument.isRelated&&_liveDocument.isRelated(absolutePath)&&"javascript"===doc.getLanguage().getId()&&(_setStatus(STATUS_RELOADING),_protocol.reload())}}function _onDirtyFlagChange(event,doc){if(isActive()&&_server&&_liveDocument&&_liveDocument.isRelated){var absolutePath=doc.file.fullPath;_liveDocument.isRelated&&_liveDocument.isRelated(absolutePath)&&_setStatus(_docIsOutOfSync(doc)?STATUS_OUT_OF_SYNC:STATUS_ACTIVE)}}function setTransport(transport){_protocol.setTransport(transport)}function init(config){_config=config,MainViewManager.on("currentFileChange",_onFileChange),DocumentManager.on("documentSaved",_onDocumentSaved).on("dirtyFlagChange",_onDirtyFlagChange),setTransport(LivePreviewTransport),_setStatus(STATUS_INACTIVE)}function getLiveDocForEditor(editor){return editor?getLiveDocForPath(editor.document.file.fullPath):null}function showHighlight(){var doc=getLiveDocForEditor(EditorManager.getActiveEditor());doc&&doc.updateHighlight&&doc.updateHighlight()}function hideHighlight(){_protocol&&_protocol.evaluate("_LD.hideHighlight()")}function redrawHighlight(){_protocol&&_protocol.evaluate("_LD.redrawHighlights()")}function updateConfig(config){const previousConfig=_config;_config=config,_updateVirtualServerScripts(),refreshConfig();const modeChanged=!previousConfig||previousConfig.mode!==config.mode,oldHighlights=previousConfig&&previousConfig.elemHighlights?previousConfig.elemHighlights.toLowerCase():"hover",newHighlights=config.elemHighlights?config.elemHighlights.toLowerCase():"hover";if(modeChanged||oldHighlights!==newHighlights){const doc=getLiveDocForEditor(EditorManager.getActiveEditor());doc&&(doc._lastHighlight=null)}}function refreshConfig(){_protocol&&_protocol.evaluate("_LD.updateConfig("+JSON.stringify(_config)+")")}function _handleLivePreviewEscapeKey(event){const currLiveDoc=getCurrentLiveDoc();return currLiveDoc&&currLiveDoc.protocol&&currLiveDoc.protocol.evaluate&&currLiveDoc.protocol.evaluate("_LD.escapeKeyPressInEditor()"),!1}function getConfig(){return JSON.parse(JSON.stringify(_config||{}))}function reconnect(){return $.Deferred().resolve()}function reload(){_protocol&&_protocol.reload()}function setLivePreviewPinned(urlPinned,currentPinnedFilePath){livePreviewUrlPinned=urlPinned,currentPreviewFilePath=currentPinnedFilePath}function getCurrentLiveDoc(){return _liveDocument}function getConnectionIds(){return _protocol.getConnectionIds()}function getLivePreviewDetails(){return{liveDocument:_liveDocument,URL:_liveDocument?_resolveUrl(_liveDocument.doc.file.fullPath):null}}ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN,()=>{_lastPreviewedHTMLFilePath=null}),WorkspaceManager.addEscapeKeyEventHandler("livePreview",_handleLivePreviewEscapeKey),EventDispatcher.makeEventDispatcher(exports),exports._server=_server,exports.EVENT_OPEN_PREVIEW_URL=EVENT_OPEN_PREVIEW_URL,exports.EVENT_CONNECTION_CLOSE=EVENT_CONNECTION_CLOSE,exports.EVENT_STATUS_CHANGE=EVENT_STATUS_CHANGE,exports.EVENT_LIVE_PREVIEW_CLICKED=LiveDevProtocol.EVENT_LIVE_PREVIEW_CLICKED,exports.EVENT_LIVE_PREVIEW_RELOAD=LiveDevProtocol.EVENT_LIVE_PREVIEW_RELOAD,exports.open=open,exports.close=close,exports.reconnect=reconnect,exports.reload=reload,exports.getLiveDocForPath=getLiveDocForPath,exports.showHighlight=showHighlight,exports.hideHighlight=hideHighlight,exports.redrawHighlight=redrawHighlight,exports.getConfig=getConfig,exports.updateConfig=updateConfig,exports.refreshConfig=refreshConfig,exports.init=init,exports.isActive=isActive,exports.setLivePreviewPinned=setLivePreviewPinned,exports.getCurrentLiveDoc=getCurrentLiveDoc,exports.getLivePreviewDetails=getLivePreviewDetails,exports.getConnectionIds=getConnectionIds,exports.setTransport=setTransport});