hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { |
| 2 | type Accessor, |
| 3 | type ParentProps, |
| 4 | createContext, |
| 5 | createEffect, |
| 6 | createSignal, |
| 7 | useContext, |
| 8 | } from "solid-js"; |
| 9 | import { patchMyPreferences } from "@/api/users"; |
| 10 | import type { User } from "@/api/client"; |
| 11 | import { formatMessage, isLocaleLoaded, loadLocale, messageFor, type Locale, type MessageKey } from "@/i18n/messages"; |
| 12 | |
| 13 | export type ThemeMode = "light" | "dark"; |
| 14 | |
| 15 | type PreferencesContextValue = { |
| 16 | locale: Accessor<Locale>; |
| 17 | setLocale: (locale: Locale) => void; |
| 18 | theme: Accessor<ThemeMode>; |
| 19 | setTheme: (theme: ThemeMode) => void; |
| 20 | paletteColor: Accessor<string | null>; |
| 21 | setPaletteColor: (color: string | null) => void; |
| 22 | toggleTheme: () => void; |
| 23 | hydratePreferences: (user: Pick<User, "theme" | "language" | "palette_color">) => void; |
| 24 | sidebarCollapsed: Accessor<boolean>; |
| 25 | setSidebarCollapsed: (collapsed: boolean) => void; |
| 26 | toggleSidebar: () => void; |
| 27 | t: (key: MessageKey, vars?: Record<string, string | number>) => string; |
| 28 | }; |
| 29 | |
| 30 | const PreferencesContext = createContext<PreferencesContextValue>(); |
| 31 | |
| 32 | const LOCALE_KEY = "hezarfen.locale"; |
| 33 | const THEME_KEY = "hezarfen.theme"; |
| 34 | const PALETTE_COLOR_KEY = "hezarfen.paletteColor"; |
| 35 | const SIDEBAR_KEY = "hezarfen.sidebarCollapsed"; |
| 36 | const HEX_COLOR = /^#[\da-f]{6}$/i; |
| 37 | |
| 38 | function getStorage(): Storage | null { |
| 39 | if (typeof window === "undefined") return null; |
| 40 | try { |
| 41 | return window.localStorage; |
| 42 | } catch { |
| 43 | return null; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | function writeStorage(key: string, value: string) { |
| 48 | try { |
| 49 | getStorage()?.setItem(key, value); |
| 50 | } catch { |
| 51 | // Preferences still work for this session when storage is blocked/full. |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | function removeStorage(key: string) { |
| 56 | try { |
| 57 | getStorage()?.removeItem(key); |
| 58 | } catch { |
| 59 | // Preferences still work for this session when storage is blocked. |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /** The locale the app boots in — the saved choice, else the browser language. */ |
| 64 | export function readLocale(): Locale { |
| 65 | const storage = getStorage(); |
| 66 | if (!storage) return "en"; |
| 67 | try { |
| 68 | const saved = storage.getItem(LOCALE_KEY); |
| 69 | if (saved === "en" || saved === "tr") return saved; |
| 70 | return navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; |
| 71 | } catch { |
| 72 | return "en"; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | function readTheme(): ThemeMode { |
| 77 | const storage = getStorage(); |
| 78 | if (!storage) return "light"; |
| 79 | try { |
| 80 | const saved = storage.getItem(THEME_KEY); |
| 81 | if (saved === "light" || saved === "dark") return saved; |
| 82 | return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; |
| 83 | } catch { |
| 84 | return "light"; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | function readPaletteColor(): string | null { |
| 89 | try { |
| 90 | const saved = getStorage()?.getItem(PALETTE_COLOR_KEY); |
| 91 | return saved && HEX_COLOR.test(saved) ? saved.toLowerCase() : null; |
| 92 | } catch { |
| 93 | return null; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | function hexToHslParts(hex: string): { h: number; s: number; l: number } { |
| 98 | const [red, green, blue] = hex.slice(1).match(/.{2}/g)!.map((value) => parseInt(value, 16) / 255); |
| 99 | const max = Math.max(red, green, blue); |
| 100 | const min = Math.min(red, green, blue); |
| 101 | const delta = max - min; |
| 102 | const lightness = (max + min) / 2; |
| 103 | |
| 104 | if (delta === 0) return { h: 0, s: 0, l: lightness * 100 }; |
| 105 | |
| 106 | const saturation = delta / (1 - Math.abs(2 * lightness - 1)); |
| 107 | const hue = |
| 108 | max === red |
| 109 | ? 60 * (((green - blue) / delta) % 6) |
| 110 | : max === green |
| 111 | ? 60 * ((blue - red) / delta + 2) |
| 112 | : 60 * ((red - green) / delta + 4); |
| 113 | |
| 114 | return { h: hue < 0 ? hue + 360 : hue, s: saturation * 100, l: lightness * 100 }; |
| 115 | } |
| 116 | |
| 117 | function hslToRgb(h: number, s: number, l: number): [number, number, number] { |
| 118 | const sat = s / 100; |
| 119 | const light = l / 100; |
| 120 | const chroma = (1 - Math.abs(2 * light - 1)) * sat; |
| 121 | const x = chroma * (1 - Math.abs(((h / 60) % 2) - 1)); |
| 122 | const m = light - chroma / 2; |
| 123 | const [r1, g1, b1] = |
| 124 | h < 60 ? [chroma, x, 0] |
| 125 | : h < 120 ? [x, chroma, 0] |
| 126 | : h < 180 ? [0, chroma, x] |
| 127 | : h < 240 ? [0, x, chroma] |
| 128 | : h < 300 ? [x, 0, chroma] |
| 129 | : [chroma, 0, x]; |
| 130 | return [(r1 + m) * 255, (g1 + m) * 255, (b1 + m) * 255]; |
| 131 | } |
| 132 | |
| 133 | function relativeLuminance(r: number, g: number, b: number): number { |
| 134 | const channel = (value: number) => { |
| 135 | const c = value / 255; |
| 136 | return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; |
| 137 | }; |
| 138 | return channel(r) * 0.2126 + channel(g) * 0.7152 + channel(b) * 0.0722; |
| 139 | } |
| 140 | |
| 141 | function foregroundFor(h: number, s: number, l: number): string { |
| 142 | const [r, g, b] = hslToRgb(h, s, l); |
| 143 | return relativeLuminance(r, g, b) > 0.179 ? "210 10.8% 14.5%" : "210 16.7% 97.6%"; |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * A theme-appropriate variant of the user's chosen accent: the hue is kept, |
| 148 | * saturation is clamped into a tasteful range, but lightness is pinned to a |
| 149 | * value known to read well against that theme's background — the swatch's own |
| 150 | * lightness is deliberately ignored. Without this, a pastel pick (e.g. |
| 151 | * `#fefae0`) would be nearly invisible as a light-mode button, and a near-black |
| 152 | * pick (e.g. `#023047`) would vanish against the near-black dark background. |
| 153 | */ |
| 154 | /** WCAG contrast ratio between two relative luminances. */ |
| 155 | function contrastRatio(a: number, b: number): number { |
| 156 | const [hi, lo] = a > b ? [a, b] : [b, a]; |
| 157 | return (hi + 0.05) / (lo + 0.05); |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * The darkest-needed step of the light-mode accent that still reads as the |
| 162 | * accent but reaches 4.5:1 as small text on white and on the 97% page |
| 163 | * background. A yellow or cyan pick at the button lightness does not. |
| 164 | */ |
| 165 | export function accentTextLightness(h: number, s: number, from: number): number { |
| 166 | const page = relativeLuminance(...hslToRgb(0, 0, 97)); |
| 167 | for (let l = from; l > 10; l -= 1) { |
| 168 | const text = relativeLuminance(...hslToRgb(h, s, l)); |
| 169 | if (contrastRatio(text, page) >= 4.5) return l; |
| 170 | } |
| 171 | return 10; |
| 172 | } |
| 173 | |
| 174 | function themedAccent(hex: string, mode: ThemeMode): { hsl: string; fg: string } { |
| 175 | const { h, s } = hexToHslParts(hex); |
| 176 | const sat = Math.min(88, Math.max(30, s)); |
| 177 | const lightness = mode === "light" ? 40 : 68; |
| 178 | return { |
| 179 | hsl: `${Math.round(h)} ${Math.round(sat)}% ${lightness}%`, |
| 180 | fg: foregroundFor(h, sat, lightness), |
| 181 | }; |
| 182 | } |
| 183 | |
| 184 | function readSidebarCollapsed(): boolean { |
| 185 | const storage = getStorage(); |
| 186 | if (!storage) return false; |
| 187 | try { |
| 188 | return storage.getItem(SIDEBAR_KEY) === "1"; |
| 189 | } catch { |
| 190 | return false; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | export function PreferencesProvider(props: ParentProps) { |
| 195 | const [locale, setLocaleSignal] = createSignal<Locale>(readLocale()); |
| 196 | const [theme, setThemeSignal] = createSignal<ThemeMode>(readTheme()); |
| 197 | const [paletteColor, setPaletteColorSignal] = createSignal<string | null>(readPaletteColor()); |
| 198 | const [sidebarCollapsed, setSidebarCollapsedSignal] = createSignal(readSidebarCollapsed()); |
| 199 | |
| 200 | createEffect(() => { |
| 201 | const l = locale(); |
| 202 | writeStorage(LOCALE_KEY, l); |
| 203 | document.documentElement.lang = l; |
| 204 | }); |
| 205 | |
| 206 | createEffect(() => { |
| 207 | const th = theme(); |
| 208 | writeStorage(THEME_KEY, th); |
| 209 | document.documentElement.setAttribute("data-kb-theme", th); |
| 210 | document.documentElement.classList.toggle("dark", th === "dark"); |
| 211 | // The boot script paints an inline background on <html> because it runs |
| 212 | // before the stylesheet; from here on the stylesheet owns that color, and |
| 213 | // a stale literal would survive a theme switch. |
| 214 | document.documentElement.style.removeProperty("background-color"); |
| 215 | // The system bars (status bar, gesture bar) are painted by the shell from |
| 216 | // this meta tag, not from the page, so without the update they keep the |
| 217 | // boot value and a switched theme left a white strip framing a dark app. |
| 218 | // The value is read back from --background so the two cannot drift apart. |
| 219 | const meta = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]'); |
| 220 | if (meta) { |
| 221 | const background = getComputedStyle(document.documentElement).getPropertyValue("--background").trim(); |
| 222 | if (background) meta.content = `hsl(${background})`; |
| 223 | } |
| 224 | }); |
| 225 | |
| 226 | createEffect(() => { |
| 227 | const color = paletteColor(); |
| 228 | const root = document.documentElement.style; |
| 229 | if (!color) { |
| 230 | removeStorage(PALETTE_COLOR_KEY); |
| 231 | root.removeProperty("--accent-light"); |
| 232 | root.removeProperty("--accent-light-fg"); |
| 233 | root.removeProperty("--accent-light-text"); |
| 234 | root.removeProperty("--accent-dark"); |
| 235 | root.removeProperty("--accent-dark-fg"); |
| 236 | return; |
| 237 | } |
| 238 | writeStorage(PALETTE_COLOR_KEY, color); |
| 239 | // Both variants are always set, regardless of the active theme, so a live |
| 240 | // light/dark toggle picks up the right one immediately via the CSS |
| 241 | // `[data-kb-theme="dark"]` cascade — no need to recompute on theme change. |
| 242 | const light = themedAccent(color, "light"); |
| 243 | const dark = themedAccent(color, "dark"); |
| 244 | root.setProperty("--accent-light", light.hsl); |
| 245 | root.setProperty("--accent-light-fg", light.fg); |
| 246 | { |
| 247 | const { h, s } = hexToHslParts(color); |
| 248 | const sat = Math.min(88, Math.max(30, s)); |
| 249 | root.setProperty("--accent-light-text", `${Math.round(h)} ${Math.round(sat)}% ${accentTextLightness(h, sat, 40)}%`); |
| 250 | } |
| 251 | root.setProperty("--accent-dark", dark.hsl); |
| 252 | root.setProperty("--accent-dark-fg", dark.fg); |
| 253 | }); |
| 254 | |
| 255 | createEffect(() => { |
| 256 | writeStorage(SIDEBAR_KEY, sidebarCollapsed() ? "1" : "0"); |
| 257 | }); |
| 258 | |
| 259 | const persistPreferences = (body: Parameters<typeof patchMyPreferences>[0]) => { |
| 260 | void patchMyPreferences(body).catch(() => undefined); |
| 261 | }; |
| 262 | |
| 263 | // A dictionary is its own chunk, so a switch waits for it before flipping — |
| 264 | // otherwise one frame would render raw keys. The last request wins when two |
| 265 | // switches race. |
| 266 | let wantedLocale: Locale = locale(); |
| 267 | const switchLocale = (l: Locale) => { |
| 268 | wantedLocale = l; |
| 269 | if (isLocaleLoaded(l)) { |
| 270 | setLocaleSignal(l); |
| 271 | return; |
| 272 | } |
| 273 | void loadLocale(l).then( |
| 274 | () => { |
| 275 | if (wantedLocale === l) setLocaleSignal(l); |
| 276 | }, |
| 277 | () => undefined, |
| 278 | ); |
| 279 | }; |
| 280 | const setLocale = (l: Locale) => { |
| 281 | switchLocale(l); |
| 282 | persistPreferences({ language: l }); |
| 283 | }; |
| 284 | const setTheme = (th: ThemeMode) => { |
| 285 | setThemeSignal(th); |
| 286 | persistPreferences({ theme: th }); |
| 287 | }; |
| 288 | const setPaletteColor = (color: string | null) => { |
| 289 | const next = color && HEX_COLOR.test(color) ? color.toLowerCase() : null; |
| 290 | setPaletteColorSignal(next); |
| 291 | // Empty string clears the accent back to "never chose" on the backend; a |
| 292 | // valid hex sets it. Mirrors the theme/language sync. |
| 293 | persistPreferences({ palette_color: next ?? "" }); |
| 294 | }; |
| 295 | const toggleTheme = () => { |
| 296 | const next = theme() === "dark" ? "light" : "dark"; |
| 297 | setTheme(next); |
| 298 | }; |
| 299 | const hydratePreferences = (user: Pick<User, "theme" | "language" | "palette_color">) => { |
| 300 | if (user.language === "en" || user.language === "tr") switchLocale(user.language); |
| 301 | if (user.theme === "light" || user.theme === "dark") setThemeSignal(user.theme); |
| 302 | if (user.palette_color && HEX_COLOR.test(user.palette_color)) { |
| 303 | setPaletteColorSignal(user.palette_color.toLowerCase()); |
| 304 | } |
| 305 | }; |
| 306 | const setSidebarCollapsed = (v: boolean) => setSidebarCollapsedSignal(v); |
| 307 | const toggleSidebar = () => setSidebarCollapsedSignal((v) => !v); |
| 308 | |
| 309 | const t = (key: MessageKey, vars?: Record<string, string | number>) => { |
| 310 | const loc = locale(); |
| 311 | const text = messageFor(loc, key) ?? key; |
| 312 | return formatMessage(text, vars); |
| 313 | }; |
| 314 | |
| 315 | return ( |
| 316 | <PreferencesContext.Provider |
| 317 | value={{ |
| 318 | locale, |
| 319 | setLocale, |
| 320 | theme, |
| 321 | setTheme, |
| 322 | paletteColor, |
| 323 | setPaletteColor, |
| 324 | toggleTheme, |
| 325 | hydratePreferences, |
| 326 | sidebarCollapsed, |
| 327 | setSidebarCollapsed, |
| 328 | toggleSidebar, |
| 329 | t, |
| 330 | }} |
| 331 | > |
| 332 | {props.children} |
| 333 | </PreferencesContext.Provider> |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | export function usePreferences(): PreferencesContextValue { |
| 338 | const ctx = useContext(PreferencesContext); |
| 339 | if (!ctx) throw new Error("usePreferences must be used within PreferencesProvider"); |
| 340 | return ctx; |
| 341 | } |
| 342 | |
| 343 | export function useT() { |
| 344 | const { t, locale } = usePreferences(); |
| 345 | // Touch locale so callers re-render when language changes even if they |
| 346 | // only hold a reference to `t` in some edge paths. |
| 347 | void locale(); |
| 348 | return t; |
| 349 | } |