@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
@@ -1,847 +1,847 @@
1
- // Treemap: weighted items laid into a rectangle as tiles close to square, each tinted by its
2
- // value on a diverging scale (up above zero, down below, stronger as the value grows) and
3
- // labeled when it has room. Items with children are groups: their tiles share a block headed
4
- // by the group's name and a figure of its values. With `drill`, a group's header zooms into it
5
- // and a breadcrumb leads back. Values repaint without a new layout, and a tile keeps its
6
- // element across layouts, so a resize or a zoom moves it instead of redrawing it.
7
- import { showTip } from '@luxalgo/vela-ui/chart';
8
- import { css, defineStyles } from '@luxalgo/vela-ui';
9
- import { defineComponent } from '@luxalgo/vela-ui';
10
- import { h } from '@luxalgo/vela-ui';
11
- import { msg, textOf, type Translator } from '@luxalgo/vela-ui/i18n';
12
- import { kitTranslator } from '@luxalgo/vela-ui/kit-text';
13
- import { t } from '@luxalgo/vela-ui';
14
-
15
- export const treemapDef = defineComponent({
16
- name: 'treemap',
17
- parts: ['root', 'crumbs', 'crumb', 'map', 'group', 'group-name', 'group-value', 'tile', 'tile-label', 'tile-value', 'legend', 'legend-bar', 'tip'],
18
- settings: {
19
- radius: t.radius.sm,
20
- up: t.up,
21
- down: t.down,
22
- 'tile-bg': `color-mix(in srgb, ${t.fg.bright} 2.5%, ${t.surface})`,
23
- 'tint-min': '3%',
24
- 'tint-max': '25%',
25
- 'hover-z': '1',
26
- 'tip-radius': t.radius.md,
27
- 'tip-bg': t.surface.elev,
28
- 'tip-shadow': t.shadow,
29
- 'tip-z': '2',
30
- },
31
- });
32
-
33
- export interface TreemapItem {
34
- /** Stable across updates: a tile keeps its element by id. */
35
- id: string;
36
- label: string;
37
- /** The tile's share of the area (default 1, equal tiles); zero or less leaves it out. A
38
- * group's share is the sum of its items'. */
39
- weight?: number;
40
- /** What the tile is tinted by and shows; null while it is unknown. */
41
- value?: number | null;
42
- /** The tile's ink instead of its value's tone: a token's `var()` (`t.accent.var`) or a color. */
43
- color?: string;
44
- /** The group's items: the item becomes a group. */
45
- children?: readonly TreemapItem[];
46
- }
47
-
48
- /** How a group's header sums up its items' values, or a function of them. */
49
- export type TreemapGroupValue = 'median' | 'mean' | 'sum' | 'none' | ((values: readonly number[], group: TreemapItem) => number | null);
50
-
51
- export interface TreemapProps {
52
- items?: readonly TreemapItem[];
53
- /** The size of a value whose tint is full. Default: the largest one on the map. */
54
- domain?: number;
55
- /** A value as the tiles, the headers, the readout and the legend write it. Default: signed,
56
- * two decimals. */
57
- format?: (value: number) => string;
58
- /** A group header's figure (default the median of its items' values). */
59
- groupValue?: TreemapGroupValue;
60
- /** The readout beside a hovered or focused tile, or `false` for none. Default: its label,
61
- * value and groups. */
62
- tip?: ((item: TreemapItem, path: readonly TreemapItem[]) => string | Node) | false;
63
- /** A tile's click, Enter or Space. `path` lists its groups, outermost first. */
64
- onSelect?: (item: TreemapItem, path: readonly TreemapItem[]) => void;
65
- /** The id of the tile drawn as selected. */
66
- selected?: string | null;
67
- /** Group headers zoom into their group, and a breadcrumb above the map leads back. */
68
- drill?: boolean;
69
- /** A zoom changed: `path` is the zoomed group's path (empty at the top). */
70
- onDrill?: (path: readonly TreemapItem[]) => void;
71
- /** The breadcrumb's first entry (default "All"). */
72
- rootLabel?: string;
73
- /** A scale under the map, from the negative to the positive domain. */
74
- legend?: boolean;
75
- /** Space between tiles, in pixels (default 3). */
76
- gap?: number;
77
- /** The map's accessible name. */
78
- label?: string;
79
- /** The translator of the treemap's own words. Default: the kit build's, else English. */
80
- i18n?: Translator | null;
81
- /** Extra class names (layout hooks). */
82
- className?: string;
83
- }
84
-
85
- export interface TreemapHandle {
86
- readonly el: HTMLElement;
87
- /** New items: lays the map out again. A zoom stays on its group while the group exists. */
88
- setData(items: readonly TreemapItem[]): void;
89
- /** New values by id: repaints the tints, figures and readout without a new layout. */
90
- setValues(values: ReadonlyMap<string, number | null> | Readonly<Record<string, number | null>>): void;
91
- setSelected(id: string | null): void;
92
- /** Zoom into a group by id, or back to the top with null. */
93
- drillTo(id: string | null): void;
94
- destroy(): void;
95
- }
96
-
97
- export interface TreemapRect {
98
- x: number;
99
- y: number;
100
- w: number;
101
- h: number;
102
- }
103
-
104
- /** Lay weighted items into `bounds` as tiles close to square (the squarified layout): areas
105
- * follow the weights and fill the bounds exactly, heaviest first. Items weighing nothing are
106
- * left out. */
107
- export function squarify<T extends { weight: number }>(items: readonly T[], bounds: TreemapRect): Array<T & TreemapRect> {
108
- const total = items.reduce((s, item) => s + Math.max(0, item.weight), 0);
109
- if (!total || bounds.w <= 0 || bounds.h <= 0) return [];
110
- const scale = (bounds.w * bounds.h) / total;
111
- let queue = items
112
- .filter((item) => item.weight > 0)
113
- .map((item) => ({ item, area: item.weight * scale }))
114
- .sort((a, b) => b.area - a.area);
115
- let { x, y, w, h } = bounds;
116
- const out: Array<T & TreemapRect> = [];
117
- const worst = (row: ReadonlyArray<{ area: number }>, side: number): number => {
118
- const sum = row.reduce((s, r) => s + r.area, 0);
119
- const max = Math.max(...row.map((r) => r.area));
120
- const min = Math.min(...row.map((r) => r.area));
121
- return Math.max((side * side * max) / (sum * sum), (sum * sum) / (side * side * min));
122
- };
123
- while (queue.length) {
124
- const side = Math.min(w, h);
125
- const row = [queue[0]!];
126
- let i = 1;
127
- while (i < queue.length && worst([...row, queue[i]!], side) <= worst(row, side)) row.push(queue[i++]!);
128
- queue = queue.slice(i);
129
- const sum = row.reduce((s, r) => s + r.area, 0);
130
- if (w >= h) {
131
- const cw = sum / h;
132
- let cy = y;
133
- for (const r of row) {
134
- const ch = r.area / cw;
135
- out.push({ ...r.item, x, y: cy, w: cw, h: ch });
136
- cy += ch;
137
- }
138
- x += cw;
139
- w -= cw;
140
- } else {
141
- const rh = sum / w;
142
- let cx = x;
143
- for (const r of row) {
144
- const rw = r.area / rh;
145
- out.push({ ...r.item, x: cx, y, w: rw, h: rh });
146
- cx += rw;
147
- }
148
- y += rh;
149
- h -= rh;
150
- }
151
- }
152
- return out;
153
- }
154
-
155
- const TEXT = {
156
- all: msg('ui.treemap.all', 'All'),
157
- zoomIn: msg('ui.treemap.zoomIn', 'Zoom in'),
158
- };
159
-
160
- /** A group's header row, and the smallest block that gets one. */
161
- const HEADER = 16;
162
- const HEADED = { w: 80, h: 64 };
163
-
164
- const injectStyles = defineStyles(
165
- 'vela-ui-treemap',
166
- css`
167
- @layer vela.ui {
168
- [data-slot='treemap'] {
169
- position: relative;
170
- width: 100%;
171
- height: 100%;
172
- min-height: 0;
173
- color: ${t.fg};
174
- font-size: ${t.fontSize.sm};
175
-
176
- &:where(:not([hidden])) {
177
- display: flex;
178
- flex-direction: column;
179
- gap: 8px;
180
- }
181
- }
182
- [data-slot='treemap-crumbs'] {
183
- display: flex;
184
- flex-wrap: wrap;
185
- align-items: center;
186
- gap: 2px;
187
- min-height: 22px;
188
- font-size: 12px;
189
- color: ${t.fg.muted};
190
- }
191
- [data-slot='treemap-crumb'] {
192
- all: unset;
193
- padding: 2px 6px;
194
- border-radius: ${treemapDef.vars.radius};
195
- cursor: pointer;
196
-
197
- &:hover {
198
- background: ${t.hover};
199
- color: ${t.fg.bright};
200
- }
201
- &:focus-visible {
202
- outline: 2px solid ${t.focus};
203
- }
204
- &[aria-current] {
205
- cursor: default;
206
- color: ${t.fg.bright};
207
- font-weight: 600;
208
- background: none;
209
- }
210
- &:not(:first-child)::before {
211
- content: '›';
212
- margin-inline-end: 8px;
213
- color: ${t.fg.faint};
214
- }
215
- }
216
- [data-slot='treemap-map'] {
217
- position: relative;
218
- flex: 1 1 auto;
219
- min-height: 0;
220
- isolation: isolate;
221
- }
222
- [data-slot='treemap-group'] {
223
- all: unset;
224
- position: absolute;
225
- display: flex;
226
- align-items: center;
227
- gap: 6px;
228
- height: 16px;
229
- padding-inline: 2px;
230
- overflow: hidden;
231
- font-size: 9px;
232
- font-weight: 500;
233
- letter-spacing: 0.06em;
234
- text-transform: uppercase;
235
- white-space: nowrap;
236
- color: ${t.fg.muted};
237
- transition:
238
- left ${t.dur.med} ${t.ease},
239
- top ${t.dur.med} ${t.ease},
240
- width ${t.dur.med} ${t.ease};
241
-
242
- &[data-drill] {
243
- border-radius: ${treemapDef.vars.radius};
244
- cursor: zoom-in;
245
- }
246
- &[data-drill]:hover {
247
- color: ${t.fg.bright};
248
- background: ${t.hover};
249
- }
250
- &:focus-visible {
251
- outline: 2px solid ${t.focus};
252
- }
253
- }
254
- [data-slot='treemap-group-name'] {
255
- overflow: hidden;
256
- text-overflow: ellipsis;
257
- }
258
- [data-slot='treemap-group-value'] {
259
- margin-inline-start: auto;
260
- font-variant-numeric: tabular-nums;
261
-
262
- &[data-tone='up'] {
263
- color: ${treemapDef.vars.up};
264
- }
265
- &[data-tone='down'] {
266
- color: ${treemapDef.vars.down};
267
- }
268
- }
269
- [data-slot='treemap-tile'] {
270
- all: unset;
271
- --_tone: ${t.fg.muted};
272
- --_tint: calc(${treemapDef.vars['tint-min']} + (${treemapDef.vars['tint-max']} - ${treemapDef.vars['tint-min']}) * var(--_level, 0));
273
-
274
- position: absolute;
275
- display: flex;
276
- flex-direction: column;
277
- align-items: center;
278
- justify-content: center;
279
- gap: 1px;
280
- overflow: hidden;
281
- border: 1px solid color-mix(in srgb, var(--_tone) calc(var(--_tint) * 0.8), ${t.border});
282
- border-radius: ${treemapDef.vars.radius};
283
- background: color-mix(in srgb, var(--_tone) var(--_tint), ${treemapDef.vars['tile-bg']});
284
- text-align: center;
285
- cursor: pointer;
286
- transition:
287
- left ${t.dur.med} ${t.ease},
288
- top ${t.dur.med} ${t.ease},
289
- width ${t.dur.med} ${t.ease},
290
- height ${t.dur.med} ${t.ease},
291
- background-color ${t.dur.med} linear,
292
- scale ${t.dur.fast} ${t.ease};
293
-
294
- &[data-tone='up'] {
295
- --_tone: ${treemapDef.vars.up};
296
- }
297
- &[data-tone='down'] {
298
- --_tone: ${treemapDef.vars.down};
299
- }
300
- &[data-tone='custom'] {
301
- --_tone: var(--_color);
302
- }
303
- &[data-tone='none'] {
304
- --_tint: 0%;
305
- }
306
- &:hover {
307
- z-index: ${treemapDef.vars['hover-z']};
308
- scale: 1.04;
309
- border-color: ${t.fg.bright};
310
- }
311
- &:focus-visible {
312
- z-index: ${treemapDef.vars['hover-z']};
313
- outline: 2px solid ${t.focus};
314
- }
315
- &[data-selected] {
316
- border-color: ${t.fg.bright};
317
- outline: 1px solid ${t.fg.bright};
318
- }
319
- }
320
- [data-slot='treemap-tile-label'] {
321
- max-width: 100%;
322
- overflow: hidden;
323
- text-overflow: ellipsis;
324
- font-weight: 600;
325
- line-height: 1.1;
326
- white-space: nowrap;
327
- color: ${t.fg.bright};
328
- }
329
- [data-slot='treemap-tile-value'] {
330
- white-space: nowrap;
331
- font-variant-numeric: tabular-nums;
332
- color: ${t.fg.bright};
333
- opacity: 0.92;
334
- }
335
- [data-slot='treemap-legend'] {
336
- display: grid;
337
- grid-template-columns: auto 1fr auto;
338
- align-items: center;
339
- gap: 8px;
340
- font-size: 10px;
341
- font-variant-numeric: tabular-nums;
342
- color: ${t.fg.muted};
343
- }
344
- [data-slot='treemap-legend-bar'] {
345
- height: 6px;
346
- border: 1px solid ${t.border};
347
- border-radius: 999px;
348
- background: linear-gradient(
349
- to right,
350
- color-mix(in srgb, ${treemapDef.vars.down} 70%, ${treemapDef.vars['tile-bg']}),
351
- ${treemapDef.vars['tile-bg']},
352
- color-mix(in srgb, ${treemapDef.vars.up} 70%, ${treemapDef.vars['tile-bg']})
353
- );
354
- }
355
- [data-slot='treemap-tip'] {
356
- position: absolute;
357
- z-index: ${treemapDef.vars['tip-z']};
358
- top: 0;
359
- gap: 2px;
360
- pointer-events: none;
361
- padding: 8px;
362
- border: 1px solid ${t.border};
363
- border-radius: ${treemapDef.vars['tip-radius']};
364
- background: ${treemapDef.vars['tip-bg']};
365
- box-shadow: ${treemapDef.vars['tip-shadow']};
366
- color: ${t.fg.bright};
367
- font-size: 12px;
368
- line-height: 1.35;
369
- white-space: nowrap;
370
- font-variant-numeric: tabular-nums;
371
- transition:
372
- left ${t.dur.fast} ease-out,
373
- top ${t.dur.fast} ease-out;
374
-
375
- &:where(:not([hidden])) {
376
- display: grid;
377
- }
378
- &[data-instant] {
379
- transition: none;
380
- }
381
- & [data-tone='up'] {
382
- color: ${treemapDef.vars.up};
383
- }
384
- & [data-tone='down'] {
385
- color: ${treemapDef.vars.down};
386
- }
387
- & small {
388
- color: ${t.fg.muted};
389
- }
390
- }
391
- }
392
- `,
393
- );
394
-
395
- const weightOf = (item: TreemapItem): number => (item.children ? item.children.reduce((s, c) => s + weightOf(c), 0) : Math.max(0, item.weight ?? 1));
396
-
397
- function median(values: readonly number[]): number | null {
398
- if (values.length === 0) return null;
399
- const sorted = [...values].sort((a, b) => a - b);
400
- const mid = (sorted.length - 1) / 2;
401
- return (sorted[Math.floor(mid)]! + sorted[Math.ceil(mid)]!) / 2;
402
- }
403
-
404
- const toneOf = (value: number | null): 'up' | 'down' | 'flat' | 'none' => (value === null ? 'none' : value > 0 ? 'up' : value < 0 ? 'down' : 'flat');
405
-
406
- const defaultFormat = (value: number): string => `${value > 0 ? '+' : ''}${value.toFixed(2)}`;
407
-
408
- interface Placed extends TreemapRect {
409
- item: TreemapItem;
410
- /** The groups above it, outermost first. */
411
- path: TreemapItem[];
412
- }
413
-
414
- interface TileView {
415
- el: HTMLButtonElement;
416
- label: HTMLElement | null;
417
- value: HTMLElement | null;
418
- placed: Placed;
419
- }
420
-
421
- interface GroupView {
422
- el: HTMLElement;
423
- value: HTMLElement;
424
- placed: Placed;
425
- }
426
-
427
- class TreemapImpl implements TreemapHandle {
428
- readonly el: HTMLElement;
429
- private readonly map: HTMLElement;
430
- private readonly tip: HTMLElement;
431
- private readonly crumbs: HTMLElement | null;
432
- private readonly legend: { low: HTMLElement; high: HTMLElement } | null;
433
- private readonly ro: ResizeObserver | null;
434
- private readonly i18n: Translator | null;
435
- private readonly gap: number;
436
- private items: readonly TreemapItem[];
437
- private readonly values = new Map<string, number | null>();
438
- private tiles = new Map<string, TileView>();
439
- private groups = new Map<string, GroupView>();
440
- /** The zoomed groups' ids, outermost first. */
441
- private zoom: string[] = [];
442
- private selected: string | null;
443
- /** The tile that takes the map's tab stop. */
444
- private current: string | null = null;
445
- /** The tile the readout describes. */
446
- private tipFor: string | null = null;
447
- private box = { w: 0, h: 0 };
448
-
449
- constructor(private readonly props: TreemapProps) {
450
- injectStyles(document);
451
- this.i18n = props.i18n ?? kitTranslator();
452
- this.gap = Math.max(0, props.gap ?? 3);
453
- this.items = props.items ?? [];
454
- this.selected = props.selected ?? null;
455
- this.map = h('div', { slot: treemapDef.slot('map'), attrs: { role: 'group', dir: 'ltr', 'aria-label': props.label ?? null } });
456
- this.tip = h('div', { slot: treemapDef.slot('tip'), attrs: { 'aria-hidden': 'true' } });
457
- this.tip.hidden = true;
458
- this.crumbs = props.drill ? h('nav', { slot: treemapDef.slot('crumbs') }) : null;
459
- let legendEl: HTMLElement | null = null;
460
- if (props.legend) {
461
- const low = h('span');
462
- const high = h('span');
463
- legendEl = h('div', { slot: treemapDef.slot('legend'), attrs: { 'aria-hidden': 'true', dir: 'ltr' } }, low, h('i', { slot: treemapDef.slot('legend-bar') }), high);
464
- this.legend = { low, high };
465
- } else this.legend = null;
466
- this.el = h('div', { className: props.className, slot: treemapDef.slot('root') }, this.crumbs, this.map, legendEl, this.tip);
467
- this.map.addEventListener('keydown', (e) => this.onKey(e));
468
- this.map.addEventListener('pointerleave', () => this.hideTip());
469
- this.el.addEventListener('keydown', (e) => {
470
- if (e.key !== 'Escape' || this.zoom.length === 0) return;
471
- e.preventDefault();
472
- e.stopPropagation();
473
- this.setZoom(this.zoom.slice(0, -1), true);
474
- });
475
- this.ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => this.measure()) : null;
476
- this.ro?.observe(this.map);
477
- this.renderCrumbs();
478
- this.layout();
479
- }
480
-
481
- setData(items: readonly TreemapItem[]): void {
482
- this.items = items;
483
- this.values.clear();
484
- const zoom: string[] = [];
485
- let level = items;
486
- for (const id of this.zoom) {
487
- const group = level.find((item) => item.id === id && item.children);
488
- if (!group) break;
489
- zoom.push(id);
490
- level = group.children!;
491
- }
492
- const changed = zoom.length !== this.zoom.length;
493
- this.zoom = zoom;
494
- this.renderCrumbs();
495
- this.layout();
496
- if (changed) this.props.onDrill?.(this.zoomPath());
497
- }
498
-
499
- setValues(values: ReadonlyMap<string, number | null> | Readonly<Record<string, number | null>>): void {
500
- const entries = values instanceof Map ? values.entries() : Object.entries(values);
501
- for (const [id, value] of entries) this.values.set(id, value);
502
- this.paint();
503
- }
504
-
505
- setSelected(id: string | null): void {
506
- this.selected = id;
507
- for (const [key, tile] of this.tiles) tile.el.toggleAttribute('data-selected', key === id);
508
- }
509
-
510
- drillTo(id: string | null): void {
511
- if (id === null) {
512
- this.setZoom([], true);
513
- return;
514
- }
515
- const path = this.pathTo(id, this.items, []);
516
- if (path) this.setZoom([...path.map((g) => g.id), id], true);
517
- }
518
-
519
- destroy(): void {
520
- this.ro?.disconnect();
521
- this.el.remove();
522
- }
523
-
524
- private pathTo(id: string, level: readonly TreemapItem[], above: TreemapItem[]): TreemapItem[] | null {
525
- for (const item of level) {
526
- if (!item.children) continue;
527
- if (item.id === id) return above;
528
- const found = this.pathTo(id, item.children, [...above, item]);
529
- if (found) return found;
530
- }
531
- return null;
532
- }
533
-
534
- /** The zoomed groups, outermost first. */
535
- private zoomPath(): TreemapItem[] {
536
- const path: TreemapItem[] = [];
537
- let level = this.items;
538
- for (const id of this.zoom) {
539
- const group = level.find((item) => item.id === id);
540
- if (!group?.children) break;
541
- path.push(group);
542
- level = group.children;
543
- }
544
- return path;
545
- }
546
-
547
- private setZoom(zoom: string[], announce: boolean): void {
548
- if (zoom.join('\u0000') === this.zoom.join('\u0000')) return;
549
- this.zoom = zoom;
550
- this.current = null;
551
- this.hideTip();
552
- this.renderCrumbs();
553
- this.layout();
554
- if (announce) this.props.onDrill?.(this.zoomPath());
555
- }
556
-
557
- private renderCrumbs(): void {
558
- if (!this.crumbs) return;
559
- const path = this.zoomPath();
560
- const entries: Array<{ label: string; zoom: string[] }> = [{ label: this.props.rootLabel ?? textOf(this.i18n, TEXT.all), zoom: [] }];
561
- path.forEach((group, i) => entries.push({ label: group.label, zoom: this.zoom.slice(0, i + 1) }));
562
- this.crumbs.replaceChildren(
563
- ...entries.map((entry, i) => {
564
- const last = i === entries.length - 1;
565
- return h('button', {
566
- slot: treemapDef.slot('crumb'),
567
- text: entry.label,
568
- attrs: { type: 'button', 'aria-current': last ? 'true' : null, tabindex: last ? '-1' : null },
569
- on: { click: () => !last && this.setZoom(entry.zoom, true) },
570
- });
571
- }),
572
- );
573
- }
574
-
575
- private measure(): void {
576
- const w = this.map.clientWidth;
577
- const hh = this.map.clientHeight;
578
- if (Math.abs(w - this.box.w) < 0.5 && Math.abs(hh - this.box.h) < 0.5) return;
579
- this.box = { w, h: hh };
580
- this.layout();
581
- }
582
-
583
- /** The items on the map: the zoomed group's, or the top level's. */
584
- private level(): { items: readonly TreemapItem[]; path: TreemapItem[] } {
585
- const path = this.zoomPath();
586
- return { items: path.length > 0 ? path[path.length - 1]!.children! : this.items, path };
587
- }
588
-
589
- private place(items: readonly TreemapItem[], bounds: TreemapRect, path: TreemapItem[], groups: Placed[], tiles: Placed[]): void {
590
- const half = this.gap / 2;
591
- for (const r of squarify(
592
- items.map((item) => ({ item, weight: weightOf(item) })),
593
- bounds,
594
- )) {
595
- const box = { x: r.x + half, y: r.y + half, w: Math.max(0, r.w - this.gap), h: Math.max(0, r.h - this.gap) };
596
- if (r.item.children) {
597
- const headed = box.w >= HEADED.w && box.h >= HEADED.h;
598
- if (headed) groups.push({ item: r.item, path, ...box, h: HEADER });
599
- const top = headed ? HEADER : 0;
600
- this.place(r.item.children, { x: box.x, y: box.y + top, w: box.w, h: box.h - top }, [...path, r.item], groups, tiles);
601
- } else tiles.push({ item: r.item, path, ...box });
602
- }
603
- }
604
-
605
- private layout(): void {
606
- const level = this.level();
607
- const groups: Placed[] = [];
608
- const tiles: Placed[] = [];
609
- this.place(level.items, { x: 0, y: 0, w: this.box.w, h: this.box.h }, level.path, groups, tiles);
610
-
611
- const nextGroups = new Map<string, GroupView>();
612
- for (const placed of groups) {
613
- const view = this.groups.get(placed.item.id) ?? this.groupView(placed);
614
- view.placed = placed;
615
- view.el.firstElementChild!.textContent = placed.item.label;
616
- position(view.el, placed);
617
- nextGroups.set(placed.item.id, view);
618
- }
619
- const nextTiles = new Map<string, TileView>();
620
- for (const placed of tiles) {
621
- const old = this.tiles.get(placed.item.id);
622
- const view = old ?? this.tileView(placed);
623
- view.placed = placed;
624
- this.fitTile(view);
625
- position(view.el, placed);
626
- nextTiles.set(placed.item.id, view);
627
- }
628
- for (const [id, view] of this.groups) if (!nextGroups.has(id)) view.el.remove();
629
- for (const [id, view] of this.tiles) if (!nextTiles.has(id)) view.el.remove();
630
- this.groups = nextGroups;
631
- this.tiles = nextTiles;
632
-
633
- // Reading order: each group's header, then its tiles. Nodes that already sit in that
634
- // order stay put, as a moved node restarts its transitions.
635
- const order: HTMLElement[] = [];
636
- const headerOf = new Map(groups.map((g) => [g.item.id, nextGroups.get(g.item.id)!.el]));
637
- const written = new Set<string>();
638
- for (const placed of tiles) {
639
- for (const group of placed.path) {
640
- const header = headerOf.get(group.id);
641
- if (header && !written.has(group.id)) {
642
- written.add(group.id);
643
- order.push(header);
644
- }
645
- }
646
- order.push(nextTiles.get(placed.item.id)!.el);
647
- }
648
- const children = this.map.children;
649
- const same = children.length === order.length && order.every((node, i) => children[i] === node);
650
- if (!same) this.map.replaceChildren(...order);
651
-
652
- if (this.current === null || !this.tiles.has(this.current)) this.current = tiles[0]?.item.id ?? null;
653
- for (const [id, tile] of this.tiles) {
654
- tile.el.tabIndex = id === this.current ? 0 : -1;
655
- tile.el.toggleAttribute('data-selected', id === this.selected);
656
- }
657
- this.paint();
658
- }
659
-
660
- private groupView(placed: Placed): GroupView {
661
- const name = h('span', { slot: treemapDef.slot('group-name') });
662
- const value = h('span', { slot: treemapDef.slot('group-value') });
663
- const drill = this.props.drill === true;
664
- const el = drill
665
- ? h(
666
- 'button',
667
- {
668
- slot: treemapDef.slot('group'),
669
- data: { drill: true },
670
- attrs: { type: 'button', title: textOf(this.i18n, TEXT.zoomIn) },
671
- },
672
- name,
673
- value,
674
- )
675
- : h('div', { slot: treemapDef.slot('group') }, name, value);
676
- const view: GroupView = { el, value, placed };
677
- if (drill) el.addEventListener('click', () => this.drillTo(view.placed.item.id));
678
- return view;
679
- }
680
-
681
- private tileView(placed: Placed): TileView {
682
- const el = h('button', { slot: treemapDef.slot('tile'), attrs: { type: 'button' } });
683
- const view: TileView = { el, label: null, value: null, placed };
684
- el.addEventListener('click', () => this.choose(view));
685
- el.addEventListener('focus', () => {
686
- this.current = view.placed.item.id;
687
- for (const tile of this.tiles.values()) tile.el.tabIndex = tile === view ? 0 : -1;
688
- this.showTipFor(view);
689
- });
690
- el.addEventListener('blur', () => this.hideTip());
691
- el.addEventListener('pointerenter', () => this.showTipFor(view));
692
- return view;
693
- }
694
-
695
- /** Text sized to the tile: the label from a small tile up, the value from a larger one. */
696
- private fitTile(view: TileView): void {
697
- const { w, h: ht } = view.placed;
698
- const font = Math.max(10, Math.min(18, Math.min(w, ht) / 4.2));
699
- const showLabel = w > 34 && ht > 20;
700
- const showValue = w > 48 && ht > 38;
701
- if (showLabel && !view.label) view.label = h('span', { slot: treemapDef.slot('tile-label') });
702
- if (!showLabel) view.label = null;
703
- if (showValue && !view.value) view.value = h('span', { slot: treemapDef.slot('tile-value') });
704
- if (!showValue) view.value = null;
705
- if (view.label) {
706
- view.label.textContent = view.placed.item.label;
707
- view.label.style.fontSize = `${font}px`;
708
- }
709
- if (view.value) view.value.style.fontSize = `${Math.max(9.5, font * 0.72)}px`;
710
- const parts = [view.label, view.value].filter((part): part is HTMLElement => part !== null);
711
- if (parts.length !== view.el.childElementCount || parts.some((part, i) => view.el.children[i] !== part)) view.el.replaceChildren(...parts);
712
- }
713
-
714
- private valueOf(item: TreemapItem): number | null {
715
- const value = this.values.has(item.id) ? this.values.get(item.id)! : (item.value ?? null);
716
- return value === null || !Number.isFinite(value) ? null : value;
717
- }
718
-
719
- private leafValues(item: TreemapItem): number[] {
720
- if (!item.children) {
721
- const value = this.valueOf(item);
722
- return value === null ? [] : [value];
723
- }
724
- return item.children.flatMap((child) => this.leafValues(child));
725
- }
726
-
727
- private groupFigure(group: TreemapItem): number | null {
728
- const mode = this.props.groupValue ?? 'median';
729
- if (mode === 'none') return null;
730
- const values = this.leafValues(group);
731
- if (typeof mode === 'function') return mode(values, group);
732
- if (values.length === 0) return null;
733
- if (mode === 'sum') return values.reduce((s, v) => s + v, 0);
734
- if (mode === 'mean') return values.reduce((s, v) => s + v, 0) / values.length;
735
- return median(values);
736
- }
737
-
738
- private format(value: number): string {
739
- return (this.props.format ?? defaultFormat)(value);
740
- }
741
-
742
- private paint(): void {
743
- let largest = 0;
744
- for (const tile of this.tiles.values()) largest = Math.max(largest, Math.abs(this.valueOf(tile.placed.item) ?? 0));
745
- const domain = this.props.domain !== undefined && this.props.domain > 0 ? this.props.domain : largest;
746
- for (const tile of this.tiles.values()) {
747
- const item = tile.placed.item;
748
- const value = this.valueOf(item);
749
- if (item.color !== undefined) {
750
- tile.el.dataset.tone = 'custom';
751
- tile.el.style.setProperty('--_color', item.color);
752
- } else tile.el.dataset.tone = toneOf(value);
753
- tile.el.style.setProperty('--_level', value === null || domain === 0 ? '0' : String(Math.min(Math.abs(value) / domain, 1)));
754
- const text = value === null ? '' : this.format(value);
755
- if (tile.value) tile.value.textContent = text;
756
- tile.el.setAttribute('aria-label', text === '' ? item.label : `${item.label} ${text}`);
757
- }
758
- for (const group of this.groups.values()) {
759
- const figure = this.groupFigure(group.placed.item);
760
- group.value.textContent = figure === null ? '' : this.format(figure);
761
- group.value.dataset.tone = toneOf(figure);
762
- const name = group.placed.item.label;
763
- group.el.setAttribute('aria-label', figure === null ? name : `${name} ${this.format(figure)}`);
764
- }
765
- if (this.legend) {
766
- this.legend.low.textContent = domain > 0 ? this.format(-domain) : '';
767
- this.legend.high.textContent = domain > 0 ? this.format(domain) : '';
768
- }
769
- const shown = this.tipFor !== null ? this.tiles.get(this.tipFor) : undefined;
770
- if (shown) this.showTipFor(shown);
771
- else this.hideTip();
772
- }
773
-
774
- private choose(view: TileView): void {
775
- this.props.onSelect?.(view.placed.item, view.placed.path);
776
- }
777
-
778
- private tipContent(view: TileView): string | Node | null {
779
- const { item, path } = view.placed;
780
- if (this.props.tip === false) return null;
781
- if (this.props.tip) return this.props.tip(item, path);
782
- const value = this.valueOf(item);
783
- return h(
784
- 'div',
785
- {},
786
- h('div', {}, h('b', { text: item.label }), value === null ? null : h('span', { text: ` ${this.format(value)}`, data: { tone: toneOf(value) } })),
787
- path.length > 0 ? h('small', { text: path.map((g) => g.label).join(' › ') }) : null,
788
- );
789
- }
790
-
791
- private showTipFor(view: TileView): void {
792
- const content = this.tipContent(view);
793
- if (content === null) return;
794
- this.tipFor = view.placed.item.id;
795
- const { x, y, w, h: ht } = view.placed;
796
- showTip(this.tip, content, { w: this.el.clientWidth, h: this.el.clientHeight }, this.map.offsetLeft + x + w / 2, this.map.offsetTop + y + ht / 2);
797
- }
798
-
799
- private hideTip(): void {
800
- this.tipFor = null;
801
- this.tip.hidden = true;
802
- }
803
-
804
- /** Arrows move to the nearest tile that way, Home and End to the first and the last. */
805
- private onKey(e: KeyboardEvent): void {
806
- const from = this.current !== null ? this.tiles.get(this.current) : undefined;
807
- if (!from || !(e.target instanceof HTMLElement) || e.target.dataset.slot !== treemapDef.slot('tile')) return;
808
- const list = [...this.tiles.values()];
809
- let next: TileView | undefined;
810
- if (e.key === 'Home') next = list[0];
811
- else if (e.key === 'End') next = list[list.length - 1];
812
- else {
813
- const dir = { ArrowRight: [1, 0], ArrowLeft: [-1, 0], ArrowDown: [0, 1], ArrowUp: [0, -1] }[e.key];
814
- if (!dir) return;
815
- const cx = from.placed.x + from.placed.w / 2;
816
- const cy = from.placed.y + from.placed.h / 2;
817
- let best = Infinity;
818
- for (const tile of list) {
819
- if (tile === from) continue;
820
- const dx = tile.placed.x + tile.placed.w / 2 - cx;
821
- const dy = tile.placed.y + tile.placed.h / 2 - cy;
822
- const along = dx * dir[0]! + dy * dir[1]!;
823
- if (along <= 0) continue;
824
- const across = Math.abs(dx * dir[1]! - dy * dir[0]!);
825
- const score = along + across * 2;
826
- if (score < best) {
827
- best = score;
828
- next = tile;
829
- }
830
- }
831
- }
832
- if (!next) return;
833
- e.preventDefault();
834
- next.el.focus();
835
- }
836
- }
837
-
838
- function position(el: HTMLElement, box: TreemapRect): void {
839
- el.style.left = `${box.x}px`;
840
- el.style.top = `${box.y}px`;
841
- el.style.width = `${box.w}px`;
842
- el.style.height = `${box.h}px`;
843
- }
844
-
845
- export function createTreemap(props: TreemapProps = {}): TreemapHandle {
846
- return new TreemapImpl(props);
847
- }
1
+ // Treemap: weighted items laid into a rectangle as tiles close to square, each tinted by its
2
+ // value on a diverging scale (up above zero, down below, stronger as the value grows) and
3
+ // labeled when it has room. Items with children are groups: their tiles share a block headed
4
+ // by the group's name and a figure of its values. With `drill`, a group's header zooms into it
5
+ // and a breadcrumb leads back. Values repaint without a new layout, and a tile keeps its
6
+ // element across layouts, so a resize or a zoom moves it instead of redrawing it.
7
+ import { showTip } from '@luxalgo/vela-ui/chart';
8
+ import { css, defineStyles } from '@luxalgo/vela-ui';
9
+ import { defineComponent } from '@luxalgo/vela-ui';
10
+ import { h } from '@luxalgo/vela-ui';
11
+ import { msg, textOf, type Translator } from '@luxalgo/vela-ui/i18n';
12
+ import { kitTranslator } from '@luxalgo/vela-ui/kit-text';
13
+ import { t } from '@luxalgo/vela-ui';
14
+
15
+ export const treemapDef = defineComponent({
16
+ name: 'treemap',
17
+ parts: ['root', 'crumbs', 'crumb', 'map', 'group', 'group-name', 'group-value', 'tile', 'tile-label', 'tile-value', 'legend', 'legend-bar', 'tip'],
18
+ settings: {
19
+ radius: t.radius.sm,
20
+ up: t.up,
21
+ down: t.down,
22
+ 'tile-bg': `color-mix(in srgb, ${t.fg.bright} 2.5%, ${t.surface})`,
23
+ 'tint-min': '3%',
24
+ 'tint-max': '25%',
25
+ 'hover-z': '1',
26
+ 'tip-radius': t.radius.md,
27
+ 'tip-bg': t.surface.elev,
28
+ 'tip-shadow': t.shadow,
29
+ 'tip-z': '2',
30
+ },
31
+ });
32
+
33
+ export interface TreemapItem {
34
+ /** Stable across updates: a tile keeps its element by id. */
35
+ id: string;
36
+ label: string;
37
+ /** The tile's share of the area (default 1, equal tiles); zero or less leaves it out. A
38
+ * group's share is the sum of its items'. */
39
+ weight?: number;
40
+ /** What the tile is tinted by and shows; null while it is unknown. */
41
+ value?: number | null;
42
+ /** The tile's ink instead of its value's tone: a token's `var()` (`t.accent.var`) or a color. */
43
+ color?: string;
44
+ /** The group's items: the item becomes a group. */
45
+ children?: readonly TreemapItem[];
46
+ }
47
+
48
+ /** How a group's header sums up its items' values, or a function of them. */
49
+ export type TreemapGroupValue = 'median' | 'mean' | 'sum' | 'none' | ((values: readonly number[], group: TreemapItem) => number | null);
50
+
51
+ export interface TreemapProps {
52
+ items?: readonly TreemapItem[];
53
+ /** The size of a value whose tint is full. Default: the largest one on the map. */
54
+ domain?: number;
55
+ /** A value as the tiles, the headers, the readout and the legend write it. Default: signed,
56
+ * two decimals. */
57
+ format?: (value: number) => string;
58
+ /** A group header's figure (default the median of its items' values). */
59
+ groupValue?: TreemapGroupValue;
60
+ /** The readout beside a hovered or focused tile, or `false` for none. Default: its label,
61
+ * value and groups. */
62
+ tip?: ((item: TreemapItem, path: readonly TreemapItem[]) => string | Node) | false;
63
+ /** A tile's click, Enter or Space. `path` lists its groups, outermost first. */
64
+ onSelect?: (item: TreemapItem, path: readonly TreemapItem[]) => void;
65
+ /** The id of the tile drawn as selected. */
66
+ selected?: string | null;
67
+ /** Group headers zoom into their group, and a breadcrumb above the map leads back. */
68
+ drill?: boolean;
69
+ /** A zoom changed: `path` is the zoomed group's path (empty at the top). */
70
+ onDrill?: (path: readonly TreemapItem[]) => void;
71
+ /** The breadcrumb's first entry (default "All"). */
72
+ rootLabel?: string;
73
+ /** A scale under the map, from the negative to the positive domain. */
74
+ legend?: boolean;
75
+ /** Space between tiles, in pixels (default 3). */
76
+ gap?: number;
77
+ /** The map's accessible name. */
78
+ label?: string;
79
+ /** The translator of the treemap's own words. Default: the kit build's, else English. */
80
+ i18n?: Translator | null;
81
+ /** Extra class names (layout hooks). */
82
+ className?: string;
83
+ }
84
+
85
+ export interface TreemapHandle {
86
+ readonly el: HTMLElement;
87
+ /** New items: lays the map out again. A zoom stays on its group while the group exists. */
88
+ setData(items: readonly TreemapItem[]): void;
89
+ /** New values by id: repaints the tints, figures and readout without a new layout. */
90
+ setValues(values: ReadonlyMap<string, number | null> | Readonly<Record<string, number | null>>): void;
91
+ setSelected(id: string | null): void;
92
+ /** Zoom into a group by id, or back to the top with null. */
93
+ drillTo(id: string | null): void;
94
+ destroy(): void;
95
+ }
96
+
97
+ export interface TreemapRect {
98
+ x: number;
99
+ y: number;
100
+ w: number;
101
+ h: number;
102
+ }
103
+
104
+ /** Lay weighted items into `bounds` as tiles close to square (the squarified layout): areas
105
+ * follow the weights and fill the bounds exactly, heaviest first. Items weighing nothing are
106
+ * left out. */
107
+ export function squarify<T extends { weight: number }>(items: readonly T[], bounds: TreemapRect): Array<T & TreemapRect> {
108
+ const total = items.reduce((s, item) => s + Math.max(0, item.weight), 0);
109
+ if (!total || bounds.w <= 0 || bounds.h <= 0) return [];
110
+ const scale = (bounds.w * bounds.h) / total;
111
+ let queue = items
112
+ .filter((item) => item.weight > 0)
113
+ .map((item) => ({ item, area: item.weight * scale }))
114
+ .sort((a, b) => b.area - a.area);
115
+ let { x, y, w, h } = bounds;
116
+ const out: Array<T & TreemapRect> = [];
117
+ const worst = (row: ReadonlyArray<{ area: number }>, side: number): number => {
118
+ const sum = row.reduce((s, r) => s + r.area, 0);
119
+ const max = Math.max(...row.map((r) => r.area));
120
+ const min = Math.min(...row.map((r) => r.area));
121
+ return Math.max((side * side * max) / (sum * sum), (sum * sum) / (side * side * min));
122
+ };
123
+ while (queue.length) {
124
+ const side = Math.min(w, h);
125
+ const row = [queue[0]!];
126
+ let i = 1;
127
+ while (i < queue.length && worst([...row, queue[i]!], side) <= worst(row, side)) row.push(queue[i++]!);
128
+ queue = queue.slice(i);
129
+ const sum = row.reduce((s, r) => s + r.area, 0);
130
+ if (w >= h) {
131
+ const cw = sum / h;
132
+ let cy = y;
133
+ for (const r of row) {
134
+ const ch = r.area / cw;
135
+ out.push({ ...r.item, x, y: cy, w: cw, h: ch });
136
+ cy += ch;
137
+ }
138
+ x += cw;
139
+ w -= cw;
140
+ } else {
141
+ const rh = sum / w;
142
+ let cx = x;
143
+ for (const r of row) {
144
+ const rw = r.area / rh;
145
+ out.push({ ...r.item, x: cx, y, w: rw, h: rh });
146
+ cx += rw;
147
+ }
148
+ y += rh;
149
+ h -= rh;
150
+ }
151
+ }
152
+ return out;
153
+ }
154
+
155
+ const TEXT = {
156
+ all: msg('ui.treemap.all', 'All'),
157
+ zoomIn: msg('ui.treemap.zoomIn', 'Zoom in'),
158
+ };
159
+
160
+ /** A group's header row, and the smallest block that gets one. */
161
+ const HEADER = 16;
162
+ const HEADED = { w: 80, h: 64 };
163
+
164
+ const injectStyles = defineStyles(
165
+ 'vela-ui-treemap',
166
+ css`
167
+ @layer vela.ui {
168
+ [data-slot='treemap'] {
169
+ position: relative;
170
+ width: 100%;
171
+ height: 100%;
172
+ min-height: 0;
173
+ color: ${t.fg};
174
+ font-size: ${t.fontSize.sm};
175
+
176
+ &:where(:not([hidden])) {
177
+ display: flex;
178
+ flex-direction: column;
179
+ gap: 8px;
180
+ }
181
+ }
182
+ [data-slot='treemap-crumbs'] {
183
+ display: flex;
184
+ flex-wrap: wrap;
185
+ align-items: center;
186
+ gap: 2px;
187
+ min-height: 22px;
188
+ font-size: 12px;
189
+ color: ${t.fg.muted};
190
+ }
191
+ [data-slot='treemap-crumb'] {
192
+ all: unset;
193
+ padding: 2px 6px;
194
+ border-radius: ${treemapDef.vars.radius};
195
+ cursor: pointer;
196
+
197
+ &:hover {
198
+ background: ${t.hover};
199
+ color: ${t.fg.bright};
200
+ }
201
+ &:focus-visible {
202
+ outline: 2px solid ${t.focus};
203
+ }
204
+ &[aria-current] {
205
+ cursor: default;
206
+ color: ${t.fg.bright};
207
+ font-weight: 600;
208
+ background: none;
209
+ }
210
+ &:not(:first-child)::before {
211
+ content: '›';
212
+ margin-inline-end: 8px;
213
+ color: ${t.fg.faint};
214
+ }
215
+ }
216
+ [data-slot='treemap-map'] {
217
+ position: relative;
218
+ flex: 1 1 auto;
219
+ min-height: 0;
220
+ isolation: isolate;
221
+ }
222
+ [data-slot='treemap-group'] {
223
+ all: unset;
224
+ position: absolute;
225
+ display: flex;
226
+ align-items: center;
227
+ gap: 6px;
228
+ height: 16px;
229
+ padding-inline: 2px;
230
+ overflow: hidden;
231
+ font-size: 9px;
232
+ font-weight: 500;
233
+ letter-spacing: 0.06em;
234
+ text-transform: uppercase;
235
+ white-space: nowrap;
236
+ color: ${t.fg.muted};
237
+ transition:
238
+ left ${t.dur.med} ${t.ease},
239
+ top ${t.dur.med} ${t.ease},
240
+ width ${t.dur.med} ${t.ease};
241
+
242
+ &[data-drill] {
243
+ border-radius: ${treemapDef.vars.radius};
244
+ cursor: zoom-in;
245
+ }
246
+ &[data-drill]:hover {
247
+ color: ${t.fg.bright};
248
+ background: ${t.hover};
249
+ }
250
+ &:focus-visible {
251
+ outline: 2px solid ${t.focus};
252
+ }
253
+ }
254
+ [data-slot='treemap-group-name'] {
255
+ overflow: hidden;
256
+ text-overflow: ellipsis;
257
+ }
258
+ [data-slot='treemap-group-value'] {
259
+ margin-inline-start: auto;
260
+ font-variant-numeric: tabular-nums;
261
+
262
+ &[data-tone='up'] {
263
+ color: ${treemapDef.vars.up};
264
+ }
265
+ &[data-tone='down'] {
266
+ color: ${treemapDef.vars.down};
267
+ }
268
+ }
269
+ [data-slot='treemap-tile'] {
270
+ all: unset;
271
+ --_tone: ${t.fg.muted};
272
+ --_tint: calc(${treemapDef.vars['tint-min']} + (${treemapDef.vars['tint-max']} - ${treemapDef.vars['tint-min']}) * var(--_level, 0));
273
+
274
+ position: absolute;
275
+ display: flex;
276
+ flex-direction: column;
277
+ align-items: center;
278
+ justify-content: center;
279
+ gap: 1px;
280
+ overflow: hidden;
281
+ border: 1px solid color-mix(in srgb, var(--_tone) calc(var(--_tint) * 0.8), ${t.border});
282
+ border-radius: ${treemapDef.vars.radius};
283
+ background: color-mix(in srgb, var(--_tone) var(--_tint), ${treemapDef.vars['tile-bg']});
284
+ text-align: center;
285
+ cursor: pointer;
286
+ transition:
287
+ left ${t.dur.med} ${t.ease},
288
+ top ${t.dur.med} ${t.ease},
289
+ width ${t.dur.med} ${t.ease},
290
+ height ${t.dur.med} ${t.ease},
291
+ background-color ${t.dur.med} linear,
292
+ scale ${t.dur.fast} ${t.ease};
293
+
294
+ &[data-tone='up'] {
295
+ --_tone: ${treemapDef.vars.up};
296
+ }
297
+ &[data-tone='down'] {
298
+ --_tone: ${treemapDef.vars.down};
299
+ }
300
+ &[data-tone='custom'] {
301
+ --_tone: var(--_color);
302
+ }
303
+ &[data-tone='none'] {
304
+ --_tint: 0%;
305
+ }
306
+ &:hover {
307
+ z-index: ${treemapDef.vars['hover-z']};
308
+ scale: 1.04;
309
+ border-color: ${t.fg.bright};
310
+ }
311
+ &:focus-visible {
312
+ z-index: ${treemapDef.vars['hover-z']};
313
+ outline: 2px solid ${t.focus};
314
+ }
315
+ &[data-selected] {
316
+ border-color: ${t.fg.bright};
317
+ outline: 1px solid ${t.fg.bright};
318
+ }
319
+ }
320
+ [data-slot='treemap-tile-label'] {
321
+ max-width: 100%;
322
+ overflow: hidden;
323
+ text-overflow: ellipsis;
324
+ font-weight: 600;
325
+ line-height: 1.1;
326
+ white-space: nowrap;
327
+ color: ${t.fg.bright};
328
+ }
329
+ [data-slot='treemap-tile-value'] {
330
+ white-space: nowrap;
331
+ font-variant-numeric: tabular-nums;
332
+ color: ${t.fg.bright};
333
+ opacity: 0.92;
334
+ }
335
+ [data-slot='treemap-legend'] {
336
+ display: grid;
337
+ grid-template-columns: auto 1fr auto;
338
+ align-items: center;
339
+ gap: 8px;
340
+ font-size: 10px;
341
+ font-variant-numeric: tabular-nums;
342
+ color: ${t.fg.muted};
343
+ }
344
+ [data-slot='treemap-legend-bar'] {
345
+ height: 6px;
346
+ border: 1px solid ${t.border};
347
+ border-radius: 999px;
348
+ background: linear-gradient(
349
+ to right,
350
+ color-mix(in srgb, ${treemapDef.vars.down} 70%, ${treemapDef.vars['tile-bg']}),
351
+ ${treemapDef.vars['tile-bg']},
352
+ color-mix(in srgb, ${treemapDef.vars.up} 70%, ${treemapDef.vars['tile-bg']})
353
+ );
354
+ }
355
+ [data-slot='treemap-tip'] {
356
+ position: absolute;
357
+ z-index: ${treemapDef.vars['tip-z']};
358
+ top: 0;
359
+ gap: 2px;
360
+ pointer-events: none;
361
+ padding: 8px;
362
+ border: 1px solid ${t.border};
363
+ border-radius: ${treemapDef.vars['tip-radius']};
364
+ background: ${treemapDef.vars['tip-bg']};
365
+ box-shadow: ${treemapDef.vars['tip-shadow']};
366
+ color: ${t.fg.bright};
367
+ font-size: 12px;
368
+ line-height: 1.35;
369
+ white-space: nowrap;
370
+ font-variant-numeric: tabular-nums;
371
+ transition:
372
+ left ${t.dur.fast} ease-out,
373
+ top ${t.dur.fast} ease-out;
374
+
375
+ &:where(:not([hidden])) {
376
+ display: grid;
377
+ }
378
+ &[data-instant] {
379
+ transition: none;
380
+ }
381
+ & [data-tone='up'] {
382
+ color: ${treemapDef.vars.up};
383
+ }
384
+ & [data-tone='down'] {
385
+ color: ${treemapDef.vars.down};
386
+ }
387
+ & small {
388
+ color: ${t.fg.muted};
389
+ }
390
+ }
391
+ }
392
+ `,
393
+ );
394
+
395
+ const weightOf = (item: TreemapItem): number => (item.children ? item.children.reduce((s, c) => s + weightOf(c), 0) : Math.max(0, item.weight ?? 1));
396
+
397
+ function median(values: readonly number[]): number | null {
398
+ if (values.length === 0) return null;
399
+ const sorted = [...values].sort((a, b) => a - b);
400
+ const mid = (sorted.length - 1) / 2;
401
+ return (sorted[Math.floor(mid)]! + sorted[Math.ceil(mid)]!) / 2;
402
+ }
403
+
404
+ const toneOf = (value: number | null): 'up' | 'down' | 'flat' | 'none' => (value === null ? 'none' : value > 0 ? 'up' : value < 0 ? 'down' : 'flat');
405
+
406
+ const defaultFormat = (value: number): string => `${value > 0 ? '+' : ''}${value.toFixed(2)}`;
407
+
408
+ interface Placed extends TreemapRect {
409
+ item: TreemapItem;
410
+ /** The groups above it, outermost first. */
411
+ path: TreemapItem[];
412
+ }
413
+
414
+ interface TileView {
415
+ el: HTMLButtonElement;
416
+ label: HTMLElement | null;
417
+ value: HTMLElement | null;
418
+ placed: Placed;
419
+ }
420
+
421
+ interface GroupView {
422
+ el: HTMLElement;
423
+ value: HTMLElement;
424
+ placed: Placed;
425
+ }
426
+
427
+ class TreemapImpl implements TreemapHandle {
428
+ readonly el: HTMLElement;
429
+ private readonly map: HTMLElement;
430
+ private readonly tip: HTMLElement;
431
+ private readonly crumbs: HTMLElement | null;
432
+ private readonly legend: { low: HTMLElement; high: HTMLElement } | null;
433
+ private readonly ro: ResizeObserver | null;
434
+ private readonly i18n: Translator | null;
435
+ private readonly gap: number;
436
+ private items: readonly TreemapItem[];
437
+ private readonly values = new Map<string, number | null>();
438
+ private tiles = new Map<string, TileView>();
439
+ private groups = new Map<string, GroupView>();
440
+ /** The zoomed groups' ids, outermost first. */
441
+ private zoom: string[] = [];
442
+ private selected: string | null;
443
+ /** The tile that takes the map's tab stop. */
444
+ private current: string | null = null;
445
+ /** The tile the readout describes. */
446
+ private tipFor: string | null = null;
447
+ private box = { w: 0, h: 0 };
448
+
449
+ constructor(private readonly props: TreemapProps) {
450
+ injectStyles(document);
451
+ this.i18n = props.i18n ?? kitTranslator();
452
+ this.gap = Math.max(0, props.gap ?? 3);
453
+ this.items = props.items ?? [];
454
+ this.selected = props.selected ?? null;
455
+ this.map = h('div', { slot: treemapDef.slot('map'), attrs: { role: 'group', dir: 'ltr', 'aria-label': props.label ?? null } });
456
+ this.tip = h('div', { slot: treemapDef.slot('tip'), attrs: { 'aria-hidden': 'true' } });
457
+ this.tip.hidden = true;
458
+ this.crumbs = props.drill ? h('nav', { slot: treemapDef.slot('crumbs') }) : null;
459
+ let legendEl: HTMLElement | null = null;
460
+ if (props.legend) {
461
+ const low = h('span');
462
+ const high = h('span');
463
+ legendEl = h('div', { slot: treemapDef.slot('legend'), attrs: { 'aria-hidden': 'true', dir: 'ltr' } }, low, h('i', { slot: treemapDef.slot('legend-bar') }), high);
464
+ this.legend = { low, high };
465
+ } else this.legend = null;
466
+ this.el = h('div', { className: props.className, slot: treemapDef.slot('root') }, this.crumbs, this.map, legendEl, this.tip);
467
+ this.map.addEventListener('keydown', (e) => this.onKey(e));
468
+ this.map.addEventListener('pointerleave', () => this.hideTip());
469
+ this.el.addEventListener('keydown', (e) => {
470
+ if (e.key !== 'Escape' || this.zoom.length === 0) return;
471
+ e.preventDefault();
472
+ e.stopPropagation();
473
+ this.setZoom(this.zoom.slice(0, -1), true);
474
+ });
475
+ this.ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => this.measure()) : null;
476
+ this.ro?.observe(this.map);
477
+ this.renderCrumbs();
478
+ this.layout();
479
+ }
480
+
481
+ setData(items: readonly TreemapItem[]): void {
482
+ this.items = items;
483
+ this.values.clear();
484
+ const zoom: string[] = [];
485
+ let level = items;
486
+ for (const id of this.zoom) {
487
+ const group = level.find((item) => item.id === id && item.children);
488
+ if (!group) break;
489
+ zoom.push(id);
490
+ level = group.children!;
491
+ }
492
+ const changed = zoom.length !== this.zoom.length;
493
+ this.zoom = zoom;
494
+ this.renderCrumbs();
495
+ this.layout();
496
+ if (changed) this.props.onDrill?.(this.zoomPath());
497
+ }
498
+
499
+ setValues(values: ReadonlyMap<string, number | null> | Readonly<Record<string, number | null>>): void {
500
+ const entries = values instanceof Map ? values.entries() : Object.entries(values);
501
+ for (const [id, value] of entries) this.values.set(id, value);
502
+ this.paint();
503
+ }
504
+
505
+ setSelected(id: string | null): void {
506
+ this.selected = id;
507
+ for (const [key, tile] of this.tiles) tile.el.toggleAttribute('data-selected', key === id);
508
+ }
509
+
510
+ drillTo(id: string | null): void {
511
+ if (id === null) {
512
+ this.setZoom([], true);
513
+ return;
514
+ }
515
+ const path = this.pathTo(id, this.items, []);
516
+ if (path) this.setZoom([...path.map((g) => g.id), id], true);
517
+ }
518
+
519
+ destroy(): void {
520
+ this.ro?.disconnect();
521
+ this.el.remove();
522
+ }
523
+
524
+ private pathTo(id: string, level: readonly TreemapItem[], above: TreemapItem[]): TreemapItem[] | null {
525
+ for (const item of level) {
526
+ if (!item.children) continue;
527
+ if (item.id === id) return above;
528
+ const found = this.pathTo(id, item.children, [...above, item]);
529
+ if (found) return found;
530
+ }
531
+ return null;
532
+ }
533
+
534
+ /** The zoomed groups, outermost first. */
535
+ private zoomPath(): TreemapItem[] {
536
+ const path: TreemapItem[] = [];
537
+ let level = this.items;
538
+ for (const id of this.zoom) {
539
+ const group = level.find((item) => item.id === id);
540
+ if (!group?.children) break;
541
+ path.push(group);
542
+ level = group.children;
543
+ }
544
+ return path;
545
+ }
546
+
547
+ private setZoom(zoom: string[], announce: boolean): void {
548
+ if (zoom.join('\u0000') === this.zoom.join('\u0000')) return;
549
+ this.zoom = zoom;
550
+ this.current = null;
551
+ this.hideTip();
552
+ this.renderCrumbs();
553
+ this.layout();
554
+ if (announce) this.props.onDrill?.(this.zoomPath());
555
+ }
556
+
557
+ private renderCrumbs(): void {
558
+ if (!this.crumbs) return;
559
+ const path = this.zoomPath();
560
+ const entries: Array<{ label: string; zoom: string[] }> = [{ label: this.props.rootLabel ?? textOf(this.i18n, TEXT.all), zoom: [] }];
561
+ path.forEach((group, i) => entries.push({ label: group.label, zoom: this.zoom.slice(0, i + 1) }));
562
+ this.crumbs.replaceChildren(
563
+ ...entries.map((entry, i) => {
564
+ const last = i === entries.length - 1;
565
+ return h('button', {
566
+ slot: treemapDef.slot('crumb'),
567
+ text: entry.label,
568
+ attrs: { type: 'button', 'aria-current': last ? 'true' : null, tabindex: last ? '-1' : null },
569
+ on: { click: () => !last && this.setZoom(entry.zoom, true) },
570
+ });
571
+ }),
572
+ );
573
+ }
574
+
575
+ private measure(): void {
576
+ const w = this.map.clientWidth;
577
+ const hh = this.map.clientHeight;
578
+ if (Math.abs(w - this.box.w) < 0.5 && Math.abs(hh - this.box.h) < 0.5) return;
579
+ this.box = { w, h: hh };
580
+ this.layout();
581
+ }
582
+
583
+ /** The items on the map: the zoomed group's, or the top level's. */
584
+ private level(): { items: readonly TreemapItem[]; path: TreemapItem[] } {
585
+ const path = this.zoomPath();
586
+ return { items: path.length > 0 ? path[path.length - 1]!.children! : this.items, path };
587
+ }
588
+
589
+ private place(items: readonly TreemapItem[], bounds: TreemapRect, path: TreemapItem[], groups: Placed[], tiles: Placed[]): void {
590
+ const half = this.gap / 2;
591
+ for (const r of squarify(
592
+ items.map((item) => ({ item, weight: weightOf(item) })),
593
+ bounds,
594
+ )) {
595
+ const box = { x: r.x + half, y: r.y + half, w: Math.max(0, r.w - this.gap), h: Math.max(0, r.h - this.gap) };
596
+ if (r.item.children) {
597
+ const headed = box.w >= HEADED.w && box.h >= HEADED.h;
598
+ if (headed) groups.push({ item: r.item, path, ...box, h: HEADER });
599
+ const top = headed ? HEADER : 0;
600
+ this.place(r.item.children, { x: box.x, y: box.y + top, w: box.w, h: box.h - top }, [...path, r.item], groups, tiles);
601
+ } else tiles.push({ item: r.item, path, ...box });
602
+ }
603
+ }
604
+
605
+ private layout(): void {
606
+ const level = this.level();
607
+ const groups: Placed[] = [];
608
+ const tiles: Placed[] = [];
609
+ this.place(level.items, { x: 0, y: 0, w: this.box.w, h: this.box.h }, level.path, groups, tiles);
610
+
611
+ const nextGroups = new Map<string, GroupView>();
612
+ for (const placed of groups) {
613
+ const view = this.groups.get(placed.item.id) ?? this.groupView(placed);
614
+ view.placed = placed;
615
+ view.el.firstElementChild!.textContent = placed.item.label;
616
+ position(view.el, placed);
617
+ nextGroups.set(placed.item.id, view);
618
+ }
619
+ const nextTiles = new Map<string, TileView>();
620
+ for (const placed of tiles) {
621
+ const old = this.tiles.get(placed.item.id);
622
+ const view = old ?? this.tileView(placed);
623
+ view.placed = placed;
624
+ this.fitTile(view);
625
+ position(view.el, placed);
626
+ nextTiles.set(placed.item.id, view);
627
+ }
628
+ for (const [id, view] of this.groups) if (!nextGroups.has(id)) view.el.remove();
629
+ for (const [id, view] of this.tiles) if (!nextTiles.has(id)) view.el.remove();
630
+ this.groups = nextGroups;
631
+ this.tiles = nextTiles;
632
+
633
+ // Reading order: each group's header, then its tiles. Nodes that already sit in that
634
+ // order stay put, as a moved node restarts its transitions.
635
+ const order: HTMLElement[] = [];
636
+ const headerOf = new Map(groups.map((g) => [g.item.id, nextGroups.get(g.item.id)!.el]));
637
+ const written = new Set<string>();
638
+ for (const placed of tiles) {
639
+ for (const group of placed.path) {
640
+ const header = headerOf.get(group.id);
641
+ if (header && !written.has(group.id)) {
642
+ written.add(group.id);
643
+ order.push(header);
644
+ }
645
+ }
646
+ order.push(nextTiles.get(placed.item.id)!.el);
647
+ }
648
+ const children = this.map.children;
649
+ const same = children.length === order.length && order.every((node, i) => children[i] === node);
650
+ if (!same) this.map.replaceChildren(...order);
651
+
652
+ if (this.current === null || !this.tiles.has(this.current)) this.current = tiles[0]?.item.id ?? null;
653
+ for (const [id, tile] of this.tiles) {
654
+ tile.el.tabIndex = id === this.current ? 0 : -1;
655
+ tile.el.toggleAttribute('data-selected', id === this.selected);
656
+ }
657
+ this.paint();
658
+ }
659
+
660
+ private groupView(placed: Placed): GroupView {
661
+ const name = h('span', { slot: treemapDef.slot('group-name') });
662
+ const value = h('span', { slot: treemapDef.slot('group-value') });
663
+ const drill = this.props.drill === true;
664
+ const el = drill
665
+ ? h(
666
+ 'button',
667
+ {
668
+ slot: treemapDef.slot('group'),
669
+ data: { drill: true },
670
+ attrs: { type: 'button', title: textOf(this.i18n, TEXT.zoomIn) },
671
+ },
672
+ name,
673
+ value,
674
+ )
675
+ : h('div', { slot: treemapDef.slot('group') }, name, value);
676
+ const view: GroupView = { el, value, placed };
677
+ if (drill) el.addEventListener('click', () => this.drillTo(view.placed.item.id));
678
+ return view;
679
+ }
680
+
681
+ private tileView(placed: Placed): TileView {
682
+ const el = h('button', { slot: treemapDef.slot('tile'), attrs: { type: 'button' } });
683
+ const view: TileView = { el, label: null, value: null, placed };
684
+ el.addEventListener('click', () => this.choose(view));
685
+ el.addEventListener('focus', () => {
686
+ this.current = view.placed.item.id;
687
+ for (const tile of this.tiles.values()) tile.el.tabIndex = tile === view ? 0 : -1;
688
+ this.showTipFor(view);
689
+ });
690
+ el.addEventListener('blur', () => this.hideTip());
691
+ el.addEventListener('pointerenter', () => this.showTipFor(view));
692
+ return view;
693
+ }
694
+
695
+ /** Text sized to the tile: the label from a small tile up, the value from a larger one. */
696
+ private fitTile(view: TileView): void {
697
+ const { w, h: ht } = view.placed;
698
+ const font = Math.max(10, Math.min(18, Math.min(w, ht) / 4.2));
699
+ const showLabel = w > 34 && ht > 20;
700
+ const showValue = w > 48 && ht > 38;
701
+ if (showLabel && !view.label) view.label = h('span', { slot: treemapDef.slot('tile-label') });
702
+ if (!showLabel) view.label = null;
703
+ if (showValue && !view.value) view.value = h('span', { slot: treemapDef.slot('tile-value') });
704
+ if (!showValue) view.value = null;
705
+ if (view.label) {
706
+ view.label.textContent = view.placed.item.label;
707
+ view.label.style.fontSize = `${font}px`;
708
+ }
709
+ if (view.value) view.value.style.fontSize = `${Math.max(9.5, font * 0.72)}px`;
710
+ const parts = [view.label, view.value].filter((part): part is HTMLElement => part !== null);
711
+ if (parts.length !== view.el.childElementCount || parts.some((part, i) => view.el.children[i] !== part)) view.el.replaceChildren(...parts);
712
+ }
713
+
714
+ private valueOf(item: TreemapItem): number | null {
715
+ const value = this.values.has(item.id) ? this.values.get(item.id)! : (item.value ?? null);
716
+ return value === null || !Number.isFinite(value) ? null : value;
717
+ }
718
+
719
+ private leafValues(item: TreemapItem): number[] {
720
+ if (!item.children) {
721
+ const value = this.valueOf(item);
722
+ return value === null ? [] : [value];
723
+ }
724
+ return item.children.flatMap((child) => this.leafValues(child));
725
+ }
726
+
727
+ private groupFigure(group: TreemapItem): number | null {
728
+ const mode = this.props.groupValue ?? 'median';
729
+ if (mode === 'none') return null;
730
+ const values = this.leafValues(group);
731
+ if (typeof mode === 'function') return mode(values, group);
732
+ if (values.length === 0) return null;
733
+ if (mode === 'sum') return values.reduce((s, v) => s + v, 0);
734
+ if (mode === 'mean') return values.reduce((s, v) => s + v, 0) / values.length;
735
+ return median(values);
736
+ }
737
+
738
+ private format(value: number): string {
739
+ return (this.props.format ?? defaultFormat)(value);
740
+ }
741
+
742
+ private paint(): void {
743
+ let largest = 0;
744
+ for (const tile of this.tiles.values()) largest = Math.max(largest, Math.abs(this.valueOf(tile.placed.item) ?? 0));
745
+ const domain = this.props.domain !== undefined && this.props.domain > 0 ? this.props.domain : largest;
746
+ for (const tile of this.tiles.values()) {
747
+ const item = tile.placed.item;
748
+ const value = this.valueOf(item);
749
+ if (item.color !== undefined) {
750
+ tile.el.dataset.tone = 'custom';
751
+ tile.el.style.setProperty('--_color', item.color);
752
+ } else tile.el.dataset.tone = toneOf(value);
753
+ tile.el.style.setProperty('--_level', value === null || domain === 0 ? '0' : String(Math.min(Math.abs(value) / domain, 1)));
754
+ const text = value === null ? '' : this.format(value);
755
+ if (tile.value) tile.value.textContent = text;
756
+ tile.el.setAttribute('aria-label', text === '' ? item.label : `${item.label} ${text}`);
757
+ }
758
+ for (const group of this.groups.values()) {
759
+ const figure = this.groupFigure(group.placed.item);
760
+ group.value.textContent = figure === null ? '' : this.format(figure);
761
+ group.value.dataset.tone = toneOf(figure);
762
+ const name = group.placed.item.label;
763
+ group.el.setAttribute('aria-label', figure === null ? name : `${name} ${this.format(figure)}`);
764
+ }
765
+ if (this.legend) {
766
+ this.legend.low.textContent = domain > 0 ? this.format(-domain) : '';
767
+ this.legend.high.textContent = domain > 0 ? this.format(domain) : '';
768
+ }
769
+ const shown = this.tipFor !== null ? this.tiles.get(this.tipFor) : undefined;
770
+ if (shown) this.showTipFor(shown);
771
+ else this.hideTip();
772
+ }
773
+
774
+ private choose(view: TileView): void {
775
+ this.props.onSelect?.(view.placed.item, view.placed.path);
776
+ }
777
+
778
+ private tipContent(view: TileView): string | Node | null {
779
+ const { item, path } = view.placed;
780
+ if (this.props.tip === false) return null;
781
+ if (this.props.tip) return this.props.tip(item, path);
782
+ const value = this.valueOf(item);
783
+ return h(
784
+ 'div',
785
+ {},
786
+ h('div', {}, h('b', { text: item.label }), value === null ? null : h('span', { text: ` ${this.format(value)}`, data: { tone: toneOf(value) } })),
787
+ path.length > 0 ? h('small', { text: path.map((g) => g.label).join(' › ') }) : null,
788
+ );
789
+ }
790
+
791
+ private showTipFor(view: TileView): void {
792
+ const content = this.tipContent(view);
793
+ if (content === null) return;
794
+ this.tipFor = view.placed.item.id;
795
+ const { x, y, w, h: ht } = view.placed;
796
+ showTip(this.tip, content, { w: this.el.clientWidth, h: this.el.clientHeight }, this.map.offsetLeft + x + w / 2, this.map.offsetTop + y + ht / 2);
797
+ }
798
+
799
+ private hideTip(): void {
800
+ this.tipFor = null;
801
+ this.tip.hidden = true;
802
+ }
803
+
804
+ /** Arrows move to the nearest tile that way, Home and End to the first and the last. */
805
+ private onKey(e: KeyboardEvent): void {
806
+ const from = this.current !== null ? this.tiles.get(this.current) : undefined;
807
+ if (!from || !(e.target instanceof HTMLElement) || e.target.dataset.slot !== treemapDef.slot('tile')) return;
808
+ const list = [...this.tiles.values()];
809
+ let next: TileView | undefined;
810
+ if (e.key === 'Home') next = list[0];
811
+ else if (e.key === 'End') next = list[list.length - 1];
812
+ else {
813
+ const dir = { ArrowRight: [1, 0], ArrowLeft: [-1, 0], ArrowDown: [0, 1], ArrowUp: [0, -1] }[e.key];
814
+ if (!dir) return;
815
+ const cx = from.placed.x + from.placed.w / 2;
816
+ const cy = from.placed.y + from.placed.h / 2;
817
+ let best = Infinity;
818
+ for (const tile of list) {
819
+ if (tile === from) continue;
820
+ const dx = tile.placed.x + tile.placed.w / 2 - cx;
821
+ const dy = tile.placed.y + tile.placed.h / 2 - cy;
822
+ const along = dx * dir[0]! + dy * dir[1]!;
823
+ if (along <= 0) continue;
824
+ const across = Math.abs(dx * dir[1]! - dy * dir[0]!);
825
+ const score = along + across * 2;
826
+ if (score < best) {
827
+ best = score;
828
+ next = tile;
829
+ }
830
+ }
831
+ }
832
+ if (!next) return;
833
+ e.preventDefault();
834
+ next.el.focus();
835
+ }
836
+ }
837
+
838
+ function position(el: HTMLElement, box: TreemapRect): void {
839
+ el.style.left = `${box.x}px`;
840
+ el.style.top = `${box.y}px`;
841
+ el.style.width = `${box.w}px`;
842
+ el.style.height = `${box.h}px`;
843
+ }
844
+
845
+ export function createTreemap(props: TreemapProps = {}): TreemapHandle {
846
+ return new TreemapImpl(props);
847
+ }