@k2b/editor 0.9.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.9.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.52.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
 
@@ -51,6 +51,7 @@ export const chartKindSchema = () =>
51
51
  "pareto",
52
52
  "bubble",
53
53
  "radar",
54
+ "sankey",
54
55
  ]);
55
56
 
56
57
  export const chartParts = (limits?: ChartLimits) => {
@@ -101,6 +102,7 @@ export const chartParts = (limits?: ChartLimits) => {
101
102
  );
102
103
  return {
103
104
  ChartLabel,
105
+ ChartCoordinate: z.union([z.number(), ChartDate]),
104
106
  ChartTooltip,
105
107
  ChartNumber,
106
108
  list,
@@ -115,13 +117,26 @@ export const chartParts = (limits?: ChartLimits) => {
115
117
  }),
116
118
  ChartCategory: z.object({ label: ChartLabel, value: ChartNumber }),
117
119
  ChartSlice: z.object({ label: ChartLabel, value: limits ? z.number().min(0) : ChartNumber }),
118
- ChartSeries: (points: z.ZodArray<typeof ChartPoint>) =>
120
+ ChartSeries: <T extends z.ZodType>(points: z.ZodArray<T>) =>
119
121
  z.object({
120
122
  label: ChartLabel.optional(),
121
123
  data: points,
122
124
  role: z.literal("reference").optional(),
123
125
  }),
124
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
+ ),
125
140
  ChartBins: z
126
141
  .union([
127
142
  limits ? z.number().int().min(1).max(limits?.maxValues) : z.number().int().min(1),
@@ -156,7 +171,9 @@ export const chartKinds = (limits?: ChartLimits) => {
156
171
  ChartCommon,
157
172
  ChartTooltip,
158
173
  ChartLabel,
174
+ ChartCoordinate,
159
175
  ChartPoints,
176
+ ChartLinePoints,
160
177
  ChartSeries,
161
178
  ChartSlice,
162
179
  ChartReferences,
@@ -222,8 +239,11 @@ export const chartKinds = (limits?: ChartLimits) => {
222
239
  1,
223
240
  limits?.maxSeries,
224
241
  ).optional(),
225
- layout: z.enum(["columns", "rows", "grouped", "stacked"]).optional(),
242
+ layout: z.enum(["columns", "rows", "grouped", "stacked", "nested"]).optional(),
226
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(),
227
247
  share: z.boolean().optional(),
228
248
  limit: z.number().int().positive().optional(),
229
249
  tone: z.enum(["in", "out"]).optional(),
@@ -242,19 +262,26 @@ export const chartKinds = (limits?: ChartLimits) => {
242
262
  ctx.addIssue({ code: "custom", path: ["data"], message: "A bar chart needs data or aligned series." });
243
263
  if ((bar.share !== undefined || bar.limit !== undefined || bar.tone !== undefined) && bar.layout !== "rows")
244
264
  issue("Share, limit and tone require rows layout.");
245
- if (bar.layout === "rows" && bar.data.some((d) => Number.isFinite(d.value) && d.value < 0))
246
- issue("Ranked bar lists require nonnegative values.");
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.");
247
270
  if (bar.series) {
248
271
  if (!bar.x || bar.series.some((s) => s.data.length !== bar.x?.length)) issue("Bar series must have the same length as x.");
249
272
  if (bar.data.length) issue("Use data or aligned series, not both.");
250
273
  if (bar.layout === "rows" || bar.layout === "columns") issue("Series bars use grouped or stacked layout.");
251
- } 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")
252
275
  issue("This layout needs aligned x and series.");
253
276
  if (bar.layout === "stacked" && bar.yAxis?.scale === "log") issue("Stacked bars need a linear axis.");
254
277
  if (bar.normalize && bar.layout !== "stacked") issue("Normalized bars must be stacked.");
278
+ nestedDotOptions(bar, issue);
255
279
  if (bar.layout === "stacked" && bar.series?.some((s) => s.data.some((v) => v !== null && v < 0)))
256
280
  issue("Stacked bars require nonnegative values.");
257
- 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
+ )
258
285
  issue("Comparison needs one current series and aligned previous values.");
259
286
  }),
260
287
  z.object({
@@ -284,25 +311,78 @@ export const chartKinds = (limits?: ChartLimits) => {
284
311
  if (bar.rows.some((r) => r.values.length !== bar.series.length))
285
312
  ctx.addIssue({ code: "custom", message: "Horizontal bar values must match series." });
286
313
  }),
287
- z.object({
288
- kind: z.literal("line"),
289
- ...ChartKindCommon,
290
- series: list(
291
- ChartSeries(
292
- limits
293
- ? ChartPoints.min(2, "A line needs at least two points per series; show single values as a bar or scatter chart.")
294
- : ChartPoints,
295
- ).extend({ style: z.enum(["solid", "dashed", "dotted"]).optional() }),
296
- 1,
297
- limits?.maxSeries,
298
- ),
299
- xAxis: ChartAxis.optional(),
300
- yAxis: ChartAxis.optional(),
301
- legend: z.boolean().optional(),
302
- area: z.boolean().optional(),
303
- smooth: z.boolean().optional(),
304
- references: ChartReferences.optional(),
305
- }),
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
+ }),
306
386
  z.object({
307
387
  kind: z.literal("scatter"),
308
388
  ...ChartKindCommon,
@@ -438,7 +518,11 @@ export const chartKinds = (limits?: ChartLimits) => {
438
518
  kind: z.literal("pareto"),
439
519
  ...ChartKindCommon,
440
520
  labels: z.tuple([ChartLabel, ChartLabel]),
441
- data: list(z.object({ label: ChartLabel, value: z.number().nonnegative(), prev: z.number().nonnegative() }), 1, limits?.maxValues),
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
+ ),
442
526
  format: numberFormat.optional(),
443
527
  locale: chartLocaleSchema().optional(),
444
528
  })
