Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

⚑ Performance, functionality and robustness work for multi-config editing

Alicia Sykes4b7644721c0a
diff --git a/src/assets/locales/en.json b/src/assets/locales/en.json
index bd90edd6..389fce89 100644
--- a/src/assets/locales/en.json
+++ b/src/assets/locales/en.json
@@ -291,6 +291,7 @@
"edit-app-config-tooltip": "All other app configuration options",
"edit-pages-btn": "Edit Pages",
"edit-pages-tooltip": "Add or remove additional views",
+ "edit-pages-subconfig-disabled": "Pages can only be edited from the root config",
"config-save-methods-subheading": "Config Saving Options",
"save-locally-btn": "Save Locally",
"save-locally-tooltip": "Save config locally, to browser storage. This will not affect your config file, but changes will only be saved on this device",
@@ -304,6 +305,7 @@
"edit-raw-config-tooltip": "View and modify raw config via JSON editor",
"cancel-changes-btn": "Cancel Edit",
"cancel-changes-tooltip": "Reset current modifications, and exit Edit Mode. This will not affect your saved config",
+ "leave-while-editing-confirm": "You have unsaved changes. Leave this page and discard them?",
"edit-mode-name": "Edit Mode",
"edit-mode-subtitle": "You are in Edit Mode",
"edit-mode-description": "This means you can make modifications to your config, and preview the results, but until you save, none of your changes will be preserved.",
diff --git a/src/components/Configuration/CloudBackupRestore.vue b/src/components/Configuration/CloudBackupRestore.vue
index 6863fdd3..0f7dd4f3 100644
--- a/src/components/Configuration/CloudBackupRestore.vue
+++ b/src/components/Configuration/CloudBackupRestore.vue
@@ -76,8 +76,10 @@ import IconRestore from '@/assets/interface-icons/config-restore.svg';
export default {
name: 'CloudBackupRestore',
computed: {
- config() { // Users config from store
- return this.$store.state.config;
+ // Back up the active page's OWN config (partial for sub-pages, full for root)
+ // so a restored sub-page file doesn't pin root's inherited values.
+ config() {
+ return this.$store.state.configSource;
},
},
data() {
diff --git a/src/components/Configuration/ConfigContainer.vue b/src/components/Configuration/ConfigContainer.vue
index d85dfb94..93d919f1 100644
--- a/src/components/Configuration/ConfigContainer.vue
+++ b/src/components/Configuration/ConfigContainer.vue
@@ -193,7 +193,7 @@ export default {
openEditCssTab() {
this.navigateToTab(3);
},
- /* Checks that the user is sure, then resets site-wide local storage, and reloads page */
+ /* Checks that the user is sure, then resets site-wide local storage, and reloads current page */
resetLocalSettings() {
const msg = `${this.$t('config.reset-config-msg-l1')} `
+ `${this.$t('config.reset-config-msg-l2')}\n\n${this.$t('config.reset-config-msg-l3')}`;
@@ -201,7 +201,7 @@ export default {
if (isTheUserSure) {
localStorage.clear();
this.$toast(this.$t('config.data-cleared-msg'));
- this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG);
+ this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG, this.$store.state.currentConfigInfo.confId);
}
},
getLanguage() {
diff --git a/src/components/Configuration/JsonEditor.vue b/src/components/Configuration/JsonEditor.vue
index 93494d97..2fe95a2d 100644
--- a/src/components/Configuration/JsonEditor.vue
+++ b/src/components/Configuration/JsonEditor.vue
@@ -177,7 +177,8 @@ export default {
};
},
computed: {
- config() { return this.$store.state.config; },
+ // Uses full config for root page, partial config for sub-pages, Dashy still reads full/merged conf
+ editorSource() { return this.$store.state.configSource; },
// Used to prevent preview/save on invalid YAML
isValid() { return !this.errorMessages.some((e) => e.type === 'error'); },
// For chip to show "valid", "warnings", "error"
@@ -214,9 +215,13 @@ export default {
},
methods: {
initialText() {
- const data = { ...this.config };
+ const src = this.editorSource || {};
+ const data = { ...src };
data.sections = (data.sections || []).map(({ filteredItems: _filteredItems, ...s }) => s);
- if (!data.pageInfo) data.pageInfo = { title: 'Dashy' };
+ const { confId } = this.$store.state.currentConfigInfo;
+ // Root config always has a pageInfo; show a sensible default if missing.
+ // Sub-pages can legitimately have an empty pageInfo (they inherit from root).
+ if (!confId && !data.pageInfo) data.pageInfo = { title: 'Dashy' };
return jsYaml.dump(data, DUMP_OPTS);
},
createEditor() {
@@ -321,26 +326,18 @@ export default {
if (data == null) return;
const ok = await this.writeConfigToDisk(data);
if (!ok) return;
- this.$store.commit(StoreKeys.SET_PAGE_INFO, data.pageInfo);
- this.$store.commit(StoreKeys.SET_SECTIONS, data.sections);
- this.$store.commit(StoreKeys.SET_PAGES, data.pages || []);
+ this.applyConfigToStore(data);
},
onSaveLocally() {
const data = this.parseCurrent();
if (data == null) return;
// eslint-disable-next-line no-alert, no-restricted-globals
- if (confirm(this.$t('interactive-editor.menu.save-locally-warning'))) {
- this.saveConfigLocally(data);
- }
+ if (!confirm(this.$t('interactive-editor.menu.save-locally-warning'))) return;
+ this.saveConfigLocally(data);
+ this.applyConfigToStore(data);
},
- // Commits a full parsed config object to the Vuex store (preview / reset).
- // Each top-level section is only committed when present, so a user saving
- // a YAML that omits e.g. `appConfig:` can't nuke existing store state.
applyConfigToStore(data) {
- if (data.appConfig !== undefined) this.$store.commit(StoreKeys.SET_APP_CONFIG, data.appConfig);
- if (data.pageInfo !== undefined) this.$store.commit(StoreKeys.SET_PAGE_INFO, data.pageInfo);
- if (data.sections !== undefined) this.$store.commit(StoreKeys.SET_SECTIONS, data.sections);
- this.$store.commit(StoreKeys.SET_PAGES, data.pages || []);
+ this.$store.dispatch(StoreKeys.APPLY_EDITED_CONFIG, data);
},
onPreview() {
const data = this.parseCurrent();
diff --git a/src/components/InteractiveEditor/EditAppConfig.vue b/src/components/InteractiveEditor/EditAppConfig.vue
index 085125c4..596ef0b3 100644
--- a/src/components/InteractiveEditor/EditAppConfig.vue
+++ b/src/components/InteractiveEditor/EditAppConfig.vue
@@ -1,6 +1,6 @@
<template>
<modal
- :name="modalName" @closed="modalClosed"
+ :name="modalName" @closed="modalClosed" @before-open="initForm"
:resizable="true" width="50%" height="80%"
classes="dashy-modal edit-app-config"
>
@@ -46,16 +46,19 @@ export default {
};
},
computed: {
- appConfig() { return this.$store.getters.appConfig; },
+ // Read root appConfig, for partial sub-pages to inherit from
+ ownAppConfig() { return this.$store.state.configSource.appConfig || {}; },
allowViewConfig() { return this.$store.getters.permissions.allowViewConfig; },
},
- mounted() {
- this.formData = safeClone(this.appConfig, {});
- },
methods: {
+ // Re-runs on each modal open so the forms reflects changes made elsewhere
+ initForm() {
+ this.formData = safeClone(this.ownAppConfig, {});
+ },
saveToState() {
try {
- this.$store.commit(StoreKeys.SET_APP_CONFIG, this.formData);
+ const patched = { ...this.$store.state.configSource, appConfig: this.formData };
+ this.$store.dispatch(StoreKeys.APPLY_EDITED_CONFIG, patched);
this.$store.commit(StoreKeys.SET_EDIT_MODE, true);
InfoHandler('App config updated', InfoKeys.EDITOR);
this.cancelEditing();
diff --git a/src/components/InteractiveEditor/EditModeSaveMenu.vue b/src/components/InteractiveEditor/EditModeSaveMenu.vue
index 53f4dc02..74fd49be 100644
--- a/src/components/InteractiveEditor/EditModeSaveMenu.vue
+++ b/src/components/InteractiveEditor/EditModeSaveMenu.vue
@@ -46,11 +46,13 @@
{{ $t('interactive-editor.menu.edit-app-config-btn') }}
<AppConfigIcon />
</Button>
- <!-- Button to open pages editor -->
+ <!-- Button to open pages editor (only if not on sub-page rn) -->
<Button
:click="openEditMultiPages"
- :disallow="!permissions.allowViewConfig"
- v-tooltip="tooltip($t('interactive-editor.menu.edit-pages-tooltip'))"
+ :disallow="!permissions.allowViewConfig || isSubConfig"
+ v-tooltip="tooltip($t(isSubConfig
+ ? 'interactive-editor.menu.edit-pages-subconfig-disabled'
+ : 'interactive-editor.menu.edit-pages-tooltip'))"
>
{{ $t('interactive-editor.menu.edit-pages-btn') }}
<MultiPagesIcon />
@@ -142,8 +144,8 @@ export default {
AccessError,
},
computed: {
- config() {
- return this.$store.state.config;
+ configToSave() {
+ return this.$store.state.configSource;
},
permissions() {
// Returns: { allowWriteToDisk, allowSaveLocally, allowViewConfig }
@@ -152,10 +154,13 @@ export default {
showEditMsg() {
return this.permissions.allowWriteToDisk || this.permissions.allowSaveLocally;
},
+ isSubConfig() {
+ return this.$store.getters.isSubConfig;
+ },
},
methods: {
reset() {
- this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG);
+ this.$store.dispatch(StoreKeys.INITIALIZE_CONFIG, this.$store.state.currentConfigInfo.confId);
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
},
openExportConfigMenu() {
@@ -189,11 +194,11 @@ export default {
const msg = this.$t('interactive-editor.menu.save-locally-warning');
const youSure = confirm(msg); // eslint-disable-line no-alert, no-restricted-globals
if (youSure) {
- this.saveConfigLocally(this.config);
+ this.saveConfigLocally(this.configToSave);
}
},
writeToDisk() {
- this.writeConfigToDisk(this.config);
+ this.writeConfigToDisk(this.configToSave);
},
},
};
diff --git a/src/components/InteractiveEditor/EditMultiPages.vue b/src/components/InteractiveEditor/EditMultiPages.vue
index 1b6ee5eb..8265f554 100644
--- a/src/components/InteractiveEditor/EditMultiPages.vue
+++ b/src/components/InteractiveEditor/EditMultiPages.vue
@@ -1,6 +1,6 @@
<template>
<modal
- :name="modalName" @closed="modalClosed"
+ :name="modalName" @closed="modalClosed" @before-open="initForm"
:resizable="true" width="50%" height="80%"
classes="dashy-modal edit-multi-pages"
>
@@ -64,10 +64,11 @@ export default {
pages() { return this.$store.getters.pages; },
allowViewConfig() { return this.$store.getters.permissions.allowViewConfig; },
},
- mounted() {
- this.formData = safeClone(Array.isArray(this.pages) ? this.pages : [], []);
- },
methods: {
+ // Re-runs on each modal open so preview / save-locally elsewhere is reflected.
+ initForm() {
+ this.formData = safeClone(Array.isArray(this.pages) ? this.pages : [], []);
+ },
saveToState() {
try {
this.$store.commit(StoreKeys.SET_PAGES, this.formData);
diff --git a/src/components/InteractiveEditor/EditPageInfo.vue b/src/components/InteractiveEditor/EditPageInfo.vue
index 8f12a65a..c8c1d6df 100644
--- a/src/components/InteractiveEditor/EditPageInfo.vue
+++ b/src/components/InteractiveEditor/EditPageInfo.vue
@@ -1,6 +1,6 @@
<template>
<modal
- :name="modalName" @closed="modalClosed"
+ :name="modalName" @closed="modalClosed" @before-open="initForm"
:resizable="true" width="50%" height="80%"
classes="dashy-modal edit-page-info"
>
@@ -35,16 +35,17 @@ export default {
};
},
computed: {
- pageInfo() { return this.$store.getters.pageInfo; },
+ ownPageInfo() { return this.$store.state.configSource.pageInfo || {}; },
allowViewConfig() { return this.$store.getters.permissions.allowViewConfig; },
},
- mounted() {
- this.formData = safeClone(this.pageInfo, {});
- },
methods: {
+ initForm() {
+ this.formData = safeClone(this.ownPageInfo, {});
+ },
saveToState() {
try {
- this.$store.commit(StoreKeys.SET_PAGE_INFO, this.formData);
+ const patched = { ...this.$store.state.configSource, pageInfo: this.formData };
+ this.$store.dispatch(StoreKeys.APPLY_EDITED_CONFIG, patched);
this.$store.commit(StoreKeys.SET_EDIT_MODE, true);
InfoHandler('Page info updated', InfoKeys.EDITOR);
this.cancelEditing();
diff --git a/src/components/InteractiveEditor/ExportConfigMenu.vue b/src/components/InteractiveEditor/ExportConfigMenu.vue
index e25f7c79..5d25b13e 100644
--- a/src/components/InteractiveEditor/ExportConfigMenu.vue
+++ b/src/components/InteractiveEditor/ExportConfigMenu.vue
@@ -64,7 +64,7 @@ export default {
props: {},
computed: {
config() {
- return this.$store.state.config;
+ return this.$store.state.configSource;
},
allowViewConfig() {
return this.$store.getters.permissions.allowViewConfig;
diff --git a/src/components/PageStrcture/PageTitle.vue b/src/components/PageStrcture/PageTitle.vue
index ada571ad..b289f513 100644
--- a/src/components/PageStrcture/PageTitle.vue
+++ b/src/components/PageStrcture/PageTitle.vue
@@ -7,8 +7,7 @@
<h1>{{ title }}</h1>
<span class="subtitle">{{ description }}</span>
</div>
- <!-- When in edit mode, show Edit Title button -->
- <EditModeIcon v-if="isEditMode" @click="editTitle()"
+ <EditModeIcon v-if="isEditMode" @click.stop.prevent="editTitle()"
class="edit-icon" v-tooltip="tooltip()" />
</router-link>
</template>
diff --git a/src/main.js b/src/main.js
index 17acfb4b..6eee1495 100644
--- a/src/main.js
+++ b/src/main.js
@@ -1,7 +1,6 @@
/* eslint-disable no-multi-spaces */
// Import core framework and essential utils
import { createApp } from 'vue';
-import { createI18n } from 'vue-i18n';
// Import component Vue plugins, used throughout the app
import VModal from '@febe95/vue-js-modal'; // Modal component (Vue 3 fork)
@@ -13,11 +12,10 @@ import Dashy from '@/App.vue'; // Main Dashy Vue app
import store from '@/store'; // Store, for local state management
import router from '@/router'; // Router, for navigation
import serviceWorker from '@/utils/InitServiceWorker'; // Service worker initialization
-import { messages } from '@/utils/languages'; // Language texts
+import i18n from '@/utils/i18n'; // i18n instance (exported so non-component callers can t())
import ErrorReporting from '@/utils/logging/ErrorReporting'; // Error reporting initializer (off)
import clickOutside from '@/directives/ClickOutside'; // Directive for closing popups, modals, etc
import tooltip from '@/directives/Tooltip'; // Custom tooltip directive
-import { language as defaultLanguage } from '@/utils/config/defaults';
import { initKeycloakAuth, isKeycloakEnabled } from '@/utils/auth/KeycloakAuth';
import { initHeaderAuth, isHeaderAuthEnabled } from '@/utils/auth/HeaderAuth';
import { initOidcAuth, isOidcEnabled } from '@/utils/auth/OidcAuth';
@@ -26,14 +24,6 @@ import ErrorHandler from '@/utils/logging/ErrorHandler';
import Toast from '@/utils/Toast';
import '@/utils/patchResizeObserver';
-// Setup i18n translations
-const i18n = createI18n({
- legacy: true,
- locale: defaultLanguage,
- fallbackLocale: defaultLanguage,
- messages,
-});
-
// Create the Vue 3 app instance
const app = createApp(Dashy);
diff --git a/src/mixins/ConfigSaving.js b/src/mixins/ConfigSaving.js
index e28d186b..2a72605c 100644
--- a/src/mixins/ConfigSaving.js
+++ b/src/mixins/ConfigSaving.js
@@ -4,7 +4,7 @@ import request from '@/utils/request';
import ErrorHandler, { InfoHandler } from '@/utils/logging/ErrorHandler';
import { localStorageKeys, serviceEndpoints } from '@/utils/config/defaults';
-import { makePageName } from '@/utils/config/ConfigHelpers';
+import { makePageName, configScope, stripRootOwnedFields } from '@/utils/config/ConfigHelpers';
import StoreKeys from '@/utils/StoreMutations';
export default {
@@ -17,35 +17,29 @@ export default {
},
methods: {
writeConfigToDisk(config) {
- if (config.appConfig.preventWriteToDisk) {
- ErrorHandler('Unable to write changed to disk, as this functionality is disabled');
+ const { state } = this.$store;
+ if (state.config?.appConfig?.preventWriteToDisk) {
+ ErrorHandler('Unable to write changes to disk, as this functionality is disabled');
return Promise.resolve(false);
}
- // 1. Get the config, and strip appConfig if is sub-page
- const isSubPag = !!this.$store.state.currentConfigInfo.confId;
- const jsonConfig = config;
- jsonConfig.sections = jsonConfig.sections.map(({ filteredItems: _filteredItems, ...section }) => section);
- // If a sub-config, then remove appConfig, and check path isn't an external URL
- if (isSubPag) {
- delete jsonConfig.appConfig;
- if (this.$store.state.currentConfigInfo.confPath.includes('http')) {
- ErrorHandler('Cannot save to an external URL');
- return Promise.resolve(false);
- }
+ const isSubPag = !!state.currentConfigInfo.confId;
+ if (isSubPag && state.currentConfigInfo.confPath?.includes('http')) {
+ ErrorHandler('Cannot save to an external URL');
+ return Promise.resolve(false);
}
- // 2. Convert JSON into YAML
- const yamlOptions = {};
- const strjsonConfig = JSON.stringify(jsonConfig);
- const jsonObj = JSON.parse(strjsonConfig);
- const yaml = jsYaml.dump(jsonObj, yamlOptions);
- // 3. Prepare the request
+ // Strip runtime-only `filteredItems` and (for sub-pages) root-owned fields.
+ // Spread to avoid mutating the caller's object (may be state.configSource)
+ const base = isSubPag ? stripRootOwnedFields(config) : { ...(config || {}) };
+ const jsonConfig = {
+ ...base,
+ sections: (base.sections || []).map(({ filteredItems: _filteredItems, ...s }) => s),
+ };
+ const yaml = jsYaml.dump(JSON.parse(JSON.stringify(jsonConfig)));
const baseUrl = import.meta.env.VITE_APP_DOMAIN || window.location.origin;
const endpoint = `${baseUrl}${serviceEndpoints.save}`;
- const filename = isSubPag
- ? (this.$store.state.currentConfigInfo.confPath || '') : '';
+ const filename = isSubPag ? (state.currentConfigInfo.confPath || '') : '';
const body = { config: yaml, timestamp: new Date(), filename };
const saveRequest = request.post(endpoint, body);
- // 4. Make the request, and handle response
this.progress.start();
return saveRequest.then((response) => {
this.saveSuccess = response.data.success || false;
@@ -70,44 +64,46 @@ export default {
return false;
});
},
+ /* Persist the given config to localStorage under keys scoped to the active page */
saveConfigLocally(config) {
if (!this.permissions.allowSaveLocally) {
ErrorHandler('Unable to save changes locally, this feature has been disabled');
return;
}
+ const { confId } = this.$store.state.currentConfigInfo;
+ const scope = configScope(confId);
+ const clean = confId ? stripRootOwnedFields(config) : (config || {});
+ const appConfig = clean.appConfig || {};
- const isSubPag = !!this.$store.state.currentConfigInfo.confId;
- if (isSubPag) { // Save for sub-page only
- const configId = this.$store.state.currentConfigInfo.confId;
- const localStorageKeySections = `${localStorageKeys.CONF_SECTIONS}-${configId}`;
- const localStorageKeyPageInfo = `${localStorageKeys.PAGE_INFO}-${configId}`;
- localStorage.setItem(localStorageKeySections, JSON.stringify(config.sections));
- localStorage.setItem(localStorageKeyPageInfo, JSON.stringify(config.pageInfo));
- } else { // Or save to main config
- localStorage.setItem(localStorageKeys.CONF_SECTIONS, JSON.stringify(config.sections));
- localStorage.setItem(localStorageKeys.PAGE_INFO, JSON.stringify(config.pageInfo));
- localStorage.setItem(localStorageKeys.APP_CONFIG, JSON.stringify(config.appConfig));
+ localStorage.setItem(scope.APP_CONFIG, JSON.stringify(appConfig));
+ localStorage.setItem(scope.PAGE_INFO, JSON.stringify(clean.pageInfo || {}));
+ localStorage.setItem(scope.CONF_SECTIONS, JSON.stringify(clean.sections || []));
+ const setOrClear = (key, value) => {
+ if (value) localStorage.setItem(key, value);
+ else localStorage.removeItem(key);
+ };
+ setOrClear(scope.THEME, appConfig.theme);
+ setOrClear(scope.LAYOUT, appConfig.layout);
+ setOrClear(scope.ICON_SIZE, appConfig.iconSize);
+ setOrClear(scope.LANGUAGE, appConfig.language);
+ // pages is root-owned - only persisted from root context
+ if (!confId) {
+ localStorage.setItem(localStorageKeys.CONF_PAGES, JSON.stringify(clean.pages || []));
}
- if (config.appConfig.theme) {
- localStorage.setItem(localStorageKeys.THEME, config.appConfig.theme);
- }
InfoHandler('Config has successfully been saved in browser storage', 'Config Update');
this.showToast(this.$t('config-editor.success-msg-local'), true);
this.$store.commit(StoreKeys.SET_EDIT_MODE, false);
},
+ /* After a successful disk write clear local overrides */
carefullyClearLocalStorage() {
- // Delete the main keys
- localStorage.removeItem(localStorageKeys.PAGE_INFO);
- localStorage.removeItem(localStorageKeys.APP_CONFIG);
- localStorage.removeItem(localStorageKeys.CONF_SECTIONS);
+ const clearScope = (confId) => {
+ const s = configScope(confId);
+ Object.values(s).forEach((key) => localStorage.removeItem(key));
+ };
+ clearScope(null); // root
localStorage.removeItem(localStorageKeys.CONF_PAGES);
- // Then, if we've got any sub-pages, delete those too
- (this.$store.getters.pages || []).forEach((page) => {
- const pageId = makePageName(page.name);
- localStorage.removeItem(`${localStorageKeys.CONF_SECTIONS}-${pageId}`);
- localStorage.removeItem(`${localStorageKeys.PAGE_INFO}-${pageId}`);
- });
+ (this.$store.getters.pages || []).forEach((page) => clearScope(makePageName(page.name)));
},
},
};
diff --git a/src/router.js b/src/router.js
index 3b37770e..fffca35f 100644
--- a/src/router.js
+++ b/src/router.js
@@ -13,6 +13,7 @@ import Home from '@/views/Home.vue';
// Import helper functions, config data and defaults
import store from '@/store';
+import i18n from '@/utils/i18n';
import Keys from '@/utils/StoreMutations';
import { isAuthEnabled, isLoggedIn, isGuestAccessEnabled } from '@/utils/auth/Auth';
import { startingView as defaultStartingView, routePaths } from '@/utils/config/defaults';
@@ -121,8 +122,10 @@ const router = createRouter({
});
/**
- * On first page load, initialize and wait for the the config loading
- * Then, if auth enabled and user not logged in yet, redirect to login page
+ * On first page load, initialize and wait for the the config loading.
+ * Also guards against silently leaving an active edit session for a
+ * different config (unsaved edits would otherwise become untethered
+ * from whatever page the user switched to).
*/
router.beforeEach(async (to, from, next) => {
progress.start();
@@ -130,6 +133,20 @@ router.beforeEach(async (to, from, next) => {
if (!store.state.rootConfig && !store.state.criticalError) {
await store.dispatch(Keys.INITIALIZE_CONFIG);
}
+ // If in edit mode and navigating to a DIFFERENT page, confirm + cancel edit.
+ const pageChanged = from.params?.page !== to.params?.page;
+ if (store.state.editMode && pageChanged) {
+ // eslint-disable-next-line no-alert, no-restricted-globals
+ const ok = confirm(i18n.global.t('interactive-editor.menu.leave-while-editing-confirm'));
+ if (!ok) {
+ progress.end();
+ next(false);
+ return;
+ }
+ // Discard edits for the page we're leaving and exit edit mode.
+ await store.dispatch(Keys.INITIALIZE_CONFIG, store.state.currentConfigInfo.confId);
+ store.commit(Keys.SET_EDIT_MODE, false);
+ }
if (to.name !== 'login' && !isAuthenticated()) next({ name: 'login' });
else next();
} catch (e) {
diff --git a/src/store.js b/src/store.js
index 2ea0d8b5..b6972172 100644
--- a/src/store.js
+++ b/src/store.js
@@ -3,7 +3,9 @@ import { createStore } from 'vuex';
import yaml from 'js-yaml';
import request from '@/utils/request';
import Keys from '@/utils/StoreMutations';
-import { makePageName, formatConfigPath, componentVisibility } from '@/utils/config/ConfigHelpers';
+import {
+ makePageName, formatConfigPath, componentVisibility, configScope, stripRootOwnedFields,
+} from '@/utils/config/ConfigHelpers';
import { applyItemId } from '@/utils/config/SectionHelpers';
import filterUserSections from '@/utils/CheckSectionVisibility';
import ErrorHandler, { InfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';
@@ -19,6 +21,8 @@ const {
INITIALIZE_CONFIG,
INITIALIZE_ROOT_CONFIG,
SET_CONFIG,
+ SET_CONFIG_SOURCE,
+ APPLY_EDITED_CONFIG,
SET_ROOT_CONFIG,
SET_CURRENT_CONFIG_INFO,
SET_IS_USING_LOCAL_CONFIG,
@@ -52,43 +56,112 @@ const emptyConfig = {
sections: [],
};
-/* Merge any local overrides (written by "Save Locally") into a config object.
- * On sub-pages only `sections` + `pageInfo` are per-page; the rest are root-scoped. */
-function applyLocalOverrides(config, subConfigId) {
- const suffix = subConfigId ? `-${subConfigId}` : '';
- const read = (key) => {
- const raw = localStorage[`${key}${suffix}`];
- if (!raw) return undefined;
- try { return JSON.parse(raw); } catch (e) {
- ErrorHandler(`Malformed local config for '${key}${suffix}'`, e);
- return undefined;
- }
+/* Read + JSON-parse a raw localStorage slot, returning undefined on miss/fail. */
+const readLocal = (key) => {
+ const raw = localStorage.getItem(key);
+ if (!raw) return undefined;
+ try { return JSON.parse(raw); } catch (e) {
+ ErrorHandler(`Malformed local config for '${key}'`, e);
+ return undefined;
+ }
+};
+
+/* Write one top-level config field to both the merged runtime view (`config`)
+ * and the active page's source. Keeps the two from drifting.
+ * Item/widget `id`s are runtime-only β€” applied to `config` for rendering,
+ * kept out of `configSource` so they never land in persisted YAML. */
+const commitConfigField = (state, field, value) => {
+ const runtime = field === 'sections' ? applyItemId(value) : value;
+ state.config = { ...state.config, [field]: runtime };
+ state.configSource = { ...state.configSource, [field]: value };
+};
+
+/* Patch a single appConfig key. Optionally persists to a localStorage slot
+ * (used by the quick-pickers; omitted for pure runtime-state updates). */
+const patchAppConfigField = (state, key, value, storageKey) => {
+ state.config = { ...state.config, appConfig: { ...state.config.appConfig, [key]: value } };
+ state.configSource = {
+ ...state.configSource,
+ appConfig: { ...(state.configSource.appConfig || {}), [key]: value },
};
- let overridden = false;
- const localSections = read(localStorageKeys.CONF_SECTIONS);
- const localPageInfo = read(localStorageKeys.PAGE_INFO);
- if (Array.isArray(localSections) && localSections.length) {
- config.sections = localSections; overridden = true;
+ if (storageKey) localStorage.setItem(storageKey, value);
+};
+
+ /* Read locally saved configs/overrides from localStorage */
+function readLocalOverrides(subConfigId) {
+ const scope = configScope(subConfigId);
+ const own = {};
+ let hasStructural = false;
+
+ const localAppConfig = readLocal(scope.APP_CONFIG);
+ const localPageInfo = readLocal(scope.PAGE_INFO);
+ const localSections = readLocal(scope.CONF_SECTIONS);
+
+ const appConfig = {};
+ if (localAppConfig && typeof localAppConfig === 'object') {
+ Object.assign(appConfig, localAppConfig);
+ hasStructural = true;
}
+ // Quick-picker slots layer on top for normal local stuff
+ const theme = localStorage.getItem(scope.THEME);
+ const layout = localStorage.getItem(scope.LAYOUT);
+ const iconSize = localStorage.getItem(scope.ICON_SIZE);
+ const language = localStorage.getItem(scope.LANGUAGE);
+ if (theme) appConfig.theme = theme;
+ if (layout) appConfig.layout = layout;
+ if (iconSize) appConfig.iconSize = iconSize;
+ if (language) appConfig.language = language;
+ if (Object.keys(appConfig).length) own.appConfig = appConfig;
+
if (localPageInfo && typeof localPageInfo === 'object') {
- config.pageInfo = localPageInfo; overridden = true;
+ own.pageInfo = localPageInfo;
+ hasStructural = true;
+ }
+ if (Array.isArray(localSections) && localSections.length) {
+ own.sections = localSections;
+ hasStructural = true;
}
if (!subConfigId) {
- const localAppConfig = read(localStorageKeys.APP_CONFIG);
- const localPages = read(localStorageKeys.CONF_PAGES);
- if (localAppConfig && typeof localAppConfig === 'object') {
- config.appConfig = localAppConfig; overridden = true;
- }
+ const localPages = readLocal(localStorageKeys.CONF_PAGES);
if (Array.isArray(localPages)) {
- config.pages = localPages; overridden = true;
+ own.pages = localPages;
+ hasStructural = true;
}
}
- return overridden;
+ return { own, hasStructural };
+}
+
+/* Root config with its own local overrides layered on */
+function buildRootEffective(state) {
+ const root = state.rootConfig || {};
+ const { own } = readLocalOverrides(null);
+ return {
+ appConfig: { ...(root.appConfig || {}), ...(own.appConfig || {}) },
+ pageInfo: { ...(root.pageInfo || {}), ...(own.pageInfo || {}) },
+ sections: own.sections || root.sections || [],
+ pages: own.pages || root.pages || [],
+ };
+}
+
+/* Merges root config and sub-page config */
+function mergeWithRoot(root, own) {
+ const rootApp = root.appConfig || {};
+ const ownApp = own.appConfig || {};
+ const appConfig = { ...rootApp, ...ownApp };
+ if (rootApp.auth !== undefined) appConfig.auth = rootApp.auth;
+ else delete appConfig.auth;
+ return {
+ appConfig,
+ pageInfo: { ...(root.pageInfo || {}), ...(own.pageInfo || {}) },
+ sections: own.sections || [],
+ pages: root.pages || [],
+ };
}
const store = createStore({
state: {
- config: {}, // The current config being used, and rendered to the UI
+ config: {}, // The current config being used, and rendered to the UI (merged runtime view)
+ configSource: {}, // The current config as it appears in the file (before root merges)
rootConfig: null, // Always the content of main config file, never used directly
editMode: false, // While true, the user can drag and edit items + sections
modalOpen: false, // KB shortcut functionality will be disabled when modal is open
@@ -102,6 +175,12 @@ const store = createStore({
config(state) {
return state.config;
},
+ configSource(state) {
+ return state.configSource;
+ },
+ isSubConfig(state) {
+ return !!state.currentConfigInfo.confId;
+ },
pageInfo(state) {
if (!state.config) return {};
return state.config.pageInfo || {};
@@ -118,19 +197,16 @@ const store = createStore({
return state.config.pages || [];
},
theme(state) {
- const localStorageKey = state.currentConfigInfo.confId
- ? `${localStorageKeys.THEME}-${state.currentConfigInfo.confId}` : localStorageKeys.THEME;
// Read reactive deps upfront so Vuex tracks every branch (avoids the
// short-circuit caching bug where unread props wouldn't invalidate).
const cfg = state.config?.appConfig;
const configTheme = cfg?.theme;
const dayTheme = cfg?.dayTheme;
const nightTheme = cfg?.nightTheme;
- // Resolution: user's saved choice β†’ OS preference (if configured) β†’ config default
- const localTheme = localStorage[localStorageKey];
- if (localTheme) return localTheme;
const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;
- return (prefersDark ? nightTheme : dayTheme) || configTheme || defaultTheme;
+ const fromState = (prefersDark ? nightTheme : dayTheme) || configTheme || defaultTheme;
+ if (state.editMode) return fromState;
+ return localStorage.getItem(configScope(state.currentConfigInfo.confId).THEME) || fromState;
},
webSearch(state, getters) {
return getters.appConfig.webSearch || {};
@@ -174,6 +250,7 @@ const store = createStore({
return getters.sections[index];
},
getItemById: (state, getters) => (id) => {
+ if (!id) return undefined;
let item;
getters.sections.forEach(sec => {
if (sec.items) {
@@ -193,18 +270,16 @@ const store = createStore({
return foundSection;
},
layout(state) {
- const pageId = state.currentConfigInfo.confId;
- const layoutStoreKey = pageId
- ? `${localStorageKeys.LAYOUT_ORIENTATION}-${pageId}` : localStorageKeys.LAYOUT_ORIENTATION;
- const appConfigLayout = state.config.appConfig.layout;
- return localStorage.getItem(layoutStoreKey) || appConfigLayout || 'auto';
+ const scope = configScope(state.currentConfigInfo.confId);
+ const fromState = state.config.appConfig.layout || 'auto';
+ if (state.editMode) return fromState;
+ return localStorage.getItem(scope.LAYOUT) || fromState;
},
iconSize(state) {
- const pageId = state.currentConfigInfo.confId;
- const sizeStoreKey = pageId
- ? `${localStorageKeys.ICON_SIZE}-${pageId}` : localStorageKeys.ICON_SIZE;
- const appConfigSize = state.config.appConfig.iconSize;
- return localStorage.getItem(sizeStoreKey) || appConfigSize || 'medium';
+ const scope = configScope(state.currentConfigInfo.confId);
+ const fromState = state.config.appConfig.iconSize || 'medium';
+ if (state.editMode) return fromState;
+ return localStorage.getItem(scope.ICON_SIZE) || fromState;
},
},
mutations: {
@@ -215,8 +290,14 @@ const store = createStore({
},
/* The config to display and edit. Will differ from ROOT_CONFIG when using multi-page */
[SET_CONFIG](state, config) {
- if (!config.appConfig) config.appConfig = {};
- state.config = config;
+ const next = { ...(config || {}) };
+ if (!next.appConfig) next.appConfig = {};
+ if (next.sections) next.sections = applyItemId(next.sections);
+ state.config = next;
+ },
+ /* The active page's own/intent config (partial for sub-pages). Editor reads this. */
+ [SET_CONFIG_SOURCE](state, source) {
+ state.configSource = source || {};
},
[SET_CURRENT_CONFIG_INFO](state, subConfigInfo) {
state.currentConfigInfo = subConfigInfo;
@@ -225,9 +306,8 @@ const store = createStore({
state.isUsingLocalConfig = isUsingLocalConfig;
},
[SET_LANGUAGE](state, lang) {
- const newConfig = state.config;
- newConfig.appConfig.language = lang;
- state.config = newConfig;
+ patchAppConfigField(state, 'language', lang, configScope(state.currentConfigInfo.confId).LANGUAGE);
+ InfoHandler('Language updated', InfoKeys.VISUAL);
},
[SET_MODAL_OPEN](state, modalOpen) {
state.modalOpen = modalOpen;
@@ -242,146 +322,100 @@ const store = createStore({
if (message) ErrorHandler(message);
state.criticalError = message;
},
- [UPDATE_ITEM](state, payload) {
- const { itemId, newItem } = payload;
- const newConfig = { ...state.config };
- newConfig.sections.forEach((section, secIndex) => {
- (section.items || []).forEach((item, itemIndex) => {
- if (item.id === itemId) {
- newConfig.sections[secIndex].items[itemIndex] = newItem;
- InfoHandler('Item updated', InfoKeys.EDITOR);
- }
- });
- });
- state.config = newConfig;
- },
- [SET_PAGE_INFO](state, newPageInfo) {
- const newConfig = state.config;
- newConfig.pageInfo = newPageInfo;
- state.config = newConfig;
+ [SET_PAGE_INFO](state, pageInfo) {
+ commitConfigField(state, 'pageInfo', pageInfo || {});
InfoHandler('Page info updated', InfoKeys.EDITOR);
},
- [SET_APP_CONFIG](state, newAppConfig) {
- const newConfig = state.config;
- newConfig.appConfig = newAppConfig;
- state.config = newConfig;
+ [SET_APP_CONFIG](state, appConfig) {
+ commitConfigField(state, 'appConfig', appConfig || {});
InfoHandler('App config updated', InfoKeys.EDITOR);
},
[SET_PAGES](state, multiPages) {
- const newConfig = state.config;
- newConfig.pages = multiPages;
- state.config = newConfig;
+ // `pages` is always root-owned, regardless of the active page.
+ const pages = Array.isArray(multiPages) ? multiPages : [];
+ if (state.rootConfig) state.rootConfig = { ...state.rootConfig, pages };
+ state.config = { ...state.config, pages };
+ if (!state.currentConfigInfo.confId) {
+ state.configSource = { ...state.configSource, pages };
+ }
InfoHandler('Pages updated', InfoKeys.EDITOR);
},
- [SET_SECTIONS](state, newSections) {
- const newConfig = state.config;
- newConfig.sections = newSections;
- state.config = newConfig;
+ [SET_SECTIONS](state, sections) {
+ commitConfigField(state, 'sections', sections || []);
InfoHandler('Sections updated', InfoKeys.EDITOR);
},
- [UPDATE_SECTION](state, payload) {
- const { sectionIndex, sectionData } = payload;
- const newConfig = { ...state.config };
- newConfig.sections[sectionIndex] = sectionData;
- state.config = newConfig;
+ [UPDATE_ITEM](state, { itemId, newItem }) {
+ commitConfigField(state, 'sections', state.config.sections.map((section) => ({
+ ...section,
+ items: (section.items || []).map((item) => (item.id === itemId ? newItem : item)),
+ })));
+ InfoHandler('Item updated', InfoKeys.EDITOR);
+ },
+ [UPDATE_SECTION](state, { sectionIndex, sectionData }) {
+ commitConfigField(state, 'sections', state.config.sections.map((s, i) => (
+ i === sectionIndex ? sectionData : s
+ )));
InfoHandler('Section updated', InfoKeys.EDITOR);
},
[INSERT_SECTION](state, newSection) {
- const newConfig = { ...state.config };
- newSection.items = [];
- newConfig.sections.push(newSection);
- state.config = newConfig;
+ commitConfigField(state, 'sections', [
+ ...state.config.sections,
+ { ...newSection, items: [] },
+ ]);
InfoHandler('New section added', InfoKeys.EDITOR);
},
- [REMOVE_SECTION](state, payload) {
- const { sectionIndex, sectionName } = payload;
- const newConfig = { ...state.config };
- if (newConfig.sections[sectionIndex].name === sectionName) {
- newConfig.sections.splice(sectionIndex, 1);
- InfoHandler('Section removed', InfoKeys.EDITOR);
- }
- state.config = newConfig;
- },
- [INSERT_ITEM](state, payload) {
- const { newItem, targetSection } = payload;
- const config = { ...state.config };
- config.sections.forEach((section) => {
- if (section.name === targetSection) {
- if (!section.items) section.items = [];
- section.items.push(newItem);
- InfoHandler('New item added', InfoKeys.EDITOR);
- }
+ [REMOVE_SECTION](state, { sectionIndex, sectionName }) {
+ const current = state.config.sections;
+ if (current[sectionIndex]?.name !== sectionName) return;
+ commitConfigField(state, 'sections', current.filter((_, i) => i !== sectionIndex));
+ InfoHandler('Section removed', InfoKeys.EDITOR);
+ },
+ [INSERT_ITEM](state, { newItem, targetSection }) {
+ const patched = state.config.sections.map((section) => {
+ if (section.name !== targetSection) return section;
+ return { ...section, items: [...(section.items || []), newItem] };
});
- config.sections = applyItemId(config.sections);
- state.config = config;
+ commitConfigField(state, 'sections', patched);
+ InfoHandler('New item added', InfoKeys.EDITOR);
},
- [COPY_ITEM](state, payload) {
- const { item, toSection, appendTo } = payload;
- const config = { ...state.config };
+ [COPY_ITEM](state, { item, toSection, appendTo }) {
const newItem = { ...item };
- config.sections.forEach((section) => {
- if (section.name === toSection) {
- if (!section.items) section.items = [];
- if (appendTo === 'beginning') {
- section.items.unshift(newItem);
- } else {
- section.items.push(newItem);
- }
- InfoHandler('Item copied', InfoKeys.EDITOR);
- }
+ const patched = state.config.sections.map((section) => {
+ if (section.name !== toSection) return section;
+ const items = appendTo === 'beginning'
+ ? [newItem, ...(section.items || [])]
+ : [...(section.items || []), newItem];
+ return { ...section, items };
});
- config.sections = applyItemId(config.sections);
- state.config = config;
- },
- [REMOVE_ITEM](state, payload) {
- const { itemId, sectionName } = payload;
- const config = { ...state.config };
- config.sections.forEach((section) => {
- if (section.name === sectionName && section.items) {
- section.items.forEach((item, index) => {
- if (item.id === itemId) {
- section.items.splice(index, 1);
- InfoHandler('Item removed', InfoKeys.EDITOR);
- }
- });
- }
+ commitConfigField(state, 'sections', patched);
+ InfoHandler('Item copied', InfoKeys.EDITOR);
+ },
+ [REMOVE_ITEM](state, { itemId, sectionName }) {
+ const patched = state.config.sections.map((section) => {
+ if (section.name !== sectionName) return section;
+ return {
+ ...section,
+ items: (section.items || []).filter((item) => item.id !== itemId),
+ };
});
- config.sections = applyItemId(config.sections);
- state.config = config;
+ commitConfigField(state, 'sections', patched);
+ InfoHandler('Item removed', InfoKeys.EDITOR);
},
[SET_THEME](state, theme) {
- const newConfig = { ...state.config };
- newConfig.appConfig.theme = theme;
- state.config = newConfig;
- const pageId = state.currentConfigInfo.confId;
- const themeStoreKey = pageId
- ? `${localStorageKeys.THEME}-${pageId}` : localStorageKeys.THEME;
- localStorage.setItem(themeStoreKey, theme);
+ patchAppConfigField(state, 'theme', theme, configScope(state.currentConfigInfo.confId).THEME);
InfoHandler('Theme updated', InfoKeys.VISUAL);
},
[SET_ITEM_LAYOUT](state, layout) {
- const newConfig = { ...state.config };
- newConfig.appConfig.layout = layout;
- state.config = newConfig;
- const pageId = state.currentConfigInfo.confId;
- const layoutStoreKey = pageId
- ? `${localStorageKeys.LAYOUT_ORIENTATION}-${pageId}` : localStorageKeys.LAYOUT_ORIENTATION;
- localStorage.setItem(layoutStoreKey, layout);
+ patchAppConfigField(state, 'layout', layout, configScope(state.currentConfigInfo.confId).LAYOUT);
InfoHandler('Layout updated', InfoKeys.VISUAL);
},
[SET_ITEM_SIZE](state, iconSize) {
- const newConfig = { ...state.config };
- newConfig.appConfig.iconSize = iconSize;
- state.config = newConfig;
- const pageId = state.currentConfigInfo.confId;
- const sizeStoreKey = pageId
- ? `${localStorageKeys.ICON_SIZE}-${pageId}` : localStorageKeys.ICON_SIZE;
- localStorage.setItem(sizeStoreKey, iconSize);
+ patchAppConfigField(state, 'iconSize', iconSize, configScope(state.currentConfigInfo.confId).ICON_SIZE);
InfoHandler('Item size updated', InfoKeys.VISUAL);
},
[UPDATE_CUSTOM_CSS](state, customCss) {
- state.config.appConfig.customCss = customCss;
- InfoHandler('Custom colors updated', InfoKeys.VISUAL);
+ patchAppConfigField(state, 'customCss', customCss);
+ InfoHandler('Custom CSS updated', InfoKeys.VISUAL);
},
[CONF_MENU_INDEX](state, index) {
state.navigateConfToTab = index;
@@ -432,31 +466,28 @@ const store = createStore({
}
},
/**
- * Fetches config and updates state
- * If not on sub-page, will trigger the fetch of main config, then use that
- * If using sub-page config, then fetch that sub-config, then
- * override certain fields (appConfig, pages) and update config
+ * Loads the active config. Pass a sub-page id to load that sub-page
*/
async [INITIALIZE_CONFIG]({ commit, state }, subConfigId) {
try {
- const rootConfig = state.rootConfig
- || await this.dispatch(Keys.INITIALIZE_ROOT_CONFIG);
- // Needs deep clone, so overrides can't mutate cached root
- const root = JSON.parse(JSON.stringify(rootConfig));
- const rootUsingLocal = applyLocalOverrides(root);
+ const targetId = subConfigId || null;
+ if (!state.rootConfig) await this.dispatch(Keys.INITIALIZE_ROOT_CONFIG);
+ const { hasStructural: rootHasStructural } = readLocalOverrides(null);
+ const rootEffective = buildRootEffective(state);
- if (!subConfigId) { // Root page: commit the overridden root config directly
- commit(SET_CONFIG, root);
+ if (!targetId) {
+ commit(SET_CONFIG, rootEffective);
+ commit(SET_CONFIG_SOURCE, rootEffective);
commit(SET_CURRENT_CONFIG_INFO, {});
- commit(SET_IS_USING_LOCAL_CONFIG, rootUsingLocal);
- return root;
+ commit(SET_IS_USING_LOCAL_CONFIG, rootHasStructural);
+ return rootEffective;
}
- const subConfigPath = formatConfigPath(root?.pages?.find(
- (page) => page?.name && makePageName(page.name) === subConfigId,
+ const subConfigPath = formatConfigPath(rootEffective.pages.find(
+ (page) => page?.name && makePageName(page.name) === targetId,
)?.path);
if (!subConfigPath) {
- commit(CRITICAL_ERROR_MSG, `Unable to find config for '${subConfigId}'`);
+ commit(CRITICAL_ERROR_MSG, `Unable to find config for '${targetId}'`);
return { ...emptyConfig };
}
let response;
@@ -467,30 +498,49 @@ const store = createStore({
ErrorHandler(`Sub-config load failed: ${subConfigPath}`, fetchErr);
return { ...emptyConfig };
}
- let configContent;
+ let subFile;
try {
- configContent = yaml.load(response.data) || {};
+ subFile = yaml.load(response.data) || {};
} catch (parseError) {
commit(CRITICAL_ERROR_MSG, `Failed to parse sub-config YAML: ${parseError.message}`);
return { ...emptyConfig };
}
- // Inherit shared appConfig + pages from root, but override theme per sub-page
- // TODO: Actually, need to think about which props it is totally safe for a sub-config to inherit.
- const theme = configContent?.appConfig?.theme || root.appConfig?.theme || 'default';
- configContent.appConfig = { ...root.appConfig, theme };
- configContent.pages = root.pages;
- const subUsingLocal = applyLocalOverrides(configContent, subConfigId);
+ // Sub-page's own intent: file merged with per-page localStorage, minus root-owned fields.
+ const { own: subOwnLocal, hasStructural: subHasStructural } = readLocalOverrides(targetId);
+ const subOwn = stripRootOwnedFields({
+ appConfig: { ...(subFile.appConfig || {}), ...(subOwnLocal.appConfig || {}) },
+ pageInfo: { ...(subFile.pageInfo || {}), ...(subOwnLocal.pageInfo || {}) },
+ sections: subOwnLocal.sections || subFile.sections || [],
+ });
- commit(SET_CONFIG, configContent);
- commit(SET_CURRENT_CONFIG_INFO, { confPath: subConfigPath, confId: subConfigId });
- commit(SET_IS_USING_LOCAL_CONFIG, subUsingLocal);
- return configContent;
+ commit(SET_CONFIG, mergeWithRoot(rootEffective, subOwn));
+ commit(SET_CONFIG_SOURCE, subOwn);
+ commit(SET_CURRENT_CONFIG_INFO, { confPath: subConfigPath, confId: targetId });
+ commit(SET_IS_USING_LOCAL_CONFIG, subHasStructural);
+ return state.config;
} catch (err) { // If we get here, then somethings really fucked up
commit(CRITICAL_ERROR_MSG, `Unexpected error loading config: ${err.message}`);
ErrorHandler('INITIALIZE_CONFIG failed', err);
return { ...emptyConfig };
}
},
+
+ /* Apply edited config content (from the YAML editor or the field modals) to the store. */
+ [APPLY_EDITED_CONFIG]({ commit, state }, source) {
+ const data = source || {};
+ if (!state.currentConfigInfo.confId) {
+ commit(SET_CONFIG, data);
+ commit(SET_CONFIG_SOURCE, data);
+ return;
+ }
+ const own = stripRootOwnedFields({
+ appConfig: data.appConfig || {},
+ pageInfo: data.pageInfo || {},
+ sections: data.sections || [],
+ });
+ commit(SET_CONFIG, mergeWithRoot(buildRootEffective(state), own));
+ commit(SET_CONFIG_SOURCE, own);
+ },
},
modules: {},
});
diff --git a/src/utils/StoreMutations.js b/src/utils/StoreMutations.js
index b3e009f2..f9f4201d 100644
--- a/src/utils/StoreMutations.js
+++ b/src/utils/StoreMutations.js
@@ -4,6 +4,8 @@ const KEY_NAMES = [
'INITIALIZE_ROOT_CONFIG',
'INITIALIZE_MULTI_PAGE_CONFIG',
'SET_CONFIG',
+ 'SET_CONFIG_SOURCE',
+ 'APPLY_EDITED_CONFIG',
'SET_ROOT_CONFIG',
'SET_CURRENT_CONFIG_INFO',
'SET_IS_USING_LOCAL_CONFIG',
diff --git a/src/utils/config/ConfigHelpers.js b/src/utils/config/ConfigHelpers.js
index 3fedb755..a2378874 100644
--- a/src/utils/config/ConfigHelpers.js
+++ b/src/utils/config/ConfigHelpers.js
@@ -1,5 +1,4 @@
import ConfigAccumulator from '@/utils/config/ConfigAccumalator';
-// import $store from '@/store';
import filterUserSections from '@/utils/CheckSectionVisibility';
import { languages } from '@/utils/languages';
import {
@@ -11,6 +10,36 @@ import {
/* Page id used in URLs to mean "the root config" */
export const RESERVED_ROOT = 'main';
+/* Fields owned exclusively by the root config, sub-pages always inherit */
+const ROOT_OWNED_TOP_LEVEL = ['pages'];
+const ROOT_OWNED_APP_CONFIG = ['auth'];
+
+/* Return a shallow copy of `config` with root-owned fields removed */
+export const stripRootOwnedFields = (config) => {
+ if (!config || typeof config !== 'object') return config;
+ const clean = { ...config };
+ ROOT_OWNED_TOP_LEVEL.forEach((key) => delete clean[key]);
+ if (clean.appConfig && typeof clean.appConfig === 'object') {
+ clean.appConfig = { ...clean.appConfig };
+ ROOT_OWNED_APP_CONFIG.forEach((key) => delete clean.appConfig[key]);
+ }
+ return clean;
+};
+
+/* Local storage keys for local settings, if confId is set it's for a sub-page */
+export const configScope = (confId) => {
+ const suffix = confId ? `-${confId}` : '';
+ return {
+ APP_CONFIG: `${localStorageKeys.APP_CONFIG}${suffix}`,
+ PAGE_INFO: `${localStorageKeys.PAGE_INFO}${suffix}`,
+ CONF_SECTIONS: `${localStorageKeys.CONF_SECTIONS}${suffix}`,
+ THEME: `${localStorageKeys.THEME}${suffix}`,
+ LAYOUT: `${localStorageKeys.LAYOUT_ORIENTATION}${suffix}`,
+ ICON_SIZE: `${localStorageKeys.ICON_SIZE}${suffix}`,
+ LANGUAGE: `${localStorageKeys.LANGUAGE}${suffix}`,
+ };
+};
+
/* Metadata for each view in the canonical /<view>/:page?/:section? URL scheme */
export const VIEW_META = {
home: { supportsSection: true },
diff --git a/src/utils/config/SectionHelpers.js b/src/utils/config/SectionHelpers.js
index 873fc2f6..c31ab3b6 100644
--- a/src/utils/config/SectionHelpers.js
+++ b/src/utils/config/SectionHelpers.js
@@ -22,20 +22,20 @@ const makeItemId = (sectionStr, itemStr, index) => {
return `${index}_${charSum}_${itemTitleStr}`;
};
-/* Given an array of sections, apply a unique ID to each item, and return modified array */
-export const applyItemId = (inputSections) => {
- const sections = inputSections || [];
- sections.forEach((sec, secIdx) => {
- if (sec.items) {
- sec.items.forEach((item, itemIdx) => {
- sections[secIdx].items[itemIdx].id = makeItemId(sec.name, item.title, itemIdx);
- });
- }
- if (sec.widgets) {
- sec.widgets.forEach((widget, widgetIdx) => {
- sections[secIdx].widgets[widgetIdx].id = makeItemId(sec.name, widget.type, widgetIdx);
- });
- }
- });
- return sections;
-};
+/* Return a new array of sections with a unique id on each item and widget */
+export const applyItemId = (inputSections) => (inputSections || []).map((section) => {
+ const next = { ...section };
+ if (Array.isArray(section.items)) {
+ next.items = section.items.map((item, i) => ({
+ ...item,
+ id: makeItemId(section.name, item.title, i),
+ }));
+ }
+ if (Array.isArray(section.widgets)) {
+ next.widgets = section.widgets.map((widget, i) => ({
+ ...widget,
+ id: makeItemId(section.name, widget.type, i),
+ }));
+ }
+ return next;
+});
diff --git a/src/utils/i18n.js b/src/utils/i18n.js
new file mode 100644
index 00000000..69a3e044
--- /dev/null
+++ b/src/utils/i18n.js
@@ -0,0 +1,16 @@
+import { createI18n } from 'vue-i18n';
+import { messages } from '@/utils/languages';
+import { language as defaultLanguage } from '@/utils/config/defaults';
+
+/**
+ * Single i18n instance used by the Vue app and shared with non-component
+ * callers (e.g. the router guard) via the `i18n.global.t(...)` API.
+ */
+const i18n = createI18n({
+ legacy: true,
+ locale: defaultLanguage,
+ fallbackLocale: defaultLanguage,
+ messages,
+});
+
+export default i18n;
diff --git a/src/views/DownloadConfig.vue b/src/views/DownloadConfig.vue
index e056daa0..6bb8f804 100644
--- a/src/views/DownloadConfig.vue
+++ b/src/views/DownloadConfig.vue
@@ -14,7 +14,7 @@ export default {
},
computed: {
config() {
- return this.$store.state.config;
+ return this.$store.state.configSource;
},
yamlConfig() {
return JsYaml.dump(this.config);
diff --git a/src/views/Home.vue b/src/views/Home.vue
index 34515ecb..d872a3ed 100644
--- a/src/views/Home.vue
+++ b/src/views/Home.vue
@@ -107,11 +107,10 @@ export default {
/* Return sections with filtered items, that match users search term */
filteredSections() {
const sections = this.singleSectionView || this.sections;
- return sections.map((_section) => {
- const section = _section;
- section.filteredItems = this.filterTiles(section.items, this.searchValue);
- return section;
- });
+ return sections.map((section) => ({
+ ...section,
+ filteredItems: this.filterTiles(section.items, this.searchValue),
+ }));
},
/* Updates layout (when button clicked), and saves in local storage */
layoutOrientation() {