Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: live preview StaticServer into self contained component #1263

Merged
merged 2 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"lint:fix": "eslint --quiet --fix src test",
"prepare": "husky install",
"_serveTest": "http-server . -p 5000 -c-1",
"_zipTestFiles": "gulp zipTestFiles",
"zipTestFiles": "gulp zipTestFiles",
"test": "echo please see `Running and debugging tests` section in readme.md",
"testIntegHelp": "echo By default this command only runs unit tests.To Run integration tests, please see `Running and debugging tests` section in readme.md",
"testChromium": "npm run testIntegHelp && npx playwright test --project=chromium",
Expand All @@ -61,8 +61,8 @@
"_buildonlyDebug": "gulp buildDebug",
"_vulnerabilityCheck": "echo Scanning for vulnarabilities && npm audit --prod --audit-level=critical",
"_create-src-node-pkg-lock": "cd src-node && npm i --package-lock-only && cd ..",
"build": "npm run _create-src-node-pkg-lock && npm run _buildonly && npm run createJSDocs && npm run _zipTestFiles && npm run lint && npm run _vulnerabilityCheck",
"build:debug": "npm run _create-src-node-pkg-lock && npm run _buildonlyDebug && npm run createJSDocs && npm run _zipTestFiles && npm run lint && npm run _vulnerabilityCheck",
"build": "npm run _create-src-node-pkg-lock && npm run _buildonly && npm run createJSDocs && npm run zipTestFiles && npm run lint && npm run _vulnerabilityCheck",
"build:debug": "npm run _create-src-node-pkg-lock && npm run _buildonlyDebug && npm run createJSDocs && npm run zipTestFiles && npm run lint && npm run _vulnerabilityCheck",
"clean": "gulp clean && gulp reset",
"release:dev": "gulp releaseDev",
"release:staging": "gulp releaseStaging",
Expand Down
72 changes: 69 additions & 3 deletions src/extensions/default/Phoenix-live-preview/StaticServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ define(function (require, exports, module) {
EventManager = brackets.getModule("utils/EventManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
Strings = brackets.getModule("strings"),
utils = require('utils'),
BootstrapCSSText = require("text!../../../thirdparty/bootstrap/bootstrap.min.css"),
GithubCSSText = require("text!../../../thirdparty/highlight.js/styles/github.min.css"),
HilightJSText = require("text!../../../thirdparty/highlight.js/highlight.min.js"),
Expand All @@ -49,10 +50,30 @@ define(function (require, exports, module) {
const EVENT_GET_CONTENT = 'GET_CONTENT';
const EVENT_TAB_ONLINE = 'TAB_ONLINE';
const EVENT_REPORT_ERROR = 'REPORT_ERROR';
const EVENT_UPDATE_TITLE_ICON = 'UPDATE_TITLE_AND_ICON';

EventDispatcher.makeEventDispatcher(exports);
const PHCODE_LIVE_PREVIEW_QUERY_PARAM = "phcodeLivePreview";

const LOADER_BROADCAST_ID = `live-preview-loader-${Phoenix.PHOENIX_INSTANCE_ID}`;
const navigatorChannel = new BroadcastChannel(LOADER_BROADCAST_ID);

const livePreviewTabs = new Map();
navigatorChannel.onmessage = (event) => {
window.logger.livePreview.log("Live Preview navigator channel: Phoenix received event from tab: ", event);
const type = event.data.type;
switch (type) {
case 'TAB_LOADER_ONLINE':
livePreviewTabs.set(event.data.pageLoaderID, {
lastSeen: new Date(),
URL: event.data.URL,
navigationTab: true
});
return;
default: return; // ignore messages not intended for us.
}
};

const LIVE_PREVIEW_MESSENGER_CHANNEL = `live-preview-messenger-${Phoenix.PHOENIX_INSTANCE_ID}`;
const livePreviewChannel = new BroadcastChannel(LIVE_PREVIEW_MESSENGER_CHANNEL);

Expand Down Expand Up @@ -459,7 +480,6 @@ define(function (require, exports, module) {
});
});

const livePreviewTabs = new Map();
exports.on(EVENT_TAB_ONLINE, function(_ev, event){
livePreviewTabs.set(event.data.message.clientID, {
lastSeen: new Date(),
Expand All @@ -472,10 +492,15 @@ define(function (require, exports, module) {
setInterval(()=>{
let endTime = new Date();
for(let tab of livePreviewTabs.keys()){
let timeDiff = endTime - livePreviewTabs.get(tab).lastSeen; // in ms
const tabInfo = livePreviewTabs.get(tab);
let timeDiff = endTime - tabInfo.lastSeen; // in ms
if(timeDiff > TAB_HEARTBEAT_TIMEOUT){
livePreviewTabs.delete(tab);
exports.trigger('BROWSER_CLOSE', { data: { message: {clientID: tab}}});
// the parent navigationTab `phcode.dev/live-preview-loader.html` which loads the live preview tab also
// is in this list. We should not raise browser close event if its just a live-preview-loader tab.
if(!tabInfo.navigationTab) {
exports.trigger('BROWSER_CLOSE', { data: { message: {clientID: tab}}});
}
}
}
}, 1000);
Expand All @@ -498,9 +523,50 @@ define(function (require, exports, module) {
_sendToLivePreviewServerTabs(message);
}

function redirectAllTabs(newURL) {
navigatorChannel.postMessage({
type: 'REDIRECT_PAGE',
url: newURL
});
}

function _projectOpened(_evt, projectRoot) {
navigatorChannel.postMessage({
type: 'PROJECT_SWITCH',
projectRoot: projectRoot.fullPath
});
}

exports.on(EVENT_UPDATE_TITLE_ICON, function(_ev, event){
const title = event.data.message.title;
const faviconBase64 = event.data.message.faviconBase64;
navigatorChannel.postMessage({
type: 'UPDATE_TITLE_ICON',
title,
faviconBase64
});
});

ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN, _projectOpened);

function getTabPopoutURL(url) {
let openURL = new URL(url);
// we tag all externally opened urls with query string parameter phcodeLivePreview="true" to address
// #LIVE_PREVIEW_TAB_NAVIGATION_RACE_FIX
openURL.searchParams.set(StaticServer.PHCODE_LIVE_PREVIEW_QUERY_PARAM, "true");
return utils.getPageLoaderURL(openURL.href);
}

function hasActiveLivePreviews() {
return livePreviewTabs.size > 0;
}

LiveDevelopment.setLivePreviewTransportBridge(exports);
exports.StaticServer = StaticServer;
exports.messageToLivePreviewTabs = messageToLivePreviewTabs;
exports.livePreviewTabs = livePreviewTabs;
exports.redirectAllTabs = redirectAllTabs;
exports.getTabPopoutURL = getTabPopoutURL;
exports.hasActiveLivePreviews = hasActiveLivePreviews;
exports.PHCODE_LIVE_PREVIEW_QUERY_PARAM = PHCODE_LIVE_PREVIEW_QUERY_PARAM;
});
78 changes: 10 additions & 68 deletions src/extensions/default/Phoenix-live-preview/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ define(function (require, exports, module) {
Metrics = brackets.getModule("utils/Metrics"),
LiveDevelopment = brackets.getModule("LiveDevelopment/main"),
LiveDevServerManager = brackets.getModule("LiveDevelopment/LiveDevServerManager"),
StaticServer = require("StaticServer"),
NativeApp = brackets.getModule("utils/NativeApp"),
StaticServer = require("StaticServer"),
utils = require('utils');

const LIVE_PREVIEW_PANEL_ID = "live-preview-panel",
IFRAME_EVENT_SERVER_READY = 'SERVER_READY';
const EVENT_UPDATE_TITLE_ICON = 'UPDATE_TITLE_AND_ICON';
let serverReady = false;
const LIVE_PREVIEW_IFRAME_HTML = `
<iframe id="panel-live-preview-frame" title="Live Preview" style="border: none"
Expand All @@ -70,36 +70,6 @@ define(function (require, exports, module) {
</iframe>
`;

const LOADER_BROADCAST_ID = `live-preview-loader-${Phoenix.PHOENIX_INSTANCE_ID}`;
const navigatorChannel = new BroadcastChannel(LOADER_BROADCAST_ID);

const livePreviewTabs = new Map();
navigatorChannel.onmessage = (event) => {
window.logger.livePreview.log("Live Preview navigator channel: Phoenix received event from tab: ", event);
const type = event.data.type;
switch (type) {
case 'TAB_LOADER_ONLINE':
livePreviewTabs.set(event.data.pageLoaderID, {
lastSeen: new Date(),
URL: event.data.URL
});
return;
default: return; // ignore messages not intended for us.
}
};

// If we didn't receive heartbeat message from a tab for 10 seconds, we assume tab closed
const TAB_HEARTBEAT_TIMEOUT = 10000; // in millis secs
setInterval(()=>{
let endTime = new Date();
for(let tab of livePreviewTabs.keys()){
let timeDiff = endTime - livePreviewTabs.get(tab).lastSeen; // in ms
if(timeDiff > TAB_HEARTBEAT_TIMEOUT){
livePreviewTabs.delete(tab);
}
}
}, 1000);

ExtensionInterface.registerExtensionInterface(
ExtensionInterface._DEFAULT_EXTENSIONS_INTERFACE_NAMES.PHOENIX_LIVE_PREVIEW, exports);

Expand Down Expand Up @@ -164,7 +134,7 @@ define(function (require, exports, module) {
LiveDevelopment.closeLivePreview();
LiveDevelopment.openLivePreview();
} else if(!visible && LiveDevelopment.isActive()
&& StaticServer.livePreviewTabs.size === 0 && livePreviewTabs.size === 0) {
&& !StaticServer.hasActiveLivePreviews()) {
LiveDevelopment.closeLivePreview();
}
}
Expand Down Expand Up @@ -201,25 +171,10 @@ define(function (require, exports, module) {
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "HighlightBtn", "click");
}

function _getTabNavigationURL(url) {
let openURL = new URL(url);
// we tag all externally opened urls with query string parameter phcodeLivePreview="true" to address
// #LIVE_PREVIEW_TAB_NAVIGATION_RACE_FIX
openURL.searchParams.set(StaticServer.PHCODE_LIVE_PREVIEW_QUERY_PARAM, "true");
return utils.getPageLoaderURL(openURL.href);
}

function _redirectAllTabs(newURL) {
navigatorChannel.postMessage({
type: 'REDIRECT_PAGE',
url: newURL
});
}

function _popoutLivePreview() {
// We cannot use $iframe.src here if panel is hidden
const openURL = _getTabNavigationURL(currentLivePreviewURL);
open(openURL, "livePreview", "noopener,noreferrer");
const openURL = StaticServer.getTabPopoutURL(currentLivePreviewURL);
NativeApp.openURLInDefaultBrowser(openURL, "livePreview");
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "popoutBtn", "click");
_loadPreview(true);
_setPanelVisibility(false);
Expand Down Expand Up @@ -290,7 +245,7 @@ define(function (require, exports, module) {
async function _loadPreview(force) {
// we wait till the first server ready event is received till we render anything. else a 404-page may
// briefly flash on first load of phoenix as we try to load the page before the server is available.
const isPreviewLoadable = serverReady && (panel.isVisible() || StaticServer.livePreviewTabs.size > 0 || livePreviewTabs.size > 0);
const isPreviewLoadable = serverReady && (panel.isVisible() || StaticServer.hasActiveLivePreviews());
if(!isPreviewLoadable){
return;
}
Expand All @@ -314,7 +269,7 @@ define(function (require, exports, module) {
}
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "render",
utils.getExtension(previewDetails.fullPath));
_redirectAllTabs(newSrc);
StaticServer.redirectAllTabs(newSrc);
}

async function _projectFileChanges(evt, changedFile) {
Expand All @@ -331,11 +286,7 @@ define(function (require, exports, module) {
}

let livePreviewEnabledOnProjectSwitch = false;
async function _projectOpened(_evt, projectRoot) {
navigatorChannel.postMessage({
type: 'PROJECT_SWITCH',
projectRoot: projectRoot.fullPath
});
async function _projectOpened(_evt) {
if(urlPinned){
_togglePinUrl();
}
Expand All @@ -353,7 +304,7 @@ define(function (require, exports, module) {

function _activeDocChanged() {
if(!LiveDevelopment.isActive() && !livePreviewEnabledOnProjectSwitch
&& (panel.isVisible() || StaticServer.livePreviewTabs.size > 0 || livePreviewTabs.size > 0)) {
&& (panel.isVisible() || StaticServer.hasActiveLivePreviews())) {
// we do this only once after project switch if live preview for a doc is not active.
LiveDevelopment.closeLivePreview();
LiveDevelopment.openLivePreview();
Expand Down Expand Up @@ -423,19 +374,10 @@ define(function (require, exports, module) {
serverReady = true;
_loadPreview(true);
});
StaticServer.on(EVENT_UPDATE_TITLE_ICON, function(_ev, event){
const title = event.data.message.title;
const faviconBase64 = event.data.message.faviconBase64;
navigatorChannel.postMessage({
type: 'UPDATE_TITLE_ICON',
title,
faviconBase64
});
});

let consecutiveEmptyClientsCount = 0;
setInterval(()=>{
if(StaticServer.livePreviewTabs.size === 0 && livePreviewTabs.size === 0){
if(!StaticServer.hasActiveLivePreviews()){
consecutiveEmptyClientsCount ++;
} else {
consecutiveEmptyClientsCount = 0;
Expand Down
4 changes: 2 additions & 2 deletions src/phoenix/shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,10 @@ Phoenix.app = {
.catch(reject);
});
},
openURLInDefaultBrowser: function (url){
openURLInDefaultBrowser: function (url, tabIdentifier='_blank'){
return new Promise((resolve, reject)=>{
if(!window.__TAURI__) {
resolve(window.open(url, '_blank', 'noopener,noreferrer'));
resolve(window.open(url, tabIdentifier, 'noopener,noreferrer'));
return;
}
if( !(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) ) {
Expand Down
9 changes: 6 additions & 3 deletions src/utils/NativeApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,13 @@ define(function (require, exports, module) {
}

/**
* Opens a URL in the system default browser
* Opens a URL in the system default browser.
* @param {string} url
* @param {string?} tabIdentifier - An optional tab identifier can be set to group the tabs. Maps to target option
* in browser. Doesn't do anything in tauri.
*/
function openURLInDefaultBrowser(url) {
brackets.app.openURLInDefaultBrowser(url);
function openURLInDefaultBrowser(url, tabIdentifier) {
brackets.app.openURLInDefaultBrowser(url, tabIdentifier);
}

function getApplicationSupportDirectory() {
Expand Down
Loading