@k2b/editor 0.9.0 → 0.11.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/src/charts.ts CHANGED
@@ -3,13 +3,19 @@ import { i18n } from "@k2b/stdlib";
3
3
  import {
4
4
  type AreaOptions,
5
5
  autoBin,
6
+ type BalanceFlowOptions,
6
7
  type BarChartOptions,
7
8
  type BubbleOptions,
9
+ balanceFlowDatums,
10
+ balanceFlowFields,
11
+ balanceFlowRenderOptions,
8
12
  barChartLayout,
9
13
  barGauge,
10
14
  boxplot,
11
15
  type ChartDatum,
16
+ type ChartRenderSettings,
12
17
  calendarWords,
18
+ chartNumberFormatters,
13
19
  type charts,
14
20
  computeDomain,
15
21
  donut,
@@ -21,6 +27,7 @@ import {
21
27
  hbarLayout,
22
28
  histogram,
23
29
  line,
30
+ lineDetailsEnabled,
24
31
  niceLogTicks,
25
32
  niceStep,
26
33
  type ParetoOptions,
@@ -28,6 +35,7 @@ import {
28
35
  type RadarOptions,
29
36
  rankedBarLayout,
30
37
  renderAreaSvg,
38
+ renderBalanceFlowSvg,
31
39
  renderBarChartSvg,
32
40
  renderBubbleSvg,
33
41
  renderFunnelSvg,
@@ -35,8 +43,11 @@ import {
35
43
  renderHeatmapSvg,
36
44
  renderParetoSvg,
37
45
  renderRadarSvg,
46
+ renderSankeySvg,
38
47
  renderTreemapSvg,
39
48
  renderWaterfallSvg,
49
+ type SankeyOptions,
50
+ sankeyGraph,
40
51
  scatter,
41
52
  sparkline,
42
53
  stat,
@@ -44,6 +55,9 @@ import {
44
55
  type WaterfallOptions,
45
56
  } from "@k2b/ui/charts/core";
46
57
  import { z } from "zod";
58
+
59
+ export { balanceFlowRenderOptions, chartNumberFormatters } from "@k2b/ui/charts/core";
60
+
47
61
  import { type ChartFormat, type ChartInput, type ChartNumberFormat, chartDateTime, chartKinds } from "./chart-schema";
48
62
 
49
63
  export * from "./chart-schema";
@@ -51,28 +65,34 @@ export * from "./chart-schema";
51
65
  type RenderOptions = {
52
66
  [K in ChartInput["kind"]]: { kind: K } & (K extends "funnel"
53
67
  ? FunnelOptions
54
- : K extends "hbar"
55
- ? HorizontalBarOptions
56
- : K extends "waterfall"
57
- ? WaterfallOptions
58
- : K extends "area"
59
- ? AreaOptions
60
- : K extends "treemap"
61
- ? TreemapOptions
62
- : K extends "pareto"
63
- ? ParetoOptions
64
- : K extends "bubble"
65
- ? BubbleOptions
66
- : K extends "radar"
67
- ? 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);
68
+ : K extends "balanceFlow"
69
+ ? BalanceFlowOptions
70
+ : K extends "hbar"
71
+ ? HorizontalBarOptions
72
+ : K extends "waterfall"
73
+ ? WaterfallOptions
74
+ : K extends "area"
75
+ ? AreaOptions
76
+ : K extends "treemap"
77
+ ? TreemapOptions
78
+ : K extends "pareto"
79
+ ? ParetoOptions
80
+ : K extends "bubble"
81
+ ? BubbleOptions
82
+ : K extends "radar"
83
+ ? RadarOptions
84
+ : K extends "sankey"
85
+ ? SankeyOptions
86
+ : K extends "heatmap"
87
+ ? HeatmapChartOptions
88
+ : K extends "bar"
89
+ ? BarChartOptions & { data: NonNullable<BarChartOptions["data"]> }
90
+ : K extends keyof typeof charts
91
+ ? Omit<Parameters<(typeof charts)[K]>[0], "width" | "height" | "inspect">
92
+ : never);
75
93
  }[ChartInput["kind"]];
94
+ type BalanceFlowInput = Extract<ChartInput, { kind: "balanceFlow" }>;
95
+ type BaseChartInput = Exclude<ChartInput, BalanceFlowInput>;
76
96
 
77
97
  /**
78
98
  * Plain-data chart options become the options of the shared
@@ -86,6 +106,7 @@ const labels = /* @__PURE__ */ i18n.define({
86
106
  messages: {
87
107
  en: {
88
108
  category: "Category",
109
+ flow: "Flow",
89
110
  size: "Size",
90
111
  axis: "Axis",
91
112
  series: "Series",
@@ -93,6 +114,8 @@ const labels = /* @__PURE__ */ i18n.define({
93
114
  previous: "Previous",
94
115
  change: "Change",
95
116
  cumulative: "Cumulative",
117
+ incoming: "Incoming",
118
+ outgoing: "Outgoing",
96
119
  balance: "Balance",
97
120
  before: "Balance before",
98
121
  inflow: "In",
@@ -112,6 +135,8 @@ const labels = /* @__PURE__ */ i18n.define({
112
135
  q3: "Q3",
113
136
  whiskerLow: "Whisker low",
114
137
  whiskerHigh: "Whisker high",
138
+ forecastLow: "Lower forecast bound",
139
+ forecastHigh: "Upper forecast bound",
115
140
  delta: "Change",
116
141
  startShare: "Share of start",
117
142
  previousShare: "Share of previous step",
@@ -119,6 +144,7 @@ const labels = /* @__PURE__ */ i18n.define({
119
144
  },
120
145
  de: {
121
146
  category: "Kategorie",
147
+ flow: "Fluss",
122
148
  size: "Größe",
123
149
  axis: "Achse",
124
150
  series: "Datenreihe",
@@ -126,6 +152,8 @@ const labels = /* @__PURE__ */ i18n.define({
126
152
  previous: "Vorher",
127
153
  change: "Änderung",
128
154
  cumulative: "Kumuliert",
155
+ incoming: "Eingang",
156
+ outgoing: "Ausgang",
129
157
  balance: "Stand",
130
158
  before: "Stand davor",
131
159
  inflow: "Rein",
@@ -145,6 +173,8 @@ const labels = /* @__PURE__ */ i18n.define({
145
173
  q3: "Q3",
146
174
  whiskerLow: "Unterer Whisker",
147
175
  whiskerHigh: "Oberer Whisker",
176
+ forecastLow: "Untere Prognosegrenze",
177
+ forecastHigh: "Obere Prognosegrenze",
148
178
  delta: "Änderung",
149
179
  startShare: "Anteil am Start",
150
180
  previousShare: "Anteil am vorigen Schritt",
@@ -192,8 +222,21 @@ const axis = ({ domain, format: _format, ...value }: ChartAxisInput = {}, format
192
222
  format,
193
223
  });
194
224
 
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)) : [];
225
+ export const chartReferenceValues = (input: ChartInput, name: "x" | "y") => {
226
+ const values =
227
+ "references" in input ? (input.references ?? []).filter((ref) => (ref.axis ?? "y") === name).map((ref) => dateTime(ref.value)) : [];
228
+ if (input.kind === "line") {
229
+ if (name === "x") {
230
+ if (input.forecast) values.push(dateTime(input.forecast.from));
231
+ if (input.marker) values.push(dateTime(input.marker.at));
232
+ } else {
233
+ if (input.threshold) values.push(input.threshold.value);
234
+ if (input.zero) values.push(0);
235
+ for (const bounds of input.forecast?.band ?? []) values.push(...bounds);
236
+ }
237
+ }
238
+ return values;
239
+ };
197
240
 
198
241
  /** The value axes of a chart with what they show: the data checks and the label room read them alike. */
199
242
  export const chartValueAxes = (input: ChartInput): { values: number[]; axis?: ChartAxisInput; zero?: boolean; name: "x" | "y" }[] => {
@@ -278,46 +321,12 @@ type Formats = {
278
321
  x: { tick: (value: number) => string; value: (value: number) => string };
279
322
  };
280
323
 
281
- /**
282
- * Value precision and tick precision share the same style and units; ticks must remain distinct. A currency without
283
- * `decimals` or compact notation writes cents only when one of the formatted `values` has them: 418,000 € rather than
284
- * 418,000.00 €.
285
- */
286
- export const chartNumberFormatters = (format: ChartNumberFormat | undefined, locale: string, values?: readonly number[]) => {
287
- const common: Intl.NumberFormatOptions = {
288
- style: format?.style === "number" ? "decimal" : format?.style,
289
- currency: format?.currency,
290
- };
291
- // Compact notation keeps its fraction: 1.2K and 1.4K must not both read 1K.
292
- const decimals =
293
- format?.decimals ??
294
- (format?.style === "currency" && !format.compact && values?.length && values.every(Number.isInteger) ? 0 : undefined);
295
- const value = new Intl.NumberFormat(
296
- locale,
297
- format
298
- ? {
299
- ...common,
300
- ...(decimals === undefined ? {} : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }),
301
- ...(format.compact ? { notation: "compact" } : {}),
302
- }
303
- : { maximumSignificantDigits: 15 },
304
- );
305
- let tick: Intl.NumberFormat | undefined;
306
- const tickValue = (v: number) => {
307
- tick ??= new Intl.NumberFormat(locale, {
308
- ...common,
309
- notation: !format || format.compact ? "compact" : "standard",
310
- maximumSignificantDigits: 15,
311
- });
312
- return tick.format(v);
313
- };
314
- const unit = format?.unit ? ` ${format.unit}` : "";
315
- return { value: (v: number) => `${value.format(v)}${unit}`, tick: (v: number) => `${tickValue(v)}${unit}` };
316
- };
317
324
  const numberFormat = (format: ChartFormat | undefined) => (format && !("date" in format) ? format : undefined);
318
325
  /** The values a chart writes with its value format, for whole-number currency. */
319
- const formattedValues = (input: ChartInput): number[] => {
326
+ const formattedValues = (input: BaseChartInput): number[] => {
320
327
  switch (input.kind) {
328
+ case "sankey":
329
+ return input.links.map((link) => link.value);
321
330
  case "bubble":
322
331
  return input.data.flatMap((p) => (p.size === undefined ? [] : [p.size]));
323
332
  case "radar":
@@ -364,7 +373,7 @@ const formattedValues = (input: ChartInput): number[] => {
364
373
  return [];
365
374
  }
366
375
  };
367
- const formats = (input: ChartInput, locale: string): Formats => {
376
+ const formats = (input: BaseChartInput, locale: string): Formats => {
368
377
  const yFormat = ("yAxis" in input ? numberFormat(input.yAxis?.format) : undefined) ?? ("format" in input ? input.format : undefined);
369
378
  const y = chartNumberFormatters(yFormat, locale, formattedValues(input));
370
379
  const xFormat = "xAxis" in input && input.kind !== "bar" ? input.xAxis?.format : undefined;
@@ -372,8 +381,9 @@ const formats = (input: ChartInput, locale: string): Formats => {
372
381
  // An unformatted x axis often counts years or steps, which compact notation would turn into 2.02K.
373
382
  const xTick = new Intl.NumberFormat(locale, { maximumSignificantDigits: 15, useGrouping: "min2" });
374
383
  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
384
  const dateFormat = xFormat && "date" in xFormat ? xFormat.date : undefined;
385
+ if (!written.length && !(input.kind === "line" && lineDetailsEnabled(input) && dateFormat))
386
+ return { ...y, x: { tick: xFormat ? x.tick : (v) => xTick.format(v), value: x.value } };
377
387
  const times = dateFormat ? dateFormat !== "day" : written.some((date) => date.length > 10);
378
388
  const seconds = dateFormat ? dateFormat === "second" : written.some((date) => date.length > 16);
379
389
  const clock: Intl.DateTimeFormatOptions = times ? { hour: "2-digit", minute: "2-digit", ...(seconds ? { second: "2-digit" } : {}) } : {};
@@ -387,7 +397,8 @@ const formats = (input: ChartInput, locale: string): Formats => {
387
397
  };
388
398
 
389
399
  /** The table's x formatter also titles the shared cursor. */
390
- export const chartXValueFormat = (input: ChartInput, locale: string): ((x: number) => string) => formats(input, locale).x.value;
400
+ export const chartXValueFormat = (input: ChartInput, locale: string): ((x: number) => string) =>
401
+ input.kind === "balanceFlow" ? chartNumberFormatters(undefined, locale).value : formats(input, locale).x.value;
391
402
 
392
403
  /** Room for the longest y tick label, so values like 1.2M never run past the left edge on a phone. */
393
404
  const leftPadding = (values: number[], value: ChartAxisInput | undefined, tick: (value: number) => string, factor = NARROW) => {
@@ -411,7 +422,7 @@ const thinned = <T extends { label: string }>(data: T[], left: number, width = W
411
422
  export function chartLegend(
412
423
  input: ChartInput,
413
424
  locale: string,
414
- ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean }[] {
425
+ ): { label: string; color: number; style?: "solid" | "dashed" | "dotted"; reference?: boolean; seriesIndex?: number }[] {
415
426
  // These category renderers own their live legends, including prepared snapshots.
416
427
  if (input.kind === "hbar" || (input.kind === "bar" && input.series)) return [];
417
428
  if (input.kind === "bar")
@@ -423,6 +434,7 @@ export function chartLegend(
423
434
  return input.series.map((entry, index) => ({
424
435
  label: entry.label ?? `${t.series} ${index + 1}`,
425
436
  color: index % 8,
437
+ ...(input.kind === "line" && lineDetailsEnabled(input) ? { seriesIndex: index } : {}),
426
438
  ...(input.kind === "line" ? { style: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : "solid") } : {}),
427
439
  ...(entry.role === "reference" ? { reference: true } : {}),
428
440
  }));
@@ -436,15 +448,16 @@ export const chartReferenceMark = (input: ChartInput, datum: ChartDatum): boolea
436
448
  input.kind === "scatter" && input.series[datum.seriesIndex ?? 0]?.role === "reference";
437
449
 
438
450
  /** Options for the shared renderer; the chat block draws the title itself. */
439
- export function chartRenderOptions(
440
- input: ChartInput,
451
+ export function chartRenderOptions(input: ChartInput, locale: string, options: ChartRenderSettings = {}): RenderOptions {
452
+ return input.kind === "balanceFlow" ? balanceFlowRenderOptions(input, locale, options) : chartBaseRenderOptions(input, locale, options);
453
+ }
454
+
455
+ /** Plain-chart mapping; hosts that defer the self-contained BalanceFlow frame keep its formatter lazy. */
456
+ export function chartBaseRenderOptions(
457
+ input: BaseChartInput,
441
458
  locale: string,
442
- options: {
443
- width?: number;
444
- legend?: "svg" | "outside";
445
- formats?: { x?: (v: number) => string; y?: (v: number) => string; value?: (v: number) => string };
446
- } = {},
447
- ): RenderOptions {
459
+ options: ChartRenderSettings = {},
460
+ ): Exclude<RenderOptions, { kind: "balanceFlow" }> {
448
461
  if ("locale" in input && input.locale) locale = input.locale;
449
462
  const defaults = formats(input, locale);
450
463
  // Function formats must be measured with the same text the renderer will print.
@@ -458,6 +471,16 @@ export function chartRenderOptions(
458
471
  const width = options.width ?? WIDTH;
459
472
  const references = renderReferences(input);
460
473
  switch (input.kind) {
474
+ case "sankey":
475
+ return {
476
+ kind: "sankey",
477
+ nodes: input.nodes,
478
+ links: input.links,
479
+ legend: input.legend,
480
+ format: format.value,
481
+ locale: input.locale ?? locale,
482
+ displayWidth: options.width,
483
+ };
461
484
  case "treemap":
462
485
  return {
463
486
  kind: "treemap",
@@ -551,6 +574,14 @@ export function chartRenderOptions(
551
574
  series: input.series,
552
575
  layout: input.layout,
553
576
  normalize: input.normalize,
577
+ // Rates describe each category; summing percentages across periods has no meaning.
578
+ legendValues:
579
+ input.format?.style === "percent" || (yAxis?.format && "style" in yAxis.format && yAxis.format.style === "percent")
580
+ ? "latest"
581
+ : "total",
582
+ marks: input.marks,
583
+ total: input.total,
584
+ dots: input.dots,
554
585
  share: input.share,
555
586
  limit: input.limit,
556
587
  tone: input.tone,
@@ -588,7 +619,13 @@ export function chartRenderOptions(
588
619
  ...(input.kind === "line" ? { lineStyle: input.series[index]?.style ?? (entry.role === "reference" ? "dashed" : undefined) } : {}),
589
620
  }));
590
621
  const points = series.flatMap((entry) => entry.data);
591
- const xAxis = referencedAxis(input, "x");
622
+ const calendarLine =
623
+ input.kind === "line" &&
624
+ lineDetailsEnabled(input) &&
625
+ (input.series.some((entry) => entry.data.some((point) => typeof point.x === "string")) ||
626
+ (input.xAxis?.format && "date" in input.xAxis.format));
627
+ // The detailed time renderer includes references without rounding their domain to decimal milliseconds.
628
+ const xAxis = calendarLine ? input.xAxis : referencedAxis(input, "x");
592
629
  const yAxis = referencedAxis(input, "y");
593
630
  const candidates = tickCandidates([...points.map((point) => point.x), ...chartReferenceValues(input, "x")], xAxis).filter(
594
631
  Number.isFinite,
@@ -606,7 +643,21 @@ export function chartRenderOptions(
606
643
  right: Math.max(16, Math.ceil(((format.x.tick(lastTick).length * CHAR) / 2 + 4) * factor)),
607
644
  },
608
645
  };
609
- return input.kind === "line" ? { kind: "line", ...common, area: input.area, smooth: input.smooth } : { kind: "scatter", ...common };
646
+ return input.kind === "line"
647
+ ? {
648
+ kind: "line",
649
+ ...common,
650
+ area: input.area,
651
+ smooth: input.smooth,
652
+ step: input.step,
653
+ zero: input.zero,
654
+ legendValues: input.legendValues,
655
+ forecast: input.forecast ? { ...input.forecast, from: dateTime(input.forecast.from) } : undefined,
656
+ marker: input.marker ? { ...input.marker, at: dateTime(input.marker.at) } : undefined,
657
+ threshold: input.threshold,
658
+ ...(calendarLine ? { timeAxis: { timeZone: "UTC", locale } } : {}),
659
+ }
660
+ : { kind: "scatter", ...common };
610
661
  }
611
662
  case "pie":
612
663
  case "donut":
@@ -717,6 +768,10 @@ export const drawChart = (options: RenderOptions): string => {
717
768
  return renderTreemapSvg({ ...options, ...common });
718
769
  case "pareto":
719
770
  return renderParetoSvg({ ...options, ...common });
771
+ case "balanceFlow":
772
+ return renderBalanceFlowSvg({ ...options, ...common });
773
+ case "sankey":
774
+ return renderSankeySvg({ ...options, ...common });
720
775
  case "bubble":
721
776
  return renderBubbleSvg({ ...options, ...common });
722
777
  case "radar":
@@ -788,10 +843,11 @@ export type ChartTable = { columns: ChartColumn[]; rows: ChartRow[] };
788
843
  export function chartTooltip(
789
844
  columns: ChartColumn[],
790
845
  row: ChartRow,
791
- kind?: ChartInput["kind"],
846
+ kind?: ChartInput["kind"] | ChartInput,
792
847
  ): { title?: string; rows: { label: string; value: string }[] } {
793
848
  if (row.tooltip) return row.tooltip;
794
- if (kind === "area")
849
+ const chartKind = typeof kind === "object" ? kind.kind : kind;
850
+ if (chartKind === "area")
795
851
  return {
796
852
  title: row.cells.x,
797
853
  rows: [{ label: row.cells.series ?? "", value: `${row.cells.percent ? `${row.cells.percent} · ` : ""}${row.cells.value ?? "—"}` }],
@@ -814,6 +870,49 @@ export function chartRows(
814
870
  input: ChartInput,
815
871
  locale: string,
816
872
  options: { formats?: { x?: (v: number) => string; y?: (v: number) => string; value?: (v: number) => string } } = {},
873
+ ): ReturnType<typeof chartBaseRows> {
874
+ return input.kind === "balanceFlow" ? balanceFlowChartRows(input, locale) : chartBaseRows(input, locale, options);
875
+ }
876
+
877
+ function balanceFlowChartRows(input: BalanceFlowInput, locale: string): ReturnType<typeof chartBaseRows> {
878
+ const words = balanceFlowFields(input.locale ?? locale);
879
+ const columns = new Map<string, ChartColumn>();
880
+ const rows: ChartRow[] = [];
881
+ return {
882
+ add(datum) {
883
+ columns.set("label", { id: "label", label: words.chartFields({ key: "detail" }), numeric: false });
884
+ const cells: Record<string, string> = { label: datum.label ?? "" };
885
+ const values: Record<string, string | number> = { label: datum.label ?? "" };
886
+ for (const field of datum.values) {
887
+ if (!columns.has(field.key))
888
+ columns.set(field.key, {
889
+ id: field.key,
890
+ label:
891
+ field.label ??
892
+ (field.key === "period"
893
+ ? words.balancePeriod
894
+ : field.key === "direction"
895
+ ? words.balanceDirection
896
+ : words.chartFields({ key: field.key })),
897
+ numeric: typeof field.value === "number",
898
+ });
899
+ cells[field.key] = field.formatted ?? String(field.value);
900
+ values[field.key] = field.value;
901
+ }
902
+ const row = { key: chartMarkKey(datum), cells, values };
903
+ rows.push(row);
904
+ return row;
905
+ },
906
+ columns: () => [...columns.values()],
907
+ table: () => ({ columns: [...columns.values()], rows }),
908
+ };
909
+ }
910
+
911
+ /** Table builder for ordinary SVG charts; the BalanceFlow asset owns its complete table. */
912
+ export function chartBaseRows(
913
+ input: BaseChartInput,
914
+ locale: string,
915
+ options: { formats?: { x?: (v: number) => string; y?: (v: number) => string; value?: (v: number) => string } } = {},
817
916
  ) {
818
917
  if ("locale" in input && input.locale) locale = input.locale;
819
918
  const t = labels.resolve([locale]).t;
@@ -871,9 +970,11 @@ export function chartRows(
871
970
  "label",
872
971
  input.kind === "heatmap" && input.layout === "calendar"
873
972
  ? calendarWords(locale).day
874
- : input.kind === "radar"
875
- ? t.axis
876
- : t.category,
973
+ : input.kind === "sankey"
974
+ ? t.flow
975
+ : input.kind === "radar"
976
+ ? t.axis
977
+ : t.category,
877
978
  label,
878
979
  label,
879
980
  );
@@ -1013,6 +1114,8 @@ export function chartRows(
1013
1114
  ? (field.formatted ?? valueFormat(value))
1014
1115
  : `${valueFormat(value)}${unit}`,
1015
1116
  );
1117
+ else if (field.key === "incoming" || field.key === "outgoing") cell(field.key, t[field.key], value, valueFormat(value));
1118
+ else if (field.key === "forecastLow" || field.key === "forecastHigh") cell(field.key, t[field.key], value, valueFormat(value));
1016
1119
  else if (field.key === "delta") cell("delta", t.delta, value, `${value > 0 ? "+" : ""}${valueFormat(value)}`);
1017
1120
  else if (field.key === "q1" || field.key === "q2" || field.key === "q3" || field.key === "whiskerLow" || field.key === "whiskerHigh")
1018
1121
  cell(field.key, t[field.key], value, valueFormat(value));
@@ -1035,9 +1138,14 @@ export function chartRows(
1035
1138
  add,
1036
1139
  columns: () => [...columns.values()],
1037
1140
  table: (): ChartTable => {
1038
- if (input.kind === "bar" && input.layout === "rows" && input.limit !== undefined) {
1141
+ if (
1142
+ input.kind === "bar" &&
1143
+ input.layout === "rows" &&
1144
+ input.limit !== undefined &&
1145
+ rows.some((row) => row.values.rank !== undefined)
1146
+ ) {
1039
1147
  const source = { ...input, limit: undefined };
1040
- const all = chartRows(source, locale, options);
1148
+ const all = chartBaseRows(source, locale, options);
1041
1149
  const layout = rankedBarLayout({ data: source.data, title: source.title, subtitle: source.subtitle, valueFormat, locale });
1042
1150
  for (const row of layout.rows) {
1043
1151
  const value = Number.isFinite(row.value) ? row.value : null;
@@ -1059,6 +1167,23 @@ export function chartRows(
1059
1167
  }
1060
1168
  return all.table();
1061
1169
  }
1170
+ if (input.kind === "treemap") {
1171
+ const total = input.data.reduce((sum, item) => sum + item.value, 0);
1172
+ input.data.forEach((item, index) => {
1173
+ if (item.value !== 0 || rows.some((row) => row.key === chartMarkKey({ index }))) return;
1174
+ add({
1175
+ role: "item",
1176
+ index,
1177
+ label: item.label,
1178
+ anchor: [0, 0],
1179
+ values: [
1180
+ { key: "group", value: item.group },
1181
+ { key: "value", value: 0 },
1182
+ { key: "percent", value: 0, formatted: total ? percent.format(0) : "–" },
1183
+ ],
1184
+ });
1185
+ });
1186
+ }
1062
1187
  return { columns: [...columns.values()], rows };
1063
1188
  },
1064
1189
  };
@@ -1067,7 +1192,8 @@ export function chartRows(
1067
1192
  /** The data behind every mark of the chart as a table: the accessible alternative and what Copy data copies. */
1068
1193
  export function chartTable(input: ChartInput, locale: string): ChartTable {
1069
1194
  const rows = chartRows(input, locale);
1070
- for (const datum of chartSvgMarks(drawChart(chartRenderOptions(input, locale)))) rows.add(datum);
1195
+ const drawing = chartRenderOptions(input, locale);
1196
+ for (const datum of drawing.kind === "balanceFlow" ? balanceFlowDatums(drawing) : chartSvgMarks(drawChart(drawing))) rows.add(datum);
1071
1197
  return rows.table();
1072
1198
  }
1073
1199
 
@@ -1076,6 +1202,18 @@ export const chartMarks = (input: ChartInput): number => {
1076
1202
  switch (input.kind) {
1077
1203
  case "pareto":
1078
1204
  return input.data.length * 3;
1205
+ case "balanceFlow":
1206
+ return input.periods.reduce((total, p) => total + p.inflows.length + p.outflows.length + 3, 0);
1207
+ case "sankey": {
1208
+ const graph = sankeyGraph(input);
1209
+ return (
1210
+ input.nodes.length +
1211
+ input.links.reduce(
1212
+ (sum, link) => sum + graph.nodes[graph.ids.get(link.target)!]!.stage - graph.nodes[graph.ids.get(link.source)!]!.stage,
1213
+ 0,
1214
+ )
1215
+ );
1216
+ }
1079
1217
  case "radar":
1080
1218
  return input.axes.length * input.series.length;
1081
1219
  case "waterfall":
@@ -1086,7 +1224,11 @@ export const chartMarks = (input: ChartInput): number => {
1086
1224
  case "scatter":
1087
1225
  return input.series.reduce((sum, series) => sum + series.data.length, 0);
1088
1226
  case "bar":
1089
- return input.series ? (input.x?.length ?? 0) * (input.series.length + (input.compare ? 1 : 0)) : input.data.length;
1227
+ return input.marks === "dots"
1228
+ ? (input.x?.length ?? 0) * (input.dots ?? 100)
1229
+ : input.series
1230
+ ? (input.x?.length ?? 0) * (input.series.length + (input.compare ? 1 : 0))
1231
+ : input.data.length;
1090
1232
  case "hbar":
1091
1233
  return input.rows.length * input.series.length;
1092
1234
  case "boxplot":
@@ -269,8 +269,16 @@ export const remoteCursors = (ytext: Y.Text, awareness: Awareness): Extension =>
269
269
  ) {
270
270
  awareness.setLocalStateField("cursor", { anchor, head });
271
271
  }
272
- } else if (cursor != null && hasFocus) {
273
- awareness.setLocalStateField("cursor", null);
272
+ } else if (cursor != null && !update.view.dom.contains(update.view.dom.ownerDocument.activeElement)) {
273
+ // Focus moved to another field: the others no longer see a caret here until it returns. A table cell inside
274
+ // the editor keeps the cursor it publishes itself, and another window keeps the last place. The change is
275
+ // written after this update: other editors on the same awareness may be inside an update of their own,
276
+ // such as the one whose edit reached this view, and redraw on it.
277
+ const view = update.view;
278
+ queueMicrotask(() => {
279
+ if (view.hasFocus || view.dom.contains(view.dom.ownerDocument.activeElement)) return;
280
+ if (awareness.getLocalState()?.cursor != null) awareness.setLocalStateField("cursor", null);
281
+ });
274
282
  }
275
283
  }
276
284
  }
@@ -0,0 +1,66 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import type { Transaction } from "@codemirror/state";
3
+ import { Tree, type TreeBuffer } from "@lezer/common";
4
+
5
+ export type MarkdownSpan = { from: number; to: number };
6
+ const changedBlocks = new WeakMap<Transaction, readonly MarkdownSpan[]>();
7
+ const blocks = (tree: Tree, offset = 0, result = new Map<Tree | TreeBuffer, number>()): Map<Tree | TreeBuffer, number> => {
8
+ tree.children.forEach((child, i) => {
9
+ const from = offset + tree.positions[i]!;
10
+ if (child instanceof Tree && child.type.isAnonymous) blocks(child, from, result);
11
+ else result.set(child, from);
12
+ });
13
+ return result;
14
+ };
15
+
16
+ /** Markdown reparses whole top-level blocks and reuses the other child trees.
17
+ * Compare those identities, including parser-only progress, before visiting nodes.
18
+ */
19
+ export const changedMarkdownBlocks = (tr: Transaction): readonly MarkdownSpan[] => {
20
+ const cached = changedBlocks.get(tr);
21
+ if (cached) return cached;
22
+ const before = syntaxTree(tr.startState);
23
+ const after = syntaxTree(tr.state);
24
+ if (before === after) return [];
25
+ const old = blocks(before);
26
+ const spans: MarkdownSpan[] = [];
27
+ for (const [child, from] of blocks(after)) {
28
+ const previous = old.get(child);
29
+ if (previous !== undefined && tr.changes.mapPos(previous, 1) === from) old.delete(child);
30
+ else spans.push({ from, to: from + child.length });
31
+ }
32
+ for (const [child, from] of old) spans.push({ from: tr.changes.mapPos(from, -1), to: tr.changes.mapPos(from + child.length, 1) });
33
+ const merged = mergeMarkdownSpans(spans);
34
+ changedBlocks.set(tr, merged);
35
+ return merged;
36
+ };
37
+
38
+ export const mergeMarkdownSpans = (spans: MarkdownSpan[]): MarkdownSpan[] => {
39
+ const merged: MarkdownSpan[] = [];
40
+ for (const span of spans.sort((a, b) => a.from - b.from)) {
41
+ const previous = merged.at(-1);
42
+ if (previous && span.from <= previous.to) previous.to = Math.max(previous.to, span.to);
43
+ else merged.push({ ...span });
44
+ }
45
+ return merged;
46
+ };
47
+
48
+ /** Sorted, merged spans allow bounded lookups even for a bulk transaction. */
49
+ export const intersectsMarkdownSpans = (spans: readonly MarkdownSpan[], from: number, to: number): boolean => {
50
+ let low = 0,
51
+ high = spans.length;
52
+ while (low < high) {
53
+ const middle = (low + high) >>> 1;
54
+ if (spans[middle]!.to <= from) low = middle + 1;
55
+ else high = middle;
56
+ }
57
+ return low < spans.length && spans[low]!.from < to;
58
+ };
59
+
60
+ export const markdownBlockAt = (tree: Tree, position: number): MarkdownSpan => {
61
+ let node = tree.resolve(position, 1);
62
+ if (!node.parent) node = tree.resolve(position, -1);
63
+ if (!node.parent) return { from: position, to: position };
64
+ while (node.parent?.parent) node = node.parent;
65
+ return { from: node.from, to: node.to };
66
+ };