@k2b/editor 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k2b/editor",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Configurable Markdown editor for SolidJS: editor, toolbar, bubble menu, and slash menu on one shared state.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -69,8 +69,8 @@
69
69
  "@codemirror/search": "6.7.2",
70
70
  "@codemirror/state": "6.7.1",
71
71
  "@codemirror/view": "6.43.7",
72
- "@k2b/stdlib": "0.30.0",
73
- "@k2b/ui": "0.51.0",
72
+ "@k2b/stdlib": "0.31.1",
73
+ "@k2b/ui": "0.53.0",
74
74
  "@lezer/common": "1.5.3",
75
75
  "@lezer/highlight": "1.2.4",
76
76
  "@lezer/markdown": "1.7.2",
package/src/Toolbar.tsx CHANGED
@@ -51,6 +51,11 @@ export type ToolbarProps = {
51
51
  class?: string;
52
52
  /** Class of the scrolling action row inside. */
53
53
  toolsClass?: string;
54
+ /**
55
+ * With a class, `start`, the action row, and dictation share one wrapper with this class, and `end` stands beside
56
+ * it, so a host can draw them as two floating pills at the edges of its column.
57
+ */
58
+ mainClass?: string;
54
59
  /**
55
60
  * On touch screens with an open keyboard, lift the toolbar to the keyboard's top edge while the editor has focus,
56
61
  * and give up the same height in the page above it, so the caret line stays visible.
@@ -201,18 +206,8 @@ export function Toolbar(props: ToolbarProps) {
201
206
  measure();
202
207
  });
203
208
 
204
- return (
205
- // Pointer presses on any control, menu items included, keep focus and selection in the editor. A native listener,
206
- // because the menus are popovers inside this element and must not depend on delegation reaching them.
207
- <div
208
- ref={root}
209
- class={props.class ?? "k2b-editor-toolbar flex min-w-0 items-center gap-2 text-dimmed"}
210
- // The stylesheet sizes every control's icon here, the host's start and end controls included.
211
- data-k2b-editor-toolbar=""
212
- data-dictating={dictating() ? "" : undefined}
213
- style={{ "margin-bottom": lift() ? `${lift()}px` : undefined }}
214
- on:mousedown={(event) => event.preventDefault()}
215
- >
209
+ const main = () => (
210
+ <>
216
211
  {props.start}
217
212
  <Show when={!dictating()} fallback={<DictationBar dictation={dictation} />}>
218
213
  <UiToolbar label={props.label ?? t().formatting} class={props.toolsClass ?? "no-scrollbar min-w-0 flex-1 overflow-x-auto"}>
@@ -243,6 +238,24 @@ export function Toolbar(props: ToolbarProps) {
243
238
  <Show when={props.dictation && !dictating()}>
244
239
  <DictationButton dictation={dictation} size="xs" class="text-dimmed" />
245
240
  </Show>
241
+ </>
242
+ );
243
+
244
+ return (
245
+ // Pointer presses on any control, menu items included, keep focus and selection in the editor. A native listener,
246
+ // because the menus are popovers inside this element and must not depend on delegation reaching them.
247
+ <div
248
+ ref={root}
249
+ class={props.class ?? "k2b-editor-toolbar flex min-w-0 items-center gap-2 text-dimmed"}
250
+ // The stylesheet sizes every control's icon here, the host's start and end controls included.
251
+ data-k2b-editor-toolbar=""
252
+ data-dictating={dictating() ? "" : undefined}
253
+ style={{ "margin-bottom": lift() ? `${lift()}px` : undefined }}
254
+ on:mousedown={(event) => event.preventDefault()}
255
+ >
256
+ <Show when={props.mainClass} fallback={main()}>
257
+ {(mainClass) => <div class={mainClass()}>{main()}</div>}
258
+ </Show>
246
259
  {props.end}
247
260
  </div>
248
261
  );
@@ -14,6 +14,6 @@ export const chartLocaleSchema = () =>
14
14
  }, "Use a valid BCP 47 locale, such as de-DE.");
15
15
 
16
16
  /** The portable renderers which honour an explicit locale. Keep one policy for single charts and groups. */
17
- const localeKinds = new Set(["sankey", "treemap", "pareto", "bubble", "radar"]);
17
+ const localeKinds = new Set(["treemap", "pareto", "bubble", "radar", "sankey"]);
18
18
  export const chartAcceptsLocale = (chart: { kind?: string; layout?: string }): boolean =>
19
19
  chart.kind === "heatmap" ? chart.layout === "calendar" : localeKinds.has(chart.kind ?? "");
@@ -1,5 +1,5 @@
1
1
  import type { ChartInput, ChartLimits } from "@k2b/ui/charts";
2
- import { CALENDAR_MAX_DAYS, calendarDay } from "@k2b/ui/charts/core";
2
+ import { CALENDAR_MAX_DAYS, calendarDay, lineDetailsEnabled, nestedDotOptions, sankeyGraph } from "@k2b/ui/charts/core";
3
3
  import { z } from "zod";
4
4
  import { chartLocaleSchema } from "./chart-locale";
5
5
 
@@ -35,6 +35,7 @@ export const chartKindSchema = () =>
35
35
  "area",
36
36
  "bar",
37
37
  "hbar",
38
+ "funnel",
38
39
  "line",
39
40
  "scatter",
40
41
  "pie",
@@ -46,6 +47,11 @@ export const chartKindSchema = () =>
46
47
  "heatmap",
47
48
  "barGauge",
48
49
  "stat",
50
+ "treemap",
51
+ "pareto",
52
+ "bubble",
53
+ "radar",
54
+ "sankey",
49
55
  ]);
50
56
 
