feat(theme-switcher)!: respect `theme_default` when JS is enabled (#224)

BREAKING CHANGE: changes the behaviour of `theme_default`
main
Óscar Fernández 1 year ago committed by GitHub
parent c2664c85cd
commit bf31f7ff47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -44,15 +44,12 @@ taxonomies = [{name = "tags", feed = true}]
# https://welpo.github.io/tabi/blog/mastering-tabi-settings/
# Enable JavaScript theme toggler to allow users to switch between dark/light mode.
# Also enables automatic switching based on user's OS-level theme settings.
# If disabled, your site will only use the theme specified in the `default_theme` variable.
theme_switcher = true
# This setting determines the default theme ("light" or "dark").
# If you wish to use only a dark or light theme, disable the `theme_switcher` above and set this variable.
# If `theme_switcher` is enabled, this will be the theme that is visible to users who have JavaScript disabled.
# Defaults to "light", if unset.
default_theme = "light"
# This setting determines the default theme on load ("light" or "dark").
# To default to the user's OS-level theme, leave it empty or unset.
default_theme = ""
# Choose the colourscheme (skin) for the theme. Default is "teal".
# Skin available: blue, lavender, mint, red, sakura, teal, monochrome, lowcontrast_orange, lowcontrast_peach, lowcontrast_pink, indigo_ingot, evangelion

@ -1,7 +1,7 @@
+++
title = "Personalitza el color de tabi i el tema per defecte"
date = 2023-08-09
updated = 2023-10-07
updated = 2023-11-24
description = "Aprèn a personalitzar tabi fent servir skins i establint un tema per defecte, aconseguint un aspecte únic."
[taxonomies]
@ -17,6 +17,8 @@ tabi pot ser personalitzat de dues maneres: establint el tema per defecte (fosc
## Tema per defecte
Utilitza `default_theme = "dark"` per establir el tema fosc com a predeterminat, o `default_theme = "light"` per establir el tema clar com a predeterminat.
Per configurar permanentment el teu lloc en el tema fosc o clar, necessites desactivar el `theme_switcher` a `config.toml` i establir el teu tema preferit (`light` o `dark`) a `default_theme`.
Per exemple, per tenir un tema fosc permanent:
@ -27,8 +29,6 @@ theme_switcher = false
default_theme = "dark"
```
Si el teu interruptor de mode clar/fosc està activat, el `default_theme` només s'utilitzarà com a reserva, en cas que un visitant tingui JavaScript desactivat.
## Skins
No t'agrada l'aiguamarina? Cap problema! tabi té 12 skins per triar. Si cap d'aquestes t'agrada, pots [crear la teva pròpia skin](#crea-la-teva-propia-skin).

@ -1,7 +1,7 @@
+++
title = "Personaliza el color de tabi y el tema predeterminado"
date = 2023-08-09
updated = 2023-10-07
updated = 2023-11-24
description = "Aprende a personalizar tabi usando skins y estableciendo un tema predeterminado, haciendo que tu sitio sea único."
[taxonomies]
@ -17,6 +17,8 @@ tabi puede ser personalizado de dos maneras: estableciendo el tema predeterminad
## Tema predeterminado
Usa `default_theme = "dark"` para establecer el tema oscuro como predeterminado, o `default_theme = "light"` para establecer el tema claro como predeterminado.
Para configurar permanentemente tu sitio en el tema oscuro o claro, necesitas desactivar el `theme_switcher` en `config.toml` y establecer tu tema preferido (`light` o `dark`) como el `default_theme`.
Por ejemplo, para tener un tema oscuro permanente:
@ -27,8 +29,6 @@ theme_switcher = false
default_theme = "dark"
```
Si tu interruptor de modo claro/oscuro está activado, el `default_theme` sólo se usará como respaldo, en caso de que un visitante tenga JavaScript desactivado.
## Skins
¿No te gusta el aguamarina? ¡No hay problema! tabi tiene 12 skins (pieles) para elegir. Si ninguna de estas te convence, puedes [crear tu propia skin](#crea-tu-propia-skin).

@ -1,7 +1,7 @@
+++
title = "Customise tabi with skins and a default theme"
date = 2023-08-09
updated = 2023-10-07
updated = 2023-11-24
description = "Learn how to customise tabi using skins and setting a default theme, making your site uniquely yours."
[taxonomies]
@ -17,6 +17,8 @@ tabi can be customised in two ways: by setting the default theme (dark or light)
## Default theme
Use `default_theme = "dark"` to set the dark theme as the default, or `default_theme = "light"` to set the light theme as the default.
To permanently set your site to either the dark or light theme, you need to disable the theme switcher in `config.toml` and set your preferred theme as the `default_theme`.
For example, to have a permanent dark theme:
@ -27,8 +29,6 @@ theme_switcher = false
default_theme = "dark"
```
If your theme switcher is enabled, the `default_theme` will only be used as fallback, in case a visitor has JavaScript disabled.
## Skins
Not a fan of teal? No problem! tabi has 12 skins for you to choose from. If none of these work for you, you can [create your own](#create-your-own-skin).

@ -1,7 +1,7 @@
+++
title = "Domina la configuració de tabi: guia completa"
date = 2023-09-18
updated = 2023-11-05
updated = 2023-11-24
description = "Descobreix les múltiples maneres en què pots personalitzar tabi."
[taxonomies]
@ -102,9 +102,7 @@ El commutador de mode clar i fosc (la icona de lluna/sol a la cantonada superior
|:------:|:------:|:-------------:|:---------------:|:-------------------:|
| ❌ | ❌ | ✅ | ❌ | ❌ |
El mode predeterminat es pot especificar amb la variable `default_theme`, que accepta `"dark"` o `"light"`. Per defecte és `"light"`.
**Nota**: el mode predeterminat només s'usa quan el commutador de mode està desactivat, ja sigui perquè s'ha configurat com a `false` a `config.toml` o perquè un usuari ha deshabilitat JavaScript.
El mode predeterminat es pot especificar amb la variable `default_theme`, que accepta `"dark"` o `"light"`. Si no s'especifica, el mode predeterminat és el mode del sistema.
### Skin personalitzada

@ -1,7 +1,7 @@
+++
title = "Domina la configuración de tabi: guía completa"
date = 2023-09-18
updated = 2023-11-05
updated = 2023-11-24
description = "Descubre las múltiples maneras en que puedes personalizar tabi."
[taxonomies]
@ -100,9 +100,7 @@ El interruptor de modo claro y oscuro (el icono de luna/sol en la esquina superi
|:------:|:-------:|:-------------:|:---------------:|:-------------------:|
| ❌ | ❌ | ✅ | ❌ | ❌ |
El tema predeterminado puede especificarse con la variable `default_theme`, que acepta `"dark"` o `"light"`. Por defecto es `"light"`.
**Nota**: el tema predeterminado solo se usa cuando el interruptor de tema está desactivado, ya sea porque se ha configurado como `false` en el config o porque un usuario ha deshabilitado JavaScript.
El tema predeterminado puede especificarse con la variable `default_theme`, que acepta `"dark"` o `"light"`. Si no lo especificas, el tema predeterminado será el tema del sistema.
### Pieles personalizadas

@ -1,7 +1,7 @@
+++
title = "Mastering tabi Settings: A Comprehensive Guide"
date = 2023-09-18
updated = 2023-11-05
updated = 2023-11-24
description = "Discover the many ways you can customise your tabi site."
[taxonomies]
@ -102,9 +102,7 @@ The light and dark mode switcher (the moon/sun icon on the top right) can be ena
|:----:|:-------:|:-------------:|:-----------------:|:-------------------:|
| ❌ | ❌ | ✅ | ❌ | ❌ |
The default theme can be specified with the `default_theme` variable, which accepts either `"dark"` or `"light"`. Defaults to `"light"`.
**Note**: the default theme is only used when the theme switcher is disabled, either because it's set to `false` in the config or because a user has JavaScript disabled.
The default theme can be specified with the `default_theme` variable, which accepts either `"dark"` or `"light"`. If you don't set it, the default theme will be the one set in the user's browser.
### Custom Skins

@ -27,7 +27,7 @@ language_selection = "Selecció d'idioma"
toggle_mode = "Canvia el mode $MODE" # $MODE will be replaced by a value (or both) below.
dark = "obscur"
light = "clar"
reset_mode = "Restableix el mode als valors predeterminats del sistema"
reset_mode = "Restableix el mode al valor predeterminat"
# Quick navigation buttons.
toggle_toc = "Mostrar/ocultar la taula de continguts"

@ -31,7 +31,7 @@ language_selection = "Sprachauswahl"
toggle_mode = "Wechsle in den $MODE Modus" # $MODE will be replaced by a value (or both) below.
dark = "dunkel"
light = "hell"
reset_mode = "Modus auf Betriebssystemstandard zurücksetzen"
reset_mode = "Modus auf Standard zurücksetzen"
# Quick navigation buttons.
toggle_toc = "Inhaltsverzeichnis ein-/ausblenden"

@ -27,7 +27,7 @@ language_selection = "Language selection"
toggle_mode = "Toggle $MODE mode" # $MODE will be replaced by a value (or both) below.
dark = "dark"
light = "light"
reset_mode = "Reset mode to OS default"
reset_mode = "Reset mode to default"
# Quick navigation buttons.
toggle_toc = "Toggle Table of Contents"

@ -27,7 +27,7 @@ language_selection = "Selección de idioma"
toggle_mode = "Cambiar a modo $MODE" # $MODE will be replaced by a value (or both) below.
dark = "oscuro"
light = "claro"
reset_mode = "Restablecer modo a configuración predeterminada del SO"
reset_mode = "Restablecer modo a configuración predeterminada"
# Quick navigation buttons.
toggle_toc = "Mostrar/ocultar la tabla de contenidos"

@ -31,7 +31,7 @@ language_selection = "Sélection de la langue"
toggle_mode = "Basculer en mode $MODE" # $MODE will be replaced by a value (or both) below.
dark = "sombre"
light = "clair"
reset_mode = "Réinitialiser le mode aux paramètres par défaut du système"
reset_mode = "Réinitialiser le mode aux paramètres par défaut"
# Quick navigation buttons.
toggle_toc = "Afficher/Masquer la table des matières"

@ -29,7 +29,7 @@ language_selection = "भाषा चयन"
toggle_mode = "$MODE मोड में टॉगल करें" # $MODE will be replaced by a value (or both) below.
dark = "अंधेरा"
light = "रोशनी"
reset_mode = "मोड को ओएस डिफ़ॉल्ट पर रीसेट करें"
reset_mode = "मोड को ाइट डिफ़ॉल्ट पर रीसेट करें"
# Quick navigation buttons.
toggle_toc = "विषय-सूची टॉगल करें"

@ -27,7 +27,7 @@ language_selection = "Selezione della lingua"
toggle_mode = "Passa alla modalità $MODE" # $MODE will be replaced by a value (or both) below.
dark = "scuro"
light = "chiaro"
reset_mode = "Reimposta la modalità alle impostazioni predefinite del sistema operativo"
reset_mode = "Reimposta la modalità alle impostazioni predefinite"
# Quick navigation buttons.
toggle_toc = "Attiva/Disattiva indice"

@ -31,7 +31,7 @@ language_selection = "言語選択"
toggle_mode = "$MODE モードに切り替え" # $MODE will be replaced by a value (or both) below.
dark = "暗い"
light = "明るい"
reset_mode = "モードをOSデフォルトにリセット"
reset_mode = "モードをサイトのデフォルトにリセット"
# Quick navigation buttons.
toggle_toc = "目次を切り替え"

@ -31,7 +31,7 @@ language_selection = "언어 선택"
toggle_mode = "$MODE 모드로 전환" # $MODE will be replaced by a value (or both) below.
dark = "어두운"
light = "밝은"
reset_mode = "모드를 OS 기본값으로 재설정"
reset_mode = "모드를 사이트 기본값으로 재설정"
# Quick navigation buttons.
toggle_toc = "목차 토글"

@ -27,7 +27,7 @@ language_selection = "Seleção de idioma"
toggle_mode = "Alternar para o modo $MODE" # $MODE will be replaced by a value (or both) below.
dark = "escuro"
light = "claro"
reset_mode = "Repor o modo para o padrão do SO"
reset_mode = "Repor o modo para o padrão"
# Quick navigation buttons.
toggle_toc = "Alternar Índice"

@ -27,7 +27,7 @@ language_selection = "Выбор языка"
toggle_mode = "Переключить на режим $MODE" # $MODE will be replaced by a value (or both) below.
dark = "тёмный"
light = "светлый"
reset_mode = "Сбросить режим к настройкам ОС по умолчанию"
reset_mode = "Сбросить режим к стандартным настройкам сайта"
# Quick navigation buttons.
toggle_toc = "Показать/Скрыть оглавление"

@ -31,7 +31,7 @@ language_selection = "Вибір мови"
toggle_mode = "Перемкнути в режим $MODE" # $MODE will be replaced by a value (or both) below.
dark = "темний"
light = "світлий"
reset_mode = "Скинути режим до типових параметрів ОС"
reset_mode = "Скинути режим до типових налаштувань сайту"
# Quick navigation buttons.
toggle_toc = "Показати/Сховати зміст"

@ -27,7 +27,8 @@ language_selection = "语言选择" # Machine translated.
toggle_mode = "切换到$MODE模式" # $MODE will be replaced by a value (or both) below. Machine translated.
dark = "暗" # Machine translated.
light = "亮" # Machine translated.
reset_mode = "重置为操作系统默认模式" # Machine translated.
reset_mode = "将模式重置为网站默认值" # Machine translated.
# Quick navigation buttons.
toggle_toc = "切换目录" # Machine translated.

@ -27,7 +27,7 @@ language_selection = "語言選擇" # Machine translated.
toggle_mode = "切換到$MODE模式" # $MODE will be replaced by a value (or both) below. Machine translated.
dark = "暗" # Machine translated.
light = "亮" # Machine translated.
reset_mode = "重置為操作系統預設模式" # Machine translated.
reset_mode = "將模式重置為網站默認值" # Machine translated.
# Quick navigation buttons.
toggle_toc = "切換目錄" # Machine translated.

File diff suppressed because one or more lines are too long

@ -1,17 +1,22 @@
(function () {
// Get the current theme from the browser's local storage.
// This allows the user's theme preference to persist across sessions.
const currentTheme = localStorage.getItem('theme');
// Get the default theme from the HTML data-theme attribute.
const defaultTheme = document.documentElement.getAttribute('data-theme');
// Check if the current theme is stored in local storage.
if (currentTheme) {
// If a theme is found in local storage, apply it to the document.
document.documentElement.setAttribute('data-theme', currentTheme);
// Set the data-default-theme attribute only if defaultTheme is not null.
if (defaultTheme) {
document.documentElement.setAttribute('data-default-theme', defaultTheme);
}
// Attempt to retrieve the current theme from the browser's local storage.
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
document.documentElement.setAttribute('data-theme', storedTheme);
} else if (defaultTheme) {
document.documentElement.setAttribute('data-theme', defaultTheme);
} else {
// If no theme is found in local storage, determine if the user's system prefers a dark color scheme.
// If no theme is found in local storage and no default theme is set, use user's system preference.
const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// Set the document's theme attribute to match the system preference.
document.documentElement.setAttribute('data-theme', isSystemDark ? 'dark' : 'light');
}
})();

@ -1 +1 @@
!function(){var e=localStorage.getItem("theme");e?document.documentElement.setAttribute("data-theme",e):(e=window.matchMedia("(prefers-color-scheme: dark)").matches,document.documentElement.setAttribute("data-theme",e?"dark":"light"))}();
!function(){var t=document.documentElement.getAttribute("data-theme"),e=(t&&document.documentElement.setAttribute("data-default-theme",t),localStorage.getItem("theme"));e?document.documentElement.setAttribute("data-theme",e):t?document.documentElement.setAttribute("data-theme",t):(e=window.matchMedia("(prefers-color-scheme: dark)").matches,document.documentElement.setAttribute("data-theme",e?"dark":"light"))}();

@ -1,60 +1,54 @@
// Get the theme switcher button elements.
const themeSwitcher = document.querySelector(".theme-switcher");
const themeResetter = document.querySelector(".theme-resetter");
const defaultTheme = document.documentElement.getAttribute('data-default-theme');
// Retrieve theme from either the localStorage or the data-theme attribute on the document element.
let currentTheme = localStorage.getItem("theme") || document.documentElement.getAttribute('data-theme');
function getSystemThemePreference() {
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
// Determine the initial theme.
let currentTheme = localStorage.getItem("theme") || document.documentElement.getAttribute('data-theme') || getSystemThemePreference();
function setTheme(theme, saveToLocalStorage = false) {
document.documentElement.setAttribute("data-theme", theme);
currentTheme = theme;
let togglePressed = theme === "dark" ? "true" : "false";
themeSwitcher.setAttribute("aria-pressed", togglePressed);
themeSwitcher.setAttribute("aria-pressed", theme === "dark");
if (saveToLocalStorage) {
localStorage.setItem("theme", theme);
themeResetter.classList.add("has-custom-theme");
themeResetter.setAttribute("aria-hidden", "false");
} else {
localStorage.removeItem("theme");
themeResetter.classList.remove("has-custom-theme");
themeResetter.setAttribute("aria-hidden", "true");
}
// Dispatch a custom event for comment systems.
const event = new CustomEvent("themeChanged", {
detail: { theme: theme }
});
window.dispatchEvent(event);
window.dispatchEvent(new CustomEvent("themeChanged", { detail: { theme } }));
}
function resetTheme() {
setTheme(window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
setTheme(defaultTheme || getSystemThemePreference());
}
// Function to switch between dark and light themes.
function switchTheme() {
// Set the new theme based on the current theme.
const newTheme = currentTheme === "dark" ? "light" : "dark";
setTheme(newTheme, true); // Save the theme to localStorage when the user changes it.
setTheme(currentTheme === "dark" ? "light" : "dark", true);
}
// Initialize the theme switcher button.
themeSwitcher.addEventListener("click", switchTheme, false);
themeResetter.addEventListener("click", resetTheme, false);
themeSwitcher.setAttribute("role", "button");
let togglePressed = currentTheme === "dark" ? "true" : "false";
themeSwitcher.setAttribute("aria-pressed", togglePressed);
themeSwitcher.addEventListener("click", switchTheme);
themeResetter.addEventListener("click", resetTheme);
// Update the theme based on system preference if the user hasn't manually changed the theme.
// Update the theme based on system preference if necessary.
if (!defaultTheme) {
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", e => {
const newTheme = e.matches ? "dark" : "light";
setTheme(newTheme);
setTheme(e.matches ? "dark" : "light");
});
}
// Set initial ARIA attribute and custom theme class.
themeSwitcher.setAttribute("aria-pressed", currentTheme === "dark");
if (localStorage.getItem("theme")) {
themeResetter.classList.add("has-custom-theme");
} else {
themeResetter.classList.remove("has-custom-theme");
}

@ -1 +1 @@
const themeSwitcher=document.querySelector(".theme-switcher"),themeResetter=document.querySelector(".theme-resetter");let currentTheme=localStorage.getItem("theme")||document.documentElement.getAttribute("data-theme");function setTheme(e,t=!1){document.documentElement.setAttribute("data-theme",e);var r="dark"===(currentTheme=e)?"true":"false",r=(themeSwitcher.setAttribute("aria-pressed",r),t?(localStorage.setItem("theme",e),themeResetter.classList.add("has-custom-theme"),themeResetter.setAttribute("aria-hidden","false")):(localStorage.removeItem("theme"),themeResetter.classList.remove("has-custom-theme"),themeResetter.setAttribute("aria-hidden","true")),new CustomEvent("themeChanged",{detail:{theme:e}}));window.dispatchEvent(r)}function resetTheme(){setTheme(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}function switchTheme(){setTheme("dark"===currentTheme?"light":"dark",!0)}themeSwitcher.addEventListener("click",switchTheme,!1),themeResetter.addEventListener("click",resetTheme,!1),themeSwitcher.setAttribute("role","button");let togglePressed="dark"===currentTheme?"true":"false";themeSwitcher.setAttribute("aria-pressed",togglePressed),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{setTheme(e.matches?"dark":"light")}),localStorage.getItem("theme")?themeResetter.classList.add("has-custom-theme"):themeResetter.classList.remove("has-custom-theme");
const themeSwitcher=document.querySelector(".theme-switcher"),themeResetter=document.querySelector(".theme-resetter"),defaultTheme=document.documentElement.getAttribute("data-default-theme");function getSystemThemePreference(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}let currentTheme=localStorage.getItem("theme")||document.documentElement.getAttribute("data-theme")||getSystemThemePreference();function setTheme(e,t=!1){document.documentElement.setAttribute("data-theme",e),currentTheme=e,themeSwitcher.setAttribute("aria-pressed","dark"===e),t?(localStorage.setItem("theme",e),themeResetter.classList.add("has-custom-theme")):(localStorage.removeItem("theme"),themeResetter.classList.remove("has-custom-theme")),window.dispatchEvent(new CustomEvent("themeChanged",{detail:{theme:e}}))}function resetTheme(){setTheme(defaultTheme||getSystemThemePreference())}function switchTheme(){setTheme("dark"===currentTheme?"light":"dark",!0)}themeSwitcher.addEventListener("click",switchTheme),themeResetter.addEventListener("click",resetTheme),defaultTheme||window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{setTheme(e.matches?"dark":"light")}),themeSwitcher.setAttribute("aria-pressed","dark"===currentTheme),localStorage.getItem("theme")&&themeResetter.classList.add("has-custom-theme");

@ -16,7 +16,7 @@
aria-pressed="false">
</div>
{%- set reset_str = macros_translate::translate(key='reset_mode', default='Reset mode to OS default', language_strings=language_strings) -%}
{%- set reset_str = macros_translate::translate(key='reset_mode', default='Reset mode to default', language_strings=language_strings) -%}
<div
title="{{ reset_str }}"

@ -23,15 +23,12 @@ homepage = "https://osc.garden"
# https://welpo.github.io/tabi/blog/mastering-tabi-settings/
# Enable JavaScript theme toggler to allow users to switch between dark/light mode.
# Also enables automatic switching based on user's OS-level theme settings.
# If disabled, your site will only use the theme specified in the `default_theme` variable.
theme_switcher = true
# This setting determines the default theme ("light" or "dark").
# If you wish to use only a dark or light theme, disable the `theme_switcher` above and set this variable.
# If `theme_switcher` is enabled, this will be the theme that is visible to users who have JavaScript disabled.
# Defaults to "light", if unset.
default_theme = "light"
# This setting determines the default theme on load ("light" or "dark").
# To default to the user's OS-level theme, leave it empty or unset.
default_theme = ""
# Choose the colourscheme (skin) for the theme. Default is "teal".
# Skin available: blue, lavender, mint, red, sakura, teal, monochrome, lowcontrast_orange, lowcontrast_peach, lowcontrast_pink, indigo_ingot, evangelion

Loading…
Cancel
Save