Skip to content

Commit

Permalink
add meta theme color
Browse files Browse the repository at this point in the history
  • Loading branch information
e111077 committed Feb 29, 2024
1 parent 5023d0e commit 9c4b190
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/lit-dev-content/site/_includes/default.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
{% endif %}
<link rel="modulepreload" href="{{ site.baseurl }}/js/global/hydrate-common-components.js">

<meta name="theme-color" content="#fff">
{% inlinejs "global/apply-saved-theme.js" %}
{% inlinecss "colors.css" %}
{% inlinecss "global.css" %}
Expand Down
3 changes: 3 additions & 0 deletions packages/lit-dev-content/src/global/apply-saved-theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {updateMetaColor} from './theme.js';

// Checks if there has been a theme already set from a prior visit
let lastTheme = localStorage.getItem('color-mode');

Expand All @@ -15,3 +17,4 @@ if (!lastTheme) {

// Applies the theme string to the document.
document.body.classList.add(lastTheme);
updateMetaColor(lastTheme as 'light' | 'dark' | 'auto');
38 changes: 38 additions & 0 deletions packages/lit-dev-content/src/global/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,36 @@ function saveColorMode(mode: ColorMode) {
localStorage.setItem('color-mode', mode);
}

/**
* Updates the `<meta name="theme-color">` tag to match the current color mode.
*
* @param mode Mode from which to update the meta color.
*/
export function updateMetaColor(mode: ColorMode) {
const meta = document.head.querySelector(
'meta[name="theme-color"]:not([media])'
);
if (!meta) {
return;
}

let isLight = mode === 'light';

if (mode === 'auto') {
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)'
).matches;
isLight = !prefersDark;
}

if (isLight) {
meta?.setAttribute('content', '#fff');
return;
}

meta?.setAttribute('content', '#121212');
}

/**
* Applies theme-based event listeners such as changing color mode.
*/
Expand All @@ -46,5 +76,13 @@ export function applyColorThemeListeners() {
}
document.body.addEventListener('change-color-mode', (event) => {
applyColorMode(event.mode);
updateMetaColor(event.mode);
});
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (event) => {
if (getCurrentMode() === 'auto') {
updateMetaColor(event.matches ? 'dark' : 'light');
}
});
}

0 comments on commit 9c4b190

Please sign in to comment.