51
57
  export const chartParts = (limits?: ChartLimits) => {
@@ -96,6 +102,7 @@ export const chartParts = (limits?: ChartLimits) => {
96
102
  );
97
103
  return {
98
104
  ChartLabel,
105
+ ChartCoordinate: z.union([z.number(), ChartDate]),
99
106
  ChartTooltip,
100
107
  ChartNumber,
101
108
  list,
@@ -110,13 +117,26 @@ export const chartParts = (limits?: ChartLimits) => {
110
117
  }),
111
118
  ChartCategory: z.object({ label: ChartLabel, value: ChartNumber }),
112
119
  ChartSlice: z.object({ label: ChartLabel, value: limits ? z.number().min(0) : ChartNumber }),
113
- ChartSeries: (points: z.ZodArray<typeof ChartPoint>) =>
120
+ ChartSeries: <T extends z.ZodType>(points: z.ZodArray<T>) =>
114
121
  z.object({
115
122
  label: ChartLabel.optional(),
116
123
  data: points,
117
124
  role: z.literal("reference").optional(),
118
125
  }),
119
126
  ChartPoints: list(ChartPoint, 0, limits?.maxValues),
127
+ ChartLinePoints: list(
128
+ ChartPoint.extend({
129
+ y: (limits
130
+ ? z
131
+ .number()
132
+ .nullable()
133
+ .transform((value) => value ?? Number.NaN)
134
+ : ChartNumber
135
+ ).describe("line: value; null is a gap only with forecast, zero, threshold, marker or legendValues enabled."),
136
+ }),
137
+ 0,
138
+ limits?.maxValues,
139
+ ),
120
140
  ChartBins: z
121
141
  .union([
122
142
  limits ? z.number().int().min(1).max(limits?.maxValues) : z.number().int().min(1),
@@ -151,7 +171,9 @@ export const chartKinds = (limits?: ChartLimits) => {
151
171
  ChartCommon,
152
172
  ChartTooltip,
153
173
  ChartLabel,
174
+ ChartCoordinate,
154
175
  ChartPoints,
176
+ ChartLinePoints,
155
177
  ChartSeries,
156
178
  ChartSlice,
157
179
  ChartReferences,
@@ -217,8 +239,15 @@ export const chartKinds = (limits?: ChartLimits) => {
217
239
  1,
218
240
  limits?.maxSeries,
219
241
  ).optional(),
220
- layout: z.enum(["columns", "rows", "grouped", "stacked"]).optional(),
242
+ layout: z.enum(["columns", "rows", "grouped", "stacked", "nested"]).optional(),
221
243
  normalize: z.boolean().optional(),
244
+ marks: z.enum(["bars", "dots"]).optional(),
245
+ total: z.number().positive().optional(),
246
+ dots: z.number().int().min(2).optional(),
247
+ share: z.boolean().optional(),
248
+ limit: z.number().int().positive().optional(),
249
+ tone: z.enum(["in", "out"]).optional(),
250
+ format: numberFormat.optional(),
222
251
  compare: z.object({ label: ChartLabel, data: list(ChartNumber.nullable(), 0, limits?.maxValues) }).optional(),
223
252
  xAxis: ChartAxis.pick({ label: true }).extend({ ordered: z.boolean().optional() }).strict().optional(),
224
253
  yAxis: ChartAxis.optional(),
@@ -231,19 +260,36 @@ export const chartKinds = (limits?: ChartLimits) => {
231
260
  const issue = (message: string) => ctx.addIssue({ code: "custom", message });
232
261
  if (limits && !bar.series && !bar.data.length)
233
262
  ctx.addIssue({ code: "custom", path: ["data"], message: "A bar chart needs data or aligned series." });
263
+ if ((bar.share !== undefined || bar.limit !== undefined || bar.tone !== undefined) && bar.layout !== "rows")
264
+ issue("Share, limit and tone require rows layout.");
265
+ if (
266
+ (bar.share !== undefined || bar.limit !== undefined || bar.tone !== undefined) &&
267
+ bar.data.some((d) => Number.isFinite(d.value) && d.value < 0)
268
+ )
269
+ issue("Share, limit and tone need nonnegative values.");
234
270
  if (bar.series) {
235
271
  if (!bar.x || bar.series.some((s) => s.data.length !== bar.x?.length)) issue("Bar series must have the same length as x.");
236
272
  if (bar.data.length) issue("Use data or aligned series, not both.");
237
273
  if (bar.layout === "rows" || bar.layout === "columns") issue("Series bars use grouped or stacked layout.");
238
- } else if (bar.x || bar.compare || bar.layout === "grouped" || bar.layout === "stacked")
274
+ } else if (bar.x || bar.compare || bar.layout === "grouped" || bar.layout === "stacked" || bar.layout === "nested")
239
275
  issue("This layout needs aligned x and series.");
240
276
  if (bar.layout === "stacked" && bar.yAxis?.scale === "log") issue("Stacked bars need a linear axis.");
241
277
  if (bar.normalize && bar.layout !== "stacked") issue("Normalized bars must be stacked.");
278
+ nestedDotOptions(bar, issue);
242
279
  if (bar.layout === "stacked" && bar.series?.some((s) => s.data.some((v) => v !== null && v < 0)))
243
280
  issue("Stacked bars require nonnegative values.");
244
- if (bar.compare && (bar.series?.length !== 1 || bar.compare.data.length !== bar.x?.length || bar.layout === "stacked"))
281
+ if (
282
+ bar.compare &&
283
+ (bar.series?.length !== 1 || bar.compare.data.length !== bar.x?.length || bar.layout === "stacked" || bar.layout === "nested")
284
+ )
245
285
  issue("Comparison needs one current series and aligned previous values.");
246
286
  }),
287
+ z.object({
288
+ kind: z.literal("funnel"),
289
+ ...ChartKindCommon,
290
+ data: list(z.object({ label: ChartLabel, value: z.number().nonnegative().nullable() }), 1, limits?.maxValues),
291
+ format: numberFormat.optional(),
292
+ }),
247
293
  z
248
294
  .object({
249
295
  kind: z.literal("hbar"),
@@ -265,25 +311,78 @@ export const chartKinds = (limits?: ChartLimits) => {
265
311
  if (bar.rows.some((r) => r.values.length !== bar.series.length))
266
312
  ctx.addIssue({ code: "custom", message: "Horizontal bar values must match series." });
267
313
  }),
268
- z.object({
269
- kind: z.literal("line"),
270
- ...ChartKindCommon,
271
- series: list(
272
- ChartSeries(
273
- limits
274
- ? ChartPoints.min(2, "A line needs at least two points per series; show single values as a bar or scatter chart.")
275
- : ChartPoints,
276
- ).extend({ style: z.enum(["solid", "dashed", "dotted"]).optional() }),
277
- 1,
278
- limits?.maxSeries,
279
- ),
280
- xAxis: ChartAxis.optional(),
281
- yAxis: ChartAxis.optional(),
282
- legend: z.boolean().optional(),
283
- area: z.boolean().optional(),
284
- smooth: z.boolean().optional(),
285
- references: ChartReferences.optional(),
286
- }),
314
+ z
315
+ .object({
316
+ kind: z.literal("line"),
317
+ ...ChartKindCommon,
318
+ series: list(
319
+ ChartSeries(
320
+ limits
321
+ ? ChartLinePoints.min(2, "A line needs at least two points per series; show single values as a bar or scatter chart.")
322
+ : ChartLinePoints,
323
+ ).extend({ style: z.enum(["solid", "dashed", "dotted"]).optional() }),
324
+ 1,
325
+ limits?.maxSeries,
326
+ ),
327
+ xAxis: ChartAxis.optional(),
328
+ yAxis: ChartAxis.optional(),
329
+ legend: z.boolean().optional(),
330
+ area: z.boolean().optional(),
331
+ smooth: z.boolean().optional(),
332
+ step: z.enum(["after", "before", "middle"]).optional(),
333
+ zero: z.boolean().optional(),
334
+ legendValues: z.boolean().optional(),
335
+ forecast: z
336
+ .object({
337
+ from: ChartCoordinate,
338
+ band: list(z.tuple([z.number(), z.number()]), 0, limits?.maxValues).optional(),
339
+ })
340
+ .optional(),
341
+ threshold: z.object({ value: z.number(), label: ChartLabel }).optional(),
342
+ marker: z.object({ at: ChartCoordinate, label: ChartLabel }).optional(),
343
+ references: ChartReferences.optional(),
344
+ })
345
+ .superRefine((spec, ctx) => {
346
+ if (limits && !lineDetailsEnabled(spec))
347
+ spec.series.forEach((series, seriesIndex) => {
348
+ series.data.forEach((point, pointIndex) => {
349
+ if (!Number.isFinite(point.y))
350
+ ctx.addIssue({
351
+ code: "custom",
352
+ path: ["series", seriesIndex, "data", pointIndex, "y"],
353
+ message: "Null gaps require forecast, zero, threshold, marker or legendValues enabled.",
354
+ });
355
+ });
356
+ });
357
+ const coordinate = (x: number | string) => (typeof x === "number" ? x : chartDateTime(x));
358
+ const at = spec.marker && coordinate(spec.marker.at);
359
+ if (at !== undefined && spec.xAxis?.domain && (at < spec.xAxis.domain[0]! || at > spec.xAxis.domain[1]!))
360
+ ctx.addIssue({ code: "custom", path: ["marker", "at"], message: "Marker must be inside the explicit X domain." });
361
+ if (!spec.forecast) return;
362
+ const from = coordinate(spec.forecast.from);
363
+ const points = spec.series[0]?.data ?? [];
364
+ if (!points.some((point) => coordinate(point.x) === from)) {
365
+ ctx.addIssue({ code: "custom", path: ["forecast", "from"], message: "Forecast must start at an X value of the first series." });
366
+ }
367
+ const count = points.filter((point) => {
368
+ const x = coordinate(point.x);
369
+ return x !== undefined && from !== undefined && x >= from;
370
+ }).length;
371
+ if (spec.forecast.band && spec.forecast.band.length !== count)
372
+ ctx.addIssue({
373
+ code: "custom",
374
+ path: ["forecast", "band"],
375
+ message: "Forecast band must match the first series from forecast.from, ordered by X.",
376
+ });
377
+ spec.forecast.band?.forEach(([lo, hi], index) => {
378
+ if (lo > hi)
379
+ ctx.addIssue({
380
+ code: "custom",
381
+ path: ["forecast", "band", index],
382
+ message: "Forecast lower bound must not exceed its upper bound.",
383
+ });
384
+ });
385
+ }),
287
386
  z.object({
288
387
  kind: z.literal("scatter"),
289
388
  ...ChartKindCommon,
@@ -398,6 +497,114 @@ export const chartKinds = (limits?: ChartLimits) => {
398
497
  better: z.enum(["up", "down"]).optional(),
399
498
  sparkline: list(ChartNumber, 2, limits?.maxValues).optional(),
400
499
  }),
500
+ z
501
+ .object({
502
+ kind: z.literal("treemap"),
503
+ ...ChartKindCommon,
504
+ groups: list(ChartLabel, 1, limits?.maxSeries),
505
+ data: list(z.object({ label: ChartLabel, group: ChartLabel, value: z.number().nonnegative() }), 1, limits?.maxMarks),
506
+ legend: z.boolean().optional(),
507
+ format: numberFormat.optional(),
508
+ locale: chartLocaleSchema().optional(),
509
+ })
510
+ .superRefine((spec, ctx) => {
511
+ if (!Number.isFinite(spec.data.reduce((sum, d) => sum + d.value, 0)))
512
+ ctx.addIssue({ code: "custom", message: "Treemap total must be finite." });
513
+ if (spec.data.some((d) => !spec.groups.includes(d.group)))
514
+ ctx.addIssue({ code: "custom", message: "Treemap groups must contain every item group." });
515
+ }),
516
+ z
517
+ .object({
518
+ kind: z.literal("pareto"),
519
+ ...ChartKindCommon,
520
+ labels: z.tuple([ChartLabel, ChartLabel]),
521
+ data: list(
522
+ z.object({ label: ChartLabel, value: z.number().nonnegative(), prev: z.number().nonnegative(), rest: z.boolean().optional() }),
523
+ 1,
524
+ limits?.maxValues,
525
+ ),
526
+ format: numberFormat.optional(),
527
+ locale: chartLocaleSchema().optional(),
528
+ })
529
+ .superRefine((spec, ctx) => {
530
+ if (!Number.isFinite(spec.data.reduce((sum, d) => sum + d.value, 0)))
531
+ ctx.addIssue({ code: "custom", message: "Pareto total must be finite." });
532
+ }),
533
+ z
534
+ .object({
535
+ kind: z.literal("sankey"),
536
+ ...ChartKindCommon,
537
+ nodes: list(
538
+ z.object({
539
+ id: z.string().min(1),
540
+ label: ChartLabel,
541
+ tone: z.enum(["in", "out", "muted", "blue", "green", "amber", "red", "violet", "tax"]).optional(),
542
+ }),
543
+ 1,
544
+ limits?.maxValues,
545
+ ),
546
+ links: list(z.object({ source: z.string(), target: z.string(), value: z.number().positive() }), 1, limits?.maxMarks),
547
+ legend: list(
548
+ z.object({ tone: z.enum(["in", "out", "muted", "blue", "green", "amber", "red", "violet", "tax"]), label: ChartLabel }),
549
+ 0,
550
+ limits?.maxSeries,
551
+ ).optional(),
552
+ format: numberFormat.optional(),
553
+ locale: chartLocaleSchema().optional(),
554
+ })
555
+ .superRefine((spec, ctx) => {
556
+ try {
557
+ sankeyGraph(spec);
558
+ } catch (error) {
559
+ ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : "Invalid Sankey graph." });
560
+ }
561
+ }),
562
+ z
563
+ .object({
564
+ kind: z.literal("bubble"),
565
+ ...ChartKindCommon,
566
+ groups: list(ChartLabel, 1, limits?.maxSeries),
567
+ data: list(
568
+ z.object({ label: ChartLabel, group: ChartLabel, x: z.number(), y: z.number(), size: z.number().nonnegative().optional() }),
569
+ 1,
570
+ limits?.maxMarks,
571
+ ),
572
+ xLabel: ChartLabel,
573
+ yLabel: ChartLabel,
574
+ sizeLabel: ChartLabel.optional(),
575
+ averages: z.boolean().optional(),
576
+ legend: z.boolean().optional(),
577
+ xFormat: numberFormat.optional(),
578
+ yFormat: numberFormat.optional(),
579
+ format: numberFormat.optional(),
580
+ locale: chartLocaleSchema().optional(),
581
+ })
582
+ .superRefine((spec, ctx) => {
583
+ if (spec.data.some((p) => !spec.groups.includes(p.group)))
584
+ ctx.addIssue({ code: "custom", message: "Bubble groups must contain every point group." });
585
+ for (const key of ["x", "y"] as const)
586
+ if (!Number.isFinite(Math.max(0, ...spec.data.map((p) => p[key])) - Math.min(0, ...spec.data.map((p) => p[key]))))
587
+ ctx.addIssue({ code: "custom", message: "Bubble coordinate ranges must be finite." });
588
+ }),
589
+ z
590
+ .object({
591
+ kind: z.literal("radar"),
592
+ ...ChartKindCommon,
593
+ axes: z.array(ChartLabel).min(3).max(8),
594
+ max: z.number().positive(),
595
+ unit: ChartUnit.optional(),
596
+ series: z
597
+ .array(z.object({ label: ChartLabel, data: z.array(z.number().nonnegative()).min(3).max(8) }))
598
+ .min(1)
599
+ .max(4),
600
+ format: numberFormat.optional(),
601
+ legend: z.boolean().optional(),
602
+ locale: chartLocaleSchema().optional(),
603
+ })
604
+ .superRefine((spec, ctx) => {
605
+ if (spec.series.some((s) => s.data.length !== spec.axes.length || s.data.some((v) => v > spec.max)))
606
+ ctx.addIssue({ code: "custom", message: "Radar series need one value per axis between zero and the common maximum." });
607
+ }),
401
608
  ]);
