@luxalgo/vela-ui 0.3.0 → 0.4.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.
Files changed (167) hide show
  1. package/CHANGELOG.md +153 -132
  2. package/LICENSE +201 -201
  3. package/NOTICE +28 -28
  4. package/README.md +86 -86
  5. package/cli/engine.mjs +282 -282
  6. package/cli/index.mjs +154 -154
  7. package/dist/callout-bubble.js +2 -2
  8. package/dist/checkbox.js +2 -2
  9. package/dist/{chunk-KKS6NEGI.js → chunk-BWSOMG3G.js} +1 -1
  10. package/dist/chunk-GUIYFQ27.js +30 -0
  11. package/dist/{chunk-B2EZB5ZG.js → chunk-KUWTI2PE.js} +2 -2
  12. package/dist/{chunk-WWHNUKSZ.js → chunk-QGWAN3EP.js} +2 -2
  13. package/dist/{chunk-TBXUF5YX.js → chunk-RH53NQGE.js} +18 -4
  14. package/dist/{chunk-IOOYDSSK.js → chunk-SKFAYTDK.js} +1 -1
  15. package/dist/{chunk-OQXFQMZM.js → chunk-TGJNHUYV.js} +2 -2
  16. package/dist/{chunk-UEO6W37Z.js → chunk-VC7SVSDK.js} +1 -1
  17. package/dist/{chunk-OJ2SEMN6.js → chunk-YT2BSP7O.js} +1 -1
  18. package/dist/collapsible.js +1 -1
  19. package/dist/color-picker.js +4 -4
  20. package/dist/context-menu.js +3 -3
  21. package/dist/dialog.js +3 -3
  22. package/dist/donut.d.ts +1 -1
  23. package/dist/drawer.js +1 -1
  24. package/dist/dropdown-menu.js +3 -3
  25. package/dist/field.js +8 -8
  26. package/dist/{stat.d.ts → figure.d.ts} +9 -9
  27. package/dist/figure.js +41 -0
  28. package/dist/glyph-select.js +3 -3
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +1 -1
  31. package/dist/manifest.json +74 -74
  32. package/dist/number-input.js +2 -2
  33. package/dist/popover.js +2 -2
  34. package/dist/select.d.ts +1 -1
  35. package/dist/select.js +4 -4
  36. package/dist/slider.js +1 -1
  37. package/dist/sort-button.js +1 -1
  38. package/dist/switch.js +1 -1
  39. package/dist/tabs.js +1 -1
  40. package/dist/{theme-Ct-q58xz.d.ts → theme-TefB8vtl.d.ts} +2 -2
  41. package/dist/theme.d.ts +2 -2
  42. package/dist/theme.js +1 -1
  43. package/dist/theme.schema.json +30 -30
  44. package/dist/toast.d.ts +2 -2
  45. package/dist/toast.js +1 -1
  46. package/dist/toggle-group.js +1 -1
  47. package/dist/tooltip.js +1 -1
  48. package/dist/zag.d.ts +11 -2
  49. package/dist/zag.js +1 -1
  50. package/docs/theming.md +217 -217
  51. package/docs/what-to-change.md +20 -20
  52. package/docs/writing-a-component.md +250 -250
  53. package/llms.txt +3 -3
  54. package/package.json +90 -90
  55. package/registry/badge.ts +119 -119
  56. package/registry/bar-chart.ts +215 -215
  57. package/registry/button.ts +387 -387
  58. package/registry/callout-bubble.ts +347 -347
  59. package/registry/card.ts +379 -379
  60. package/registry/checkbox.ts +234 -234
  61. package/registry/collapsible.ts +271 -271
  62. package/registry/color-picker.ts +582 -582
  63. package/registry/context-menu.ts +208 -208
  64. package/registry/data-table.ts +215 -215
  65. package/registry/date-picker.ts +483 -483
  66. package/registry/dialog.ts +551 -551
  67. package/registry/donut.ts +145 -145
  68. package/registry/drawer.ts +636 -636
  69. package/registry/dropdown-menu.ts +762 -762
  70. package/registry/empty.ts +91 -91
  71. package/registry/field.ts +584 -584
  72. package/registry/{stat.ts → figure.ts} +96 -96
  73. package/registry/glyph-select.ts +268 -268
  74. package/registry/hover-card.ts +222 -222
  75. package/registry/input-group.ts +229 -229
  76. package/registry/input.ts +181 -181
  77. package/registry/item.ts +376 -376
  78. package/registry/kbd.ts +64 -64
  79. package/registry/line-chart.ts +218 -218
  80. package/registry/month-grid.ts +328 -328
  81. package/registry/number-input.ts +443 -443
  82. package/registry/popover.ts +368 -368
  83. package/registry/scatter-chart.ts +221 -221
  84. package/registry/select.ts +620 -620
  85. package/registry/slider.ts +259 -259
  86. package/registry/sort-button.ts +189 -189
  87. package/registry/sparkline.ts +114 -114
  88. package/registry/switch.ts +205 -205
  89. package/registry/tabs.ts +426 -426
  90. package/registry/text-area.ts +186 -186
  91. package/registry/toast.ts +965 -965
  92. package/registry/toggle-group.ts +295 -295
  93. package/registry/tooltip.ts +156 -156
  94. package/registry/treemap.ts +847 -847
  95. package/skills/theming-vela-ui/SKILL.md +137 -137
  96. package/skills/using-vela-ui-components/SKILL.md +139 -139
  97. package/skills/writing-vela-ui-components/SKILL.md +163 -163
  98. package/src/components/badge.ts +119 -119
  99. package/src/components/bar-chart.ts +215 -215
  100. package/src/components/button.ts +387 -387
  101. package/src/components/callout-bubble.ts +347 -347
  102. package/src/components/card.ts +379 -379
  103. package/src/components/checkbox.ts +234 -234
  104. package/src/components/collapsible.ts +271 -271
  105. package/src/components/color-picker.ts +582 -582
  106. package/src/components/context-menu.ts +208 -208
  107. package/src/components/data-table.ts +215 -215
  108. package/src/components/date-picker.ts +483 -483
  109. package/src/components/dialog.ts +551 -551
  110. package/src/components/donut.ts +145 -145
  111. package/src/components/drawer.ts +636 -636
  112. package/src/components/dropdown-menu.ts +762 -762
  113. package/src/components/empty.ts +91 -91
  114. package/src/components/field.ts +584 -584
  115. package/src/components/{stat.ts → figure.ts} +96 -96
  116. package/src/components/glyph-select.ts +268 -268
  117. package/src/components/hover-card.ts +222 -222
  118. package/src/components/input-group.ts +229 -229
  119. package/src/components/input.ts +181 -181
  120. package/src/components/item.ts +376 -376
  121. package/src/components/kbd.ts +64 -64
  122. package/src/components/line-chart.ts +218 -218
  123. package/src/components/month-grid.ts +328 -328
  124. package/src/components/number-input.ts +443 -443
  125. package/src/components/popover.ts +368 -368
  126. package/src/components/scatter-chart.ts +221 -221
  127. package/src/components/select.ts +620 -620
  128. package/src/components/slider.ts +259 -259
  129. package/src/components/sort-button.ts +189 -189
  130. package/src/components/sparkline.ts +114 -114
  131. package/src/components/switch.ts +205 -205
  132. package/src/components/tabs.ts +426 -426
  133. package/src/components/text-area.ts +186 -186
  134. package/src/components/toast.ts +965 -965
  135. package/src/components/toggle-group.ts +295 -295
  136. package/src/components/tooltip.ts +156 -156
  137. package/src/components/treemap.ts +847 -847
  138. package/src/index.ts +24 -24
  139. package/src/lib/calendar.ts +117 -117
  140. package/src/lib/chart.ts +72 -72
  141. package/src/lib/color.ts +89 -89
  142. package/src/lib/component-index.ts +163 -163
  143. package/src/lib/css.ts +48 -48
  144. package/src/lib/define.ts +45 -45
  145. package/src/lib/dispose.ts +36 -36
  146. package/src/lib/h.ts +55 -55
  147. package/src/lib/headless.ts +16 -16
  148. package/src/lib/i18n.ts +30 -30
  149. package/src/lib/icons.ts +244 -244
  150. package/src/lib/kit-text.ts +26 -26
  151. package/src/lib/page.ts +24 -24
  152. package/src/lib/palette.ts +81 -81
  153. package/src/lib/placement.ts +188 -188
  154. package/src/lib/scope.ts +135 -135
  155. package/src/lib/styles.ts +53 -53
  156. package/src/lib/surface-events.ts +31 -31
  157. package/src/lib/surface-exit.ts +87 -87
  158. package/src/lib/t.ts +68 -68
  159. package/src/lib/theme.ts +684 -670
  160. package/src/lib/tokens.ts +110 -110
  161. package/src/lib/variants.ts +32 -32
  162. package/src/lib/zag.ts +61 -46
  163. package/stylelint/index.mjs +60 -60
  164. package/stylelint/lint.mjs +81 -81
  165. package/stylelint/plugin.mjs +115 -115
  166. package/dist/chunk-P4MTEMT7.js +0 -23
  167. package/dist/stat.js +0 -41
