π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
π¨ Consolidated theme logic
Alicia Sykes8dcf8b3a3d29
diff --git a/src/App.vue b/src/App.vueindex 21796dac..a305274f 100644--- a/src/App.vue+++ b/src/App.vue@@ -19,6 +19,7 @@ import { welcomeMsg } from '@/utils/logging/CoolConsole';import ErrorHandler from '@/utils/logging/ErrorHandler';import { syncPageMeta } from '@/utils/PageMeta';import { viewFromPath } from '@/utils/config/ConfigHelpers';+import { applyTheme } from '@/utils/Theming';import Keys from '@/utils/StoreMutations';import {localStorageKeys,@@ -54,6 +55,13 @@ export default {handler() { syncPageMeta(this.$route, this.$store); },immediate: true,},+ /* Apply the effective theme whenever it changes β on app load, when the+ * user picks a new theme, when navigating between sub-configs, or when+ * a route declares its own theme via `meta.theme` (e.g. the 404 page). */+ effectiveTheme: {+ immediate: true,+ handler(t) { applyTheme(t, this.appConfig); },+ },},computed: {/* If the user has specified custom text for footer - get it */@@ -72,6 +80,10 @@ export default {config() {return this.$store.state.config;},+ /* Route-declared themes (e.g. 404) win over the user's saved theme */+ effectiveTheme() {+ return this.$route?.meta?.theme || this.$store.getters.theme;+ },appConfig() {return this.$store.getters.appConfig;},@@ -208,21 +220,19 @@ export default {e.preventDefault();return 'You may have unsaved edits. Are you sure you want to exit the page?';},- /* Detect and apply theme based on OS preference */+ /* If dayTheme/nightTheme is configured, switch to it based on OS preference.+ * Commits to the store β the `theme` watcher then handles DOM application. */applyThemeBasedOnOSPreference() {- const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;+ const prefersDark = window.matchMedia?.('(prefers-color-scheme: dark)').matches;const osTheme = prefersDark ? this.appConfig.nightTheme : this.appConfig.dayTheme;- if (osTheme) {- this.$store.commit(Keys.SET_THEME, osTheme);- this.updateTheme(osTheme);- }+ if (osTheme) this.$store.commit(Keys.SET_THEME, osTheme);},},/* Basic initialization tasks on app load */async mounted() {await this.$store.dispatch(Keys.INITIALIZE_CONFIG); // Initialize config before moving onthis.applyLanguage(); // Apply users local language- this.applyThemeBasedOnOSPreference(); // Apply theme based on OS preference+ this.applyThemeBasedOnOSPreference(); // Override with OS-preference theme, if configuredthis.hideSplash(); // Hide the splash screen, if visiblethis.applyCustomStyles(); // Apply custom CSS and external stylesheetsthis.hideLoader(); // If initial placeholder still visible, hide itdiff --git a/src/components/Settings/ThemeSelector.vue b/src/components/Settings/ThemeSelector.vueindex 405ee5cf..54d2a30e 100644--- a/src/components/Settings/ThemeSelector.vue+++ b/src/components/Settings/ThemeSelector.vue@@ -46,10 +46,6 @@ export default {themeConfiguratorOpen: false, // Control the opening of theme config popup};},- computed: {},- mounted() {- this.initializeTheme();- },methods: {/* Opens the theme color configurator popup */openThemeConfigurator() {diff --git a/src/mixins/HomeMixin.js b/src/mixins/HomeMixin.jsindex ff31df3c..6292f286 100644--- a/src/mixins/HomeMixin.js+++ b/src/mixins/HomeMixin.js@@ -7,10 +7,8 @@ import Keys from '@/utils/StoreMutations';import { searchTiles } from '@/utils/Search';import { checkItemVisibility } from '@/utils/CheckItemVisibility';import { resolveRouteIntent, PAGE_STATUS } from '@/utils/config/ConfigHelpers';-import ThemingMixin from '@/mixins/ThemingMixin';const HomeMixin = {- mixins: [ThemingMixin],computed: {sections() {return this.$store.getters.sections;@@ -60,9 +58,6 @@ const HomeMixin = {if (status === PAGE_STATUS.ROOT || status === PAGE_STATUS.LEGACY_SECTION) return null;return pageId; // KNOWN -> load sub-config; UNKNOWN -> store raises critical error},- setTheme() {- this.initializeTheme();- },updateModalVisibility(modalState) {this.$store.commit(Keys.SET_MODAL_OPEN, modalState);},diff --git a/src/mixins/ThemingMixin.js b/src/mixins/ThemingMixin.jsindex 9a241def..18312ae2 100644--- a/src/mixins/ThemingMixin.js+++ b/src/mixins/ThemingMixin.js@@ -1,151 +1,33 @@/**- * This mixin can be extended by any component or view which needs to manage themes- * It handles fetching and applying themes from the store, updating themes,- * applying custom CSS variables and loading external stylesheets.- * */+ * Provides dropdown state + computed theme list for components that let the user+ * pick a theme (ThemeSelector, CustomThemeMaker, etc). The actual DOM+ * application of themes is handled centrally in App.vue via a watcher on+ * `$store.getters.theme`, so this mixin deliberately does no DOM work.+ */import Keys from '@/utils/StoreMutations';-import ErrorHandler from '@/utils/logging/ErrorHandler';-import { builtInThemes, localStorageKeys, mainCssVars } from '@/utils/config/defaults';+import { builtInThemes } from '@/utils/config/defaults';+import { getExternalThemes, getExtraThemeNames } from '@/utils/Theming';-const ThemingMixin = {- data: () => ({- selectedTheme: '', // Used only to bind current them to theme dropdown- }),+export default {+ data: () => ({ selectedTheme: '' }),computed: {- /* This is the theme from the central store. When it changes, the UI will update */- themeFromStore() {- return this.$store.getters.theme;- },- appConfig() {- return this.$store.getters.appConfig;- },- /* Any extra user-defined themes, to add to dropdown */- extraThemeNames() {- const userThemes = this.appConfig?.cssThemes || [];- if (typeof userThemes === 'string') return [userThemes];- return userThemes;- },- /* If user specified external stylesheet(s), format and return */- externalThemes() {- const availableThemes = {};- if (this.appConfig?.externalStyleSheet) {- const externals = this.appConfig.externalStyleSheet;- if (Array.isArray(externals)) {- externals.forEach((ext, i) => {- availableThemes[`External Stylesheet ${i + 1}`] = ext;- });- } else if (typeof externals === 'string') {- availableThemes['External Stylesheet'] = this.appConfig.externalStyleSheet;- } else {- ErrorHandler('External stylesheets must be of type string or string[]');- }- }- return availableThemes;- },- /* Combines all theme names for dropdown (built-in, user-defined and stylesheets) */+ appConfig() { return this.$store.getters.appConfig; },+ themeFromStore() { return this.$store.getters.theme; },+ externalThemes() { return getExternalThemes(this.appConfig); },+ extraThemeNames() { return getExtraThemeNames(this.appConfig); },themeNames() {- const externalThemeNames = Object.keys(this.externalThemes);- return [...this.extraThemeNames, ...externalThemeNames, ...builtInThemes];+ return [...this.extraThemeNames, ...Object.keys(this.externalThemes), ...builtInThemes];},},watch: {- /* When theme in VueX store changes, then update theme */- themeFromStore(newTheme) {- if (newTheme) {- this.resetToDefault();- this.selectedTheme = newTheme;- this.updateTheme(newTheme);- }- },+ themeFromStore: { immediate: true, handler(t) { this.selectedTheme = t; } },},methods: {- /* Called when user changes theme through the UI- * Updates store, which will in turn update theme through watcher- */+ /* Called when the user picks a theme in the dropdown β store commit+ * triggers the central watcher in App.vue to apply to the DOM. */themeChangedInUI() {- this.$store.commit(Keys.SET_THEME, this.selectedTheme); // Update store- this.updateTheme(this.selectedTheme); // Apply theme to UI- },- /**- * Gets any custom styles the user has applied, wither from local storage, or from the config- * @returns {object} An array of objects, one for each theme, containing kvps for variables- */- getCustomColors() {- const localColors = JSON.parse(localStorage[localStorageKeys.CUSTOM_COLORS] || '{}');- const configColors = this.appConfig.customColors || {};- return Object.assign(configColors, localColors);- },- /* Gets user custom color preferences for current theme, and applies to DOM */- applyCustomVariables(theme) {- mainCssVars.forEach((vName) => { document.documentElement.style.removeProperty(`--${vName}`); });- const themeColors = this.getCustomColors()[theme];- if (themeColors) {- Object.keys(themeColors).forEach((customVar) => {- document.documentElement.style.setProperty(`--${customVar}`, themeColors[customVar]);- });- }- },- /* Sets the theme, by updating data-theme attribute on the html tag */- applyLocalTheme(newTheme) {- const htmlTag = document.getElementsByTagName('html')[0];- if (htmlTag.hasAttribute('data-theme')) htmlTag.removeAttribute('data-theme');- htmlTag.setAttribute('data-theme', newTheme);- },- /* If using an external stylesheet, load it in */- applyRemoteTheme(href) {- this.resetToDefault();- const element = document.createElement('link');- element.setAttribute('rel', 'stylesheet');- element.setAttribute('type', 'text/css');- element.setAttribute('id', 'user-defined-stylesheet');- element.setAttribute('href', href);- document.getElementsByTagName('head')[0].appendChild(element);- },- /* Determines if a given theme is local / not a custom user stylesheet */- isThemeLocal(themeToCheck) {- const localThemes = [...builtInThemes, ...this.extraThemeNames];- return localThemes.includes(themeToCheck);- },- /* Updates theme. Checks if the new theme is local or external,- and calls appropriate updating function. Updates local storage */- updateTheme(newTheme) {- if (newTheme.toLowerCase() === 'default') {- this.resetToDefault();- } else if (this.isThemeLocal(newTheme)) {- this.applyLocalTheme(newTheme);- } else if (this.externalThemes[newTheme]) {- this.applyRemoteTheme(this.externalThemes[newTheme]);- }- this.applyCustomVariables(newTheme);- },- /* Removes any applied themes, and deletes any externally loaded stylesheets */- resetToDefault() {- const externalStyles = document.getElementById('user-defined-stylesheet');- if (externalStyles) document.getElementsByTagName('head')[0].removeChild(externalStyles);- document.getElementsByTagName('html')[0].removeAttribute('data-theme');- },- /* Call within mounted hook within a page to apply the correct theme */- initializeTheme() {- const initialTheme = this.themeFromStore;- this.selectedTheme = initialTheme;- const hasExternal = this.externalThemes && Object.entries(this.externalThemes).length > 0;-- if (this.isThemeLocal(initialTheme)) {- this.updateTheme(initialTheme);- } else if (hasExternal) {- this.applyRemoteTheme(this.externalThemes[initialTheme]);- }-- // Detect OS theme preference and apply the corresponding theme- const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;- const osTheme = prefersDark ? this.appConfig.nightTheme : this.appConfig.dayTheme;- if (osTheme) {- this.$store.commit(Keys.SET_THEME, osTheme);- this.updateTheme(osTheme);- }+ this.$store.commit(Keys.SET_THEME, this.selectedTheme);},},};--export default ThemingMixin;diff --git a/src/router.js b/src/router.jsindex 145ce5e8..3b37770e 100644--- a/src/router.js+++ b/src/router.js@@ -105,6 +105,7 @@ const router = createRouter({path: routePaths.notFound,name: '404',component: () => import('./views/404.vue'),+ meta: { theme: 'dashy-docs' },beforeEnter: (to, from, next) => {if (to.redirectedFrom) { // Log error, if redirected here from another routeErrorHandler(`Route not found: '${to.redirectedFrom.fullPath}'`);diff --git a/src/store.js b/src/store.jsindex f5ff3056..5440898c 100644--- a/src/store.js+++ b/src/store.js@@ -113,9 +113,8 @@ const store = createStore({theme(state) {const localStorageKey = state.currentConfigInfo.confId? `${localStorageKeys.THEME}-${state.currentConfigInfo.confId}` : localStorageKeys.THEME;- const localTheme = localStorage[localStorageKey];- // Return either theme from local storage, or from appConfig- return localTheme || state.config.appConfig.theme || defaultTheme;+ const configTheme = state.config?.appConfig?.theme;+ return localStorage[localStorageKey] || configTheme || defaultTheme;},webSearch(state, getters) {return getters.appConfig.webSearch || {};diff --git a/src/utils/Theming.js b/src/utils/Theming.jsnew file mode 100644index 00000000..e40bc203--- /dev/null+++ b/src/utils/Theming.js@@ -0,0 +1,74 @@+/**+ * Utils for applying user's theme to the document+ */++import { localStorageKeys, mainCssVars, builtInThemes } from '@/utils/config/defaults';+import ErrorHandler from '@/utils/logging/ErrorHandler';++const EXTERNAL_STYLE_ID = 'user-defined-stylesheet';+const html = () => document.documentElement;++/* Map of { label: href } for stylesheets declared in appConfig.externalStyleSheet */+export const getExternalThemes = (appConfig) => {+ const ext = appConfig?.externalStyleSheet;+ if (!ext) return {};+ if (Array.isArray(ext)) {+ return Object.fromEntries(ext.map((href, i) => [`External Stylesheet ${i + 1}`, href]));+ }+ if (typeof ext === 'string') return { 'External Stylesheet': ext };+ ErrorHandler('External stylesheets must be of type string or string[]');+ return {};+};++/* Names of user-defined themes (appConfig.cssThemes). Always returns an array. */+export const getExtraThemeNames = (appConfig) => {+ const t = appConfig?.cssThemes;+ if (!t) return [];+ return typeof t === 'string' ? [t] : t;+};++const resetDom = () => {+ document.getElementById(EXTERNAL_STYLE_ID)?.remove();+ html().removeAttribute('data-theme');+};++const applyRemote = (href) => {+ resetDom();+ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.type = 'text/css';+ link.id = EXTERNAL_STYLE_ID;+ link.href = href;+ document.head.appendChild(link);+};++const applyCustomVars = (theme, appConfig) => {+ mainCssVars.forEach((v) => html().style.removeProperty(`--${v}`));+ let localColors = {};+ try {+ localColors = JSON.parse(localStorage[localStorageKeys.CUSTOM_COLORS] || '{}');+ } catch (e) { /* corrupt JSON β skip */ }+ const vars = { ...(appConfig?.customColors || {}), ...localColors }[theme];+ if (!vars) return;+ Object.entries(vars).forEach(([k, v]) => html().style.setProperty(`--${k}`, v));+};++/**+ * Apply a theme name to the document. Handles built-in + user-defined + external+ * stylesheets + the special "default" reset + per-theme custom CSS vars+ */+export const applyTheme = (theme, appConfig = {}) => {+ if (!theme) return;+ const externals = getExternalThemes(appConfig);+ const locals = [...builtInThemes, ...getExtraThemeNames(appConfig)];++ if (theme.toLowerCase() === 'default') {+ resetDom();+ } else if (locals.includes(theme)) {+ resetDom();+ html().setAttribute('data-theme', theme);+ } else if (externals[theme]) {+ applyRemote(externals[theme]);+ }+ applyCustomVars(theme, appConfig);+};diff --git a/src/views/404.vue b/src/views/404.vueindex ef2c11f7..e1ed43e9 100644--- a/src/views/404.vue+++ b/src/views/404.vue@@ -12,17 +12,8 @@</template><script>-export default {name: 'not-found',- methods: {- setTheme() {- document.getElementsByTagName('html')[0].setAttribute('data-theme', 'dashy-docs');- },- },- mounted() {- this.setTheme();- },};</script>diff --git a/src/views/Login.vue b/src/views/Login.vueindex 944acc2e..c0c2bcb2 100644--- a/src/views/Login.vue+++ b/src/views/Login.vue@@ -75,7 +75,7 @@import router from '@/router';import Button from '@/components/FormElements/Button';import Input from '@/components/FormElements/Input';-import Defaults, { localStorageKeys } from '@/utils/config/defaults';+import { localStorageKeys } from '@/utils/config/defaults';import { InfoHandler, WarningInfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';import {checkCredentials,@@ -199,14 +199,8 @@ export default {router.push({ path: '/' });}, 250);},- /* Since Theme setter isn't loaded at this point, we must manually get and apply users theme */- setTheme() {- const theme = localStorage[localStorageKeys.THEME] || Defaults.theme;- document.getElementsByTagName('html')[0].setAttribute('data-theme', theme);- },},created() {- this.setTheme();setTimeout(() => { this.timeout = this.dropDownMenu[0]; }, 1); //eslint-disable-line},};diff --git a/src/views/Minimal.vue b/src/views/Minimal.vueindex b466cdaa..1970152d 100644--- a/src/views/Minimal.vue+++ b/src/views/Minimal.vue@@ -131,7 +131,6 @@ export default {mounted() {this.initiateFontAwesome();this.initiateMaterialDesignIcons();- this.setTheme();},};</script>diff --git a/src/views/Workspace.vue b/src/views/Workspace.vueindex f6ff635b..919e2f6e 100644--- a/src/views/Workspace.vue+++ b/src/views/Workspace.vue@@ -90,7 +90,6 @@ export default {mounted() {this.initiateFontAwesome();this.initiateMaterialDesignIcons();- this.setTheme();this.url = this.getInitialUrl();},};