|
| 1 | +import type { ColorScheme } from "./client"; |
| 2 | +import { data_fr_scheme, data_fr_theme, rootColorSchemeStyleTagId } from "./constants"; |
| 3 | +import { getColors } from "../fr/colors"; |
| 4 | + |
| 5 | +export const getScriptToRunAsap = (defaultColorScheme: ColorScheme | "system") => ` |
| 6 | +{ |
| 7 | +
|
| 8 | + window.ssrWasPerformedWithIsDark = "${defaultColorScheme}" === "dark"; |
| 9 | + |
| 10 | + const isDark = (() => { |
| 11 | + |
| 12 | + const isDarkExplicitlyProvidedAsParameter = (() => { |
| 13 | + if ("${defaultColorScheme}" === "system") { |
| 14 | + return undefined; |
| 15 | + } |
| 16 | + |
| 17 | + switch ("${defaultColorScheme}") { |
| 18 | + case "dark": return true; |
| 19 | + case "light": return false; |
| 20 | + } |
| 21 | + })(); |
| 22 | + |
| 23 | + const isDarkFromLocalStorage = (() => { |
| 24 | + const colorSchemeReadFromLocalStorage = localStorage.getItem("scheme"); |
| 25 | + |
| 26 | + if (colorSchemeReadFromLocalStorage === null) { |
| 27 | + return undefined; |
| 28 | + } |
| 29 | + |
| 30 | + if (colorSchemeReadFromLocalStorage === "system") { |
| 31 | + return undefined; |
| 32 | + } |
| 33 | + |
| 34 | + switch (colorSchemeReadFromLocalStorage) { |
| 35 | + case "dark": |
| 36 | + return true; |
| 37 | + case "light": |
| 38 | + return false; |
| 39 | + } |
| 40 | + })(); |
| 41 | + |
| 42 | + const isDarkFromOsPreference = (() => { |
| 43 | + if (!window.matchMedia) { |
| 44 | + return undefined; |
| 45 | + } |
| 46 | + |
| 47 | + return window.matchMedia("(prefers-color-scheme: dark)").matches; |
| 48 | + })(); |
| 49 | + |
| 50 | + const isDarkFallback = false; |
| 51 | + |
| 52 | + return ( |
| 53 | + isDarkFromLocalStorage ?? |
| 54 | + isDarkExplicitlyProvidedAsParameter ?? |
| 55 | + isDarkFromOsPreference ?? |
| 56 | + isDarkFallback |
| 57 | + ); |
| 58 | + |
| 59 | + })(); |
| 60 | + |
| 61 | + ["${data_fr_scheme}", "${data_fr_theme}"].forEach(attr => document.documentElement.setAttribute(attr, isDark ? "dark" : "light")); |
| 62 | +
|
| 63 | + { |
| 64 | +
|
| 65 | + const element = document.createElement("style"); |
| 66 | +
|
| 67 | + element.id = "${rootColorSchemeStyleTagId}"; |
| 68 | +
|
| 69 | + element.innerHTML = \`:root { color-scheme: \${isDark ? "dark" : "light"}; }\`; |
| 70 | +
|
| 71 | + document.head.appendChild(element); |
| 72 | +
|
| 73 | + } |
| 74 | +
|
| 75 | + { |
| 76 | +
|
| 77 | + const element = document.createElement("meta"); |
| 78 | +
|
| 79 | + element.name = "theme-color"; |
| 80 | +
|
| 81 | + element.content = isDark ? "${ |
| 82 | + getColors(true).decisions.background.default.grey.default |
| 83 | + }" : "${getColors(false).decisions.background.default.grey.default}"; |
| 84 | +
|
| 85 | + document.head.appendChild(element); |
| 86 | +
|
| 87 | + } |
| 88 | +
|
| 89 | +} |
| 90 | +`; |
0 commit comments