Skip to content

Commit e0042ce

Browse files
authored
Give theme cookie an expiration (#5429)
1 parent f2bdf22 commit e0042ce

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/Aspire.Dashboard/wwwroot/js/app-theme.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
} from "/_content/Microsoft.FluentUI.AspNetCore.Components/Microsoft.FluentUI.AspNetCore.Components.lib.module.js";
1111

1212
const currentThemeCookieName = "currentTheme";
13-
const themeSettingSystem = "System";
1413
const themeSettingDark = "Dark";
1514
const themeSettingLight = "Light";
1615
const darkThemeLuminance = 0.19;
@@ -31,11 +30,11 @@ export function updateTheme(specifiedTheme) {
3130
}
3231

3332
/**
34-
* Returns the value of the currentTheme cookie, or System if the cookie is not set.
33+
* Returns the value of the currentTheme cookie.
3534
* @returns {string}
3635
*/
3736
export function getThemeCookieValue() {
38-
return getCookieValue(currentThemeCookieName) ?? themeSettingSystem;
37+
return getCookieValue(currentThemeCookieName);
3938
}
4039

4140
export function getCurrentTheme() {
@@ -61,7 +60,15 @@ function getSystemTheme() {
6160
* @param {string} theme
6261
*/
6362
function setThemeCookie(theme) {
64-
document.cookie = `${currentThemeCookieName}=${theme}`;
63+
if (theme == themeSettingDark || theme == themeSettingLight) {
64+
// Cookie will expire after 1 year. Using a much larger value won't have an impact because
65+
// Chrome limits expiration to 400 days: https://developer.chrome.com/blog/cookie-max-age-expires
66+
// The cookie is reset when the dashboard loads to creating a sliding expiration.
67+
document.cookie = `${currentThemeCookieName}=${theme}; Path=/; expires=${new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toGMTString()}`;
68+
} else {
69+
// Delete cookie for other values (e.g. System)
70+
document.cookie = `${currentThemeCookieName}=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;
71+
}
6572
}
6673

6774
/**
@@ -260,6 +267,12 @@ function initializeTheme() {
260267
const effectiveTheme = getEffectiveTheme(themeCookieValue);
261268

262269
applyTheme(effectiveTheme);
270+
271+
// If a theme cookie has been set then set it again on page load.
272+
// This updates the cookie expiration date and creates a sliding expiration.
273+
if (themeCookieValue) {
274+
setThemeCookie(themeCookieValue);
275+
}
263276
}
264277

265278
createAdditionalDesignTokens();

0 commit comments

Comments
 (0)