@varo-ui/theme 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/css.ts ADDED
@@ -0,0 +1,244 @@
1
+ import type { ThemeDefinition } from './types'
2
+
3
+ export interface ThemeCssVariables {
4
+ '--varo-ui-white': string
5
+ '--varo-ui-black': string
6
+ '--varo-ui-bg': string
7
+ '--varo-ui-surface': string
8
+ '--varo-ui-surface-muted': string
9
+ '--varo-ui-surface-overlay': string
10
+ '--varo-ui-text': string
11
+ '--varo-ui-text-regular': string
12
+ '--varo-ui-text-muted': string
13
+ '--varo-ui-text-placeholder': string
14
+ '--varo-ui-text-disabled': string
15
+ '--varo-ui-border': string
16
+ '--varo-ui-border-strong': string
17
+ '--varo-ui-border-dark': string
18
+ '--varo-ui-border-light': string
19
+ '--varo-ui-border-lighter': string
20
+ '--varo-ui-border-extra-light': string
21
+ '--varo-ui-fill': string
22
+ '--varo-ui-fill-darker': string
23
+ '--varo-ui-fill-dark': string
24
+ '--varo-ui-fill-light': string
25
+ '--varo-ui-fill-lighter': string
26
+ '--varo-ui-fill-extra-light': string
27
+ '--varo-ui-primary': string
28
+ '--varo-ui-primary-dark': string
29
+ '--varo-ui-primary-hover': string
30
+ '--varo-ui-primary-soft': string
31
+ '--varo-ui-primary-foreground': string
32
+ '--varo-ui-primary-hover-foreground': string
33
+ '--varo-ui-primary-text': string
34
+ '--varo-ui-success': string
35
+ '--varo-ui-success-dark': string
36
+ '--varo-ui-success-hover': string
37
+ '--varo-ui-success-soft': string
38
+ '--varo-ui-success-foreground': string
39
+ '--varo-ui-success-hover-foreground': string
40
+ '--varo-ui-success-text': string
41
+ '--varo-ui-warning': string
42
+ '--varo-ui-warning-dark': string
43
+ '--varo-ui-warning-hover': string
44
+ '--varo-ui-warning-soft': string
45
+ '--varo-ui-warning-foreground': string
46
+ '--varo-ui-warning-hover-foreground': string
47
+ '--varo-ui-warning-text': string
48
+ '--varo-ui-danger': string
49
+ '--varo-ui-danger-dark': string
50
+ '--varo-ui-danger-hover': string
51
+ '--varo-ui-danger-soft': string
52
+ '--varo-ui-danger-foreground': string
53
+ '--varo-ui-danger-hover-foreground': string
54
+ '--varo-ui-danger-text': string
55
+ '--varo-ui-info': string
56
+ '--varo-ui-info-dark': string
57
+ '--varo-ui-info-hover': string
58
+ '--varo-ui-info-soft': string
59
+ '--varo-ui-info-foreground': string
60
+ '--varo-ui-info-hover-foreground': string
61
+ '--varo-ui-info-text': string
62
+ '--varo-ui-radius': string
63
+ '--varo-ui-radius-sm': string
64
+ '--varo-ui-button-radius': string
65
+ '--varo-ui-button-height-sm': string
66
+ '--varo-ui-button-height-md': string
67
+ '--varo-ui-button-height-lg': string
68
+ '--varo-ui-input-radius': string
69
+ '--varo-ui-input-height-sm': string
70
+ '--varo-ui-input-height-md': string
71
+ '--varo-ui-input-height-lg': string
72
+ '--varo-ui-shadow-sm': string
73
+ '--varo-ui-shadow-md': string
74
+ '--varo-ui-ring': string
75
+ '--varo-ui-focus': string
76
+ [name: `--${string}`]: string
77
+ }
78
+
79
+ export type ThemeCssVariableOverrides = Partial<ThemeCssVariables>
80
+
81
+ function colorWithAlpha(color: string, alpha: number): string {
82
+ const value = color.slice(1)
83
+ const normalized = value.length === 3
84
+ ? value.split('').map(part => `${part}${part}`).join('')
85
+ : value
86
+
87
+ if (!color.startsWith('#') || !/^[\da-f]{6}$/i.test(normalized)) {
88
+ return color
89
+ }
90
+
91
+ const red = Number.parseInt(normalized.slice(0, 2), 16)
92
+ const green = Number.parseInt(normalized.slice(2, 4), 16)
93
+ const blue = Number.parseInt(normalized.slice(4, 6), 16)
94
+ return `rgb(${red} ${green} ${blue} / ${alpha}%)`
95
+ }
96
+
97
+ function semanticTextColor(base: string, text: string): string {
98
+ if (!/^#[\da-f]{6}$/i.test(base) || !/^#[\da-f]{6}$/i.test(text)) {
99
+ return text
100
+ }
101
+
102
+ const channels = [1, 3, 5].map((offset) => {
103
+ const baseChannel = Number.parseInt(base.slice(offset, offset + 2), 16)
104
+ const textChannel = Number.parseInt(text.slice(offset, offset + 2), 16)
105
+ return Math.round((baseChannel + textChannel) / 2)
106
+ .toString(16)
107
+ .padStart(2, '0')
108
+ })
109
+
110
+ return `#${channels.join('')}`
111
+ }
112
+
113
+ function relativeLuminance(color: string): number | undefined {
114
+ const value = color.slice(1)
115
+ const normalized = value.length === 3
116
+ ? value.split('').map(part => `${part}${part}`).join('')
117
+ : value
118
+
119
+ if (!color.startsWith('#') || !/^[\da-f]{6}$/i.test(normalized)) {
120
+ return undefined
121
+ }
122
+
123
+ const channelLuminance = (offset: number) => {
124
+ const channel = Number.parseInt(normalized.slice(offset, offset + 2), 16) / 255
125
+ return channel <= 0.04045
126
+ ? channel / 12.92
127
+ : ((channel + 0.055) / 1.055) ** 2.4
128
+ }
129
+ return channelLuminance(0) * 0.2126
130
+ + channelLuminance(2) * 0.7152
131
+ + channelLuminance(4) * 0.0722
132
+ }
133
+
134
+ export function contrastSafeForeground(background: string): '#000000' | '#ffffff' {
135
+ const backgroundLuminance = relativeLuminance(background)
136
+ if (backgroundLuminance == null) {
137
+ throw new Error(`Contrast-safe foreground requires a hex color (#RGB or #RRGGBB): ${background}`)
138
+ }
139
+
140
+ const blackContrast = (backgroundLuminance + 0.05) / 0.05
141
+ const whiteContrast = 1.05 / (backgroundLuminance + 0.05)
142
+ return blackContrast >= whiteContrast ? '#000000' : '#ffffff'
143
+ }
144
+
145
+ export function createThemeCssVariables(
146
+ theme: ThemeDefinition,
147
+ overrides: ThemeCssVariableOverrides = {},
148
+ ): ThemeCssVariables {
149
+ return {
150
+ '--varo-ui-white': theme.palette.neutral.white,
151
+ '--varo-ui-black': theme.palette.neutral.black,
152
+ '--varo-ui-bg': theme.semantic.surfaceElevated,
153
+ '--varo-ui-surface': theme.semantic.surfaceBase,
154
+ '--varo-ui-surface-muted': theme.semantic.fillLight,
155
+ '--varo-ui-surface-overlay': theme.semantic.surfaceOverlay,
156
+ '--varo-ui-text': theme.semantic.textBase,
157
+ '--varo-ui-text-regular': theme.semantic.textRegular,
158
+ '--varo-ui-text-muted': theme.semantic.textMuted,
159
+ '--varo-ui-text-placeholder': theme.semantic.textPlaceholder,
160
+ '--varo-ui-text-disabled': theme.semantic.textDisabled,
161
+ '--varo-ui-border': theme.semantic.borderBase,
162
+ '--varo-ui-border-strong': theme.semantic.borderStrong,
163
+ '--varo-ui-border-dark': theme.palette.neutral['border-dark'],
164
+ '--varo-ui-border-light': theme.semantic.borderLight,
165
+ '--varo-ui-border-lighter': theme.semantic.borderLighter,
166
+ '--varo-ui-border-extra-light': theme.palette.neutral['border-extra-light'],
167
+ '--varo-ui-fill': theme.semantic.fillBase,
168
+ '--varo-ui-fill-darker': theme.palette.neutral['fill-darker'],
169
+ '--varo-ui-fill-dark': theme.palette.neutral['fill-dark'],
170
+ '--varo-ui-fill-light': theme.semantic.fillLight,
171
+ '--varo-ui-fill-lighter': theme.semantic.fillLighter,
172
+ '--varo-ui-fill-extra-light': theme.palette.neutral['fill-extra-light'],
173
+ '--varo-ui-primary': theme.semantic.primaryBase,
174
+ '--varo-ui-primary-dark': theme.semantic.primaryDark,
175
+ '--varo-ui-primary-hover': theme.semantic.primaryHover,
176
+ '--varo-ui-primary-soft': theme.semantic.primarySoft,
177
+ '--varo-ui-primary-foreground': contrastSafeForeground(theme.semantic.primaryBase),
178
+ '--varo-ui-primary-hover-foreground': contrastSafeForeground(theme.semantic.primaryHover),
179
+ '--varo-ui-primary-text': semanticTextColor(theme.semantic.primaryBase, theme.semantic.textBase),
180
+ '--varo-ui-success': theme.semantic.successBase,
181
+ '--varo-ui-success-dark': theme.semantic.successDark,
182
+ '--varo-ui-success-hover': theme.semantic.successHover,
183
+ '--varo-ui-success-soft': theme.semantic.successSoft,
184
+ '--varo-ui-success-foreground': contrastSafeForeground(theme.semantic.successBase),
185
+ '--varo-ui-success-hover-foreground': contrastSafeForeground(theme.semantic.successHover),
186
+ '--varo-ui-success-text': semanticTextColor(theme.semantic.successBase, theme.semantic.textBase),
187
+ '--varo-ui-warning': theme.semantic.warningBase,
188
+ '--varo-ui-warning-dark': theme.semantic.warningDark,
189
+ '--varo-ui-warning-hover': theme.semantic.warningHover,
190
+ '--varo-ui-warning-soft': theme.semantic.warningSoft,
191
+ '--varo-ui-warning-foreground': contrastSafeForeground(theme.semantic.warningBase),
192
+ '--varo-ui-warning-hover-foreground': contrastSafeForeground(theme.semantic.warningHover),
193
+ '--varo-ui-warning-text': semanticTextColor(theme.semantic.warningBase, theme.semantic.textBase),
194
+ '--varo-ui-danger': theme.semantic.dangerBase,
195
+ '--varo-ui-danger-dark': theme.semantic.dangerDark,
196
+ '--varo-ui-danger-hover': theme.semantic.dangerHover,
197
+ '--varo-ui-danger-soft': theme.semantic.dangerSoft,
198
+ '--varo-ui-danger-foreground': contrastSafeForeground(theme.semantic.dangerBase),
199
+ '--varo-ui-danger-hover-foreground': contrastSafeForeground(theme.semantic.dangerHover),
200
+ '--varo-ui-danger-text': semanticTextColor(theme.semantic.dangerBase, theme.semantic.textBase),
201
+ '--varo-ui-info': theme.semantic.infoBase,
202
+ '--varo-ui-info-dark': theme.semantic.infoDark,
203
+ '--varo-ui-info-hover': theme.semantic.infoHover,
204
+ '--varo-ui-info-soft': theme.semantic.infoSoft,
205
+ '--varo-ui-info-foreground': contrastSafeForeground(theme.semantic.infoBase),
206
+ '--varo-ui-info-hover-foreground': contrastSafeForeground(theme.semantic.infoHover),
207
+ '--varo-ui-info-text': semanticTextColor(theme.semantic.infoBase, theme.semantic.textBase),
208
+ '--varo-ui-button-radius': theme.components.button.borderRadius,
209
+ '--varo-ui-button-height-sm': theme.components.button.heightSm,
210
+ '--varo-ui-button-height-md': theme.components.button.heightMd,
211
+ '--varo-ui-button-height-lg': theme.components.button.heightLg,
212
+ '--varo-ui-input-radius': theme.components.input.borderRadius,
213
+ '--varo-ui-input-height-sm': theme.components.input.heightSm,
214
+ '--varo-ui-input-height-md': theme.components.input.heightMd,
215
+ '--varo-ui-input-height-lg': theme.components.input.heightLg,
216
+ '--varo-ui-radius': 'var(--varo-ui-button-radius)',
217
+ '--varo-ui-radius-sm': 'var(--varo-ui-input-radius)',
218
+ '--varo-ui-shadow-sm': theme.seed.mode === 'dark'
219
+ ? '0 1px 2px rgb(0 0 0 / 46%)'
220
+ : '0 1px 2px rgb(48 49 51 / 6%)',
221
+ '--varo-ui-shadow-md': theme.seed.mode === 'dark'
222
+ ? '0 12px 32px 4px rgb(0 0 0 / 36%), 0 8px 20px rgb(0 0 0 / 72%)'
223
+ : '0 12px 32px 4px rgb(0 0 0 / 4%), 0 8px 20px rgb(0 0 0 / 8%)',
224
+ '--varo-ui-ring': colorWithAlpha(theme.semantic.primaryBase, 16),
225
+ '--varo-ui-focus': contrastSafeForeground(theme.semantic.surfaceBase),
226
+ ...overrides,
227
+ }
228
+ }
229
+
230
+ export function renderThemeCssVariables(selector: string, variables: ThemeCssVariables): string {
231
+ const normalizedSelector = selector.trim()
232
+ if (!normalizedSelector || /[{}]/.test(normalizedSelector)) {
233
+ throw new Error(`Invalid theme CSS selector: ${selector}`)
234
+ }
235
+
236
+ const declarations = Object.entries(variables).map(([name, value]) => {
237
+ if (/[;{}\r\n]/.test(value)) {
238
+ throw new Error(`Invalid theme CSS variable value for ${name}`)
239
+ }
240
+ return ` ${name}: ${value};`
241
+ })
242
+
243
+ return `${normalizedSelector} {\n${declarations.join('\n')}\n}`
244
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './css'
1
2
  export * from './provider'
2
3
  export * from './theme'
3
4
  export * from './types'
package/src/provider.ts CHANGED
@@ -1,36 +1,168 @@
1
- import type { App, InjectionKey, Plugin } from 'vue'
2
- import type { ThemeDefinition } from './types'
1
+ import type {
2
+ App,
3
+ ComputedRef,
4
+ InjectionKey,
5
+ Plugin,
6
+ PropType,
7
+ } from 'vue'
8
+ import type { ThemeCssVariables } from './css'
9
+ import type { ThemeDefinition, ThemeOverrides } from './types'
3
10
  import type { ThemeConfig } from './types-runtime'
4
- import { computed, inject, provide } from 'vue'
5
- import { createTheme } from './theme'
11
+ import { computed, defineComponent, h, inject, provide, toValue, watchEffect } from 'vue'
12
+ import { createThemeCssVariables } from './css'
13
+ import { createTheme, mergeThemeOverrides } from './theme'
6
14
 
7
- const ThemeKey: InjectionKey<ThemeConfig> = Symbol('varo-theme')
15
+ const ThemeKey: InjectionKey<ComputedRef<ThemeDefinition>> = Symbol('varo-theme')
16
+ const fallbackTheme = createTheme({
17
+ primary: '#07c160',
18
+ success: '#13b248',
19
+ warning: '#fa9200',
20
+ error: '#eb3437',
21
+ neutral: '#303133',
22
+ info: '#73767a',
23
+ })
8
24
 
9
- export function provideVaroTheme(config: ThemeConfig) {
10
- provide(ThemeKey, config)
25
+ interface InlineStyleSnapshot {
26
+ priority: string
27
+ value: string
11
28
  }
12
29
 
13
- export function useVaroTheme() {
14
- const config = inject(ThemeKey, undefined)
30
+ interface ThemeLayer {
31
+ owner: symbol
32
+ variables: ThemeCssVariables
33
+ }
15
34
 
16
- if (!config) {
17
- return computed<ThemeDefinition>(() =>
18
- createTheme({
19
- primary: '#2563eb',
20
- success: '#16a34a',
21
- warning: '#d97706',
22
- error: '#dc2626',
23
- neutral: '#0f172a',
24
- }),
25
- )
35
+ interface ThemeTargetState {
36
+ base: Map<string, InlineStyleSnapshot>
37
+ layers: ThemeLayer[]
38
+ }
39
+
40
+ const targetStates = new WeakMap<HTMLElement, ThemeTargetState>()
41
+
42
+ function resolveTheme(config: ThemeConfig): ThemeDefinition {
43
+ return mergeThemeOverrides(toValue(config.theme), toValue(config.overrides) ?? {})
44
+ }
45
+
46
+ function applyTargetState(target: HTMLElement, state: ThemeTargetState): void {
47
+ const activeLayer = state.layers[state.layers.length - 1]
48
+ const activeVariables = activeLayer?.variables as unknown as Record<string, string> | undefined
49
+ for (const [name, snapshot] of state.base) {
50
+ const value = activeVariables?.[name]
51
+ if (value !== undefined) {
52
+ target.style.setProperty(name, value)
53
+ }
54
+ else if (snapshot.value) {
55
+ target.style.setProperty(name, snapshot.value, snapshot.priority)
56
+ }
57
+ else {
58
+ target.style.removeProperty(name)
59
+ }
26
60
  }
61
+ }
62
+
63
+ function bindThemeVariables(
64
+ target: HTMLElement,
65
+ theme: ComputedRef<ThemeDefinition>,
66
+ ): () => void {
67
+ let state = targetStates.get(target)
68
+ if (!state) {
69
+ state = { base: new Map(), layers: [] }
70
+ targetStates.set(target, state)
71
+ }
72
+
73
+ const owner = Symbol('varo-theme-owner')
74
+ const layer: ThemeLayer = {
75
+ owner,
76
+ variables: createThemeCssVariables(theme.value),
77
+ }
78
+ state.layers.push(layer)
79
+
80
+ const stop = watchEffect(() => {
81
+ const variables = createThemeCssVariables(theme.value)
82
+ for (const name of Object.keys(variables)) {
83
+ if (!state!.base.has(name)) {
84
+ state!.base.set(name, {
85
+ priority: target.style.getPropertyPriority(name),
86
+ value: target.style.getPropertyValue(name),
87
+ })
88
+ }
89
+ }
90
+ layer.variables = variables
91
+ if (state!.layers[state!.layers.length - 1]?.owner === owner) {
92
+ applyTargetState(target, state!)
93
+ }
94
+ })
27
95
 
28
- return computed(() => config.theme)
96
+ return () => {
97
+ stop()
98
+ const index = state!.layers.findIndex(candidate => candidate.owner === owner)
99
+ if (index < 0) {
100
+ return
101
+ }
102
+ const wasActive = index === state!.layers.length - 1
103
+ state!.layers.splice(index, 1)
104
+ if (wasActive) {
105
+ applyTargetState(target, state!)
106
+ }
107
+ if (state!.layers.length === 0) {
108
+ targetStates.delete(target)
109
+ }
110
+ }
111
+ }
112
+
113
+ export function provideVaroTheme(config: ThemeConfig): void {
114
+ provide(ThemeKey, computed(() => resolveTheme(config)))
29
115
  }
30
116
 
117
+ export function useVaroTheme(): ComputedRef<ThemeDefinition> {
118
+ return inject(ThemeKey, computed(() => fallbackTheme))
119
+ }
120
+
121
+ export const VaroThemeProvider = defineComponent({
122
+ name: 'VaroThemeProvider',
123
+ inheritAttrs: false,
124
+ props: {
125
+ theme: {
126
+ type: Object as PropType<ThemeDefinition>,
127
+ required: true,
128
+ },
129
+ overrides: {
130
+ type: Object as PropType<ThemeOverrides>,
131
+ default: undefined,
132
+ },
133
+ },
134
+ setup(props, { attrs, slots }) {
135
+ const theme = computed(() =>
136
+ mergeThemeOverrides(props.theme, props.overrides ?? {}),
137
+ )
138
+ const styles = computed(() => createThemeCssVariables(theme.value))
139
+ provide(ThemeKey, theme)
140
+
141
+ return () =>
142
+ h(
143
+ 'div',
144
+ {
145
+ ...attrs,
146
+ style: [styles.value, attrs.style],
147
+ },
148
+ slots.default?.(),
149
+ )
150
+ },
151
+ })
152
+
31
153
  export const VaroConfigProvider = {
32
154
  install(app: App, config?: ThemeConfig) {
33
- if (!config) { throw new Error('VaroConfigProvider requires a theme configuration.') }
34
- app.provide(ThemeKey, config)
155
+ if (!config) {
156
+ throw new Error('VaroConfigProvider requires a theme configuration.')
157
+ }
158
+
159
+ const theme = computed(() => resolveTheme(config))
160
+ app.provide(ThemeKey, theme)
161
+ if (typeof document === 'undefined') {
162
+ return
163
+ }
164
+
165
+ const release = bindThemeVariables(config.target ?? document.documentElement, theme)
166
+ app.onUnmount(release)
35
167
  },
36
168
  } satisfies Plugin