mirror of
https://github.com/shoelace-style/webawesome.git
synced 2026-01-12 04:09:12 +00:00
Rewrite color scheme logic (#481)
- Minimize needless swaps - Centralize logic - Use an actual `<wa-select>` rather than hacking it with `<wa-dropdown>` - Move shared includes to shared template - Rewrite critical theme JS - Refactor of theme picker code - Utilize view transitions better and use them for color scheme too - Do not store default value in localStorage - Removed unused `*-wide` templates - Fixed #482
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1,83 +1,20 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-fa-kit-code="b10bfbde90" data-cdn-url="{% cdnUrl %}">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="{{ description }}">
|
||||
{% include 'head.njk' %}
|
||||
<meta name="theme-color" content="#f36944">
|
||||
{% if noindex %}<meta name="robots" content="noindex">{% endif %}
|
||||
|
||||
<title>{{ title }}</title>
|
||||
|
||||
<link rel="icon" href="/assets/images/webawesome-logo.svg" />
|
||||
<link rel="apple-touch-icon" href="/assets/images/app-icon.png">
|
||||
|
||||
{# Scripts #}
|
||||
{# Hydration stuff #}
|
||||
<script src="/assets/scripts/hydration-errors.js"></script>
|
||||
<link rel="stylesheet" href="/assets/styles/hydration-errors.css">
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net">
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.10/+esm"></script>
|
||||
|
||||
<script type="module" src="/assets/scripts/code-examples.js"></script>
|
||||
<script type="module" src="/assets/scripts/color-scheme.js"></script>
|
||||
<script type="module" src="/assets/scripts/copy-code.js"></script>
|
||||
<script type="module" src="/assets/scripts/preset-theme.js"></script>
|
||||
<script type="module" src="/assets/scripts/theme-picker.js"></script>
|
||||
<script type="module" src="/assets/scripts/scroll.js"></script>
|
||||
<script type="module" src="/assets/scripts/turbo.js"></script>
|
||||
<script type="module" src="/assets/scripts/search.js"></script>
|
||||
<script type="module" src="/assets/scripts/outline.js"></script>
|
||||
<script defer data-domain="backers.webawesome.com" src="https://plausible.io/js/script.js"></script>
|
||||
|
||||
{# Web Awesome #}
|
||||
<script type="module" src="/dist/webawesome.ssr-loader.js"></script>
|
||||
<link rel="stylesheet" id="theme-stylesheet" href="/dist/styles/themes/default.css" />
|
||||
<link rel="stylesheet" href="/dist/styles/webawesome.css" />
|
||||
<link id="color-stylesheet" rel="stylesheet" href="/dist/styles/utilities.css" />
|
||||
<link rel="stylesheet" href="/dist/styles/forms.css" />
|
||||
|
||||
{# Docs styles #}
|
||||
<link rel="stylesheet" href="/assets/styles/docs.css" />
|
||||
|
||||
{# Set the theme to prevent flashing #}
|
||||
<script>
|
||||
function getColorScheme() {
|
||||
return localStorage.getItem('colorScheme') || 'auto';
|
||||
}
|
||||
|
||||
function getPresetTheme () {
|
||||
return localStorage.getItem('presetTheme') || 'default';
|
||||
}
|
||||
|
||||
function isDark() {
|
||||
const colorScheme = getColorScheme()
|
||||
if (colorScheme === 'auto') {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
}
|
||||
return colorScheme === 'dark';
|
||||
}
|
||||
|
||||
const oldStylesheet = document.querySelector("#theme-stylesheet")
|
||||
|
||||
const newStylesheet = document.createElement("link")
|
||||
|
||||
let preset = getPresetTheme()
|
||||
newStylesheet.href = `/dist/styles/themes/${preset}.css`
|
||||
newStylesheet.rel = "preload"
|
||||
newStylesheet.as = "style"
|
||||
|
||||
document.head.append(newStylesheet)
|
||||
|
||||
function updateStylesheet () {
|
||||
newStylesheet.rel = "stylesheet"
|
||||
newStylesheet.id = "theme-stylesheet"
|
||||
requestAnimationFrame(() => oldStylesheet.remove())
|
||||
}
|
||||
|
||||
newStylesheet.addEventListener("load", updateStylesheet)
|
||||
|
||||
document.documentElement.classList.toggle(`wa-dark`, isDark());
|
||||
</script>
|
||||
</head>
|
||||
<body class="layout-{{ layout | stripExtension }}">
|
||||
<!-- use view="desktop" as default to reduce layout jank on desktop site. -->
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
{# Color scheme selector #}
|
||||
<wa-dropdown class="color-scheme-selector">
|
||||
<wa-button slot="trigger" appearance="filled" size="small" pill caret title="Press \ to toggle">
|
||||
<wa-select class="color-scheme-selector" appearance="filled" size="small" value="auto" pill title="Press \ to toggle">
|
||||
<wa-icon class="only-light" slot="prefix" name="sun" variant="regular"></wa-icon>
|
||||
<wa-icon class="only-dark" slot="prefix" name="moon" variant="regular"></wa-icon>
|
||||
<wa-option value="light">
|
||||
<wa-icon slot="prefix" name="sun" variant="regular"></wa-icon>
|
||||
Light
|
||||
</wa-option>
|
||||
<wa-option value="dark">
|
||||
<wa-icon slot="prefix" name="moon" variant="regular"></wa-icon>
|
||||
Dark
|
||||
</wa-option>
|
||||
<wa-divider></wa-divider>
|
||||
<wa-option value="auto">
|
||||
<wa-icon class="only-light" slot="prefix" name="sun" variant="regular"></wa-icon>
|
||||
<wa-icon class="only-dark" slot="prefix" name="moon" variant="regular"></wa-icon>
|
||||
<span class="only-light">Light</span>
|
||||
<span class="only-dark">Dark</span>
|
||||
</wa-button>
|
||||
<wa-menu>
|
||||
<wa-menu-item type="checkbox" value="light">Light</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="dark">Dark</wa-menu-item>
|
||||
<wa-divider></wa-divider>
|
||||
<wa-menu-item type="checkbox" value="auto">System</wa-menu-item>
|
||||
</wa-menu>
|
||||
</wa-dropdown>
|
||||
System
|
||||
</wa-option>
|
||||
</wa-select>
|
||||
|
||||
51
docs/_includes/head.njk
Normal file
51
docs/_includes/head.njk
Normal file
@@ -0,0 +1,51 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="{{ description }}">
|
||||
{% if noindex %}<meta name="robots" content="noindex">{% endif %}
|
||||
|
||||
<title>{{ title }}</title>
|
||||
|
||||
{# Dark mode #}
|
||||
<script>
|
||||
let colorScheme = localStorage.colorScheme;
|
||||
let isDark = localStorage.colorScheme === "dark";
|
||||
if (!colorScheme || colorScheme === "auto") {
|
||||
isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
}
|
||||
document.documentElement.classList.toggle('wa-dark', isDark);
|
||||
</script>
|
||||
|
||||
<link rel="icon" href="/assets/images/webawesome-logo.svg" />
|
||||
<link rel="apple-touch-icon" href="/assets/images/app-icon.png">
|
||||
|
||||
{# Scripts #}
|
||||
{# Hydration stuff #}
|
||||
<script src="/assets/scripts/hydration-errors.js"></script>
|
||||
<link rel="stylesheet" href="/assets/styles/hydration-errors.css">
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net">
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.10/+esm"></script>
|
||||
|
||||
{# Web Awesome #}
|
||||
<script type="module" src="/dist/webawesome.ssr-loader.js"></script>
|
||||
|
||||
{# Preset Theme #}
|
||||
<link id="theme-stylesheet" rel="stylesheet" id="theme-stylesheet" href="/dist/styles/themes/{{ forceTheme or 'default' }}.css" render="blocking" fetchpriority="high" />
|
||||
{% if not forceTheme %}
|
||||
<script>
|
||||
if (localStorage.presetTheme) {
|
||||
let preset = localStorage.presetTheme;
|
||||
let script = document.currentScript;
|
||||
let link = script.previousElementSibling;
|
||||
let newLink = link.cloneNode();
|
||||
newLink.href = link.href.replace("/default.css", `/${preset}.css`);
|
||||
newLink.addEventListener('load', () => {
|
||||
link.remove();
|
||||
});
|
||||
link.after(newLink);
|
||||
}
|
||||
</script>
|
||||
{% endif %}
|
||||
|
||||
<link rel="stylesheet" href="/dist/styles/webawesome.css" />
|
||||
<link id="color-stylesheet" rel="stylesheet" href="/dist/styles/utilities.css" />
|
||||
<link rel="stylesheet" href="/dist/styles/forms.css" />
|
||||
@@ -1,19 +1,14 @@
|
||||
{# Preset theme selector #}
|
||||
<wa-dropdown class="preset-theme-selector">
|
||||
<wa-button slot="trigger" appearance="filled" size="small" pill caret>
|
||||
<wa-icon slot="prefix" name="paintbrush" variant="regular"></wa-icon>
|
||||
<span class="preset-theme-selector__text">Default</span>
|
||||
</wa-button>
|
||||
<wa-menu>
|
||||
<wa-menu-item type="checkbox" value="default" data-description="Your trusty companion, like a perfectly broken-in pair of jeans.">Default</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="classic" data-description="Timeless elegance that never goes out of style.">Classic</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="awesome" data-description="Punchy and vibrant, the rockstar of themes.">Awesome</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="active" data-description="Energetic and tactile, always in motion.">Active</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="brutalist" data-description="Sharp, square, and unapologetically bold.">Brutalist</wa-menu-item>
|
||||
<wa-menu-item data-alpha="remove" type="checkbox" value="glassy" data-description="TODO">Glassy</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="mellow" data-description="Soft and soothing, like a lazy Sunday morning.">Mellow</wa-menu-item>
|
||||
<wa-menu-item type="checkbox" value="tailspin" data-description="Like a bird in flight, guiding you from there to here.">Tailspin</wa-menu-item>
|
||||
<wa-menu-item data-alpha="remove" type="checkbox" value="playful" data-description="TODO">Playful</wa-menu-item>
|
||||
<wa-menu-item data-alpha="remove" type="checkbox" value="premium" data-description="TODO">Premium</wa-menu-item>
|
||||
</wa-menu>
|
||||
</wa-dropdown>
|
||||
<wa-select appearance="filled" size="small" value="default" pill class="preset-theme-selector">
|
||||
<wa-icon slot="prefix" name="paintbrush" variant="regular"></wa-icon>
|
||||
<wa-option value="default" data-description="Your trusty companion, like a perfectly broken-in pair of jeans.">Default</wa-option>
|
||||
<wa-option value="classic" data-description="Timeless elegance that never goes out of style.">Classic</wa-option>
|
||||
<wa-option value="awesome" data-description="Punchy and vibrant, the rockstar of themes.">Awesome</wa-option>
|
||||
<wa-option value="active" data-description="Energetic and tactile, always in motion.">Active</wa-option>
|
||||
<wa-option value="brutalist" data-description="Sharp, square, and unapologetically bold.">Brutalist</wa-option>
|
||||
<wa-option data-alpha="remove" value="glassy" data-description="TODO">Glassy</wa-option>
|
||||
<wa-option value="mellow" data-description="Soft and soothing, like a lazy Sunday morning.">Mellow</wa-option>
|
||||
<wa-option value="tailspin" data-description="Like a bird in flight, guiding you from there to here.">Tailspin</wa-option>
|
||||
<wa-option data-alpha="remove" value="playful" data-description="TODO">Playful</wa-option>
|
||||
<wa-option data-alpha="remove" value="premium" data-description="TODO">Premium</wa-option>
|
||||
</wa-select>
|
||||
|
||||
@@ -1,55 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-fa-kit-code="b10bfbde90" data-cdn-url="{% cdnUrl %}">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="{{ description }}">
|
||||
{% if noindex %}<meta name="robots" content="noindex">{% endif %}
|
||||
|
||||
<title>{{ title }}</title>
|
||||
|
||||
<link rel="icon" href="/assets/images/webawesome-logo.svg" />
|
||||
<link rel="apple-touch-icon" href="/assets/images/app-icon.png">
|
||||
|
||||
{# Scripts #}
|
||||
{# Hydration stuff #}
|
||||
<script src="/assets/scripts/hydration-errors.js"></script>
|
||||
<link rel="stylesheet" href="/assets/styles/hydration-errors.css">
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net">
|
||||
<script type="module" src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@8.0.10/+esm"></script>
|
||||
|
||||
{# Web Awesome #}
|
||||
<script type="module" src="/dist/webawesome.ssr-loader.js"></script>
|
||||
<link rel="stylesheet" id="theme-stylesheet" />
|
||||
<link rel="stylesheet" href="/dist/styles/webawesome.css" />
|
||||
<link id="color-stylesheet" rel="stylesheet" href="/dist/styles/utilities.css" />
|
||||
<link rel="stylesheet" href="/dist/styles/forms.css" />
|
||||
|
||||
{# Set the theme to prevent flashing #}
|
||||
<script>
|
||||
function getColorScheme() {
|
||||
return localStorage.getItem('colorScheme') || 'auto';
|
||||
}
|
||||
|
||||
function getPresetTheme () {
|
||||
return localStorage.getItem('presetTheme') || 'default';
|
||||
}
|
||||
|
||||
function isDark() {
|
||||
const colorScheme = getColorScheme()
|
||||
if (colorScheme === 'auto') {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
}
|
||||
return colorScheme === 'dark';
|
||||
}
|
||||
|
||||
const stylesheet = document.getElementById("theme-stylesheet")
|
||||
let preset = getPresetTheme()
|
||||
|
||||
stylesheet.href = `/dist/styles/themes/${preset}.css`
|
||||
|
||||
document.documentElement.classList.toggle(`wa-dark`, isDark());
|
||||
</script>
|
||||
{% include 'head.njk' %}
|
||||
</head>
|
||||
<body class="layout-{{ layout | stripExtension }}">
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{% set hasSidebar = true %}
|
||||
{% set hasOutline = true %}
|
||||
|
||||
{% extends "../_includes/base-wide.njk" %}
|
||||
@@ -1,63 +0,0 @@
|
||||
//
|
||||
// Color scheme selector
|
||||
//
|
||||
(() => {
|
||||
function setColorScheme(newColorScheme) {
|
||||
colorScheme = newColorScheme;
|
||||
localStorage.setItem('colorScheme', colorScheme);
|
||||
|
||||
// Update the UI
|
||||
updateSelection();
|
||||
|
||||
// Toggle the dark mode class
|
||||
document.documentElement.classList.toggle(`wa-dark`, window.isDark());
|
||||
}
|
||||
|
||||
function updateSelection() {
|
||||
const menus = document.querySelectorAll('.color-scheme-selector wa-menu');
|
||||
|
||||
menus.forEach(menu => {
|
||||
if (!menu) return;
|
||||
[...menu.querySelectorAll('wa-menu-item')].forEach(async item => {
|
||||
await customElements.whenDefined(item.localName);
|
||||
await item.updateComplete;
|
||||
item.checked = item.getAttribute('value') === colorScheme;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let colorScheme = window.getColorScheme();
|
||||
|
||||
// Selection is not preserved when changing page, so update when opening dropdown
|
||||
document.addEventListener('wa-show', event => {
|
||||
const colorSchemeSelector = event.target.closest('.color-scheme-selector');
|
||||
if (!colorSchemeSelector) return;
|
||||
updateSelection();
|
||||
});
|
||||
|
||||
// Listen for selections
|
||||
document.addEventListener('wa-select', event => {
|
||||
const selector = event.target.closest('.color-scheme-selector');
|
||||
const menu = selector?.querySelector('wa-menu');
|
||||
console.log(menu);
|
||||
if (!menu) return;
|
||||
setColorScheme(event.detail.item.value);
|
||||
});
|
||||
|
||||
// Update the color scheme when the preference changes
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => setColorScheme(colorScheme));
|
||||
|
||||
// Toggle with backslash
|
||||
document.addEventListener('keydown', event => {
|
||||
if (
|
||||
event.key === '\\' &&
|
||||
!event.composedPath().some(el => ['input', 'textarea'].includes(el?.tagName?.toLowerCase()))
|
||||
) {
|
||||
event.preventDefault();
|
||||
setColorScheme(window.isDark() ? 'light' : 'dark');
|
||||
}
|
||||
});
|
||||
|
||||
// Set the initial color scheme and sync the UI
|
||||
setColorScheme(colorScheme);
|
||||
})();
|
||||
@@ -1,114 +0,0 @@
|
||||
(() => {
|
||||
function applyThemeChange(stylesheet, newStylesheet) {
|
||||
newStylesheet.rel = 'stylesheet';
|
||||
newStylesheet.id = stylesheet.id;
|
||||
requestAnimationFrame(() => {
|
||||
stylesheet.remove();
|
||||
});
|
||||
}
|
||||
|
||||
function setPresetTheme(newPresetTheme) {
|
||||
presetTheme = newPresetTheme;
|
||||
localStorage.setItem('presetTheme', presetTheme);
|
||||
|
||||
const stylesheet = document.getElementById('theme-stylesheet');
|
||||
const newStylesheet = Object.assign(document.createElement('link'), {
|
||||
href: `/dist/styles/themes/${presetTheme}.css`,
|
||||
rel: 'preload',
|
||||
as: 'style',
|
||||
});
|
||||
|
||||
newStylesheet.addEventListener(
|
||||
'load',
|
||||
() => {
|
||||
const canUseViewTransitions =
|
||||
document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
if (canUseViewTransitions) {
|
||||
document.startViewTransition(() => applyThemeChange(stylesheet, newStylesheet));
|
||||
} else {
|
||||
applyThemeChange(stylesheet, newStylesheet);
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
document.head.append(newStylesheet);
|
||||
updateSelection();
|
||||
document.documentElement.classList.toggle(`wa-dark`, window.isDark());
|
||||
}
|
||||
|
||||
function updateSelection(container = document) {
|
||||
const menus = container.querySelectorAll('.preset-theme-selector wa-menu');
|
||||
if (!menus) return;
|
||||
|
||||
[...menus].forEach(menu => {
|
||||
// Clear all checked states
|
||||
[...menu.querySelectorAll('wa-menu-item')].forEach(async item => {
|
||||
await customElements.whenDefined(item.localName);
|
||||
await item.updateComplete;
|
||||
item.checked = false; // Reset all items to unchecked first
|
||||
});
|
||||
|
||||
// Then set only the selected item as checked
|
||||
const selectedItem = menu.querySelector(`wa-menu-item[value="${presetTheme}"]`);
|
||||
if (selectedItem) {
|
||||
customElements.whenDefined(selectedItem.localName).then(async () => {
|
||||
await selectedItem.updateComplete;
|
||||
selectedItem.checked = true;
|
||||
container.querySelectorAll('.preset-theme-selector__text').forEach(themeSelector => {
|
||||
themeSelector.textContent = selectedItem.innerText;
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Updates any element on the page with [data-theme-name] and [data-theme-description] with the current themes info
|
||||
function updateThemeNameAndDescription(name, description) {
|
||||
document.querySelectorAll('[data-theme-name]').forEach(el => (el.textContent = name));
|
||||
document.querySelectorAll('[data-theme-description]').forEach(el => (el.textContent = description));
|
||||
}
|
||||
|
||||
let presetTheme = window.getPresetTheme();
|
||||
|
||||
// Selection is not preserved when changing page, so update when opening dropdown
|
||||
document.addEventListener('wa-show', event => {
|
||||
const presetThemeSelector = event.target.closest('.preset-theme-selector');
|
||||
if (!presetThemeSelector) return;
|
||||
updateSelection();
|
||||
});
|
||||
|
||||
// Listen for selections
|
||||
document.addEventListener('wa-select', event => {
|
||||
const menu = event.target.closest('.preset-theme-selector wa-menu');
|
||||
if (!menu) return;
|
||||
setPresetTheme(event.detail.item.value);
|
||||
updateThemeNameAndDescription(event.detail.item.textContent, event.detail.item.getAttribute('data-description'));
|
||||
});
|
||||
|
||||
// Set the initial preset name/description in the UI by grabbing it from the dropdown (ugly, but quick)
|
||||
const currentTheme = document.querySelector(`.preset-theme-selector wa-menu-item[value="${presetTheme}"]`);
|
||||
if (currentTheme) {
|
||||
updateThemeNameAndDescription(currentTheme.textContent, currentTheme.getAttribute('data-description'));
|
||||
}
|
||||
|
||||
// Update the color scheme when the preference changes
|
||||
window.matchMedia('(prefers-preset-theme: dark)').addEventListener('change', () => setPresetTheme(presetTheme));
|
||||
updateSelection();
|
||||
|
||||
/**
|
||||
* Without this, there's a flash of the incorrect preset theme.
|
||||
*/
|
||||
function updateSelectionBeforeTurboLoad(e) {
|
||||
const newElement = e.detail.newBody || e.detail.newFrame || e.detail.newStream;
|
||||
if (!newElement) {
|
||||
return;
|
||||
}
|
||||
updateSelection(newElement);
|
||||
}
|
||||
|
||||
['turbo:before-render', 'turbo:before-stream-render', 'turbo:before-frame-render'].forEach(eventName => {
|
||||
document.addEventListener(eventName, updateSelectionBeforeTurboLoad);
|
||||
});
|
||||
})();
|
||||
200
docs/assets/scripts/theme-picker.js
Normal file
200
docs/assets/scripts/theme-picker.js
Normal file
@@ -0,0 +1,200 @@
|
||||
// Helper for view transitions
|
||||
export function domChange(fn, { behavior = 'smooth' } = {}) {
|
||||
const canUseViewTransitions =
|
||||
document.startViewTransition && !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
if (canUseViewTransitions && behavior === 'smooth') {
|
||||
document.startViewTransition(fn);
|
||||
} else {
|
||||
fn(true);
|
||||
}
|
||||
}
|
||||
|
||||
function nextFrame() {
|
||||
return new Promise(resolve => requestAnimationFrame(resolve));
|
||||
}
|
||||
|
||||
export class ThemeAspect {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.set();
|
||||
|
||||
// Update when local storage changes.
|
||||
// That way changes in one window will propagate to others (including iframes).
|
||||
window.addEventListener('storage', event => {
|
||||
if (event.key === this.key) {
|
||||
this.set();
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for selections
|
||||
document.addEventListener('wa-change', event => {
|
||||
const picker = event.target.closest(this.picker);
|
||||
if (picker) {
|
||||
this.set(picker.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get() {
|
||||
return localStorage.getItem(this.key) ?? this.defaultValue;
|
||||
}
|
||||
|
||||
computed = {};
|
||||
|
||||
get computedValue() {
|
||||
if (this.value in this.computed) {
|
||||
return this.computed[this.value];
|
||||
}
|
||||
|
||||
return this.value;
|
||||
}
|
||||
|
||||
set(value = this.get()) {
|
||||
if (value === this.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.value = value;
|
||||
|
||||
if (this.value === this.defaultValue) {
|
||||
localStorage.removeItem(this.key);
|
||||
} else {
|
||||
localStorage.setItem(this.key, this.value);
|
||||
}
|
||||
|
||||
this.applyChange();
|
||||
this.syncUI();
|
||||
}
|
||||
|
||||
syncUI(container = document) {
|
||||
for (let picker of container.querySelectorAll(this.picker)) {
|
||||
picker.setAttribute('value', this.value);
|
||||
picker.value = this.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const presetTheme = new ThemeAspect({
|
||||
defaultValue: 'default',
|
||||
key: 'presetTheme',
|
||||
picker: 'wa-select.preset-theme-selector',
|
||||
|
||||
applyChange() {
|
||||
const oldStylesheets = [...document.querySelectorAll('#theme-stylesheet')];
|
||||
const oldStylesheet = oldStylesheets.pop();
|
||||
|
||||
if (oldStylesheets.length > 0) {
|
||||
// Remove all but the last one
|
||||
for (let stylesheet of oldStylesheets) {
|
||||
stylesheet.remove();
|
||||
}
|
||||
}
|
||||
|
||||
const href = `/dist/styles/themes/${this.value}.css`;
|
||||
|
||||
if (!oldStylesheet || oldStylesheet.getAttribute('href') !== href) {
|
||||
const newStylesheet = document.createElement('link');
|
||||
Object.assign(newStylesheet, { href, id: 'theme-stylesheet', rel: 'preload', as: 'style' });
|
||||
oldStylesheet.after(newStylesheet);
|
||||
|
||||
newStylesheet.addEventListener(
|
||||
'load',
|
||||
e => {
|
||||
domChange(
|
||||
async instant => {
|
||||
// Swap stylesheets
|
||||
newStylesheet.rel = 'stylesheet';
|
||||
|
||||
if (instant) {
|
||||
// If no VT, delay by 1 frame to make it smoother
|
||||
await nextFrame();
|
||||
}
|
||||
|
||||
oldStylesheet.remove();
|
||||
},
|
||||
{ behavior: 'smooth' },
|
||||
);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
|
||||
nextFrame().then(_ => updateThemeNameAndDescription());
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const colorScheme = new ThemeAspect({
|
||||
defaultValue: 'auto',
|
||||
key: 'colorScheme',
|
||||
picker: 'wa-select.color-scheme-selector',
|
||||
|
||||
computed: {
|
||||
get auto() {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
},
|
||||
},
|
||||
|
||||
applyChange() {
|
||||
// Toggle the dark mode class
|
||||
domChange(() => {
|
||||
let dark = this.computedValue === 'dark';
|
||||
document.documentElement.classList.toggle(`wa-dark`, dark);
|
||||
|
||||
for (let el of document.querySelectorAll('.wa-invert')) {
|
||||
el.classList.toggle('wa-dark', !dark);
|
||||
el.classList.toggle('wa-light', dark);
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Update the color scheme when the preference changes
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => colorScheme.set());
|
||||
|
||||
/**
|
||||
* Without this, there's a flash of the incorrect preset theme.
|
||||
*/
|
||||
function updateSelectionBeforeTurboLoad(e) {
|
||||
const newElement = e.detail.newBody || e.detail.newFrame || e.detail.newStream;
|
||||
if (newElement) {
|
||||
presetTheme.syncUI(newElement);
|
||||
colorScheme.syncUI(newElement);
|
||||
}
|
||||
}
|
||||
|
||||
['turbo:before-render', 'turbo:before-stream-render', 'turbo:before-frame-render'].forEach(eventName => {
|
||||
document.addEventListener(eventName, updateSelectionBeforeTurboLoad);
|
||||
});
|
||||
|
||||
document.addEventListener('turbo:render', updateThemeNameAndDescription);
|
||||
|
||||
// Toggle color scheme with backslash
|
||||
document.addEventListener('keydown', event => {
|
||||
if (
|
||||
event.key === '\\' &&
|
||||
!event.composedPath().some(el => ['input', 'textarea'].includes(el?.tagName?.toLowerCase()))
|
||||
) {
|
||||
event.preventDefault();
|
||||
colorScheme.set(theming.colorScheme.resolvedValue === 'dark' ? 'light' : 'dark');
|
||||
}
|
||||
});
|
||||
|
||||
// Temp hack for theme switcher
|
||||
function updateThemeNameAndDescription() {
|
||||
let selectedOption = document.querySelector(`.preset-theme-selector wa-option[value="${presetTheme.value}"]`);
|
||||
|
||||
if (selectedOption) {
|
||||
let title = selectedOption.textContent;
|
||||
let description = selectedOption.dataset.description;
|
||||
for (let element of document.querySelectorAll('[data-theme-name]')) {
|
||||
element.textContent = title;
|
||||
}
|
||||
for (let element of document.querySelectorAll('[data-theme-description]')) {
|
||||
element.textContent = description;
|
||||
}
|
||||
}
|
||||
}
|
||||
updateThemeNameAndDescription();
|
||||
|
||||
window.presetTheme = presetTheme;
|
||||
Reference in New Issue
Block a user