@@ -446,6 +530,35 @@ export const chartKinds = (limits?: ChartLimits) => {
446
530
  if (!Number.isFinite(spec.data.reduce((sum, d) => sum + d.value, 0)))
447
531
  ctx.addIssue({ code: "custom", message: "Pareto total must be finite." });
448
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
+ }),
449
562
  z
450
563
  .object({
451
564
  kind: z.literal("bubble"),
package/src/charts.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  hbarLayout,
22
22
  histogram,
23
23
  line,
24
+ lineDetailsEnabled,
24
25
  niceLogTicks,
25
26
  niceStep,
26
27
  type ParetoOptions,
@@ -35,8 +36,11 @@ import {
35
36
  renderHeatmapSvg,
36
37
  renderParetoSvg,
37
38
  renderRadarSvg,
39
+ renderSankeySvg,
38
40
  renderTreemapSvg,
39
41
  renderWaterfallSvg,
42
+ type SankeyOptions,
43
+ sankeyGraph,
40
44
  scatter,
41
45
  sparkline,
42
46
  stat,
@@ -65,13 +69,15 @@ type RenderOptions = {
65
69
  ? BubbleOptions
66
70
  : K extends "radar"
67
71
  ? RadarOptions
68
- : K extends "heatmap"
69
- ? HeatmapChartOptions
70
- : K extends "bar"
71
- ? BarChartOptions & { data: NonNullable<BarChartOptions["data"]> }
72
- : K extends keyof typeof charts
73
- ? Omit<Parameters<(typeof charts)[K]>[0], "width" | "height" | "inspect">
74
- : never);
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);
75
81
  }[ChartInput["kind"]];
76
82
 
77
83
  /**
@@ -86,6 +92,7 @@ const labels = /* @__PURE__ */ i18n.define({
86
92
  messages: {
87
93
  en: {
88
94
  category: "Category",
95
+ flow: "Flow",
89
96
  size: "Size",
90
97
  axis: "Axis",
91
98
  series: "Series",
@@ -93,6 +100,8 @@ const labels = /* @__PURE__ */ i18n.define({
93
100
  previous: "Previous",
94
101
  change: "Change",
95
102
  cumulative: "Cumulative",
103
+ incoming: "Incoming",
104
+ outgoing: "Outgoing",
96
105
  balance: "Balance",
97
106
  before: "Balance before",
98
107
  inflow: "In",
@@ -112,6 +121,8 @@ const labels = /* @__PURE__ */ i18n.define({
112
121
  q3: "Q3",
113
122
  whiskerLow: "Whisker low",
114
123
  whiskerHigh: "Whisker high",
124
+ forecastLow: "Lower forecast bound",
125
+ forecastHigh: "Upper forecast bound",
115
126
  delta: "Change",
116
127
  startShare: "Share of start",
117
128
  previousShare: "Share of previous step",
@@ -119,6 +130,7 @@ const labels = /* @__PURE__ */ i18n.define({
119
130
  },
120
131
  de: {
121
132
  category: "Kategorie",
133
+ flow: "Fluss",
122
134
  size: "Größe",
123
135
  axis: "Achse",
124
136
  series: "Datenreihe",
@@ -126,6 +138,8 @@ const labels = /* @__PURE__ */ i18n.define({
126
138
  previous: "Vorher",
127
139
  change: "Änderung",
128
140
  cumulative: "Kumuliert",
141
+ incoming: "Eingang",
142
+ outgoing: "Ausgang",
129
143
  balance: "Stand",
130
144
  before: "Stand davor",
131
145
  inflow: "Rein",
@@ -145,6 +159,8 @@ const labels = /* @__PURE__ */ i18n.define({
145
159
  q3: "Q3",
146
160
  whiskerLow: "Unterer Whisker",
147
161
  whiskerHigh: "Oberer Whisker",
162
+ forecastLow: "Untere Prognosegrenze",
163
+ forecastHigh: "Obere Prognosegrenze",
148
164
  delta: "Änderung",
149
165
  startShare: "Anteil am Start",
150
166
  previousShare: "Anteil am vorigen Schritt",
@@ -192,8 +208,21 @@ const axis = ({ domain, format: _format, ...value }: ChartAxisInput = {}, format
192
208
  format,
193
209
  });
194
210
 
195
- export const chartReferenceValues = (input: ChartInput, name: "x" | "y") =>
196
- "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
+ };
197
226
 
198
227
  /** The value axes of a chart with what they show: the data checks and the label room read them alike. */
199
228
  export const chartValueAxes = (input: ChartInput): { values: number[]; axis?: ChartAxisInput; zero?: boolean; name: "x" | "y" }[] => {
@@ -318,6 +347,8 @@ const numberFormat = (format: ChartFormat | undefined) => (format && !("date" in
318
347
  /** The values a chart writes with its value format, for whole-number currency. */
319
348
  const formattedValues = (input: ChartInput): number[] => {
320
349
  switch (input.kind) {
350
+ case "sankey":
351
+ return input.links.map((link) => link.value);
321
352
  case "bubble":
322
353
  return input.data.flatMap((p) => (p.size === undefined ? [] : [p.size]));
323
354
  case "radar":
@@ -372,8 +403,9 @@ const formats = (input: ChartInput, locale: string): Formats => {
372
403
  // An unformatted x axis often counts years or steps, which compact notation would turn into 2.02K.
373
404
  const xTick = new Intl.NumberFormat(locale, { maximumSignificantDigits: 15, useGrouping: "min2" });
374
405
  const written = chartSeries(input).flatMap((series) => series.data.flatMap((point) => (typeof point.x === "string" ? [point.x] : [])));
375
- if (!written.length) return { ...y, x: { tick: xFormat ? x.tick : (v) => xTick.format(v), value: x.value } };
376
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 } };
377
409
  const times = dateFormat ? dateFormat !== "day" : written.some((date) => date.length > 10);
378
410
  const seconds = dateFormat ? dateFormat === "second" : written.some((date) => date.length > 16);
379
411
  const clock: Intl.DateTimeFormatOptions = times ? { hour: "2-digit", minute: "2-digit", ...(seconds ? { second: "2-digit" } : {}) } : {};
@@ -411,7 +443,7 @@ const thinned = <T extends { label: string }>(data: T[], left: number, width = W
411
443
  export function chartLegend(
412
444
  input: ChartInput,
413
445
  locale: string,
414
- ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean }[] {
446
+ ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean; seriesIndex?: number }[] {
415
447
  // These category renderers own their live legends, including prepared snapshots.
416
448
  if (input.kind === "hbar" || (input.kind === "bar" && input.series)) return [];
417
449
  if (input.kind === "bar")
@@ -423,6 +455,7 @@ export function chartLegend(
423
455
  return input.series.map((entry, index) => ({
424
456
  label: entry.label ?? `${t.series} ${index + 1}`,
425
457
  color: index % 8,
458
+ ...(input.kind === "line" && lineDetailsEnabled(input) ? { seriesIndex: index } : {}),
426
459
  ...(input.kind === "line" ? { style: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : "solid") } : {}),
427
460
  ...(entry.role === "reference" ? { reference: true } : {}),
428
461
  }));
@@ -458,6 +491,16 @@ export function chartRenderOptions(
458
491
  const width = options.width ?? WIDTH;
459
492
  const references = renderReferences(input);
460
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
+ };
461
504
  case "treemap":
462
505
  return {
463
506
  kind: "treemap",
@@ -551,6 +594,14 @@ export function chartRenderOptions(
551
594
  series: input.series,
552
595
  layout: input.layout,
553
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,
554
605
  share: input.share,
555
606
  limit: input.limit,
556
607
  tone: input.tone,
@@ -588,7 +639,13 @@ export function chartRenderOptions(
588
639
  ...(input.kind === "line" ? { lineStyle: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : undefined) } : {}),
589
640
  }));
590
641
  const points = series.flatMap((entry) => entry.data);
591
- 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");
592
649
  const yAxis = referencedAxis(input, "y");
593
650
  const candidates = tickCandidates([...points.map((point) => point.x), ...chartReferenceValues(input, "x")], xAxis).filter(
594
651
  Number.isFinite,
@@ -606,7 +663,21 @@ export function chartRenderOptions(
606
663
  right: Math.max(16, Math.ceil(((format.x.tick(lastTick).length * CHAR) / 2 + 4) * factor)),
607
664
  },
608
665
  };
609
- 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 };
610
681
  }
611
682
  case "pie":
612
683
  case "donut":
@@ -717,6 +788,8 @@ export const drawChart = (options: RenderOptions): string => {
717
788
  return renderTreemapSvg({ ...options, ...common });
718
789
  case "pareto":
719
790
  return renderParetoSvg({ ...options, ...common });
791
+ case "sankey":
792
+ return renderSankeySvg({ ...options, ...common });
720
793
  case "bubble":
721
794
  return renderBubbleSvg({ ...options, ...common });
722
795
  case "radar":
@@ -788,10 +861,11 @@ export type ChartTable = { columns: ChartColumn[]; rows: ChartRow[] };
788
861
  export function chartTooltip(
789
862
  columns: ChartColumn[],
790
863
  row: ChartRow,
791
- kind?: ChartInput["kind"],
864
+ kind?: ChartInput["kind"] | ChartInput,
792
865
  ): { title?: string; rows: { label: string; value: string }[] } {
793
866
  if (row.tooltip) return row.tooltip;
794
- if (kind === "area")
867
+ const chartKind = typeof kind === "object" ? kind.kind : kind;
868
+ if (chartKind === "area")
795
869
  return {
796
870
  title: row.cells.x,
797
871
  rows: [{ label: row.cells.series ?? "", value: `${row.cells.percent ? `${row.cells.percent} · ` : ""}${row.cells.value ?? "—"}` }],
@@ -871,9 +945,11 @@ export function chartRows(
871
945
  "label",
872
946
  input.kind === "heatmap" && input.layout === "calendar"
873
947
  ? calendarWords(locale).day
874
- : input.kind === "radar"
875
- ? t.axis
876
- : t.category,
948
+ : input.kind === "sankey"
949
+ ? t.flow
950
+ : input.kind === "radar"
951
+ ? t.axis
952
+ : t.category,
877
953
  label,
878
954
  label,
879
955
  );
@@ -1013,6 +1089,8 @@ export function chartRows(
1013
1089
  ? (field.formatted ?? valueFormat(value))
1014
1090
  : `${valueFormat(value)}${unit}`,
1015
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));
1016
1094
  else if (field.key === "delta") cell("delta", t.delta, value, `${value > 0 ? "+" : ""}${valueFormat(value)}`);
1017
1095
  else if (field.key === "q1" || field.key === "q2" || field.key === "q3" || field.key === "whiskerLow" || field.key === "whiskerHigh")
1018
1096
  cell(field.key, t[field.key], value, valueFormat(value));
@@ -1035,7 +1113,12 @@ export function chartRows(
1035
1113
  add,
1036
1114
  columns: () => [...columns.values()],
1037
1115
  table: (): ChartTable => {
1038
- if (input.kind === "bar" && input.layout === "rows" && input.limit !== undefined) {
1116
+ if (
1117
+ input.kind === "bar" &&
1118
+ input.layout === "rows" &&
1119
+ input.limit !== undefined &&
1120
+ rows.some((row) => row.values.rank !== undefined)
1121
+ ) {
1039
1122
  const source = { ...input, limit: undefined };
1040
1123
  const all = chartRows(source, locale, options);
1041
1124
  const layout = rankedBarLayout({ data: source.data, title: source.title, subtitle: source.subtitle, valueFormat, locale });
@@ -1059,6 +1142,23 @@ export function chartRows(
1059
1142
  }
1060
1143
  return all.table();
1061
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
+ }
1062
1162
  return { columns: [...columns.values()], rows };
1063
1163
  },
1064
1164
  };
@@ -1076,6 +1176,16 @@ export const chartMarks = (input: ChartInput): number => {
1076
1176
  switch (input.kind) {
1077
1177
  case "pareto":
1078
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
+ }
1079
1189
  case "radar":
1080
1190
  return input.axes.length * input.series.length;
1081
1191
  case "waterfall":
@@ -1086,7 +1196,11 @@ export const chartMarks = (input: ChartInput): number => {
1086
1196
  case "scatter":
1087
1197
  return input.series.reduce((sum, series) => sum + series.data.length, 0);
1088
1198
  case "bar":
1089
- 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;
1090
1204
  case "hbar":
1091
1205
  return input.rows.length * input.series.length;
1092
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,7 +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";
4
- import { paretoLayout } from "@k2b/ui/charts/core";
3
+ import { barChartLayout, calendarLayout, calendarViewportHeight, hbarLayout } from "@k2b/ui/charts";
4
+ import { chartSvgWithUiPalette, paretoLayout, sankeyFrame } from "@k2b/ui/charts/core";
5
5
  import { Lexer, type Tokens } from "marked";
6
6
  import type { z } from "zod";
7
7
  import {
@@ -32,7 +32,7 @@ export type MarkdownChartOptions = {
32
32
  };
33
33
  export type ChartBlock = { line: number; input: ChartInput };
34
34
  /** `height` is the drawing's own height in CSS pixels when it needs more than the kind's frame (app.css). */
35
- 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 };
36
36
  type Entry = { value: string; line: number };
37
37
  type Cell = { raw: string; result: EvalResult };
38
38
  type SourceData = { columns: string[]; rows: Cell[][]; implicit: boolean; entries?: NamedDataEntry[]; invalid?: boolean };
@@ -456,14 +456,14 @@ export const chartBlockFrame = (body: string[], options: Pick<MarkdownChartOptio
456
456
  * categories make the drawing taller. The server and an editor placeholder read it from the same parsed block, so
457
457
  * both reserve the same box. Undefined for every other drawing, which fits the frame.
458
458
  */
459
- export const notebookChartHeight = (input: ChartInput, locale: string): number | undefined => {
459
+ export const notebookChartHeight = (input: ChartInput, locale: string): number | string | undefined => {
460
460
  const options = chartRenderOptions(input, locale, { legend: "outside" });
461
461
  if (options.kind === "treemap") return 280;
462
462
  if (options.kind === "pareto") return paretoLayout(options).height;
463
-
463
+ if (options.kind === "sankey") return sankeyFrame(options).height;
464
464
  if (options.kind === "bubble" || options.kind === "radar") return 280;
465
465
  if (options.kind === "hbar") return hbarLayout(options).height;
466
- if (options.kind === "heatmap" && options.layout === "calendar") return 280;
466
+ if (options.kind === "heatmap" && options.layout === "calendar") return calendarViewportHeight(calendarLayout(options));
467
467
  if (options.kind === "waterfall" || options.kind === "area") return 280;
468
468
  if (options.kind !== "bar") return undefined;
469
469
  const layout = barChartLayout(options);
@@ -481,7 +481,7 @@ export const notebookChartFrameHtml = (
481
481
  viewportHtml: string,
482
482
  options: { legend?: boolean; input?: ChartInput; print?: boolean } = {},
483
483
  ): string =>
484
- `<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>`;
485
485
 
486
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. */
487
487
  export const notebookChartTableHtml = (table: ChartTable, options: { label?: string; className?: string } = {}): string =>
@@ -495,7 +495,7 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
495
495
  key: ({ datum }) => chartMarkKey(datum),
496
496
  tooltip: ({ datum }) => {
497
497
  const row = rows.add(datum);
498
- return chartTooltip(rows.columns(), row, input.kind);
498
+ return chartTooltip(rows.columns(), row, input);
499
499
  },
500
500
  reference: ({ datum }) => chartReferenceMark(input, datum),
501
501
  });
@@ -505,9 +505,16 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
505
505
  const valueField = input.kind === "area" ? (input.normalize ? "percent" : "value") : "y";
506
506
  let lastX = -Infinity;
507
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;
508
509
  const legendValue = (index: number) => {
509
510
  const field = snapshot.marks
510
- .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
+ )
511
518
  ?.datum.values.find((field) => field.key === valueField);
512
519
  return field
513
520
  ? (field.formatted ??
@@ -517,10 +524,14 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
517
524
  : "—";
518
525
  };
519
526
  const legendHtml = legend.length
520
- ? `<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>`
521
528
  : "";
522
- 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}`;
523
- 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);
524
535
  const figure = notebookChartFrameHtml(height ? { ...input, height } : input, viewport, {
525
536
  legend: legend.length > 0,
526
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
+ }