package/src/lib/theme.ts CHANGED
@@ -1,670 +1,684 @@
1
- // Theming. A theme is data: the chart's colors and font, every UI token, and the settings of
2
- // each component. `createTheme` builds one from a few choices; `applyTheme` writes it once per
3
- // document (or shadow root) as a rule in `@layer vela.theme`, keyed by the host's
4
- // `data-vela-theme`. The layer sits below every other style, so a host's own CSS overrides
5
- // any token without `!important` (`[data-vela-theme] { --vela-accent: … }` reaches every
6
- // themed host, chrome inside the chart included), and several themes coexist on one page.
7
- import type { badgeDef } from '../components/badge';
8
- import type { barChartDef } from '../components/bar-chart';
9
- import type { buttonDef } from '../components/button';
10
- import type { calloutBubbleDef } from '../components/callout-bubble';
11
- import type { cardDef } from '../components/card';
12
- import type { colorPickerDef } from '../components/color-picker';
13
- import type { dataTableDef } from '../components/data-table';
14
- import type { datePickerDef } from '../components/date-picker';
15
- import type { dialogDef } from '../components/dialog';
16
- import type { donutDef } from '../components/donut';
17
- import type { drawerDef } from '../components/drawer';
18
- import type { emptyDef } from '../components/empty';
19
- import type { fieldDef } from '../components/field';
20
- import type { glyphSelectDef } from '../components/glyph-select';
21
- import type { hoverCardDef } from '../components/hover-card';
22
- import type { kbdDef } from '../components/kbd';
23
- import type { lineChartDef } from '../components/line-chart';
24
- import type { dropdownMenuDef } from '../components/dropdown-menu';
25
- import type { numberInputDef } from '../components/number-input';
26
- import type { popoverDef } from '../components/popover';
27
- import type { scatterChartDef } from '../components/scatter-chart';
28
- import type { selectDef } from '../components/select';
29
- import type { sparklineDef } from '../components/sparkline';
30
- import type { statDef } from '../components/stat';
31
- import type { checkboxDef } from '../components/checkbox';
32
- import type { collapsibleDef } from '../components/collapsible';
33
- import type { tabsDef } from '../components/tabs';
34
- import type { textAreaDef } from '../components/text-area';
35
- import type { inputDef } from '../components/input';
36
- import type { inputGroupDef } from '../components/input-group';
37
- import type { itemDef } from '../components/item';
38
- import type { monthGridDef } from '../components/month-grid';
39
- import type { sliderDef } from '../components/slider';
40
- import type { sortButtonDef } from '../components/sort-button';
41
- import type { switchDef } from '../components/switch';
42
- import type { toastDef } from '../components/toast';
43
- import type { toggleGroupDef } from '../components/toggle-group';
44
- import type { tooltipDef } from '../components/tooltip';
45
- import type { treemapDef } from '../components/treemap';
46
- import { contrastRatio, isDarkColor, mix, parseRgb } from './color';
47
- import { KIT_COMPONENTS } from './component-index';
48
- import { acceptCss, injectLayerOrder, isWrittenCss } from './css';
49
- import { declaredComponents, type ComponentDef, type DeclaredComponent } from './define';
50
- import { BEARISH, BULLISH } from './palette';
51
- import { injectStyles } from './styles';
52
- import { STATIC_TOKENS, themeTokens, type ChartTheme } from './tokens';
53
-
54
- /** The built-in dark chart theme. */
55
- export const DARK_CHART: ChartTheme = {
56
- background: '#151619',
57
- textColor: '#b2b5be',
58
- gridColor: '#20222c',
59
- borderColor: '#2a2b30',
60
- upColor: BULLISH,
61
- downColor: BEARISH,
62
- fontFamily: 'sans-serif',
63
- };
64
-
65
- /** The built-in light chart theme. Candle hues are shared across themes: switching themes
66
- * recolors surfaces and text, never the series. */
67
- export const LIGHT_CHART: ChartTheme = {
68
- background: '#ffffff',
69
- textColor: '#1e293b',
70
- // Soft chrome on white: grid is a neutral wash; pane separator / axis border sit a
71
- // step darker so stacked panes stay distinct.
72
- gridColor: '#cccccc',
73
- borderColor: '#d4dae3',
74
- upColor: BULLISH,
75
- downColor: BEARISH,
76
- fontFamily: 'sans-serif',
77
- };
78
-
79
- /** Every token, by name without the `--vela-` prefix. A test checks the list against what
80
- * `createTheme` writes. */
81
- export const TOKEN_NAMES = [
82
- 'space-1',
83
- 'space-2',
84
- 'space-3',
85
- 'space-4',
86
- 'radius-sm',
87
- 'radius-md',
88
- 'radius-lg',
89
- 'z-tooltip',
90
- 'z-menu',
91
- 'z-dialog',
92
- 'z-popover',
93
- 'ease',
94
- 'dur-fast',
95
- 'dur-med',
96
- 'font-size-sm',
97
- 'font-size-md',
98
- 'font-size-lg',
99
- 'scroll-size',
100
- 'font',
101
- 'bg',
102
- 'fg',
103
- 'fg-muted',
104
- 'fg-faint',
105
- 'fg-bright',
106
- 'surface',
107
- 'surface-elev',
108
- 'surface-overlay',
109
- 'surface-sunken',
110
- 'border',
111
- 'border-strong',
112
- 'border-soft',
113
- 'border-faint',
114
- 'hover',
115
- 'active',
116
- 'hover-strong',
117
- 'focus',
118
- 'focus-soft',
119
- 'separator-hover-band',
120
- 'separator-hover-line',
121
- 'scroll',
122
- 'accent',
123
- 'accent-bright',
124
- 'highlight',
125
- 'selected-bg',
126
- 'selected-fg',
127
- 'fg-on-fill',
128
- 'up',
129
- 'down',
130
- 'profit',
131
- 'loss',
132
- 'danger',
133
- 'shadow',
134
- 'shadow-dialog',
135
- 'backdrop',
136
- ] as const;
137
-
138
- export type TokenName = (typeof TOKEN_NAMES)[number];
139
-
140
- /** The components a theme can set, by name: each one's declaration. A package with
141
- * components of its own adds them here by declaration merging. */
142
- export interface ComponentDefs {
143
- badge: typeof badgeDef;
144
- 'bar-chart': typeof barChartDef;
145
- button: typeof buttonDef;
146
- 'callout-bubble': typeof calloutBubbleDef;
147
- card: typeof cardDef;
148
- checkbox: typeof checkboxDef;
149
- collapsible: typeof collapsibleDef;
150
- 'color-picker': typeof colorPickerDef;
151
- 'data-table': typeof dataTableDef;
152
- 'date-picker': typeof datePickerDef;
153
- dialog: typeof dialogDef;
154
- donut: typeof donutDef;
155
- drawer: typeof drawerDef;
156
- 'dropdown-menu': typeof dropdownMenuDef;
157
- empty: typeof emptyDef;
158
- field: typeof fieldDef;
159
- 'glyph-select': typeof glyphSelectDef;
160
- 'hover-card': typeof hoverCardDef;
161
- 'input-group': typeof inputGroupDef;
162
- input: typeof inputDef;
163
- item: typeof itemDef;
164
- kbd: typeof kbdDef;
165
- 'line-chart': typeof lineChartDef;
166
- 'month-grid': typeof monthGridDef;
167
- 'number-input': typeof numberInputDef;
168
- popover: typeof popoverDef;
169
- 'scatter-chart': typeof scatterChartDef;
170
- select: typeof selectDef;
171
- slider: typeof sliderDef;
172
- 'sort-button': typeof sortButtonDef;
173
- sparkline: typeof sparklineDef;
174
- stat: typeof statDef;
175
- switch: typeof switchDef;
176
- tabs: typeof tabsDef;
177
- 'text-area': typeof textAreaDef;
178
- toast: typeof toastDef;
179
- 'toggle-group': typeof toggleGroupDef;
180
- tooltip: typeof tooltipDef;
181
- treemap: typeof treemapDef;
182
- }
183
-
184
- type SettingsOf<D> = D extends ComponentDef<string, string, infer S> ? S : never;
185
- type PartsOf<D> = D extends ComponentDef<string, infer P, string> ? P : never;
186
-
187
- /** Settings by component, then by setting (`{ button: { radius: '2px' } }`), each written
188
- * as `--vela-<component>-<setting>`. `css` restyles the component's parts completely: each
189
- * part's CSS, written with the `css` tag, applies to that part under the theme, after every
190
- * other layer of the kit. */
191
- export type ComponentSettings = {
192
- [K in keyof ComponentDefs]?: { [S in SettingsOf<ComponentDefs[K]>]?: string } & {
193
- css?: { [P in PartsOf<ComponentDefs[K]>]?: string };
194
- };
195
- };
196
-
197
- export interface CreateThemeOptions {
198
- /** Apply part CSS that was not written with the `css` tag (a theme loaded from data).
199
- * Off by default: CSS from someone else can restyle the page to mislead, and load
200
- * remote images that leak what the page shows. */
201
- allowCss?: boolean;
202
- }
203
-
204
- /** A theme's settings beyond the chart's colors. */
205
- export interface ThemeSettings {
206
- /** The brand color; its readable ink derives from it. */
207
- accent?: string;
208
- /** Scales every radius token: `none`, `sm`, `md` (default), `lg`. */
209
- radius?: 'none' | 'sm' | 'md' | 'lg';
210
- font?: string;
211
- /** Any token, by name. */
212
- tokens?: Partial<Record<TokenName, string>>;
213
- components?: ComponentSettings;
214
- }
215
-
216
- /** The choices a theme is built from. Every field is optional: `createTheme()` is the dark theme. */
217
- export interface ThemeInput extends ThemeSettings {
218
- /** The theme to start from: `dark` (default), `light`, or a chart theme's seven fields. */
219
- base?: 'dark' | 'light' | ChartTheme;
220
- /** A theme from colors alone: everything else derives from them, light or dark read
221
- * from the background. */
222
- colors?: {
223
- background?: string;
224
- text?: string;
225
- grid?: string;
226
- border?: string;
227
- up?: string;
228
- down?: string;
229
- accent?: string;
230
- };
231
- }
232
-
233
- /** A theme built by {@link createTheme}. */
234
- export interface UiTheme {
235
- /** Derived from the values: equal themes share one rule. */
236
- readonly id: string;
237
- /** The chart's colors and font. */
238
- readonly chart: ChartTheme;
239
- /** Every token, by custom property (`--vela-accent`). */
240
- readonly tokens: Readonly<Record<string, string>>;
241
- /** Component settings, by component then setting. */
242
- readonly components: Readonly<Record<string, Readonly<Record<string, string>>>>;
243
- /** Part CSS, by component then part. */
244
- readonly css: Readonly<Record<string, Readonly<Record<string, string>>>>;
245
- /** Its settings beyond the chart's colors: with {@link chart}, they rebuild the theme. */
246
- readonly settings: Readonly<ThemeSettings>;
247
- }
248
-
249
- /** A chart theme with optional settings: its seven fields seed the UI theme and `ui`
250
- * adjusts it. Chrome that recolors its surface (an overlay following the plot's
251
- * background) keeps the settings. */
252
- export type ThemedChart = ChartTheme & { readonly ui?: ThemeSettings };
253
-
254
- const RADIUS_SCALE = { none: 0, sm: 0.5, md: 1, lg: 1.5 } as const;
255
-
256
- function chartOf(input: ThemeInput): ChartTheme {
257
- const base = input.base === 'light' ? LIGHT_CHART : input.base === undefined || input.base === 'dark' ? DARK_CHART : input.base;
258
- const colors = input.colors;
259
- const font = input.font ?? base.fontFamily;
260
- if (!colors) return { ...base, fontFamily: font };
261
- const background = colors.background ?? base.background;
262
- const textColor = colors.text ?? (colors.background ? (isDarkColor(background) ? DARK_CHART.textColor : LIGHT_CHART.textColor) : base.textColor);
263
- const surfaceChanged = colors.background !== undefined || colors.text !== undefined;
264
- return {
265
- background,
266
- textColor,
267
- gridColor: colors.grid ?? (surfaceChanged ? mix(background, textColor, 0.08) : base.gridColor),
268
- borderColor: colors.border ?? (surfaceChanged ? mix(background, textColor, 0.14) : base.borderColor),
269
- upColor: colors.up ?? base.upColor,
270
- downColor: colors.down ?? base.downColor,
271
- fontFamily: font,
272
- };
273
- }
274
-
275
- /** A short stable id for a theme's values. */
276
- function themeId(values: string): string {
277
- let h = 5381;
278
- for (let i = 0; i < values.length; i += 1) h = ((h << 5) + h + values.charCodeAt(i)) | 0;
279
- return (h >>> 0).toString(36);
280
- }
281
-
282
- /** The ink that reads best on a fill. */
283
- function inkOn(fill: string): string {
284
- return (contrastRatio(fill, '#ffffff') ?? 21) >= (contrastRatio(fill, '#000000') ?? 0) ? '#ffffff' : '#000000';
285
- }
286
-
287
- function build(input: ThemeInput, options: CreateThemeOptions): { theme: UiTheme; dropped: string[] } {
288
- const chart = chartOf(input);
289
- const tokens: Record<string, string> = { ...STATIC_TOKENS, ...themeTokens(chart) };
290
- if (input.radius) {
291
- const f = RADIUS_SCALE[input.radius];
292
- for (const name of ['radius-sm', 'radius-md', 'radius-lg']) tokens[`--vela-${name}`] = `${Math.round(parseFloat(STATIC_TOKENS[`--vela-${name}`]!) * f)}px`;
293
- }
294
- const accent = input.accent ?? input.colors?.accent;
295
- if (accent) {
296
- tokens['--vela-accent'] = accent;
297
- tokens['--vela-accent-bright'] = accent;
298
- tokens['--vela-fg-on-fill'] = inkOn(accent);
299
- }
300
- for (const [name, value] of Object.entries(input.tokens ?? {})) if (value !== undefined) tokens[`--vela-${name}`] = value;
301
- const components: Record<string, Record<string, string>> = {};
302
- const partCss: Record<string, Record<string, string>> = {};
303
- const dropped: string[] = [];
304
- const entries = Object.entries(input.components ?? {}) as Array<[string, Record<string, unknown>]>;
305
- for (const [name, values] of entries) {
306
- const set: Record<string, string> = {};
307
- for (const [key, value] of Object.entries(values)) if (key !== 'css' && typeof value === 'string') set[key] = value;
308
- if (Object.keys(set).length) components[name] = set;
309
- const parts: Record<string, string> = {};
310
- for (const [part, text] of Object.entries((values.css ?? {}) as Record<string, unknown>)) {
311
- if (typeof text !== 'string') continue;
312
- if (options.allowCss) acceptCss(text);
313
- if (isWrittenCss(text)) parts[part] = text;
314
- else dropped.push(`components.${name}.css.${part}`);
315
- }
316
- if (Object.keys(parts).length) partCss[name] = parts;
317
- }
318
- const settings: ThemeSettings = {};
319
- if (accent) settings.accent = accent;
320
- if (input.radius) settings.radius = input.radius;
321
- if (input.font) settings.font = input.font;
322
- if (input.tokens) settings.tokens = { ...input.tokens };
323
- const both = new Set([...Object.keys(components), ...Object.keys(partCss)]);
324
- if (both.size) {
325
- const merged: Record<string, Record<string, unknown>> = {};
326
- for (const name of both) merged[name] = { ...components[name], ...(partCss[name] ? { css: { ...partCss[name] } } : {}) };
327
- settings.components = merged as ComponentSettings;
328
- }
329
- const theme = { id: themeId(JSON.stringify([tokens, components, partCss])), chart, tokens, components, css: partCss, settings };
330
- return { theme, dropped };
331
- }
332
-
333
- const isCssVar = (value: string) => value.trim().startsWith('var(');
334
-
335
- /** A component's parts and settings: as declared on the page, else as the kit declares them
336
- * (a kit component a page never imported is declared nowhere yet). */
337
- function componentNamed(name: string): DeclaredComponent | undefined {
338
- return declaredComponents().get(name) ?? (Object.prototype.hasOwnProperty.call(KIT_COMPONENTS, name) ? KIT_COMPONENTS[name] : undefined);
339
- }
340
-
341
- function componentProblems(input: ThemeInput): string[] {
342
- const problems: string[] = [];
343
- for (const [name, values] of Object.entries(input.components ?? {}) as Array<[string, Record<string, unknown> | undefined]>) {
344
- const def = componentNamed(name);
345
- if (!def) {
346
- problems.push(`components.${name}: no component has that name (declare a component of your own with defineComponent before creating the theme)`);
347
- continue;
348
- }
349
- for (const key of Object.keys(values ?? {})) {
350
- if (key === 'css' || def.settings.includes(key)) continue;
351
- problems.push(`components.${name}.${key} is not a setting of ${name} (${def.settings.length ? `its settings: ${def.settings.join(', ')}` : 'it has none'})`);
352
- }
353
- for (const part of Object.keys((values?.css ?? {}) as Record<string, unknown>)) {
354
- if (!def.parts.includes(part)) problems.push(`components.${name}.css.${part} is not a part of ${name} (its parts: ${def.parts.join(', ')})`);
355
- }
356
- }
357
- return problems;
358
- }
359
-
360
- function problemsOf(input: ThemeInput, theme: UiTheme): string[] {
361
- const problems: string[] = [];
362
- const known = new Set<string>(TOKEN_NAMES);
363
- for (const name of Object.keys(input.tokens ?? {})) if (!known.has(name)) problems.push(`"${name}" is not a token`);
364
- problems.push(...componentProblems(input));
365
- const colors: Array<[string, string | undefined]> = [['accent', input.accent]];
366
- for (const [k, v] of Object.entries(input.colors ?? {})) colors.push([`colors.${k}`, v]);
367
- if (typeof input.base === 'object') for (const k of CHART_FIELDS) if (k !== 'fontFamily') colors.push([`base.${k}`, input.base[k]]);
368
- for (const [where, value] of colors) {
369
- if (value !== undefined && !isCssVar(value) && !parseRgb(value)) problems.push(`${where} "${value}" is not a color the theme can derive from (use #rrggbb or rgb())`);
370
- }
371
- const pairs: Array<[string, string, number]> = [
372
- ['fg', 'bg', 4.5],
373
- ['fg-on-fill', 'accent', 3],
374
- ];
375
- for (const [ink, fill, min] of pairs) {
376
- const ratio = contrastRatio(theme.tokens[`--vela-${ink}`] ?? '', theme.tokens[`--vela-${fill}`] ?? '');
377
- if (ratio !== null && ratio < min) problems.push(`${ink} on ${fill} has a contrast of ${ratio.toFixed(1)}:1 (at least ${min}:1 reads well)`);
378
- }
379
- for (const [name, parts] of Object.entries(theme.css)) {
380
- for (const [part, text] of Object.entries(parts)) {
381
- const where = `components.${name}.css.${part}`;
382
- if (/!important/i.test(text)) problems.push(`${where} uses !important, which the custom layer does not need`);
383
- if (/(^|[\s,>+~(&])\.[a-z_-][\w-]*[^{};]*\{/im.test(text)) problems.push(`${where} targets a class name, which is not part of the component's contract (use its parts and data attributes)`);
384
- for (const at of text.match(/@[a-z-]+/gi) ?? []) {
385
- if (!CONDITIONAL.test(at)) problems.push(`${where} declares ${at}, which is left out (declare it in the page's stylesheet and use it from the part)`);
386
- }
387
- }
388
- }
389
- return problems;
390
- }
391
-
392
- const droppedProblem = (where: string) => `${where} was not written with the css tag and is left out (pass { allowCss: true } to apply CSS loaded from data)`;
393
-
394
- /** What is wrong with a theme's input: unknown tokens, components, settings and parts, colors
395
- * the theme cannot derive from, text with too little contrast on its background, and part
396
- * CSS that is left out or reaches past the component's contract. `createTheme` warns about
397
- * each. */
398
- export function checkTheme(input: ThemeInput = {}, options: CreateThemeOptions = {}): string[] {
399
- const { theme, dropped } = build(input, options);
400
- return [...dropped.map(droppedProblem), ...problemsOf(input, theme)];
401
- }
402
-
403
- const warned = new Set<string>();
404
-
405
- function warn(problems: readonly string[]): void {
406
- for (const problem of problems) {
407
- if (warned.has(problem)) continue;
408
- warned.add(problem);
409
- console.warn(`[vela-ui] theme: ${problem}`);
410
- }
411
- }
412
-
413
- /** Build a theme. Without overrides, `dark` and `light` give exactly the built-in tokens. */
414
- export function createTheme(input: ThemeInput = {}, options: CreateThemeOptions = {}): UiTheme {
415
- const { theme, dropped } = build(input, options);
416
- warn([...dropped.map(droppedProblem), ...problemsOf(input, theme)]);
417
- return theme;
418
- }
419
-
420
- const isUiTheme = (theme: UiTheme | ThemedChart): theme is UiTheme => 'tokens' in theme && 'id' in theme;
421
-
422
- const CHART_FIELDS = ['background', 'textColor', 'gridColor', 'borderColor', 'upColor', 'downColor', 'fontFamily'] as const;
423
-
424
- const chartKey = (chart: ChartTheme) => CHART_FIELDS.map((k) => chart[k]).join('|');
425
-
426
- /** The document or shadow root a host renders in (its document while it is detached). */
427
- function rootOf(host: HTMLElement): Document | ShadowRoot {
428
- const root = host.getRootNode();
429
- if (root instanceof Document) return root;
430
- if (typeof ShadowRoot !== 'undefined' && root instanceof ShadowRoot) return root;
431
- return host.ownerDocument;
432
- }
433
-
434
- /** Splits CSS at its top level into declarations and blocks (`prelude { body }`), skipping
435
- * comments and strings. */
436
- function topLevel(text: string): { decls: string; blocks: Array<[string, string]> } {
437
- const src = text.replace(/\/\*[\s\S]*?\*\//g, '');
438
- let decls = '';
439
- const blocks: Array<[string, string]> = [];
440
- let buf = '';
441
- let i = 0;
442
- while (i < src.length) {
443
- const c = src[i]!;
444
- if (c === '"' || c === "'") {
445
- const end = src.indexOf(c, i + 1);
446
- const stop = end < 0 ? src.length : end + 1;
447
- buf += src.slice(i, stop);
448
- i = stop;
449
- continue;
450
- }
451
- if (c === ';') {
452
- decls += `${buf.trim()}; `;
453
- buf = '';
454
- } else if (c === '{') {
455
- let depth = 1;
456
- let j = i + 1;
457
- while (j < src.length && depth > 0) {
458
- if (src[j] === '{') depth += 1;
459
- else if (src[j] === '}') depth -= 1;
460
- j += 1;
461
- }
462
- blocks.push([buf.trim(), src.slice(i + 1, j - 1).trim()]);
463
- buf = '';
464
- i = j;
465
- continue;
466
- } else {
467
- buf += c;
468
- }
469
- i += 1;
470
- }
471
- if (buf.trim()) decls += `${buf.trim()}; `;
472
- return { decls: decls.trim(), blocks };
473
- }
474
-
475
- /** Splits a selector list at its top-level commas. */
476
- function selectorList(prelude: string): string[] {
477
- const out: string[] = [];
478
- let depth = 0;
479
- let start = 0;
480
- for (let i = 0; i < prelude.length; i += 1) {
481
- const c = prelude[i];
482
- if (c === '(' || c === '[') depth += 1;
483
- else if (c === ')' || c === ']') depth -= 1;
484
- else if (c === ',' && depth === 0) {
485
- out.push(prelude.slice(start, i).trim());
486
- start = i + 1;
487
- }
488
- }
489
- out.push(prelude.slice(start).trim());
490
- return out.filter(Boolean);
491
- }
492
-
493
- /** The at-rules a part's CSS can hold: conditions around its rules. Others (`@keyframes`,
494
- * `@font-face`) declare something page-wide and belong in the host's stylesheet. */
495
- const CONDITIONAL = /^@(media|supports|container)\b/i;
496
-
497
- /** A part's CSS as flat rules on `scope`: its own declarations, its `&` rules (one level of
498
- * nesting, which is all a part needs; a rule without `&` is a descendant), and `@media`,
499
- * `@supports` or `@container` blocks around either. Theme CSS reaches the page without our
500
- * build, and the oldest browsers we support do not nest. */
501
- function flatPart(scope: string, text: string): string {
502
- const { decls, blocks } = topLevel(text);
503
- const rules: string[] = decls ? [`${scope} { ${decls} }`] : [];
504
- for (const [prelude, body] of blocks) {
505
- if (prelude.startsWith('@')) {
506
- if (CONDITIONAL.test(prelude)) rules.push(`${prelude} { ${flatPart(scope, body)} }`);
507
- continue;
508
- }
509
- const list = selectorList(prelude).map((s) => (s.includes('&') ? s.split('&').join(scope) : `${scope} ${s}`));
510
- const inner = topLevel(body);
511
- if (inner.decls) rules.push(`${list.join(', ')} { ${inner.decls} }`);
512
- }
513
- return rules.join(' ');
514
- }
515
-
516
- /** The theme's rules: every token and component setting, by default on the hosts that carry
517
- * its id; and the part CSS, on those parts inside them, in the last layer. */
518
- export function themeCss(theme: UiTheme, selector = `[data-vela-theme="${theme.id}"]`): string {
519
- const decls = Object.entries(theme.tokens).map(([k, v]) => `${k}: ${v};`);
520
- for (const [component, settings] of Object.entries(theme.components)) {
521
- for (const [setting, value] of Object.entries(settings)) decls.push(`--vela-${component}-${setting}: ${value};`);
522
- }
523
- const out = [`@layer vela.theme { ${selector} { ${decls.join(' ')} } }`];
524
- const parts: string[] = [];
525
- for (const [component, byPart] of Object.entries(theme.css)) {
526
- for (const [part, text] of Object.entries(byPart)) {
527
- const slot = part === 'root' ? component : `${component}-${part}`;
528
- // A part's `display` must not beat the browser's own `[hidden]` rule.
529
- parts.push(flatPart(`:where(${selector}, ${selector} *):is([data-slot~="${slot}"]):where(:not([hidden]))`, text));
530
- }
531
- }
532
- if (parts.length) out.push(`@layer vela.custom { ${parts.join(' ')} }`);
533
- return out.join('\n');
534
- }
535
-
536
- const MAX_CACHED = 32;
537
- const fromChart = new Map<string, UiTheme>();
538
-
539
- /** The UI theme for a chart theme: its seven fields with the settings it carries. */
540
- function themeOfChart(chart: ThemedChart): UiTheme {
541
- const plain: ChartTheme = { background: chart.background, textColor: chart.textColor, gridColor: chart.gridColor, borderColor: chart.borderColor, upColor: chart.upColor, downColor: chart.downColor, fontFamily: chart.fontFamily };
542
- const key = chart.ui ? `${chartKey(plain)}|${JSON.stringify(chart.ui)}` : chartKey(plain);
543
- let ui = fromChart.get(key);
544
- if (!ui) {
545
- if (fromChart.size >= MAX_CACHED) fromChart.clear();
546
- ui = createTheme({ ...chart.ui, base: plain });
547
- fromChart.set(key, ui);
548
- }
549
- return ui;
550
- }
551
-
552
- const sheets = new WeakMap<Document | ShadowRoot, Map<string, HTMLStyleElement>>();
553
-
554
- /** Writes the theme's rule into the root once. Live recoloring (a plot background dragged
555
- * through a color picker) makes a theme per step, so past {@link MAX_CACHED} rules, the
556
- * ones no element carries any more are dropped. */
557
- function installTheme(ui: UiTheme, root: Document | ShadowRoot): void {
558
- let byId = sheets.get(root);
559
- if (!byId) sheets.set(root, (byId = new Map()));
560
- const id = `vela-theme-${ui.id}`;
561
- if (byId.get(id)?.isConnected) return;
562
- const sheet = injectStyles(id, themeCss(ui), root);
563
- if (sheet) byId.set(id, sheet);
564
- if (byId.size <= MAX_CACHED) return;
565
- for (const [other, el] of byId) {
566
- if (other === id || root.querySelector(`[data-vela-theme="${other.slice('vela-theme-'.length)}"]`)) continue;
567
- el.remove();
568
- byId.delete(other);
569
- }
570
- }
571
-
572
- /** Theme a host and everything inside it. A chart theme's seven fields build the theme on
573
- * the way, keeping the choices of the UI theme it carries. */
574
- export function applyTheme(host: HTMLElement, theme: UiTheme | ThemedChart): UiTheme {
575
- const ui = isUiTheme(theme) ? theme : themeOfChart(theme);
576
- const root = rootOf(host);
577
- injectLayerOrder(root);
578
- if (typeof document !== 'undefined') installTheme(ui, root);
579
- host.setAttribute('data-vela-theme', ui.id);
580
- // Tokens an older writer left inline would hide the theme's rule.
581
- for (const name in ui.tokens) host.style.removeProperty(name);
582
- return ui;
583
- }
584
-
585
- const STATIC_ID = 'vela-ui-tokens';
586
-
587
- const STATIC_DECLS = Object.entries(STATIC_TOKENS)
588
- .map(([k, v]) => ` ${k}: ${v};`)
589
- .join('\n');
590
-
591
- const STATIC_CSS = `
592
- /* Theme-independent tokens on every kit host, at no specificity in the theme layer: a theme's
593
- own rule (radius scaling) and a host's CSS both override them. */
594
- @layer vela.theme {
595
- :where(.vela-ui, .vela-ui-layer) {
596
- ${STATIC_DECLS}
597
- }
598
- /* One scrollbar on every kit surface: thin, a rounded thumb, no track and no arrows, sized and
599
- colored by the scroll tokens. Chromium and Safari draw it from the ::-webkit-scrollbar parts,
600
- and setting scrollbar-width or scrollbar-color on an element switches them back to the native
601
- bar, so those two are for the browsers without the parts. */
602
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar { width: var(--vela-scroll-size); height: var(--vela-scroll-size); }
603
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-track { background: transparent; }
604
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-corner { background: transparent; }
605
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-thumb { background: var(--vela-scroll); border-radius: var(--vela-scroll-size); }
606
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
607
- @supports not selector(::-webkit-scrollbar) {
608
- :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *) { scrollbar-width: thin; scrollbar-color: var(--vela-scroll) transparent; }
609
- }
610
- }
611
- .vela-ui, .vela-ui-layer {
612
- font-family: var(--vela-font, -apple-system, system-ui, sans-serif);
613
- box-sizing: border-box;
614
- /* Chrome text (titles, buttons, menus, readouts) is UI, not copy — never selectable. */
615
- user-select: none;
616
- -webkit-user-select: none;
617
- }
618
- /* Unlayered, as the chrome's own controls rely on it; a kit component never declares a
619
- box-sizing of its own, which this reset would override. */
620
- .vela-ui *, .vela-ui-layer * { box-sizing: border-box; }
621
- /* Text ENTRY is the one exception: selection is part of editing. */
622
- .vela-ui :is(input, textarea), .vela-ui-layer :is(input, textarea) { user-select: text; -webkit-user-select: text; }
623
- /* iOS Safari zooms the page when a focused field is under 16px, and often
624
- keeps that zoom after the field blurs or a dialog closes. The shell's
625
- mobile size class is the honest gate — not a media query — so an embedded
626
- chart on a wide desktop still gets the rule when it is in the phone layout.
627
- Scoped to the kit root so a host page's own [data-layout] is never touched. */
628
- .vela-ui[data-layout='mobile'] :is(input, textarea, select) { font-size: 16px; }
629
- @layer vela.ui {
630
- .vela-icon { display: inline-flex; align-items: center; flex: none; }
631
- .vela-icon svg { display: block; }
632
- }
633
- `;
634
-
635
- /** Theme a host from a chart theme's seven fields.
636
- * @deprecated Use {@link applyTheme}, which also takes a theme from {@link createTheme}. */
637
- export function applyThemeTokens(el: HTMLElement, t: ThemedChart): void {
638
- applyTheme(el, t);
639
- }
640
-
641
- /** Re-token a chart-overlay host (statusline, watermark, toast — chrome floating OVER
642
- * the plot) from the LIVE plot surface: a config edit can recolor the plot background
643
- * independently of the app theme (a white plot typed into settings on the dark theme),
644
- * and the overlay ink must stay readable either way. `config` is the renderer's
645
- * `getConfig()` snapshot; a missing/shapeless one falls back to the base app theme.
646
- * Floating menus and dropdowns do NOT use this — they mount on {@link floatingLayerHost}
647
- * so their surface follows the app theme alone. */
648
- export function applyPlotOverlayTokens(host: HTMLElement, base: ThemedChart, config: unknown): void {
649
- const layout = (config as { layout?: { background?: string; textColor?: string } } | null)?.layout;
650
- const t = layout?.background && layout.textColor ? { ...base, background: layout.background, textColor: layout.textColor } : base;
651
- applyTheme(host, t);
652
- }
653
-
654
- /** Mount floating kit layers (menus, select lists) on the nearest `.vela-ui` so they
655
- * inherit the app-theme tokens. A plot-overlay host (the cell) retokens from
656
- * `layout.background`; chrome panels must not follow that. Falls back to `fallback`
657
- * (typically `document.body`) when no kit host is an ancestor. */
658
- export function floatingLayerHost(from: HTMLElement, fallback?: HTMLElement): HTMLElement {
659
- return (from.closest('.vela-ui') as HTMLElement | null) ?? fallback ?? from;
660
- }
661
-
662
- /** Mark an element as a kit host (the `.vela-ui` class and the shared sheet), themed when
663
- * a theme is given. */
664
- export function ensureUIHost(el: HTMLElement, theme?: UiTheme | ThemedChart): void {
665
- const root = rootOf(el);
666
- injectLayerOrder(root);
667
- injectStyles(STATIC_ID, STATIC_CSS, root);
668
- el.classList.add('vela-ui');
669
- if (theme) applyTheme(el, theme);
670
- }
1
+ // Theming. A theme is data: the chart's colors and font, every UI token, and the settings of
2
+ // each component. `createTheme` builds one from a few choices; `applyTheme` writes it once per
3
+ // document (or shadow root) as a rule in `@layer vela.theme`, keyed by the host's
4
+ // `data-vela-theme`. The layer sits below every other style, so a host's own CSS overrides
5
+ // any token without `!important` (`[data-vela-theme] { --vela-accent: … }` reaches every
6
+ // themed host, chrome inside the chart included), and several themes coexist on one page.
7
+ import type { badgeDef } from '../components/badge';
8
+ import type { barChartDef } from '../components/bar-chart';
9
+ import type { buttonDef } from '../components/button';
10
+ import type { calloutBubbleDef } from '../components/callout-bubble';
11
+ import type { cardDef } from '../components/card';
12
+ import type { colorPickerDef } from '../components/color-picker';
13
+ import type { dataTableDef } from '../components/data-table';
14
+ import type { datePickerDef } from '../components/date-picker';
15
+ import type { dialogDef } from '../components/dialog';
16
+ import type { donutDef } from '../components/donut';
17
+ import type { drawerDef } from '../components/drawer';
18
+ import type { emptyDef } from '../components/empty';
19
+ import type { fieldDef } from '../components/field';
20
+ import type { glyphSelectDef } from '../components/glyph-select';
21
+ import type { hoverCardDef } from '../components/hover-card';
22
+ import type { kbdDef } from '../components/kbd';
23
+ import type { lineChartDef } from '../components/line-chart';
24
+ import type { dropdownMenuDef } from '../components/dropdown-menu';
25
+ import type { numberInputDef } from '../components/number-input';
26
+ import type { popoverDef } from '../components/popover';
27
+ import type { scatterChartDef } from '../components/scatter-chart';
28
+ import type { selectDef } from '../components/select';
29
+ import type { sparklineDef } from '../components/sparkline';
30
+ import type { figureDef } from '../components/figure';
31
+ import type { checkboxDef } from '../components/checkbox';
32
+ import type { collapsibleDef } from '../components/collapsible';
33
+ import type { tabsDef } from '../components/tabs';
34
+ import type { textAreaDef } from '../components/text-area';
35
+ import type { inputDef } from '../components/input';
36
+ import type { inputGroupDef } from '../components/input-group';
37
+ import type { itemDef } from '../components/item';
38
+ import type { monthGridDef } from '../components/month-grid';
39
+ import type { sliderDef } from '../components/slider';
40
+ import type { sortButtonDef } from '../components/sort-button';
41
+ import type { switchDef } from '../components/switch';
42
+ import type { toastDef } from '../components/toast';
43
+ import type { toggleGroupDef } from '../components/toggle-group';
44
+ import type { tooltipDef } from '../components/tooltip';
45
+ import type { treemapDef } from '../components/treemap';
46
+ import { contrastRatio, isDarkColor, mix, parseRgb } from './color';
47
+ import { KIT_COMPONENTS } from './component-index';
48
+ import { acceptCss, injectLayerOrder, isWrittenCss } from './css';
49
+ import { declaredComponents, type ComponentDef, type DeclaredComponent } from './define';
50
+ import { BEARISH, BULLISH } from './palette';
51
+ import { injectStyles } from './styles';
52
+ import { STATIC_TOKENS, themeTokens, type ChartTheme } from './tokens';
53
+
54
+ /** The built-in dark chart theme. */
55
+ export const DARK_CHART: ChartTheme = {
56
+ background: '#151619',
57
+ textColor: '#b2b5be',
58
+ gridColor: '#20222c',
59
+ borderColor: '#2a2b30',
60
+ upColor: BULLISH,
61
+ downColor: BEARISH,
62
+ fontFamily: 'sans-serif',
63
+ };
64
+
65
+ /** The built-in light chart theme. Candle hues are shared across themes: switching themes
66
+ * recolors surfaces and text, never the series. */
67
+ export const LIGHT_CHART: ChartTheme = {
68
+ background: '#ffffff',
69
+ textColor: '#1e293b',
70
+ // Soft chrome on white: grid is a neutral wash; pane separator / axis border sit a
71
+ // step darker so stacked panes stay distinct.
72
+ gridColor: '#cccccc',
73
+ borderColor: '#d4dae3',
74
+ upColor: BULLISH,
75
+ downColor: BEARISH,
76
+ fontFamily: 'sans-serif',
77
+ };
78
+
79
+ /** Every token, by name without the `--vela-` prefix. A test checks the list against what
80
+ * `createTheme` writes. */
81
+ export const TOKEN_NAMES = [
82
+ 'space-1',
83
+ 'space-2',
84
+ 'space-3',
85
+ 'space-4',
86
+ 'radius-sm',
87
+ 'radius-md',
88
+ 'radius-lg',
89
+ 'z-tooltip',
90
+ 'z-menu',
91
+ 'z-dialog',
92
+ 'z-popover',
93
+ 'ease',
94
+ 'dur-fast',
95
+ 'dur-med',
96
+ 'font-size-sm',
97
+ 'font-size-md',
98
+ 'font-size-lg',
99
+ 'scroll-size',
100
+ 'font',
101
+ 'bg',
102
+ 'fg',
103
+ 'fg-muted',
104
+ 'fg-faint',
105
+ 'fg-bright',
106
+ 'surface',
107
+ 'surface-elev',
108
+ 'surface-overlay',
109
+ 'surface-sunken',
110
+ 'border',
111
+ 'border-strong',
112
+ 'border-soft',
113
+ 'border-faint',
114
+ 'hover',
115
+ 'active',
116
+ 'hover-strong',
117
+ 'focus',
118
+ 'focus-soft',
119
+ 'separator-hover-band',
120
+ 'separator-hover-line',
121
+ 'scroll',
122
+ 'accent',
123
+ 'accent-bright',
124
+ 'highlight',
125
+ 'selected-bg',
126
+ 'selected-fg',
127
+ 'fg-on-fill',
128
+ 'up',
129
+ 'down',
130
+ 'profit',
131
+ 'loss',
132
+ 'danger',
133
+ 'shadow',
134
+ 'shadow-dialog',
135
+ 'backdrop',
136
+ ] as const;
137
+
138
+ export type TokenName = (typeof TOKEN_NAMES)[number];
139
+
140
+ /** The components a theme can set, by name: each one's declaration. A package with
141
+ * components of its own adds them here by declaration merging. */
142
+ export interface ComponentDefs {
143
+ badge: typeof badgeDef;
144
+ 'bar-chart': typeof barChartDef;
145
+ button: typeof buttonDef;
146
+ 'callout-bubble': typeof calloutBubbleDef;
147
+ card: typeof cardDef;
148
+ checkbox: typeof checkboxDef;
149
+ collapsible: typeof collapsibleDef;
150
+ 'color-picker': typeof colorPickerDef;
151
+ 'data-table': typeof dataTableDef;
152
+ 'date-picker': typeof datePickerDef;
153
+ dialog: typeof dialogDef;
154
+ donut: typeof donutDef;
155
+ drawer: typeof drawerDef;
156
+ 'dropdown-menu': typeof dropdownMenuDef;
157
+ empty: typeof emptyDef;
158
+ field: typeof fieldDef;
159
+ figure: typeof figureDef;
160
+ 'glyph-select': typeof glyphSelectDef;
161
+ 'hover-card': typeof hoverCardDef;
162
+ 'input-group': typeof inputGroupDef;
163
+ input: typeof inputDef;
164
+ item: typeof itemDef;
165
+ kbd: typeof kbdDef;
166
+ 'line-chart': typeof lineChartDef;
167
+ 'month-grid': typeof monthGridDef;
168
+ 'number-input': typeof numberInputDef;
169
+ popover: typeof popoverDef;
170
+ 'scatter-chart': typeof scatterChartDef;
171
+ select: typeof selectDef;
172
+ slider: typeof sliderDef;
173
+ 'sort-button': typeof sortButtonDef;
174
+ sparkline: typeof sparklineDef;
175
+ switch: typeof switchDef;
176
+ tabs: typeof tabsDef;
177
+ 'text-area': typeof textAreaDef;
178
+ toast: typeof toastDef;
179
+ 'toggle-group': typeof toggleGroupDef;
180
+ tooltip: typeof tooltipDef;
181
+ treemap: typeof treemapDef;
182
+ }
183
+
184
+ type SettingsOf<D> = D extends ComponentDef<string, string, infer S> ? S : never;
185
+ type PartsOf<D> = D extends ComponentDef<string, infer P, string> ? P : never;
186
+
187
+ /** Settings by component, then by setting (`{ button: { radius: '2px' } }`), each written
188
+ * as `--vela-<component>-<setting>`. `css` restyles the component's parts completely: each
189
+ * part's CSS, written with the `css` tag, applies to that part under the theme, after every
190
+ * other layer of the kit. */
191
+ export type ComponentSettings = {
192
+ [K in keyof ComponentDefs]?: { [S in SettingsOf<ComponentDefs[K]>]?: string } & {
193
+ css?: { [P in PartsOf<ComponentDefs[K]>]?: string };
194
+ };
195
+ };
196
+
197
+ export interface CreateThemeOptions {
198
+ /** Apply part CSS that was not written with the `css` tag (a theme loaded from data).
199
+ * Off by default: CSS from someone else can restyle the page to mislead, and load
200
+ * remote images that leak what the page shows. */
201
+ allowCss?: boolean;
202
+ }
203
+
204
+ /** A theme's settings beyond the chart's colors. */
205
+ export interface ThemeSettings {
206
+ /** The brand color; its readable ink derives from it. */
207
+ accent?: string;
208
+ /** Scales every radius token: `none`, `sm`, `md` (default), `lg`. */
209
+ radius?: 'none' | 'sm' | 'md' | 'lg';
210
+ font?: string;
211
+ /** Any token, by name. */
212
+ tokens?: Partial<Record<TokenName, string>>;
213
+ components?: ComponentSettings;
214
+ }
215
+
216
+ /** The choices a theme is built from. Every field is optional: `createTheme()` is the dark theme. */
217
+ export interface ThemeInput extends ThemeSettings {
218
+ /** The theme to start from: `dark` (default), `light`, or a chart theme's seven fields. */
219
+ base?: 'dark' | 'light' | ChartTheme;
220
+ /** A theme from colors alone: everything else derives from them, light or dark read
221
+ * from the background. */
222
+ colors?: {
223
+ background?: string;
224
+ text?: string;
225
+ grid?: string;
226
+ border?: string;
227
+ up?: string;
228
+ down?: string;
229
+ accent?: string;
230
+ };
231
+ }
232
+
233
+ /** A theme built by {@link createTheme}. */
234
+ export interface UiTheme {
235
+ /** Derived from the values: equal themes share one rule. */
236
+ readonly id: string;
237
+ /** The chart's colors and font. */
238
+ readonly chart: ChartTheme;
239
+ /** Every token, by custom property (`--vela-accent`). */
240
+ readonly tokens: Readonly<Record<string, string>>;
241
+ /** Component settings, by component then setting. */
242
+ readonly components: Readonly<Record<string, Readonly<Record<string, string>>>>;
243
+ /** Part CSS, by component then part. */
244
+ readonly css: Readonly<Record<string, Readonly<Record<string, string>>>>;
245
+ /** Its settings beyond the chart's colors: with {@link chart}, they rebuild the theme. */
246
+ readonly settings: Readonly<ThemeSettings>;
247
+ }
248
+
249
+ /** A chart theme with optional settings: its seven fields seed the UI theme and `ui`
250
+ * adjusts it. Chrome that recolors its surface (an overlay following the plot's
251
+ * background) keeps the settings. */
252
+ export type ThemedChart = ChartTheme & { readonly ui?: ThemeSettings };
253
+
254
+ const RADIUS_SCALE = { none: 0, sm: 0.5, md: 1, lg: 1.5 } as const;
255
+
256
+ function chartOf(input: ThemeInput): ChartTheme {
257
+ const base = input.base === 'light' ? LIGHT_CHART : input.base === undefined || input.base === 'dark' ? DARK_CHART : input.base;
258
+ const colors = input.colors;
259
+ const font = input.font ?? base.fontFamily;
260
+ if (!colors) return { ...base, fontFamily: font };
261
+ const background = colors.background ?? base.background;
262
+ const textColor = colors.text ?? (colors.background ? (isDarkColor(background) ? DARK_CHART.textColor : LIGHT_CHART.textColor) : base.textColor);
263
+ const surfaceChanged = colors.background !== undefined || colors.text !== undefined;
264
+ return {
265
+ background,
266
+ textColor,
267
+ gridColor: colors.grid ?? (surfaceChanged ? mix(background, textColor, 0.08) : base.gridColor),
268
+ borderColor: colors.border ?? (surfaceChanged ? mix(background, textColor, 0.14) : base.borderColor),
269
+ upColor: colors.up ?? base.upColor,
270
+ downColor: colors.down ?? base.downColor,
271
+ fontFamily: font,
272
+ };
273
+ }
274
+
275
+ /** A short stable id for a theme's values. */
276
+ function themeId(values: string): string {
277
+ let h = 5381;
278
+ for (let i = 0; i < values.length; i += 1) h = ((h << 5) + h + values.charCodeAt(i)) | 0;
279
+ return (h >>> 0).toString(36);
280
+ }
281
+
282
+ /** The ink that reads best on a fill. */
283
+ function inkOn(fill: string): string {
284
+ return (contrastRatio(fill, '#ffffff') ?? 21) >= (contrastRatio(fill, '#000000') ?? 0) ? '#ffffff' : '#000000';
285
+ }
286
+
287
+ function build(input: ThemeInput, options: CreateThemeOptions): { theme: UiTheme; dropped: string[] } {
288
+ const chart = chartOf(input);
289
+ const tokens: Record<string, string> = { ...STATIC_TOKENS, ...themeTokens(chart) };
290
+ if (input.radius) {
291
+ const f = RADIUS_SCALE[input.radius];
292
+ for (const name of ['radius-sm', 'radius-md', 'radius-lg']) tokens[`--vela-${name}`] = `${Math.round(parseFloat(STATIC_TOKENS[`--vela-${name}`]!) * f)}px`;
293
+ }
294
+ const accent = input.accent ?? input.colors?.accent;
295
+ if (accent) {
296
+ tokens['--vela-accent'] = accent;
297
+ tokens['--vela-accent-bright'] = accent;
298
+ tokens['--vela-fg-on-fill'] = inkOn(accent);
299
+ }
300
+ for (const [name, value] of Object.entries(input.tokens ?? {})) if (value !== undefined) tokens[`--vela-${name}`] = value;
301
+ const components: Record<string, Record<string, string>> = {};
302
+ const partCss: Record<string, Record<string, string>> = {};
303
+ const dropped: string[] = [];
304
+ const entries = Object.entries(input.components ?? {}) as Array<[string, Record<string, unknown>]>;
305
+ for (const [name, values] of entries) {
306
+ const set: Record<string, string> = {};
307
+ for (const [key, value] of Object.entries(values)) if (key !== 'css' && typeof value === 'string') set[key] = value;
308
+ if (Object.keys(set).length) components[name] = set;
309
+ const parts: Record<string, string> = {};
310
+ for (const [part, text] of Object.entries((values.css ?? {}) as Record<string, unknown>)) {
311
+ if (typeof text !== 'string') continue;
312
+ if (options.allowCss) acceptCss(text);
313
+ if (isWrittenCss(text)) parts[part] = text;
314
+ else dropped.push(`components.${name}.css.${part}`);
315
+ }
316
+ if (Object.keys(parts).length) partCss[name] = parts;
317
+ }
318
+ const settings: ThemeSettings = {};
319
+ if (accent) settings.accent = accent;
320
+ if (input.radius) settings.radius = input.radius;
321
+ if (input.font) settings.font = input.font;
322
+ if (input.tokens) settings.tokens = { ...input.tokens };
323
+ const both = new Set([...Object.keys(components), ...Object.keys(partCss)]);
324
+ if (both.size) {
325
+ const merged: Record<string, Record<string, unknown>> = {};
326
+ for (const name of both) merged[name] = { ...components[name], ...(partCss[name] ? { css: { ...partCss[name] } } : {}) };
327
+ settings.components = merged as ComponentSettings;
328
+ }
329
+ const theme = { id: themeId(JSON.stringify([tokens, components, partCss])), chart, tokens, components, css: partCss, settings };
330
+ return { theme, dropped };
331
+ }
332
+
333
+ const isCssVar = (value: string) => value.trim().startsWith('var(');
334
+
335
+ /** A component's parts and settings: as declared on the page, else as the kit declares them
336
+ * (a kit component a page never imported is declared nowhere yet). */
337
+ function componentNamed(name: string): DeclaredComponent | undefined {
338
+ return declaredComponents().get(name) ?? (Object.prototype.hasOwnProperty.call(KIT_COMPONENTS, name) ? KIT_COMPONENTS[name] : undefined);
339
+ }
340
+
341
+ function componentProblems(input: ThemeInput): string[] {
342
+ const problems: string[] = [];
343
+ for (const [name, values] of Object.entries(input.components ?? {}) as Array<[string, Record<string, unknown> | undefined]>) {
344
+ const def = componentNamed(name);
345
+ if (!def) {
346
+ problems.push(`components.${name}: no component has that name (declare a component of your own with defineComponent before creating the theme)`);
347
+ continue;
348
+ }
349
+ for (const key of Object.keys(values ?? {})) {
350
+ if (key === 'css' || def.settings.includes(key)) continue;
351
+ problems.push(`components.${name}.${key} is not a setting of ${name} (${def.settings.length ? `its settings: ${def.settings.join(', ')}` : 'it has none'})`);
352
+ }
353
+ for (const part of Object.keys((values?.css ?? {}) as Record<string, unknown>)) {
354
+ if (!def.parts.includes(part)) problems.push(`components.${name}.css.${part} is not a part of ${name} (its parts: ${def.parts.join(', ')})`);
355
+ }
356
+ }
357
+ return problems;
358
+ }
359
+
360
+ function problemsOf(input: ThemeInput, theme: UiTheme): string[] {
361
+ const problems: string[] = [];
362
+ const known = new Set<string>(TOKEN_NAMES);
363
+ for (const name of Object.keys(input.tokens ?? {})) if (!known.has(name)) problems.push(`"${name}" is not a token`);
364
+ problems.push(...componentProblems(input));
365
+ const colors: Array<[string, string | undefined]> = [['accent', input.accent]];
366
+ for (const [k, v] of Object.entries(input.colors ?? {})) colors.push([`colors.${k}`, v]);
367
+ if (typeof input.base === 'object') for (const k of CHART_FIELDS) if (k !== 'fontFamily') colors.push([`base.${k}`, input.base[k]]);
368
+ for (const [where, value] of colors) {
369
+ if (value !== undefined && !isCssVar(value) && !parseRgb(value)) problems.push(`${where} "${value}" is not a color the theme can derive from (use #rrggbb or rgb())`);
370
+ }
371
+ const pairs: Array<[string, string, number]> = [
372
+ ['fg', 'bg', 4.5],
373
+ ['fg-on-fill', 'accent', 3],
374
+ ];
375
+ for (const [ink, fill, min] of pairs) {
376
+ const ratio = contrastRatio(theme.tokens[`--vela-${ink}`] ?? '', theme.tokens[`--vela-${fill}`] ?? '');
377
+ if (ratio !== null && ratio < min) problems.push(`${ink} on ${fill} has a contrast of ${ratio.toFixed(1)}:1 (at least ${min}:1 reads well)`);
378
+ }
379
+ for (const [name, parts] of Object.entries(theme.css)) {
380
+ for (const [part, text] of Object.entries(parts)) {
381
+ const where = `components.${name}.css.${part}`;
382
+ if (/!important/i.test(text)) problems.push(`${where} uses !important, which the custom layer does not need`);
383
+ if (/(^|[\s,>+~(&])\.[a-z_-][\w-]*[^{};]*\{/im.test(text)) problems.push(`${where} targets a class name, which is not part of the component's contract (use its parts and data attributes)`);
384
+ for (const at of text.match(/@[a-z-]+/gi) ?? []) {
385
+ if (!CONDITIONAL.test(at)) problems.push(`${where} declares ${at}, which is left out (declare it in the page's stylesheet and use it from the part)`);
386
+ }
387
+ }
388
+ }
389
+ return problems;
390
+ }
391
+
392
+ const droppedProblem = (where: string) => `${where} was not written with the css tag and is left out (pass { allowCss: true } to apply CSS loaded from data)`;
393
+
394
+ /** What is wrong with a theme's input: unknown tokens, components, settings and parts, colors
395
+ * the theme cannot derive from, text with too little contrast on its background, and part
396
+ * CSS that is left out or reaches past the component's contract. `createTheme` warns about
397
+ * each. */
398
+ export function checkTheme(input: ThemeInput = {}, options: CreateThemeOptions = {}): string[] {
399
+ const { theme, dropped } = build(input, options);
400
+ return [...dropped.map(droppedProblem), ...problemsOf(input, theme)];
401
+ }
402
+
403
+ const warned = new Set<string>();
404
+
405
+ function warn(problems: readonly string[]): void {
406
+ for (const problem of problems) {
407
+ if (warned.has(problem)) continue;
408
+ warned.add(problem);
409
+ console.warn(`[vela-ui] theme: ${problem}`);
410
+ }
411
+ }
412
+
413
+ /** Build a theme. Without overrides, `dark` and `light` give exactly the built-in tokens. */
414
+ export function createTheme(input: ThemeInput = {}, options: CreateThemeOptions = {}): UiTheme {
415
+ const { theme, dropped } = build(input, options);
416
+ warn([...dropped.map(droppedProblem), ...problemsOf(input, theme)]);
417
+ return theme;
418
+ }
419
+
420
+ const isUiTheme = (theme: UiTheme | ThemedChart): theme is UiTheme => 'tokens' in theme && 'id' in theme;
421
+
422
+ const CHART_FIELDS = ['background', 'textColor', 'gridColor', 'borderColor', 'upColor', 'downColor', 'fontFamily'] as const;
423
+
424
+ const chartKey = (chart: ChartTheme) => CHART_FIELDS.map((k) => chart[k]).join('|');
425
+
426
+ /** The document or shadow root a host renders in (its document while it is detached). */
427
+ function rootOf(host: HTMLElement): Document | ShadowRoot {
428
+ const root = host.getRootNode();
429
+ if (root instanceof Document) return root;
430
+ if (typeof ShadowRoot !== 'undefined' && root instanceof ShadowRoot) return root;
431
+ return host.ownerDocument;
432
+ }
433
+
434
+ /** Splits CSS at its top level into declarations and blocks (`prelude { body }`), skipping
435
+ * comments and strings. */
436
+ function topLevel(text: string): { decls: string; blocks: Array<[string, string]> } {
437
+ const src = text.replace(/\/\*[\s\S]*?\*\//g, '');
438
+ let decls = '';
439
+ const blocks: Array<[string, string]> = [];
440
+ let buf = '';
441
+ let i = 0;
442
+ while (i < src.length) {
443
+ const c = src[i]!;
444
+ if (c === '"' || c === "'") {
445
+ const end = src.indexOf(c, i + 1);
446
+ const stop = end < 0 ? src.length : end + 1;
447
+ buf += src.slice(i, stop);
448
+ i = stop;
449
+ continue;
450
+ }
451
+ if (c === ';') {
452
+ decls += `${buf.trim()}; `;
453
+ buf = '';
454
+ } else if (c === '{') {
455
+ let depth = 1;
456
+ let j = i + 1;
457
+ while (j < src.length && depth > 0) {
458
+ if (src[j] === '{') depth += 1;
459
+ else if (src[j] === '}') depth -= 1;
460
+ j += 1;
461
+ }
462
+ blocks.push([buf.trim(), src.slice(i + 1, j - 1).trim()]);
463
+ buf = '';
464
+ i = j;
465
+ continue;
466
+ } else {
467
+ buf += c;
468
+ }
469
+ i += 1;
470
+ }
471
+ if (buf.trim()) decls += `${buf.trim()}; `;
472
+ return { decls: decls.trim(), blocks };
473
+ }
474
+
475
+ /** Splits a selector list at its top-level commas. */
476
+ function selectorList(prelude: string): string[] {
477
+ const out: string[] = [];
478
+ let depth = 0;
479
+ let start = 0;
480
+ for (let i = 0; i < prelude.length; i += 1) {
481
+ const c = prelude[i];
482
+ if (c === '(' || c === '[') depth += 1;
483
+ else if (c === ')' || c === ']') depth -= 1;
484
+ else if (c === ',' && depth === 0) {
485
+ out.push(prelude.slice(start, i).trim());
486
+ start = i + 1;
487
+ }
488
+ }
489
+ out.push(prelude.slice(start).trim());
490
+ return out.filter(Boolean);
491
+ }
492
+
493
+ /** The at-rules a part's CSS can hold: conditions around its rules. Others (`@keyframes`,
494
+ * `@font-face`) declare something page-wide and belong in the host's stylesheet. */
495
+ const CONDITIONAL = /^@(media|supports|container)\b/i;
496
+
497
+ /** A part's CSS as flat rules on `scope`: its own declarations, its `&` rules (one level of
498
+ * nesting, which is all a part needs; a rule without `&` is a descendant), and `@media`,
499
+ * `@supports` or `@container` blocks around either. Theme CSS reaches the page without our
500
+ * build, and the oldest browsers we support do not nest. */
501
+ function flatPart(scope: string, text: string): string {
502
+ const { decls, blocks } = topLevel(text);
503
+ const rules: string[] = decls ? [`${scope} { ${decls} }`] : [];
504
+ for (const [prelude, body] of blocks) {
505
+ if (prelude.startsWith('@')) {
506
+ if (CONDITIONAL.test(prelude)) rules.push(`${prelude} { ${flatPart(scope, body)} }`);
507
+ continue;
508
+ }
509
+ const list = selectorList(prelude).map((s) => (s.includes('&') ? s.split('&').join(scope) : `${scope} ${s}`));
510
+ const inner = topLevel(body);
511
+ if (inner.decls) rules.push(`${list.join(', ')} { ${inner.decls} }`);
512
+ }
513
+ return rules.join(' ');
514
+ }
515
+
516
+ /** The theme's rules: every token and component setting, by default on the hosts that carry
517
+ * its id; and the part CSS, on those parts inside them, in the last layer. */
518
+ export function themeCss(theme: UiTheme, selector = `[data-vela-theme="${theme.id}"]`): string {
519
+ const decls = Object.entries(theme.tokens).map(([k, v]) => `${k}: ${v};`);
520
+ for (const [component, settings] of Object.entries(theme.components)) {
521
+ for (const [setting, value] of Object.entries(settings)) decls.push(`--vela-${component}-${setting}: ${value};`);
522
+ }
523
+ const out = [`@layer vela.theme { ${selector} { ${decls.join(' ')} } }`];
524
+ const parts: string[] = [];
525
+ for (const [component, byPart] of Object.entries(theme.css)) {
526
+ for (const [part, text] of Object.entries(byPart)) {
527
+ const slot = part === 'root' ? component : `${component}-${part}`;
528
+ // A part's `display` must not beat the browser's own `[hidden]` rule.
529
+ parts.push(flatPart(`:where(${selector}, ${selector} *):is([data-slot~="${slot}"]):where(:not([hidden]))`, text));
530
+ }
531
+ }
532
+ if (parts.length) out.push(`@layer vela.custom { ${parts.join(' ')} }`);
533
+ return out.join('\n');
534
+ }
535
+
536
+ const MAX_CACHED = 32;
537
+ const fromChart = new Map<string, UiTheme>();
538
+
539
+ /** The UI theme for a chart theme: its seven fields with the settings it carries. */
540
+ function themeOfChart(chart: ThemedChart): UiTheme {
541
+ const plain: ChartTheme = { background: chart.background, textColor: chart.textColor, gridColor: chart.gridColor, borderColor: chart.borderColor, upColor: chart.upColor, downColor: chart.downColor, fontFamily: chart.fontFamily };
542
+ const key = chart.ui ? `${chartKey(plain)}|${JSON.stringify(chart.ui)}` : chartKey(plain);
543
+ let ui = fromChart.get(key);
544
+ if (!ui) {
545
+ if (fromChart.size >= MAX_CACHED) fromChart.clear();
546
+ ui = createTheme({ ...chart.ui, base: plain });
547
+ fromChart.set(key, ui);
548
+ }
549
+ return ui;
550
+ }
551
+
552
+ const sheets = new WeakMap<Document | ShadowRoot, Map<string, HTMLStyleElement>>();
553
+
554
+ /** Writes the theme's rule into the root once. Live recoloring (a plot background dragged
555
+ * through a color picker) makes a theme per step, so past {@link MAX_CACHED} rules, the
556
+ * ones no element carries any more are dropped. */
557
+ function installTheme(ui: UiTheme, root: Document | ShadowRoot): void {
558
+ let byId = sheets.get(root);
559
+ if (!byId) sheets.set(root, (byId = new Map()));
560
+ const id = `vela-theme-${ui.id}`;
561
+ if (byId.get(id)?.isConnected) return;
562
+ const sheet = injectStyles(id, themeCss(ui), root);
563
+ if (sheet) byId.set(id, sheet);
564
+ if (byId.size <= MAX_CACHED) return;
565
+ for (const [other, el] of byId) {
566
+ if (other === id || root.querySelector(`[data-vela-theme="${other.slice('vela-theme-'.length)}"]`)) continue;
567
+ el.remove();
568
+ byId.delete(other);
569
+ }
570
+ }
571
+
572
+ /** Theme a host and everything inside it. A chart theme's seven fields build the theme on
573
+ * the way, keeping the choices of the UI theme it carries. */
574
+ export function applyTheme(host: HTMLElement, theme: UiTheme | ThemedChart): UiTheme {
575
+ const ui = isUiTheme(theme) ? theme : themeOfChart(theme);
576
+ const root = rootOf(host);
577
+ injectLayerOrder(root);
578
+ if (typeof document !== 'undefined') installTheme(ui, root);
579
+ host.setAttribute('data-vela-theme', ui.id);
580
+ // Tokens an older writer left inline would hide the theme's rule.
581
+ for (const name in ui.tokens) host.style.removeProperty(name);
582
+ return ui;
583
+ }
584
+
585
+ const STATIC_ID = 'vela-ui-tokens';
586
+
587
+ const STATIC_DECLS = Object.entries(STATIC_TOKENS)
588
+ .map(([k, v]) => ` ${k}: ${v};`)
589
+ .join('\n');
590
+
591
+ const STATIC_CSS = `
592
+ /* Theme-independent tokens on every kit host, at no specificity in the theme layer: a theme's
593
+ own rule (radius scaling) and a host's CSS both override them. */
594
+ @layer vela.theme {
595
+ :where(.vela-ui, .vela-ui-layer) {
596
+ ${STATIC_DECLS}
597
+ }
598
+ /* One scrollbar on every kit surface: thin, a rounded thumb, no track and no arrows, sized and
599
+ colored by the scroll tokens. Chromium and Safari draw it from the ::-webkit-scrollbar parts,
600
+ and setting scrollbar-width or scrollbar-color on an element switches them back to the native
601
+ bar, so those two are for the browsers without the parts. */
602
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar { width: var(--vela-scroll-size); height: var(--vela-scroll-size); }
603
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-track { background: transparent; }
604
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-corner { background: transparent; }
605
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-thumb { background: var(--vela-scroll); border-radius: var(--vela-scroll-size); }
606
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *)::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
607
+ @supports not selector(::-webkit-scrollbar) {
608
+ :where(.vela-ui, .vela-ui-layer, .vela-ui *, .vela-ui-layer *) { scrollbar-width: thin; scrollbar-color: var(--vela-scroll) transparent; }
609
+ }
610
+ /* A search field's clear cross in the theme's ink: Chromium and Safari otherwise draw their own,
611
+ blue on some systems. */
612
+ :where(.vela-ui, .vela-ui-layer) :where(input[type='search'])::-webkit-search-cancel-button {
613
+ -webkit-appearance: none;
614
+ appearance: none;
615
+ flex: none;
616
+ width: 12px;
617
+ height: 12px;
618
+ margin-inline-start: 4px;
619
+ cursor: pointer;
620
+ background-color: var(--vela-fg-bright);
621
+ -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 2.5l7 7m0-7l-7 7' stroke='%23000' stroke-width='1.6' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
622
+ mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 2.5l7 7m0-7l-7 7' stroke='%23000' stroke-width='1.6' stroke-linecap='round'/%3E%3C/svg%3E") center / contain no-repeat;
623
+ }
624
+ }
625
+ .vela-ui, .vela-ui-layer {
626
+ font-family: var(--vela-font, -apple-system, system-ui, sans-serif);
627
+ box-sizing: border-box;
628
+ /* Chrome text (titles, buttons, menus, readouts) is UI, not copy — never selectable. */
629
+ user-select: none;
630
+ -webkit-user-select: none;
631
+ }
632
+ /* Unlayered, as the chrome's own controls rely on it; a kit component never declares a
633
+ box-sizing of its own, which this reset would override. */
634
+ .vela-ui *, .vela-ui-layer * { box-sizing: border-box; }
635
+ /* Text ENTRY is the one exception: selection is part of editing. */
636
+ .vela-ui :is(input, textarea), .vela-ui-layer :is(input, textarea) { user-select: text; -webkit-user-select: text; }
637
+ /* iOS Safari zooms the page when a focused field is under 16px, and often
638
+ keeps that zoom after the field blurs or a dialog closes. The shell's
639
+ mobile size class is the honest gate — not a media query — so an embedded
640
+ chart on a wide desktop still gets the rule when it is in the phone layout.
641
+ Scoped to the kit root so a host page's own [data-layout] is never touched. */
642
+ .vela-ui[data-layout='mobile'] :is(input, textarea, select) { font-size: 16px; }
643
+ @layer vela.ui {
644
+ .vela-icon { display: inline-flex; align-items: center; flex: none; }
645
+ .vela-icon svg { display: block; }
646
+ }
647
+ `;
648
+
649
+ /** Theme a host from a chart theme's seven fields.
650
+ * @deprecated Use {@link applyTheme}, which also takes a theme from {@link createTheme}. */
651
+ export function applyThemeTokens(el: HTMLElement, t: ThemedChart): void {
652
+ applyTheme(el, t);
653
+ }
654
+
655
+ /** Re-token a chart-overlay host (statusline, watermark, toast — chrome floating OVER
656
+ * the plot) from the LIVE plot surface: a config edit can recolor the plot background
657
+ * independently of the app theme (a white plot typed into settings on the dark theme),
658
+ * and the overlay ink must stay readable either way. `config` is the renderer's
659
+ * `getConfig()` snapshot; a missing/shapeless one falls back to the base app theme.
660
+ * Floating menus and dropdowns do NOT use this — they mount on {@link floatingLayerHost}
661
+ * so their surface follows the app theme alone. */
662
+ export function applyPlotOverlayTokens(host: HTMLElement, base: ThemedChart, config: unknown): void {
663
+ const layout = (config as { layout?: { background?: string; textColor?: string } } | null)?.layout;
664
+ const t = layout?.background && layout.textColor ? { ...base, background: layout.background, textColor: layout.textColor } : base;
665
+ applyTheme(host, t);
666
+ }
667
+
668
+ /** Mount floating kit layers (menus, select lists) on the nearest `.vela-ui` so they
669
+ * inherit the app-theme tokens. A plot-overlay host (the cell) retokens from
670
+ * `layout.background`; chrome panels must not follow that. Falls back to `fallback`
671
+ * (typically `document.body`) when no kit host is an ancestor. */
672
+ export function floatingLayerHost(from: HTMLElement, fallback?: HTMLElement): HTMLElement {
673
+ return (from.closest('.vela-ui') as HTMLElement | null) ?? fallback ?? from;
674
+ }
675
+
676
+ /** Mark an element as a kit host (the `.vela-ui` class and the shared sheet), themed when
677
+ * a theme is given. */
678
+ export function ensureUIHost(el: HTMLElement, theme?: UiTheme | ThemedChart): void {
679
+ const root = rootOf(el);
680
+ injectLayerOrder(root);
681
+ injectStyles(STATIC_ID, STATIC_CSS, root);
682
+ el.classList.add('vela-ui');
683
+ if (theme) applyTheme(el, theme);
684
+ }