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