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

Replace localstorage with phstore wherever strictly required #1256

Merged
merged 4 commits into from
Dec 28, 2023
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
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ module.exports = {
"$": false,
"brackets": false,
"Phoenix": false,
"PhStore": false,
"iconv": false,
"Buffer": true,
"clearTimeout": false,
Expand Down
10 changes: 5 additions & 5 deletions src/assets/new-project/assets/js/code-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,20 +122,20 @@ function removeProject(fullPath) {
}

function _showFirstTimeExperience() {
let shownBefore = localStorage.getItem('notification.defaultProject.Shown');
let shownBefore = PhStore.getItem('notification.defaultProject.Shown');
if(!shownBefore){
createNotificationFromTemplate(Strings.DEFAULT_PROJECT_NOTIFICATION,
"defaultProjectButton", {
allowedPlacements: ["left", "right"],
autoCloseTimeS: 15,
dismissOnClick: true
});
localStorage.setItem('notification.defaultProject.Shown', 'true');
PhStore.setItem('notification.defaultProject.Shown', 'true');
}
}

function _updateDropdown() {
let shouldShowWelcome = localStorage.getItem("new-project.showWelcomeScreen") || 'Y';
let shouldShowWelcome = PhStore.getItem("new-project.showWelcomeScreen") || 'Y';
if(shouldShowWelcome === 'Y') {
document.getElementById("showWelcomeIndicator").style = "visibility: visible";
} else {
Expand All @@ -158,9 +158,9 @@ function _attachSettingBtnEventListeners() {
});

document.getElementById("showWelcome").addEventListener('click', (event)=>{
let shouldShowWelcome = localStorage.getItem("new-project.showWelcomeScreen") || 'Y';
let shouldShowWelcome = PhStore.getItem("new-project.showWelcomeScreen") || 'Y';
shouldShowWelcome = shouldShowWelcome === 'Y'? 'N' : 'Y';
localStorage.setItem("new-project.showWelcomeScreen", shouldShowWelcome);
PhStore.setItem("new-project.showWelcomeScreen", shouldShowWelcome);
});

document.getElementById("showAbout").addEventListener('click', (event)=>{
Expand Down
1 change: 1 addition & 0 deletions src/assets/new-project/assets/js/phoenix.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const RECENT_PROJECTS_INTERFACE = "Extn.Phoenix.recentProjects";
const selfFileName = location.href.split('?')[0].split('/').pop();
window.Strings = window.parent.Strings;
window.path = window.parent.path;
window.PhStore = window.parent.PhStore;
window.parent.ExtensionInterface.waitAndGetExtensionInterface(NEW_PROJECT_EXTENSION_INTERFACE)
.then(interfaceObj => {
window.newProjectExtension = interfaceObj;
Expand Down
3 changes: 1 addition & 2 deletions src/brackets.js
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,7 @@ define(function (require, exports, module) {

// Load default languages and preferences
Async.waitForAll([LanguageManager.ready, PreferencesManager.ready]).always(function () {
Promise.all([window._phoenixfsAppDirsCreatePromise, window.PhStore.storageReadyPromise])
.finally(_startupBrackets);
window._phoenixfsAppDirsCreatePromise.finally(_startupBrackets);
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/extensibility/Package.js
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +367,14 @@ define(function (require, exports, module) {
* function manages state weather an extension is enabled or disabled
*/
function _toggleDisabledExtension(path, enabled) {
let arr = JSON.parse(localStorage.getItem(DISABLED_EXTENSIONS_KEY) || "[]");
let arr = JSON.parse(PhStore.getItem(DISABLED_EXTENSIONS_KEY) || "[]");
const io = arr.indexOf(path);
if (enabled === true && io !== -1) {
arr.splice(io, 1);
} else if (enabled === false && io === -1) {
arr.push(path);
}
localStorage.setItem(DISABLED_EXTENSIONS_KEY, JSON.stringify(arr));
PhStore.setItem(DISABLED_EXTENSIONS_KEY, JSON.stringify(arr));
}

/**
Expand Down
22 changes: 11 additions & 11 deletions src/extensions/default/Phoenix/guided-tour.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ define(function (require, exports, module) {
TWO_WEEKS_IN_DAYS = 14,
USAGE_COUNTS_KEY = "healthDataUsage"; // private to phoenix, set from health data extension

const userAlreadyDidAction = localStorage.getItem(GUIDED_TOUR_LOCAL_STORAGE_KEY)
? JSON.parse(localStorage.getItem(GUIDED_TOUR_LOCAL_STORAGE_KEY)) : {
const userAlreadyDidAction = PhStore.getItem(GUIDED_TOUR_LOCAL_STORAGE_KEY)
? JSON.parse(PhStore.getItem(GUIDED_TOUR_LOCAL_STORAGE_KEY)) : {
version: 1,
newProjectShown: false,
beautifyCodeShown: false,
Expand Down Expand Up @@ -85,7 +85,7 @@ define(function (require, exports, module) {
let keyboardShortcut = KeyBindingManager.getKeyBindings(Commands.EDIT_BEAUTIFY_CODE);
keyboardShortcut = (keyboardShortcut && keyboardShortcut[0]) ? keyboardShortcut[0].displayKey : "-";
userAlreadyDidAction.beautifyCodeShown = true;
localStorage.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
PhStore.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
Metrics.countEvent(Metrics.EVENT_TYPE.UI, "guide", "beautify");
currentlyShowingNotification = NotificationUI.createFromTemplate(
StringUtils.format(Strings.BEAUTIFY_CODE_NOTIFICATION, keyboardShortcut),
Expand Down Expand Up @@ -115,7 +115,7 @@ define(function (require, exports, module) {
return;
}
userAlreadyDidAction.newProjectShown = true;
localStorage.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
PhStore.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
Metrics.countEvent(Metrics.EVENT_TYPE.UI, "guide", "newProj");
currentlyShowingNotification = NotificationUI.createFromTemplate(Strings.NEW_PROJECT_NOTIFICATION,
"newProject", {
Expand All @@ -138,7 +138,7 @@ define(function (require, exports, module) {
function _showNotification() {
// legacy key. cant change without triggering the user base
let notificationKey = 'livePreviewPopoutShown', version = "v1";
let popoutMessageShown = localStorage.getItem(notificationKey);
let popoutMessageShown = PhStore.getItem(notificationKey);
if(popoutMessageShown === version){
// already shown
LiveDevelopment.off(LiveDevelopment.EVENT_LIVE_PREVIEW_CLICKED, _showNotification);
Expand All @@ -158,7 +158,7 @@ define(function (require, exports, module) {
currentlyShowingNotification.done(()=>{
currentlyShowingNotification = null;
});
localStorage.setItem(notificationKey, version);
PhStore.setItem(notificationKey, version);
}
LiveDevelopment.off(LiveDevelopment.EVENT_LIVE_PREVIEW_CLICKED, _showNotification);
}
Expand All @@ -171,7 +171,7 @@ define(function (require, exports, module) {
function _showLivePreviewNotification() {
// legacy reasons live preview notification is called new project notification.
const livePreviewNotificationKey = "newProjectNotificationShown";
const livePreviewNotificationShown = localStorage.getItem(livePreviewNotificationKey);
const livePreviewNotificationShown = PhStore.getItem(livePreviewNotificationKey);
if(livePreviewNotificationShown){
return;
}
Expand All @@ -185,7 +185,7 @@ define(function (require, exports, module) {
autoCloseTimeS: 15,
dismissOnClick: true}
);
localStorage.setItem(livePreviewNotificationKey, "true");
PhStore.setItem(livePreviewNotificationKey, "true");
currentlyShowingNotification.done(()=>{
currentlyShowingNotification = null;
});
Expand Down Expand Up @@ -262,7 +262,7 @@ define(function (require, exports, module) {
Metrics.countEvent(Metrics.EVENT_TYPE.USER, "notify", "star", 1);
_openStarsPopup();
userAlreadyDidAction.lastShownGithubStarsDate = Date.now();
localStorage.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
PhStore.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
}, GITHUB_STARS_POPUP_TIME);
}
}
Expand All @@ -278,7 +278,7 @@ define(function (require, exports, module) {
Metrics.countEvent(Metrics.EVENT_TYPE.USER, "survey", "generalShown", 1);
Dialogs.showModalDialogUsingTemplate(Mustache.render(SurveyTemplate, templateVars));
userAlreadyDidAction.generalSurveyShownVersion = surveyVersion;
localStorage.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
PhStore.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
}
}, GENERAL_SURVEY_TIME);
}
Expand Down Expand Up @@ -326,7 +326,7 @@ define(function (require, exports, module) {
$content.find("a").click(_openPowerUserSurvey);
NotificationUI.createToastFromTemplate(Strings.POWER_USER_POPUP_TITLE, $content);
userAlreadyDidAction.lastShownPowerSurveyDate = Date.now();
localStorage.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
PhStore.setItem(GUIDED_TOUR_LOCAL_STORAGE_KEY, JSON.stringify(userAlreadyDidAction));
}, POWER_USER_SURVEY_TIME);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/default/Phoenix/new-project.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ define(function (require, exports, module) {

function init() {
_addMenuEntries();
const shouldShowWelcome = localStorage.getItem("new-project.showWelcomeScreen") || 'Y';
const shouldShowWelcome = PhStore.getItem("new-project.showWelcomeScreen") || 'Y';
if(shouldShowWelcome !== 'Y') {
Metrics.countEvent(Metrics.EVENT_TYPE.NEW_PROJECT, "dialogue", "disabled");
guidedTour.startTourIfNeeded();
Expand Down
17 changes: 15 additions & 2 deletions src/extensions/default/Phoenix/serverSync.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,24 @@ define(function (require, exports, module) {
let projectSyncCompleted = false;
let previewURL;

function _fixLegacyUserContext() {
// In earlier versions, user context data was stored in the browser's localStorage. We have since
// transitioned to using PhStore for this purpose. This function helps in migrating the user context
// from localStorage to PhStore. This ensures that existing users don't lose access to their published projects.
// Note: Published projects are retained for only 30 days. This function is primarily intended to support
// users during the transition period and is safe to remove 3 months after the date of this implementation,
// as users are informed that their published projects are kept for a 30-day period only.
if (!PhStore.getItem(USER_CONTEXT) && localStorage.getItem(USER_CONTEXT)) {
PhStore.setItem(USER_CONTEXT, localStorage.getItem(USER_CONTEXT));
}
}

function _setupUserContext() {
userContext = localStorage.getItem(USER_CONTEXT);
_fixLegacyUserContext();
userContext = PhStore.getItem(USER_CONTEXT);
if(!userContext){
userContext = "p-" + Math.round( Math.random()*10000000000000).toString(16);
localStorage.setItem(USER_CONTEXT, userContext);
PhStore.setItem(USER_CONTEXT, userContext);
}
}

Expand Down
130 changes: 66 additions & 64 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,52 +19,6 @@
*
*/

/**
* The bootstrapping module for brackets. This module sets up the require
* configuration and loads the brackets module.
*/
require.config({
paths: {
"text": "thirdparty/text/text",
"i18n": "thirdparty/i18n/i18n",

// The file system implementation. Change this value to use different
// implementations (e.g. cloud-based storage).
"fileSystemImpl": "filesystem/impls/appshell/AppshellFileSystem",
"preact-compat": "thirdparty/preact-compat/preact-compat.min",
"preact": "thirdparty/preact/preact"
},
map: {
"*": {
"thirdparty/CodeMirror2": "thirdparty/CodeMirror",
"thirdparty/preact": "preact-compat",
"view/PanelManager": "view/WorkspaceManager" // For extension compatibility
}
},
waitSeconds: 60
});

if (window.location.search.indexOf("testEnvironment") > -1) {
require.config({
paths: {
"preferences/PreferencesImpl": "../test/TestPreferencesImpl"
},
locale: "en" // force English (US)
});
} else {
/**
* hack for r.js optimization, move locale to another config call
*
* Use custom brackets property until CEF sets the correct navigator.language
* NOTE: When we change to navigator.language here, we also should change to
* navigator.language in ExtensionLoader (when making require contexts for each
* extension).
*/
require.config({
locale: window.localStorage.getItem("locale") || window.navigator.language
});
}

/**
* global util to convert jquery/js promise to a js promise. This can be used as an adapter when you do not know if the
* promise in hand is a js or jquery deferred promise. This function will always return a normal js promise.
Expand Down Expand Up @@ -132,25 +86,73 @@ window.scriptObserver = new MutationObserver(callback);
// Start observing the target node for configured mutations
window.scriptObserver.observe(mainScripts, config);

define(function (require) {
window.PhStore.storageReadyPromise
.finally(()=>{
/**
* The bootstrapping module for brackets. This module sets up the require
* configuration and loads the brackets module.
*/
require.config({
paths: {
"text": "thirdparty/text/text",
"i18n": "thirdparty/i18n/i18n",

// The file system implementation. Change this value to use different
// implementations (e.g. cloud-based storage).
"fileSystemImpl": "filesystem/impls/appshell/AppshellFileSystem",
"preact-compat": "thirdparty/preact-compat/preact-compat.min",
"preact": "thirdparty/preact/preact"
},
map: {
"*": {
"thirdparty/CodeMirror2": "thirdparty/CodeMirror",
"thirdparty/preact": "preact-compat",
"view/PanelManager": "view/WorkspaceManager" // For extension compatibility
}
},
waitSeconds: 60
});

// Load compatibility shims--these need to load early, be careful moving this
// Event dispatcher must be loaded before worker comm https://github.com/phcode-dev/phoenix/pull/678
require(["utils/Metrics", "utils/Compatibility", "utils/EventDispatcher"], function () {
window.Metrics = require("utils/Metrics");
// Load the brackets module. This is a self-running module that loads and runs the entire application.
try{
require(["brackets"]);
} catch (err) {
// try a cache refresh (not a full reset). this will happen in the service worker in the background
window.refreshServiceWorkerCache && window.refreshServiceWorkerCache();
// metrics api might not be available here as we were seeing no metrics raised. Only bugsnag there.
window.logger && window.logger.reportError(err,
'Critical error when loading brackets. Trying to reload again.');
// wait for 3 seconds for bugsnag to send report.
setTimeout(window.location.reload, 3000);
if (window.location.search.indexOf("testEnvironment") > -1) {
require.config({
paths: {
"preferences/PreferencesImpl": "../test/TestPreferencesImpl"
},
locale: "en" // force English (US)
});
} else {
/**
* hack for r.js optimization, move locale to another config call
*
* Use custom brackets property until CEF sets the correct navigator.language
* NOTE: When we change to navigator.language here, we also should change to
* navigator.language in ExtensionLoader (when making require contexts for each
* extension).
*/
require.config({
locale: window.PhStore.getItem("locale") || window.navigator.language
});
}
});
});

define(function (require) {


// Load compatibility shims--these need to load early, be careful moving this
// Event dispatcher must be loaded before worker comm https://github.com/phcode-dev/phoenix/pull/678
require(["utils/Metrics", "utils/Compatibility", "utils/EventDispatcher"], function () {
window.Metrics = require("utils/Metrics");
// Load the brackets module. This is a self-running module that loads and runs the entire application.
try{
require(["brackets"]);
} catch (err) {
// try a cache refresh (not a full reset). this will happen in the service worker in the background
window.refreshServiceWorkerCache && window.refreshServiceWorkerCache();
// metrics api might not be available here as we were seeing no metrics raised. Only bugsnag there.
window.logger && window.logger.reportError(err,
'Critical error when loading brackets. Trying to reload again.');
// wait for 3 seconds for bugsnag to send report.
setTimeout(window.location.reload, 3000);
}
});
});
});
3 changes: 3 additions & 0 deletions src/node-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -592,11 +592,14 @@ function nodeLoader() {
let commandID = 0, pendingCommands = {};
const PHNODE_PREFERENCES_KEY = "PhNode.Prefs";
function setInspectEnabled(enabled) {
// cannot use PhStore instead of localStorage here as this is required at boot. Should be fine
// as this to use non-persistent local storage(due to safari ITP) here as this is a debug flag.
const prefs = JSON.parse(localStorage.getItem(PHNODE_PREFERENCES_KEY) || "{}");
prefs.inspectEnabled = enabled;
localStorage.setItem(PHNODE_PREFERENCES_KEY, JSON.stringify(prefs));
}
function isInspectEnabled() {
// cannot use PhStore instead of localStorage here as this is required at boot.
const prefs = JSON.parse(localStorage.getItem(PHNODE_PREFERENCES_KEY) || "{}");
return !!prefs.inspectEnabled;
}
Expand Down
Loading
Loading