From 9c4b190e2710523d4e7a20baa2470f2ac2a88619 Mon Sep 17 00:00:00 2001
From: Elliott Marquez <5981958+e111077@users.noreply.github.com>
Date: Wed, 28 Feb 2024 17:44:57 -0800
Subject: [PATCH] add meta theme color
---
.../site/_includes/default.html | 1 +
.../src/global/apply-saved-theme.ts | 3 ++
packages/lit-dev-content/src/global/theme.ts | 38 +++++++++++++++++++
3 files changed, 42 insertions(+)
diff --git a/packages/lit-dev-content/site/_includes/default.html b/packages/lit-dev-content/site/_includes/default.html
index fe04aacdd..9b1754b6b 100644
--- a/packages/lit-dev-content/site/_includes/default.html
+++ b/packages/lit-dev-content/site/_includes/default.html
@@ -14,6 +14,7 @@
{% endif %}
+
{% inlinejs "global/apply-saved-theme.js" %}
{% inlinecss "colors.css" %}
{% inlinecss "global.css" %}
diff --git a/packages/lit-dev-content/src/global/apply-saved-theme.ts b/packages/lit-dev-content/src/global/apply-saved-theme.ts
index a20e1f24f..3c74ff02f 100644
--- a/packages/lit-dev-content/src/global/apply-saved-theme.ts
+++ b/packages/lit-dev-content/src/global/apply-saved-theme.ts
@@ -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');
@@ -15,3 +17,4 @@ if (!lastTheme) {
// Applies the theme string to the document.
document.body.classList.add(lastTheme);
+updateMetaColor(lastTheme as 'light' | 'dark' | 'auto');
diff --git a/packages/lit-dev-content/src/global/theme.ts b/packages/lit-dev-content/src/global/theme.ts
index 8630188b5..8fb19245e 100644
--- a/packages/lit-dev-content/src/global/theme.ts
+++ b/packages/lit-dev-content/src/global/theme.ts
@@ -37,6 +37,36 @@ function saveColorMode(mode: ColorMode) {
localStorage.setItem('color-mode', mode);
}
+/**
+ * Updates the `` 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.
*/
@@ -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');
+ }
+ });
}