402
609
  };
403
610
 
package/src/charts.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  type AreaOptions,
5
5
  autoBin,
6
6
  type BarChartOptions,
7
+ type BubbleOptions,
7
8
  barChartLayout,
8
9
  barGauge,
9
10
  boxplot,
@@ -13,23 +14,37 @@ import {
13
14
  computeDomain,
14
15
  donut,
15
16
  extendDomainToNice,
17
+ type FunnelOptions,
16
18
  gauge,
17
19
  type HeatmapChartOptions,
18
20
  type HorizontalBarOptions,
19
21
  hbarLayout,
20
22
  histogram,
21
23
  line,
24
+ lineDetailsEnabled,
22
25
  niceLogTicks,
23
26
  niceStep,
27
+ type ParetoOptions,
24
28
  pie,
29
+ type RadarOptions,
30
+ rankedBarLayout,
25
31
  renderAreaSvg,
26
32
  renderBarChartSvg,
33
+ renderBubbleSvg,
34
+ renderFunnelSvg,
27
35
  renderHbarSvg,
28
36
  renderHeatmapSvg,
37
+ renderParetoSvg,
38
+ renderRadarSvg,
39
+ renderSankeySvg,
40
+ renderTreemapSvg,
29
41
  renderWaterfallSvg,
42
+ type SankeyOptions,
43
+ sankeyGraph,
30
44
  scatter,
31
45
  sparkline,
32
46
  stat,
47
+ type TreemapOptions,
33
48
  type WaterfallOptions,
34
49
  } from "@k2b/ui/charts/core";
35
50
  import { z } from "zod";
