-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
theme.ts
428 lines (364 loc) Β· 12.1 KB
/
theme.ts
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Utilities
import {
computed,
inject,
provide,
reactive,
ref,
watch,
watchEffect,
} from 'vue'
import {
createRange,
darken,
getCurrentInstance,
getLuma,
IN_BROWSER,
lighten,
mergeDeep,
parseColor,
propsFactory,
RGBtoHex,
} from '@/util'
import { APCAcontrast } from '@/util/color/APCA'
// Types
import type { App, DeepReadonly, InjectionKey, Ref } from 'vue'
import type { HeadClient } from '@vueuse/head'
type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]> } : T
export type ThemeOptions = false | {
cspNonce?: string
defaultTheme?: string
variations?: false | VariationsOptions
themes?: Record<string, ThemeDefinition>
}
export type ThemeDefinition = DeepPartial<InternalThemeDefinition>
interface InternalThemeOptions {
cspNonce?: string
isDisabled: boolean
defaultTheme: string
variations: false | VariationsOptions
themes: Record<string, InternalThemeDefinition>
}
interface VariationsOptions {
colors: string[]
lighten: number
darken: number
}
interface InternalThemeDefinition {
dark: boolean
colors: Colors
variables: Record<string, string | number>
}
export interface Colors extends BaseColors, OnColors {
[key: string]: string
}
interface BaseColors {
background: string
surface: string
primary: string
secondary: string
success: string
warning: string
error: string
info: string
}
interface OnColors {
'on-background': string
'on-surface': string
'on-primary': string
'on-secondary': string
'on-success': string
'on-warning': string
'on-error': string
'on-info': string
}
export interface ThemeInstance {
readonly isDisabled: boolean
readonly themes: Ref<Record<string, InternalThemeDefinition>>
readonly name: Readonly<Ref<string>>
readonly current: DeepReadonly<Ref<InternalThemeDefinition>>
readonly computedThemes: DeepReadonly<Ref<Record<string, InternalThemeDefinition>>>
readonly themeClasses: Readonly<Ref<string | undefined>>
readonly styles: Readonly<Ref<string>>
readonly global: {
readonly name: Ref<string>
readonly current: DeepReadonly<Ref<InternalThemeDefinition>>
}
}
export const ThemeSymbol: InjectionKey<ThemeInstance> = Symbol.for('vuetify:theme')
export const makeThemeProps = propsFactory({
theme: String,
}, 'theme')
const defaultThemeOptions: Exclude<ThemeOptions, false> = {
defaultTheme: 'light',
variations: { colors: [], lighten: 0, darken: 0 },
themes: {
light: {
dark: false,
colors: {
background: '#FFFFFF',
surface: '#FFFFFF',
'surface-variant': '#424242',
'on-surface-variant': '#EEEEEE',
primary: '#6200EE',
'primary-darken-1': '#3700B3',
secondary: '#03DAC6',
'secondary-darken-1': '#018786',
error: '#B00020',
info: '#2196F3',
success: '#4CAF50',
warning: '#FB8C00',
},
variables: {
'border-color': '#000000',
'border-opacity': 0.12,
'high-emphasis-opacity': 0.87,
'medium-emphasis-opacity': 0.60,
'disabled-opacity': 0.38,
'idle-opacity': 0.04,
'hover-opacity': 0.04,
'focus-opacity': 0.12,
'selected-opacity': 0.08,
'activated-opacity': 0.12,
'pressed-opacity': 0.12,
'dragged-opacity': 0.08,
'theme-kbd': '#212529',
'theme-on-kbd': '#FFFFFF',
'theme-code': '#F5F5F5',
'theme-on-code': '#000000',
},
},
dark: {
dark: true,
colors: {
background: '#121212',
surface: '#212121',
'surface-variant': '#BDBDBD',
'on-surface-variant': '#424242',
primary: '#BB86FC',
'primary-darken-1': '#3700B3',
secondary: '#03DAC5',
'secondary-darken-1': '#03DAC5',
error: '#CF6679',
info: '#2196F3',
success: '#4CAF50',
warning: '#FB8C00',
},
variables: {
'border-color': '#FFFFFF',
'border-opacity': 0.12,
'high-emphasis-opacity': 0.87,
'medium-emphasis-opacity': 0.60,
'disabled-opacity': 0.38,
'idle-opacity': 0.10,
'hover-opacity': 0.04,
'focus-opacity': 0.12,
'selected-opacity': 0.08,
'activated-opacity': 0.12,
'pressed-opacity': 0.16,
'dragged-opacity': 0.08,
'theme-kbd': '#212529',
'theme-on-kbd': '#FFFFFF',
'theme-code': '#343434',
'theme-on-code': '#CCCCCC',
},
},
},
}
function parseThemeOptions (options: ThemeOptions = defaultThemeOptions): InternalThemeOptions {
if (!options) return { ...defaultThemeOptions, isDisabled: true } as InternalThemeOptions
const themes: Record<string, InternalThemeDefinition> = {}
for (const [key, theme] of Object.entries(options.themes ?? {})) {
const defaultTheme = theme.dark || key === 'dark'
? defaultThemeOptions.themes?.dark
: defaultThemeOptions.themes?.light
themes[key] = mergeDeep(defaultTheme, theme) as InternalThemeDefinition
}
return mergeDeep(
defaultThemeOptions,
{ ...options, themes },
) as InternalThemeOptions
}
// Composables
export function createTheme (options?: ThemeOptions): ThemeInstance & { install: (app: App) => void } {
const parsedOptions = reactive(parseThemeOptions(options))
const name = ref(parsedOptions.defaultTheme)
const themes = ref(parsedOptions.themes)
const computedThemes = computed(() => {
const acc: Record<string, InternalThemeDefinition> = {}
for (const [name, original] of Object.entries(themes.value)) {
const theme: InternalThemeDefinition = acc[name] = {
...original,
colors: {
...original.colors,
},
}
if (parsedOptions.variations) {
for (const name of parsedOptions.variations.colors) {
const color = theme.colors[name]
if (!color) continue
for (const variation of (['lighten', 'darken'] as const)) {
const fn = variation === 'lighten' ? lighten : darken
for (const amount of createRange(parsedOptions.variations[variation], 1)) {
theme.colors[`${name}-${variation}-${amount}`] = RGBtoHex(fn(parseColor(color), amount))
}
}
}
}
for (const color of Object.keys(theme.colors)) {
if (/^on-[a-z]/.test(color) || theme.colors[`on-${color}`]) continue
const onColor = `on-${color}` as keyof OnColors
const colorVal = parseColor(theme.colors[color]!)
const blackContrast = Math.abs(APCAcontrast(parseColor(0), colorVal))
const whiteContrast = Math.abs(APCAcontrast(parseColor(0xffffff), colorVal))
// TODO: warn about poor color selections
// const contrastAsText = Math.abs(APCAcontrast(colorVal, colorToInt(theme.colors.background)))
// const minContrast = Math.max(blackContrast, whiteContrast)
// if (minContrast < 60) {
// consoleInfo(`${key} theme color ${color} has poor contrast (${minContrast.toFixed()}%)`)
// } else if (contrastAsText < 60 && !['background', 'surface'].includes(color)) {
// consoleInfo(`${key} theme color ${color} has poor contrast as text (${contrastAsText.toFixed()}%)`)
// }
// Prefer white text if both have an acceptable contrast ratio
theme.colors[onColor] = whiteContrast > Math.min(blackContrast, 50) ? '#fff' : '#000'
}
}
return acc
})
const current = computed(() => computedThemes.value[name.value])
const styles = computed(() => {
const lines: string[] = []
if (current.value.dark) {
createCssClass(lines, ':root', ['color-scheme: dark'])
}
createCssClass(lines, ':root', genCssVariables(current.value))
for (const [themeName, theme] of Object.entries(computedThemes.value)) {
createCssClass(lines, `.v-theme--${themeName}`, [
`color-scheme: ${theme.dark ? 'dark' : 'normal'}`,
...genCssVariables(theme),
])
}
const bgLines: string[] = []
const fgLines: string[] = []
const colors = new Set(Object.values(computedThemes.value).flatMap(theme => Object.keys(theme.colors)))
for (const key of colors) {
if (/^on-[a-z]/.test(key)) {
createCssClass(fgLines, `.${key}`, [`color: rgb(var(--v-theme-${key})) !important`])
} else {
createCssClass(bgLines, `.bg-${key}`, [
`--v-theme-overlay-multiplier: var(--v-theme-${key}-overlay-multiplier)`,
`background: rgb(var(--v-theme-${key})) !important`,
`color: rgb(var(--v-theme-on-${key})) !important`,
])
createCssClass(fgLines, `.text-${key}`, [`color: rgb(var(--v-theme-${key})) !important`])
createCssClass(fgLines, `.border-${key}`, [`--v-border-color: var(--v-theme-${key})`])
}
}
lines.push(...bgLines, ...fgLines)
return lines.map((str, i) => i === 0 ? str : ` ${str}`).join('')
})
function getHead () {
return {
style: [{
children: styles.value,
id: 'vuetify-theme-stylesheet',
nonce: parsedOptions.cspNonce || false as never,
}],
}
}
function install (app: App) {
const head = app._context.provides.usehead as HeadClient | undefined
if (head) {
if (head.push) {
const entry = head.push(getHead)
watch(styles, () => { entry.patch(getHead) })
} else {
if (IN_BROWSER) {
head.addHeadObjs(computed(getHead))
watchEffect(() => head.updateDOM())
} else {
head.addHeadObjs(getHead())
}
}
} else {
let styleEl = IN_BROWSER
? document.getElementById('vuetify-theme-stylesheet')
: null
watch(styles, updateStyles, { immediate: true })
function updateStyles () {
if (parsedOptions.isDisabled) return
if (typeof document !== 'undefined' && !styleEl) {
const el = document.createElement('style')
el.type = 'text/css'
el.id = 'vuetify-theme-stylesheet'
if (parsedOptions.cspNonce) el.setAttribute('nonce', parsedOptions.cspNonce)
styleEl = el
document.head.appendChild(styleEl)
}
if (styleEl) styleEl.innerHTML = styles.value
}
}
}
const themeClasses = computed(() => parsedOptions.isDisabled ? undefined : `v-theme--${name.value}`)
return {
install,
isDisabled: parsedOptions.isDisabled,
name,
themes,
current,
computedThemes,
themeClasses,
styles,
global: {
name,
current,
},
}
}
export function provideTheme (props: { theme?: string }) {
getCurrentInstance('provideTheme')
const theme = inject(ThemeSymbol, null)
if (!theme) throw new Error('Could not find Vuetify theme injection')
const name = computed<string>(() => {
return props.theme ?? theme?.name.value
})
const themeClasses = computed(() => theme.isDisabled ? undefined : `v-theme--${name.value}`)
const newTheme: ThemeInstance = {
...theme,
name,
themeClasses,
}
provide(ThemeSymbol, newTheme)
return newTheme
}
export function useTheme () {
getCurrentInstance('useTheme')
const theme = inject(ThemeSymbol, null)
if (!theme) throw new Error('Could not find Vuetify theme injection')
return theme
}
function createCssClass (lines: string[], selector: string, content: string[]) {
lines.push(
`${selector} {\n`,
...content.map(line => ` ${line};\n`),
'}\n',
)
}
function genCssVariables (theme: InternalThemeDefinition) {
const lightOverlay = theme.dark ? 2 : 1
const darkOverlay = theme.dark ? 1 : 2
const variables: string[] = []
for (const [key, value] of Object.entries(theme.colors)) {
const rgb = parseColor(value)
variables.push(`--v-theme-${key}: ${rgb.r},${rgb.g},${rgb.b}`)
if (!key.startsWith('on-')) {
variables.push(`--v-theme-${key}-overlay-multiplier: ${getLuma(value) > 0.18 ? lightOverlay : darkOverlay}`)
}
}
for (const [key, value] of Object.entries(theme.variables)) {
const color = typeof value === 'string' && value.startsWith('#') ? parseColor(value) : undefined
const rgb = color ? `${color.r}, ${color.g}, ${color.b}` : undefined
variables.push(`--v-${key}: ${rgb ?? value}`)
}
return variables
}