forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.tsx
More file actions
369 lines (334 loc) · 11.5 KB
/
Copy pathcontext.tsx
File metadata and controls
369 lines (334 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// @refresh reload
import { createEffect, onMount } from "solid-js"
import { createStore } from "solid-js/store"
import { makeEventListener } from "@solid-primitives/event-listener"
import { createSimpleContext } from "../context/helper"
import oc2ThemeJson from "./themes/oc-2.json"
import { resolveThemeVariant, themeToCss } from "./resolve"
import { resolveThemeVariantV2, themeV2ToCss } from "./v2/resolve"
import type { DesktopTheme } from "./types"
export type ColorScheme = "light" | "dark" | "system"
const STORAGE_KEYS = {
THEME_ID: "opencode-theme-id",
COLOR_SCHEME: "opencode-color-scheme",
THEME_CSS_LIGHT: "opencode-theme-css-light",
THEME_CSS_DARK: "opencode-theme-css-dark",
} as const
const THEME_STYLE_ID = "oc-theme"
let files: Record<string, () => Promise<{ default: DesktopTheme }>> | undefined
let ids: string[] | undefined
let known: Set<string> | undefined
function getFiles() {
if (files) return files
files = import.meta.glob<{ default: DesktopTheme }>("./themes/*.json")
return files
}
function themeIDs() {
if (ids) return ids
ids = Object.keys(getFiles())
.map((path) => path.slice("./themes/".length, -".json".length))
.sort()
return ids
}
function knownThemes() {
if (known) return known
known = new Set(themeIDs())
return known
}
const names: Record<string, string> = {
"oc-2": "OC-2",
amoled: "AMOLED",
aura: "Aura",
ayu: "Ayu",
carbonfox: "Carbonfox",
catppuccin: "Catppuccin",
"catppuccin-frappe": "Catppuccin Frappe",
"catppuccin-macchiato": "Catppuccin Macchiato",
cobalt2: "Cobalt2",
cursor: "Cursor",
dracula: "Dracula",
everforest: "Everforest",
flexoki: "Flexoki",
github: "GitHub",
gruvbox: "Gruvbox",
kanagawa: "Kanagawa",
"lucent-orng": "Lucent Orng",
material: "Material",
matrix: "Matrix",
mercury: "Mercury",
monokai: "Monokai",
nightowl: "Night Owl",
nord: "Nord",
"one-dark": "One Dark",
onedarkpro: "One Dark Pro",
opencode: "OpenCode",
orng: "Orng",
"osaka-jade": "Osaka Jade",
palenight: "Palenight",
rosepine: "Rose Pine",
shadesofpurple: "Shades of Purple",
solarized: "Solarized",
synthwave84: "Synthwave '84",
tokyonight: "Tokyonight",
vercel: "Vercel",
vesper: "Vesper",
zenburn: "Zenburn",
}
const oc2Theme = oc2ThemeJson as DesktopTheme
function normalize(id: string | null | undefined) {
return id === "oc-1" ? "oc-2" : id
}
function read(key: string) {
if (typeof localStorage !== "object") return null
try {
return localStorage.getItem(key)
} catch {
return null
}
}
function write(key: string, value: string) {
if (typeof localStorage !== "object") return
try {
localStorage.setItem(key, value)
} catch {}
}
function drop(key: string) {
if (typeof localStorage !== "object") return
try {
localStorage.removeItem(key)
} catch {}
}
function clear() {
drop(STORAGE_KEYS.THEME_CSS_LIGHT)
drop(STORAGE_KEYS.THEME_CSS_DARK)
}
function ensureThemeStyleElement(): HTMLStyleElement {
const existing = document.getElementById(THEME_STYLE_ID) as HTMLStyleElement | null
if (existing) return existing
const element = document.createElement("style")
element.id = THEME_STYLE_ID
document.head.appendChild(element)
return element
}
function getSystemMode(): "light" | "dark" {
if (typeof window !== "object") return "light"
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
}
function applyThemeCss(theme: DesktopTheme, themeId: string, mode: "light" | "dark") {
const isDark = mode === "dark"
const variant = isDark ? theme.dark : theme.light
const tokens = resolveThemeVariant(variant, isDark)
const css = themeToCss(tokens)
const v2 = themeV2ToCss(resolveThemeVariantV2(variant, isDark))
if (themeId !== "oc-2") {
write(isDark ? STORAGE_KEYS.THEME_CSS_DARK : STORAGE_KEYS.THEME_CSS_LIGHT, `${css}\n ${v2}`)
}
const fullCss = `:root {
color-scheme: ${mode};
--text-mix-blend-mode: ${isDark ? "plus-lighter" : "multiply"};
${css}
${v2}
}`
document.getElementById("oc-theme-preload")?.remove()
ensureThemeStyleElement().textContent = fullCss
document.documentElement.dataset.theme = themeId
document.documentElement.dataset.colorScheme = mode
// Update theme-color meta tag to match light/dark mode
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.setAttribute("content", isDark ? "#131010" : "#F8F7F7")
}
function cacheThemeVariants(theme: DesktopTheme, themeId: string) {
if (themeId === "oc-2") return
for (const mode of ["light", "dark"] as const) {
const isDark = mode === "dark"
const variant = isDark ? theme.dark : theme.light
const tokens = resolveThemeVariant(variant, isDark)
const css = themeToCss(tokens)
const v2 = themeV2ToCss(resolveThemeVariantV2(variant, isDark))
write(isDark ? STORAGE_KEYS.THEME_CSS_DARK : STORAGE_KEYS.THEME_CSS_LIGHT, `${css}\n ${v2}`)
}
}
export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
name: "Theme",
init: (props: { defaultTheme?: string; onThemeApplied?: (theme: DesktopTheme, mode: "light" | "dark") => void }) => {
const themeId = normalize(read(STORAGE_KEYS.THEME_ID) ?? props.defaultTheme) ?? "oc-2"
const colorScheme = (read(STORAGE_KEYS.COLOR_SCHEME) as ColorScheme | null) ?? "system"
const mode = colorScheme === "system" ? getSystemMode() : colorScheme
const [store, setStore] = createStore({
themes: {
"oc-2": oc2Theme,
} as Record<string, DesktopTheme>,
themeId,
colorScheme,
mode,
previewThemeId: null as string | null,
previewScheme: null as ColorScheme | null,
})
const loads = new Map<string, Promise<DesktopTheme | undefined>>()
const load = (id: string) => {
const next = normalize(id)
if (!next) return Promise.resolve(undefined)
const hit = store.themes[next]
if (hit) return Promise.resolve(hit)
const pending = loads.get(next)
if (pending) return pending
const file = getFiles()[`./themes/${next}.json`]
if (!file) return Promise.resolve(undefined)
const task = file()
.then((mod) => {
const theme = mod.default
setStore("themes", next, theme)
return theme
})
.finally(() => {
loads.delete(next)
})
loads.set(next, task)
return task
}
const applyTheme = (theme: DesktopTheme, themeId: string, mode: "light" | "dark") => {
applyThemeCss(theme, themeId, mode)
props.onThemeApplied?.(theme, mode)
}
const ids = () => {
const extra = Object.keys(store.themes)
.filter((id) => !knownThemes().has(id))
.sort()
const all = themeIDs()
if (extra.length === 0) return all
return [...all, ...extra]
}
const loadThemes = () => Promise.all(themeIDs().map(load)).then(() => store.themes)
const onStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEYS.THEME_ID && e.newValue) {
const next = normalize(e.newValue)
if (!next) return
if (next !== "oc-2" && !knownThemes().has(next) && !store.themes[next]) return
setStore("themeId", next)
if (next === "oc-2") {
clear()
return
}
void load(next).then((theme) => {
if (!theme || store.themeId !== next) return
cacheThemeVariants(theme, next)
})
}
if (e.key === STORAGE_KEYS.COLOR_SCHEME && e.newValue) {
setStore("colorScheme", e.newValue as ColorScheme)
setStore("mode", e.newValue === "system" ? getSystemMode() : (e.newValue as "light" | "dark"))
}
}
onMount(() => {
makeEventListener(window, "storage", onStorage)
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
const onMedia = () => {
if (store.colorScheme !== "system") return
setStore("mode", getSystemMode())
}
makeEventListener(mediaQuery, "change", onMedia)
const rawTheme = read(STORAGE_KEYS.THEME_ID)
const savedTheme = normalize(rawTheme ?? props.defaultTheme) ?? "oc-2"
const savedScheme = (read(STORAGE_KEYS.COLOR_SCHEME) as ColorScheme | null) ?? "system"
if (rawTheme && rawTheme !== savedTheme) {
write(STORAGE_KEYS.THEME_ID, savedTheme)
clear()
}
if (savedTheme !== store.themeId) setStore("themeId", savedTheme)
if (savedScheme !== store.colorScheme) setStore("colorScheme", savedScheme)
setStore("mode", savedScheme === "system" ? getSystemMode() : savedScheme)
void load(savedTheme).then((theme) => {
if (!theme || store.themeId !== savedTheme) return
cacheThemeVariants(theme, savedTheme)
})
})
createEffect(() => {
const theme = store.themes[store.themeId]
if (!theme) return
applyTheme(theme, store.themeId, store.mode)
})
const setTheme = (id: string) => {
const next = normalize(id)
if (!next) {
console.warn(`Theme "${id}" not found`)
return
}
if (next !== "oc-2" && !knownThemes().has(next) && !store.themes[next]) {
console.warn(`Theme "${id}" not found`)
return
}
setStore("themeId", next)
if (next === "oc-2") {
write(STORAGE_KEYS.THEME_ID, next)
clear()
return
}
void load(next).then((theme) => {
if (!theme || store.themeId !== next) return
cacheThemeVariants(theme, next)
write(STORAGE_KEYS.THEME_ID, next)
})
}
const setColorScheme = (scheme: ColorScheme) => {
setStore("colorScheme", scheme)
write(STORAGE_KEYS.COLOR_SCHEME, scheme)
setStore("mode", scheme === "system" ? getSystemMode() : scheme)
}
return {
themeId: () => store.themeId,
colorScheme: () => store.colorScheme,
mode: () => store.mode,
ids,
name: (id: string) => store.themes[id]?.name ?? names[id] ?? id,
loadThemes,
themes: () => store.themes,
setTheme,
setColorScheme,
registerTheme: (theme: DesktopTheme) => setStore("themes", theme.id, theme),
previewTheme: (id: string) => {
const next = normalize(id)
if (!next) return
if (next !== "oc-2" && !knownThemes().has(next) && !store.themes[next]) return
setStore("previewThemeId", next)
void load(next).then((theme) => {
if (!theme || store.previewThemeId !== next) return
const mode = store.previewScheme
? store.previewScheme === "system"
? getSystemMode()
: store.previewScheme
: store.mode
applyTheme(theme, next, mode)
})
},
previewColorScheme: (scheme: ColorScheme) => {
setStore("previewScheme", scheme)
const mode = scheme === "system" ? getSystemMode() : scheme
const id = store.previewThemeId ?? store.themeId
void load(id).then((theme) => {
if (!theme) return
if ((store.previewThemeId ?? store.themeId) !== id) return
if (store.previewScheme !== scheme) return
applyTheme(theme, id, mode)
})
},
commitPreview: () => {
if (store.previewThemeId) {
setTheme(store.previewThemeId)
}
if (store.previewScheme) {
setColorScheme(store.previewScheme)
}
setStore("previewThemeId", null)
setStore("previewScheme", null)
},
cancelPreview: () => {
setStore("previewThemeId", null)
setStore("previewScheme", null)
void load(store.themeId).then((theme) => {
if (!theme) return
applyTheme(theme, store.themeId, store.mode)
})
},
}
},
})