@@ -38,19 +53,31 @@ import { type ChartFormat, type ChartInput, type ChartNumberFormat, chartDateTim
38
53
  export * from "./chart-schema";
39
54
 
40
55
  type RenderOptions = {
41
- [K in ChartInput["kind"]]: { kind: K } & (K extends "hbar"
42
- ? HorizontalBarOptions
43
- : K extends "waterfall"
44
- ? WaterfallOptions
45
- : K extends "area"
46
- ? AreaOptions
47
- : K extends "heatmap"
48
- ? HeatmapChartOptions
49
- : K extends "bar"
50
- ? BarChartOptions & { data: NonNullable<BarChartOptions["data"]> }
51
- : K extends keyof typeof charts
52
- ? Omit<Parameters<(typeof charts)[K]>[0], "width" | "height" | "inspect">
53
- : never);
56
+ [K in ChartInput["kind"]]: { kind: K } & (K extends "funnel"
57
+ ? FunnelOptions
58
+ : K extends "hbar"
59
+ ? HorizontalBarOptions
60
+ : K extends "waterfall"
61
+ ? WaterfallOptions
62
+ : K extends "area"
63
+ ? AreaOptions
64
+ : K extends "treemap"
65
+ ? TreemapOptions
66
+ : K extends "pareto"
67
+ ? ParetoOptions
68
+ : K extends "bubble"
69
+ ? BubbleOptions
70
+ : K extends "radar"
71
+ ? RadarOptions
72
+ : K extends "sankey"
73
+ ? SankeyOptions
74
+ : K extends "heatmap"
75
+ ? HeatmapChartOptions
76
+ : K extends "bar"
77
+ ? BarChartOptions & { data: NonNullable<BarChartOptions["data"]> }
78
+ : K extends keyof typeof charts
79
+ ? Omit<Parameters<(typeof charts)[K]>[0], "width" | "height" | "inspect">
80
+ : never);
54
81
  }[ChartInput["kind"]];
55
82
 
56
83
  /**
@@ -65,7 +92,16 @@ const labels = /* @__PURE__ */ i18n.define({
65
92
  messages: {
66
93
  en: {
67
94
  category: "Category",
95
+ flow: "Flow",
96
+ size: "Size",
97
+ axis: "Axis",
68
98
  series: "Series",
99
+ group: "Group",
100
+ previous: "Previous",
101
+ change: "Change",
102
+ cumulative: "Cumulative",
103
+ incoming: "Incoming",
104
+ outgoing: "Outgoing",
69
105
  balance: "Balance",
70
106
  before: "Balance before",
71
107
  inflow: "In",
@@ -85,11 +121,25 @@ const labels = /* @__PURE__ */ i18n.define({
85
121
  q3: "Q3",
86
122
  whiskerLow: "Whisker low",
87
123
  whiskerHigh: "Whisker high",
124
+ forecastLow: "Lower forecast bound",
125
+ forecastHigh: "Upper forecast bound",
88
126
  delta: "Change",
127
+ startShare: "Share of start",
128
+ previousShare: "Share of previous step",
129
+ rank: "Rank",
89
130
  },
90
131
  de: {
91
132
  category: "Kategorie",
133
+ flow: "Fluss",
134
+ size: "Größe",
135
+ axis: "Achse",
92
136
  series: "Datenreihe",
137
+ group: "Bereich",
138
+ previous: "Vorher",
139
+ change: "Änderung",
140
+ cumulative: "Kumuliert",
141
+ incoming: "Eingang",
142
+ outgoing: "Ausgang",
93
143
  balance: "Stand",
94
144
  before: "Stand davor",
95
145
  inflow: "Rein",
@@ -109,7 +159,12 @@ const labels = /* @__PURE__ */ i18n.define({
109
159
  q3: "Q3",
110
160
  whiskerLow: "Unterer Whisker",
111
161
  whiskerHigh: "Oberer Whisker",
162
+ forecastLow: "Untere Prognosegrenze",
163
+ forecastHigh: "Obere Prognosegrenze",
112
164
  delta: "Änderung",
165
+ startShare: "Anteil am Start",
166
+ previousShare: "Anteil am vorigen Schritt",
167
+ rank: "Rang",
113
168
  },
114
169
  },
115
170
  });
@@ -153,8 +208,21 @@ const axis = ({ domain, format: _format, ...value }: ChartAxisInput = {}, format
153
208
  format,
154
209
  });
155
210
 
156
- export const chartReferenceValues = (input: ChartInput, name: "x" | "y") =>
157
- "references" in input ? (input.references ?? []).filter((ref) => (ref.axis ?? "y") === name).map((ref) => dateTime(ref.value)) : [];
211
+ export const chartReferenceValues = (input: ChartInput, name: "x" | "y") => {
212
+ const values =
213
+ "references" in input ? (input.references ?? []).filter((ref) => (ref.axis ?? "y") === name).map((ref) => dateTime(ref.value)) : [];
214
+ if (input.kind === "line") {
215
+ if (name === "x") {
216
+ if (input.forecast) values.push(dateTime(input.forecast.from));
217
+ if (input.marker) values.push(dateTime(input.marker.at));
218
+ } else {
219
+ if (input.threshold) values.push(input.threshold.value);
220
+ if (input.zero) values.push(0);
221
+ for (const bounds of input.forecast?.band ?? []) values.push(...bounds);
222
+ }
223
+ }
224
+ return values;
225
+ };
158
226
 
159
227
  /** The value axes of a chart with what they show: the data checks and the label room read them alike. */
160
228
  export const chartValueAxes = (input: ChartInput): { values: number[]; axis?: ChartAxisInput; zero?: boolean; name: "x" | "y" }[] => {
@@ -279,6 +347,12 @@ const numberFormat = (format: ChartFormat | undefined) => (format && !("date" in
279
347
  /** The values a chart writes with its value format, for whole-number currency. */
280
348
  const formattedValues = (input: ChartInput): number[] => {
281
349
  switch (input.kind) {
350
+ case "sankey":
351
+ return input.links.map((link) => link.value);
352
+ case "bubble":
353
+ return input.data.flatMap((p) => (p.size === undefined ? [] : [p.size]));
354
+ case "radar":
355
+ return input.series.flatMap((s) => s.data);
282
356
  case "waterfall":
283
357
  return [input.start.value, ...input.steps.map((step) => step.value)];
284
358
  case "area":
@@ -295,6 +369,10 @@ const formattedValues = (input: ChartInput): number[] => {
295
369
  ];
296
370
  case "hbar":
297
371
  return input.rows.flatMap((r) => r.values.filter((v): v is number => v !== null));
372
+ case "funnel":
373
+ return input.data.flatMap((d) => (d.value === null ? [] : [d.value]));
374
+ case "treemap":
375
+ case "pareto":
298
376
  case "pie":
299
377
  case "donut":
300
378
  return input.data.map((item) => item.value);
@@ -318,15 +396,16 @@ const formattedValues = (input: ChartInput): number[] => {
318
396
  }
319
397
  };
320
398
  const formats = (input: ChartInput, locale: string): Formats => {
321
- const yFormat = "yAxis" in input ? numberFormat(input.yAxis?.format) : "format" in input ? input.format : undefined;
399
+ const yFormat = ("yAxis" in input ? numberFormat(input.yAxis?.format) : undefined) ?? ("format" in input ? input.format : undefined);
322
400
  const y = chartNumberFormatters(yFormat, locale, formattedValues(input));
323
401
  const xFormat = "xAxis" in input && input.kind !== "bar" ? input.xAxis?.format : undefined;
324
402
  const x = chartNumberFormatters(numberFormat(xFormat), locale);
325
403
  // An unformatted x axis often counts years or steps, which compact notation would turn into 2.02K.
326
404
  const xTick = new Intl.NumberFormat(locale, { maximumSignificantDigits: 15, useGrouping: "min2" });
327
405
  const written = chartSeries(input).flatMap((series) => series.data.flatMap((point) => (typeof point.x === "string" ? [point.x] : [])));
328
- if (!written.length) return { ...y, x: { tick: xFormat ? x.tick : (v) => xTick.format(v), value: x.value } };
329
406
  const dateFormat = xFormat && "date" in xFormat ? xFormat.date : undefined;
407
+ if (!written.length && !(input.kind === "line" && lineDetailsEnabled(input) && dateFormat))
408
+ return { ...y, x: { tick: xFormat ? x.tick : (v) => xTick.format(v), value: x.value } };
330
409
  const times = dateFormat ? dateFormat !== "day" : written.some((date) => date.length > 10);
331
410
  const seconds = dateFormat ? dateFormat === "second" : written.some((date) => date.length > 16);
332
411
  const clock: Intl.DateTimeFormatOptions = times ? { hour: "2-digit", minute: "2-digit", ...(seconds ? { second: "2-digit" } : {}) } : {};
@@ -364,7 +443,7 @@ const thinned = <T extends { label: string }>(data: T[], left: number, width = W
364
443
  export function chartLegend(
365
444
  input: ChartInput,
366
445
  locale: string,
367
- ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean }[] {
446
+ ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean; seriesIndex?: number }[] {
368
447
  // These category renderers own their live legends, including prepared snapshots.
369
448
  if (input.kind === "hbar" || (input.kind === "bar" && input.series)) return [];
370
449
  if (input.kind === "bar")
@@ -376,6 +455,7 @@ export function chartLegend(
376
455
  return input.series.map((entry, index) => ({
377
456
  label: entry.label ?? `${t.series} ${index + 1}`,
378
457
  color: index % 8,
458
+ ...(input.kind === "line" && lineDetailsEnabled(input) ? { seriesIndex: index } : {}),
379
459
  ...(input.kind === "line" ? { style: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : "solid") } : {}),
380
460
  ...(entry.role === "reference" ? { reference: true } : {}),
381
461
  }));
@@ -398,7 +478,7 @@ export function chartRenderOptions(
398
478
  formats?: { x?: (v: number) => string; y?: (v: number) => string; value?: (v: number) => string };
399
479
  } = {},
400
480
  ): RenderOptions {
401
- if (input.kind === "heatmap" && input.layout === "calendar") locale = input.locale ?? locale;
481
+ if ("locale" in input && input.locale) locale = input.locale;
402
482
  const defaults = formats(input, locale);
403
483
  // Function formats must be measured with the same text the renderer will print.
404
484
  const format = {
@@ -411,6 +491,65 @@ export function chartRenderOptions(
411
491
  const width = options.width ?? WIDTH;
412
492
  const references = renderReferences(input);
413
493
  switch (input.kind) {
494
+ case "sankey":
495
+ return {
496
+ kind: "sankey",
497
+ nodes: input.nodes,
498
+ links: input.links,
499
+ legend: input.legend,
500
+ format: format.value,
501
+ locale: input.locale ?? locale,
502
+ displayWidth: options.width,
503
+ };
504
+ case "treemap":
505
+ return {
506
+ kind: "treemap",
507
+ legend: input.legend,
508
+ groups: input.groups,
509
+ data: input.data,
510
+ format: format.value,
511
+ locale: input.locale ?? locale,
512
+ displayWidth: options.width,
513
+ };
514
+ case "pareto":
515
+ return {
516
+ kind: "pareto",
517
+ labels: input.labels,
518
+ data: input.data,
519
+ format: format.value,
520
+ locale: input.locale ?? locale,
521
+ displayWidth: options.width,
522
+ };
523
+ case "bubble":
524
+ return {
525
+ kind: "bubble",
526
+ groups: input.groups,
527
+ data: input.data,
528
+ xLabel: input.xLabel,
529
+ yLabel: input.yLabel,
530
+ sizeLabel: input.sizeLabel,
531
+ averages: input.averages,
532
+ legend: input.legend,
533
+ locale,
534
+ displayWidth: options.width,
535
+ xFormat: options.formats?.x ?? (input.xFormat ? chartNumberFormatters(input.xFormat, locale).value : undefined),
536
+ yFormat: options.formats?.y ?? (input.yFormat ? chartNumberFormatters(input.yFormat, locale).value : undefined),
537
+ sizeFormat: format.value,
538
+ };
539
+ case "radar":
540
+ return {
541
+ kind: "radar",
542
+ axes: input.axes,
543
+ max: input.max,
544
+ unit: input.unit,
545
+ series: input.series,
546
+ legend: input.legend,
547
+ locale,
548
+ displayWidth: options.width,
549
+ format: format.value,
550
+ };
551
+ case "funnel":
552
+ return { kind: "funnel", data: input.data, valueFormat: format.value, locale };
414
553
  case "hbar":
415
554
  return {
416
555
  kind: "hbar",
@@ -455,6 +594,17 @@ export function chartRenderOptions(
455
594
  series: input.series,
456
595
  layout: input.layout,
457
596
  normalize: input.normalize,
597
+ // Rates describe each category; summing percentages across periods has no meaning.
598
+ legendValues:
599
+ input.format?.style === "percent" || (yAxis?.format && "style" in yAxis.format && yAxis.format.style === "percent")
600
+ ? "latest"
601
+ : "total",
602
+ marks: input.marks,
603
+ total: input.total,
604
+ dots: input.dots,
605
+ share: input.share,
606
+ limit: input.limit,
607
+ tone: input.tone,
458
608
  compare: input.compare,
459
609
  xAxis: input.xAxis,
460
610
  yAxis: axis(yAxis, options.formats?.y ?? format.tick),
@@ -489,7 +639,13 @@ export function chartRenderOptions(
489
639
  ...(input.kind === "line" ? { lineStyle: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : undefined) } : {}),
490
640
  }));
491
641
  const points = series.flatMap((entry) => entry.data);
492
- const xAxis = referencedAxis(input, "x");
642
+ const calendarLine =
643
+ input.kind === "line" &&
644
+ lineDetailsEnabled(input) &&
645
+ (input.series.some((entry) => entry.data.some((point) => typeof point.x === "string")) ||
646
+ (input.xAxis?.format && "date" in input.xAxis.format));
647
+ // The detailed time renderer includes references without rounding their domain to decimal milliseconds.
648
+ const xAxis = calendarLine ? input.xAxis : referencedAxis(input, "x");
493
649
  const yAxis = referencedAxis(input, "y");
494
650
  const candidates = tickCandidates([...points.map((point) => point.x), ...chartReferenceValues(input, "x")], xAxis).filter(
495
651
  Number.isFinite,
@@ -507,7 +663,21 @@ export function chartRenderOptions(
507
663
  right: Math.max(16, Math.ceil(((format.x.tick(lastTick).length * CHAR) / 2 + 4) * factor)),
508
664
  },
509
665
  };
510
- return input.kind === "line" ? { kind: "line", ...common, area: input.area, smooth: input.smooth } : { kind: "scatter", ...common };
666
+ return input.kind === "line"
667
+ ? {
668
+ kind: "line",
669
+ ...common,
670
+ area: input.area,
671
+ smooth: input.smooth,
672
+ step: input.step,
673
+ zero: input.zero,
674
+ legendValues: input.legendValues,
675
+ forecast: input.forecast ? { ...input.forecast, from: dateTime(input.forecast.from) } : undefined,
676
+ marker: input.marker ? { ...input.marker, at: dateTime(input.marker.at) } : undefined,
677
+ threshold: input.threshold,
678
+ ...(calendarLine ? { timeAxis: { timeZone: "UTC", locale } } : {}),
679
+ }
680
+ : { kind: "scatter", ...common };
511
681
  }
512
682
  case "pie":
513
683
  case "donut":
@@ -614,6 +784,18 @@ const decode = (value: string) =>
614
784
  export const drawChart = (options: RenderOptions): string => {
615
785
  const common = { width: WIDTH, height: HEIGHT, inspect: true };
616
786
  switch (options.kind) {
787
+ case "treemap":
788
+ return renderTreemapSvg({ ...options, ...common });
789
+ case "pareto":
790
+ return renderParetoSvg({ ...options, ...common });
791
+ case "sankey":
792
+ return renderSankeySvg({ ...options, ...common });
793
+ case "bubble":
794
+ return renderBubbleSvg({ ...options, ...common });
795
+ case "radar":
796
+ return renderRadarSvg({ ...options, ...common });
797
+ case "funnel":
798
+ return renderFunnelSvg({ ...options, ...common });
617
799
  case "hbar":
618
800
  return renderHbarSvg({ ...options, ...common, height: hbarLayout(options).height });
619
801
  case "waterfall":
@@ -679,10 +861,11 @@ export type ChartTable = { columns: ChartColumn[]; rows: ChartRow[] };
679
861
  export function chartTooltip(
680
862
  columns: ChartColumn[],
681
863
  row: ChartRow,
682
- kind?: ChartInput["kind"],
864
+ kind?: ChartInput["kind"] | ChartInput,
683
865
  ): { title?: string; rows: { label: string; value: string }[] } {
684
866
  if (row.tooltip) return row.tooltip;
685
- if (kind === "area")
867
+ const chartKind = typeof kind === "object" ? kind.kind : kind;
868
+ if (chartKind === "area")
686
869
  return {
687
870
  title: row.cells.x,
688
871
  rows: [{ label: row.cells.series ?? "", value: `${row.cells.percent ? `${row.cells.percent} · ` : ""}${row.cells.value ?? "—"}` }],
@@ -706,7 +889,7 @@ export function chartRows(
706
889
  locale: string,
707
890
  options: { formats?: { x?: (v: number) => string; y?: (v: number) => string; value?: (v: number) => string } } = {},
708
891
  ) {
709
- if (input.kind === "heatmap" && input.layout === "calendar") locale = input.locale ?? locale;
892
+ if ("locale" in input && input.locale) locale = input.locale;
710
893
  const t = labels.resolve([locale]).t;
711
894
  const format = formats(input, locale);
712
895
  const valueFormat = input.tooltip?.format
@@ -738,8 +921,8 @@ export function chartRows(
738
921
  const tooltip = input.kind === "waterfall" ? { title: datum.label, rows: [] as { label: string; value: string }[] } : undefined;
739
922
  const cells: Record<string, string> = {};
740
923
  const values: Record<string, string | number> = {};
741
- const cell = (id: string, label: string, value: string | number, text: string) => {
742
- if (!columns.has(id)) columns.set(id, { id, label, numeric: typeof value === "number" });
924
+ const cell = (id: string, label: string, value: string | number, text: string, numeric = typeof value === "number") => {
925
+ if (!columns.has(id)) columns.set(id, { id, label, numeric });
743
926
  cells[id] = text;
744
927
  values[id] = value;
745
928
  };
@@ -758,10 +941,37 @@ export function chartRows(
758
941
  : input.data[datum.role === "outlier" ? (datum.seriesIndex ?? 0) : datum.index]?.label) ?? datum.label)
759
942
  : datum.label;
760
943
  if (label)
761
- cell("label", input.kind === "heatmap" && input.layout === "calendar" ? calendarWords(locale).day : t.category, label, label);
944
+ cell(
945
+ "label",
946
+ input.kind === "heatmap" && input.layout === "calendar"
947
+ ? calendarWords(locale).day
948
+ : input.kind === "sankey"
949
+ ? t.flow
950
+ : input.kind === "radar"
951
+ ? t.axis
952
+ : t.category,
953
+ label,
954
+ label,
955
+ );
762
956
  }
763
957
  for (const field of datum.values) {
764
958
  const value = field.value;
959
+ if (input.kind === "bubble") {
960
+ const label =
961
+ field.key === "x"
962
+ ? input.xLabel
963
+ : field.key === "y"
964
+ ? input.yLabel
965
+ : field.key === "size"
966
+ ? (input.sizeLabel ?? t.size)
967
+ : t.group;
968
+ cell(field.key, label, value, field.formatted ?? String(value));
969
+ continue;
970
+ }
971
+ if (input.kind === "radar" && field.key.startsWith("series:")) {
972
+ cell(field.key, input.series[Number(field.key.slice(7))]!.label, value, field.formatted ?? String(value));
973
+ continue;
974
+ }
765
975
  if (typeof value === "string" && input.kind === "area" && field.key === "x") {
766
976
  cell("x", t.position, value, field.formatted ?? value);
767
977
  continue;
@@ -770,6 +980,18 @@ export function chartRows(
770
980
  cell(field.key, field.key.toUpperCase(), value, value);
771
981
  continue;
772
982
  }
983
+ if (input.kind === "treemap" && field.key === "group" && typeof value === "string") {
984
+ cell("group", t.group, value, value);
985
+ continue;
986
+ }
987
+ if (
988
+ input.kind === "pareto" &&
989
+ (field.key === "previous" || field.key === "change" || field.key === "cumulative") &&
990
+ typeof value === "number"
991
+ ) {
992
+ cell(field.key, field.key === "previous" ? input.labels[1] : t[field.key], value, field.formatted ?? valueFormat(value));
993
+ continue;
994
+ }
773
995
  if (input.kind === "hbar" || (input.kind === "bar" && input.series)) {
774
996
  const seriesIndex = field.key.startsWith("series:") ? Number(field.key.slice(7)) : undefined;
775
997
  const label =
@@ -784,7 +1006,30 @@ export function chartRows(
784
1006
  : input.kind === "hbar"
785
1007
  ? input.series[seriesIndex]!
786
1008
  : input.series![seriesIndex]!.label;
787
- cell(field.key, label, value, field.formatted ?? String(value));
1009
+ cell(field.key, label, value, field.formatted ?? String(value), true);
1010
+ continue;
1011
+ }
1012
+ if (
1013
+ field.key === "startPercent" ||
1014
+ field.key === "previousPercent" ||
1015
+ field.key === "rank" ||
1016
+ ((input.kind === "bar" || input.kind === "funnel") && typeof value === "string")
1017
+ ) {
1018
+ cell(
1019
+ field.key,
1020
+ field.key === "startPercent"
1021
+ ? t.startShare
1022
+ : field.key === "previousPercent"
1023
+ ? t.previousShare
1024
+ : field.key === "rank"
1025
+ ? t.rank
1026
+ : field.key === "percent"
1027
+ ? t.share
1028
+ : t.value,
1029
+ value,
1030
+ field.formatted ?? String(value),
1031
+ true,
1032
+ );
788
1033
  continue;
789
1034
  }
790
1035
  if (typeof value !== "number" || field.key === "total") continue;
@@ -831,17 +1076,21 @@ export function chartRows(
831
1076
  cell(
832
1077
  "value",
833
1078
  input.tooltip?.label ??
834
- (input.kind === "bar"
835
- ? input.yAxis?.label
836
- : input.kind === "heatmap" && input.layout === "calendar"
837
- ? input.label
838
- : undefined) ??
1079
+ (input.kind === "pareto"
1080
+ ? input.labels[0]
1081
+ : input.kind === "bar"
1082
+ ? input.yAxis?.label
1083
+ : input.kind === "heatmap" && input.layout === "calendar"
1084
+ ? input.label
1085
+ : undefined) ??
839
1086
  t.value,
840
1087
  value,
841
1088
  input.kind === "heatmap" && input.layout === "calendar"
842
1089
  ? (field.formatted ?? valueFormat(value))
843
1090
  : `${valueFormat(value)}${unit}`,
844
1091
  );
1092
+ else if (field.key === "incoming" || field.key === "outgoing") cell(field.key, t[field.key], value, valueFormat(value));
1093
+ else if (field.key === "forecastLow" || field.key === "forecastHigh") cell(field.key, t[field.key], value, valueFormat(value));
845
1094
  else if (field.key === "delta") cell("delta", t.delta, value, `${value > 0 ? "+" : ""}${valueFormat(value)}`);
846
1095
  else if (field.key === "q1" || field.key === "q2" || field.key === "q3" || field.key === "whiskerLow" || field.key === "whiskerHigh")
847
1096
  cell(field.key, t[field.key], value, valueFormat(value));
@@ -860,7 +1109,59 @@ export function chartRows(
860
1109
  rows.push(row);
861
1110
  return row;
862
1111
  };
863
- return { add, columns: () => [...columns.values()], table: (): ChartTable => ({ columns: [...columns.values()], rows }) };
1112
+ return {
1113
+ add,
1114
+ columns: () => [...columns.values()],
1115
+ table: (): ChartTable => {
1116
+ if (
1117
+ input.kind === "bar" &&
1118
+ input.layout === "rows" &&
1119
+ input.limit !== undefined &&
1120
+ rows.some((row) => row.values.rank !== undefined)
1121
+ ) {
1122
+ const source = { ...input, limit: undefined };
1123
+ const all = chartRows(source, locale, options);
1124
+ const layout = rankedBarLayout({ data: source.data, title: source.title, subtitle: source.subtitle, valueFormat, locale });
1125
+ for (const row of layout.rows) {
1126
+ const value = Number.isFinite(row.value) ? row.value : null;
1127
+ all.add({
1128
+ role: "item",
1129
+ index: row.index,
1130
+ label: row.label,
1131
+ anchor: [0, row.y],
1132
+ values: [
1133
+ { key: "value", value: value ?? "–", formatted: value === null ? "–" : valueFormat(value) },
1134
+ {
1135
+ key: "percent",
1136
+ value: row.share === null ? "–" : row.share * 100,
1137
+ formatted: row.share === null ? "–" : percent.format(row.share),
1138
+ },
1139
+ { key: "rank", value: row.rank },
1140
+ ],
1141
+ });
1142
+ }
1143
+ return all.table();
1144
+ }
1145
+ if (input.kind === "treemap") {
1146
+ const total = input.data.reduce((sum, item) => sum + item.value, 0);
1147
+ input.data.forEach((item, index) => {
1148
+ if (item.value !== 0 || rows.some((row) => row.key === chartMarkKey({ index }))) return;
1149
+ add({
1150
+ role: "item",
1151
+ index,
1152
+ label: item.label,
1153
+ anchor: [0, 0],
1154
+ values: [
1155
+ { key: "group", value: item.group },
1156
+ { key: "value", value: 0 },
1157
+ { key: "percent", value: 0, formatted: total ? percent.format(0) : "–" },
1158
+ ],
1159
+ });
1160
+ });
1161
+ }
1162
+ return { columns: [...columns.values()], rows };
1163
+ },
1164
+ };
864
1165
  }
865
1166
 
866
1167
  /** The data behind every mark of the chart as a table: the accessible alternative and what Copy data copies. */
@@ -873,6 +1174,20 @@ export function chartTable(input: ChartInput, locale: string): ChartTable {
873
1174
  /** Input values count against the budget, including observations summarized into boxes or bins. */
874
1175
  export const chartMarks = (input: ChartInput): number => {
875
1176
  switch (input.kind) {
1177
+ case "pareto":
1178
+ return input.data.length * 3;
1179
+ case "sankey": {
1180
+ const graph = sankeyGraph(input);
1181
+ return (
1182
+ input.nodes.length +
1183
+ input.links.reduce(
1184
+ (sum, link) => sum + graph.nodes[graph.ids.get(link.target)!]!.stage - graph.nodes[graph.ids.get(link.source)!]!.stage,
1185
+ 0,
1186
+ )
1187
+ );
1188
+ }
1189
+ case "radar":
1190
+ return input.axes.length * input.series.length;
876
1191
  case "waterfall":
877
1192
  return input.steps.length + 2;
878
1193
  case "area":
@@ -881,7 +1196,11 @@ export const chartMarks = (input: ChartInput): number => {
881
1196
  case "scatter":
882
1197
  return input.series.reduce((sum, series) => sum + series.data.length, 0);
883
1198
  case "bar":
884
- return input.series ? (input.x?.length ?? 0) * (input.series.length + (input.compare ? 1 : 0)) : input.data.length;
1199
+ return input.marks === "dots"
1200
+ ? (input.x?.length ?? 0) * (input.dots ?? 100)
1201
+ : input.series
1202
+ ? (input.x?.length ?? 0) * (input.series.length + (input.compare ? 1 : 0))
1203
+ : input.data.length;
885
1204
  case "hbar":
886
1205
  return input.rows.length * input.series.length;
887
1206
  case "boxplot":
@@ -389,7 +389,7 @@ export function createBlockPreviews(options: BlockPreviewOptions): { extension:
389
389
  }),
390
390
  );
391
391
  // A placeholder reserves the height its drawing will take; the note's charts are read once, and only for one.
392
- let heights: Map<number, number | undefined> | undefined;
392
+ let heights: Map<number, number | string | undefined> | undefined;
393
393
  const heightAt = (line: number) => {
394
394
  heights ??= new Map(
395
395
  parseNotebookChartBlocks(document, options.charts).blocks.map((entry) => [
@@ -1,6 +1,7 @@
1
1
  import { highlight, text } from "@k2b/stdlib";
2
2
  import { prepareChartSnapshot } from "@k2b/ui";
3
- import { barChartLayout, hbarLayout } from "@k2b/ui/charts";
3
+ import { barChartLayout, calendarLayout, calendarViewportHeight, hbarLayout } from "@k2b/ui/charts";
4
+ import { chartSvgWithUiPalette, paretoLayout, sankeyFrame } from "@k2b/ui/charts/core";
4
5
  import { Lexer, type Tokens } from "marked";
5
6
  import type { z } from "zod";
6
7
  import {
@@ -31,7 +32,7 @@ export type MarkdownChartOptions = {
31
32
  };
32
33
  export type ChartBlock = { line: number; input: ChartInput };
33
34
  /** `height` is the drawing's own height in CSS pixels when it needs more than the kind's frame (app.css). */
34
- type Frame = { kind: ChartInput["kind"]; area?: boolean; title: string; subtitle?: string; height?: number };
35
+ type Frame = { kind: ChartInput["kind"]; area?: boolean; title: string; subtitle?: string; height?: number | string };
35
36
  type Entry = { value: string; line: number };
36
37
  type Cell = { raw: string; result: EvalResult };
37
38
  type SourceData = { columns: string[]; rows: Cell[][]; implicit: boolean; entries?: NamedDataEntry[]; invalid?: boolean };
@@ -455,10 +456,14 @@ export const chartBlockFrame = (body: string[], options: Pick<MarkdownChartOptio
455
456
  * categories make the drawing taller. The server and an editor placeholder read it from the same parsed block, so
456
457
  * both reserve the same box. Undefined for every other drawing, which fits the frame.
457
458
  */
458
- export const notebookChartHeight = (input: ChartInput, locale: string): number | undefined => {
459
+ export const notebookChartHeight = (input: ChartInput, locale: string): number | string | undefined => {
459
460
  const options = chartRenderOptions(input, locale, { legend: "outside" });
461
+ if (options.kind === "treemap") return 280;
462
+ if (options.kind === "pareto") return paretoLayout(options).height;
463
+ if (options.kind === "sankey") return sankeyFrame(options).height;
464
+ if (options.kind === "bubble" || options.kind === "radar") return 280;
460
465
  if (options.kind === "hbar") return hbarLayout(options).height;
461
- if (options.kind === "heatmap" && options.layout === "calendar") return 280;
466
+ if (options.kind === "heatmap" && options.layout === "calendar") return calendarViewportHeight(calendarLayout(options));
462
467
  if (options.kind === "waterfall" || options.kind === "area") return 280;
463
468
  if (options.kind !== "bar") return undefined;
464
469
  const layout = barChartLayout(options);
@@ -476,7 +481,7 @@ export const notebookChartFrameHtml = (
476
481
  viewportHtml: string,
477
482
  options: { legend?: boolean; input?: ChartInput; print?: boolean } = {},
478
483
  ): string =>
479
- `<figure class="notebook-book-chart" data-kind="${frame.kind === "line" && frame.area ? "area" : frame.kind}"${options.input ? ` data-chart="${escape(JSON.stringify(options.input))}"` : ""}><figcaption class="notebook-book-chart__header"><span class="notebook-book-chart__title">${escape(frame.title)}</span>${frame.subtitle ? `<span class="notebook-book-chart__subtitle">${escape(frame.subtitle)}</span>` : ""}</figcaption>${options.print ? "" : '<div class="notebook-book-chart__actions"></div>'}<div class="notebook-book-chart__viewport"${options.legend ? ' data-legend="true"' : ""}${frame.height ? ` style="--notebook-chart-height:${frame.height}px"` : ""}>${viewportHtml}</div></figure>`;
484
+ `<figure class="notebook-book-chart"${typeof frame.height === "string" ? ' data-calendar="true" style="container-type:inline-size"' : ""} data-kind="${frame.kind === "line" && frame.area ? "area" : frame.kind}"${options.input ? ` data-chart="${escape(JSON.stringify(options.input))}"` : ""}><figcaption class="notebook-book-chart__header"><span class="notebook-book-chart__title">${escape(frame.title)}</span>${frame.subtitle ? `<span class="notebook-book-chart__subtitle">${escape(frame.subtitle)}</span>` : ""}</figcaption>${options.print ? "" : '<div class="notebook-book-chart__actions"></div>'}<div class="notebook-book-chart__viewport"${options.legend ? ' data-legend="true"' : ""}${frame.height ? ` style="--notebook-chart-height:${typeof frame.height === "number" ? `${frame.height}px` : frame.height}"` : ""}>${viewportHtml}</div></figure>`;
480
485
 
481
486
  /** A chart's data as a note table: the PDF prints it below the figure, and the table view shows it in the frame. */
482
487
  export const notebookChartTableHtml = (table: ChartTable, options: { label?: string; className?: string } = {}): string =>
@@ -490,7 +495,7 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
490
495
  key: ({ datum }) => chartMarkKey(datum),
491
496
  tooltip: ({ datum }) => {
492
497
  const row = rows.add(datum);
493
- return chartTooltip(rows.columns(), row, input.kind);
498
+ return chartTooltip(rows.columns(), row, input);
494
499
  },
495
500
  reference: ({ datum }) => chartReferenceMark(input, datum),
496
501
  });
@@ -500,9 +505,16 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
500
505
  const valueField = input.kind === "area" ? (input.normalize ? "percent" : "value") : "y";
501
506
  let lastX = -Infinity;
502
507
  for (const mark of snapshot.marks) lastX = Math.max(lastX, mark.datum.anchor[0]);
508
+ const sourceX = input.kind === "line" ? snapshot.svg.match(/data-line-default-x="([^"]+)"/)?.[1] : undefined;
503
509
  const legendValue = (index: number) => {
504
510
  const field = snapshot.marks
505
- .find((mark) => mark.datum.seriesIndex === index && mark.datum.anchor[0] === lastX)
511
+ .find(
512
+ (mark) =>
513
+ mark.datum.seriesIndex === index &&
514
+ (sourceX === undefined
515
+ ? mark.datum.anchor[0] === lastX
516
+ : mark.datum.values.some((field) => field.key === "x" && field.value === Number(sourceX))),
517
+ )
506
518
  ?.datum.values.find((field) => field.key === valueField);
507
519
  return field
508
520
  ? (field.formatted ??
@@ -512,10 +524,14 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
512
524
  : "—";
513
525
  };
514
526
  const legendHtml = legend.length
515
- ? `<ul class="k2b-chart-legend" aria-label="${escape(t.chartLegend)}">${legend.map((entry, index) => `<li><span class="k2b-chart-legend__swatch"${entry.style && entry.style !== "solid" ? ` data-style="${entry.style}"` : ""}${entry.reference ? ' data-reference="true"' : ""} style="--k2b-chart-legend-color:var(--stdlib-chart-c${(entry.color % 8) + 1})" aria-hidden="true"></span>${escape(entry.label)}${input.kind === "area" ? `<b data-chart-legend-value data-series-index="${index}" data-field="${valueField}" data-default="${escape(legendValue(index))}">${escape(legendValue(index))}</b>` : ""}</li>`).join("")}</ul>`
527
+ ? `<ul class="k2b-chart-legend" aria-label="${escape(t.chartLegend)}">${legend.map((entry, index) => `<li><span class="k2b-chart-legend__swatch"${entry.style && entry.style !== "solid" ? ` data-style="${entry.style}"` : ""}${entry.reference ? ' data-reference="true"' : ""} style="--k2b-chart-legend-color:var(--stdlib-chart-c${(entry.color % 8) + 1})" aria-hidden="true"></span>${escape(entry.label)}${(input.kind === "line" && snapshot.svg.includes("data-line-details")) || input.kind === "area" ? `<b data-chart-legend-value data-series-index="${entry.seriesIndex ?? index}" data-field="${valueField}" data-default="${escape(legendValue(entry.seriesIndex ?? index))}">${escape(legendValue(entry.seriesIndex ?? index))}</b>` : ""}</li>`).join("")}</ul>`
516
528
  : "";
517
- const viewport = `<div class="k2b-chart" data-chart-kind="${snapshot.kind}"><div class="k2b-chart__svg"${snapshot.stretch ? ' data-stretch="true"' : ""} style="${snapshot.minWidth ? "min-width:0;" : ""}--k2b-chart-width:${snapshot.width}px;--k2b-chart-height:${snapshot.height}px">${snapshot.svg}</div></div>${legendHtml}`;
518
- const height = notebookChartHeight(input, locale);
529
+ const svg = options.print ? chartSvgWithUiPalette(snapshot.svg) : snapshot.svg;
530
+ const viewport = `<div class="k2b-chart" data-chart-kind="${snapshot.kind}"><div class="k2b-chart__svg"${snapshot.stretch ? ' data-stretch="true"' : ""} style="${snapshot.minWidth ? `min-width:${options.print ? "0" : `${snapshot.minWidth}px`};max-width:${snapshot.maxWidth}px;aspect-ratio:${snapshot.width}/${snapshot.height};` : ""}--k2b-chart-width:${snapshot.width}px;--k2b-chart-height:${snapshot.height}px">${svg}</div></div>${legendHtml}`;
531
+ const height =
532
+ options.print && snapshot.maxWidth
533
+ ? `calc(min(100cqw, ${snapshot.maxWidth}px) * ${snapshot.height / snapshot.width})`
534
+ : notebookChartHeight(input, locale);
519
535
  const figure = notebookChartFrameHtml(height ? { ...input, height } : input, viewport, {
520
536
  legend: legend.length > 0,
521
537
  ...(options.print ? { print: true } : { input }),
@@ -1,7 +1,7 @@
1
1
  import { i18n } from "@k2b/stdlib";
2
2
  import { CopyButton, IconButton, LocaleProvider, prepareChartSnapshot, toast } from "@k2b/ui";
3
3
  import { type ChartTooltip, inspectChart } from "@k2b/ui/chart-inspection";
4
- import { calendarInspectionNavigation, mountCalendarScroll } from "@k2b/ui/charts";
4
+ import { calendarInspectionNavigation, mountCalendarScroll, sankeyInspectionNavigation } from "@k2b/ui/charts";
5
5
  import { createSignal, onCleanup, Show } from "solid-js";
6
6
  import { render } from "solid-js/web";
7
7
  import { type ChartInput, type ChartTable, chartMarkKey, chartReferenceMark, chartRenderOptions, chartRows, chartTooltip } from "../charts";
@@ -44,7 +44,7 @@ const draw = (input: ChartInput, locale: string): Drawn => {
44
44
  key: ({ datum }) => chartMarkKey(datum),
45
45
  tooltip: ({ datum }) => {
46
46
  const row = rows.add(datum);
47
- return chartTooltip(rows.columns(), row, input.kind);
47
+ return chartTooltip(rows.columns(), row, input);
48
48
  },
49
49
  reference: ({ datum }) => chartReferenceMark(input, datum),
50
50
  });
@@ -125,7 +125,12 @@ export function enhanceNotebookCharts(root: HTMLElement, locale: string, options
125
125
  if (input.kind === "heatmap" && input.layout === "calendar") cleanups.push(mountCalendarScroll(chart));
126
126
  const inspection = inspectChart(chart, {
127
127
  kind: input.kind,
128
- nav: input.kind === "heatmap" && input.layout === "calendar" ? calendarInspectionNavigation : undefined,
128
+ nav:
129
+ input.kind === "sankey"
130
+ ? sankeyInspectionNavigation
131
+ : input.kind === "heatmap" && input.layout === "calendar"
132
+ ? calendarInspectionNavigation
133
+ : undefined,
129
134
  locale,
130
135
  legend: figure,
131
136
  format: ({ datum }) => lazy().tooltips.get(chartMarkKey(datum)) ?? { rows: [] },
package/src/styles.css CHANGED
@@ -427,3 +427,11 @@
427
427
  flex: none;
428
428
  }
429
429
  }
430
+
431
+ /* Calendar placeholders, drawings and tables share a width-derived content box. */
432
+ .k2b-ui .notebook-book-chart[data-calendar] .notebook-book-chart__viewport {
433
+ height: var(--notebook-chart-height);
434
+ }
435
+ .k2b-ui .notebook-book-chart[data-calendar] .k2b-chart__svg {
436
+ height: auto;
437
+ }