@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k2b/editor",
3
- "version": "0.9.0",
3
+ "version": "0.11.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.32.0",
73
+ "@k2b/ui": "0.54.0",
74
74
  "@lezer/common": "1.5.3",
75
75
  "@lezer/highlight": "1.2.4",
76
76
  "@lezer/markdown": "1.7.2",
@@ -1,4 +1,4 @@
1
- import { Prec } from "@codemirror/state";
1
+ import { Prec, type SelectionRange } from "@codemirror/state";
2
2
  import { EditorView, keymap } from "@codemirror/view";
3
3
  import { SelectionToolbar, Toolbar, useLocale } from "@k2b/ui";
4
4
  import { createSignal, For, type JSX, Show } from "solid-js";
@@ -40,12 +40,12 @@ export function BubbleMenu(props: BubbleMenuProps) {
40
40
  const locale = useLocale();
41
41
  const t = () => editorMessages.resolve([locale()]).t;
42
42
  const [dragging, setDragging] = createSignal(false);
43
- const [dismissed, setDismissed] = createSignal<unknown>();
43
+ const [dismissed, setDismissed] = createSignal<SelectionRange>();
44
44
  const [geometry, setGeometry] = createSignal(0);
45
45
  // Focus that moves from the text into the menu, such as Tab to a button or a host input, keeps it open.
46
46
  const [menuFocused, setMenuFocused] = createSignal(false);
47
47
  const dismiss = () => {
48
- setDismissed(props.editor.state()?.selection);
48
+ setDismissed(props.editor.state()?.selection.main);
49
49
  props.editor.view()?.focus();
50
50
  };
51
51
 
@@ -65,6 +65,13 @@ export function BubbleMenu(props: BubbleMenuProps) {
65
65
  }),
66
66
  EditorView.updateListener.of((update) => {
67
67
  if (update.geometryChanged || update.viewportChanged) setGeometry((value) => value + 1);
68
+ // An edit elsewhere, such as a collaborator typing, moves the dismissed selection along: it stays dismissed. A
69
+ // selection of the person's own ends the dismissal, also when they later select the same text again.
70
+ if (update.docChanged || update.selectionSet)
71
+ setDismissed((range) => {
72
+ const mapped = update.docChanged ? range?.map(update.changes) : range;
73
+ return mapped?.eq(update.state.selection.main) ? mapped : undefined;
74
+ });
68
75
  }),
69
76
  // Escape in the text closes an open menu first; with no menu, the key keeps its other meanings.
70
77
  Prec.high(
@@ -88,7 +95,7 @@ export function BubbleMenu(props: BubbleMenuProps) {
88
95
  if (!view || !state || dragging() || !(props.editor.focused() || menuFocused())) return null;
89
96
  if (state.readOnly && !props.readOnly) return null;
90
97
  const range = state.selection.main;
91
- if (range.empty || dismissed() === state.selection) return null;
98
+ if (range.empty || dismissed()?.eq(range)) return null;
92
99
  return selectionBox(view, range.from, range.to);
93
100
  };
94
101
  const coarse = () => typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches;
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", "balanceFlow"]);
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,13 @@
1
1
  import type { ChartInput, ChartLimits } from "@k2b/ui/charts";
2
- import { CALENDAR_MAX_DAYS, calendarDay } from "@k2b/ui/charts/core";
2
+ import {
3
+ BalanceFlowError,
4
+ CALENDAR_MAX_DAYS,
5
+ calendarDay,
6
+ lineDetailsEnabled,
7
+ nestedDotOptions,
8
+ sankeyGraph,
9
+ validateBalanceFlow,
10
+ } from "@k2b/ui/charts/core";
3
11
  import { z } from "zod";
4
12
  import { chartLocaleSchema } from "./chart-locale";
5
13
 
@@ -51,6 +59,8 @@ export const chartKindSchema = () =>
51
59
  "pareto",
52
60
  "bubble",
53
61
  "radar",
62
+ "sankey",
63
+ "balanceFlow",
54
64
  ]);
55
65
 
56
66
  export const chartParts = (limits?: ChartLimits) => {
@@ -101,6 +111,7 @@ export const chartParts = (limits?: ChartLimits) => {
101
111
  );
102
112
  return {
103
113
  ChartLabel,
114
+ ChartCoordinate: z.union([z.number(), ChartDate]),
104
115
  ChartTooltip,
105
116
  ChartNumber,
106
117
  list,
@@ -115,13 +126,26 @@ export const chartParts = (limits?: ChartLimits) => {
115
126
  }),
116
127
  ChartCategory: z.object({ label: ChartLabel, value: ChartNumber }),
117
128
  ChartSlice: z.object({ label: ChartLabel, value: limits ? z.number().min(0) : ChartNumber }),
118
- ChartSeries: (points: z.ZodArray<typeof ChartPoint>) =>
129
+ ChartSeries: <T extends z.ZodType>(points: z.ZodArray<T>) =>
119
130
  z.object({
120
131
  label: ChartLabel.optional(),
121
132
  data: points,
122
133
  role: z.literal("reference").optional(),
123
134
  }),
124
135
  ChartPoints: list(ChartPoint, 0, limits?.maxValues),
136
+ ChartLinePoints: list(
137
+ ChartPoint.extend({
138
+ y: (limits
139
+ ? z
140
+ .number()
141
+ .nullable()
142
+ .transform((value) => value ?? Number.NaN)
143
+ : ChartNumber
144
+ ).describe("line: value; null is a gap only with forecast, zero, threshold, marker or legendValues enabled."),
145
+ }),
146
+ 0,
147
+ limits?.maxValues,
148
+ ),
125
149
  ChartBins: z
126
150
  .union([
127
151
  limits ? z.number().int().min(1).max(limits?.maxValues) : z.number().int().min(1),
@@ -156,7 +180,9 @@ export const chartKinds = (limits?: ChartLimits) => {
156
180
  ChartCommon,
157
181
  ChartTooltip,
158
182
  ChartLabel,
183
+ ChartCoordinate,
159
184
  ChartPoints,
185
+ ChartLinePoints,
160
186
  ChartSeries,
161
187
  ChartSlice,
162
188
  ChartReferences,
@@ -222,8 +248,11 @@ export const chartKinds = (limits?: ChartLimits) => {
222
248
  1,
223
249
  limits?.maxSeries,
224
250
  ).optional(),
225
- layout: z.enum(["columns", "rows", "grouped", "stacked"]).optional(),
251
+ layout: z.enum(["columns", "rows", "grouped", "stacked", "nested"]).optional(),
226
252
  normalize: z.boolean().optional(),
253
+ marks: z.enum(["bars", "dots"]).optional(),
254
+ total: z.number().positive().optional(),
255
+ dots: z.number().int().min(2).optional(),
227
256
  share: z.boolean().optional(),
228
257
  limit: z.number().int().positive().optional(),
229
258
  tone: z.enum(["in", "out"]).optional(),
@@ -242,19 +271,26 @@ export const chartKinds = (limits?: ChartLimits) => {
242
271
  ctx.addIssue({ code: "custom", path: ["data"], message: "A bar chart needs data or aligned series." });
243
272
  if ((bar.share !== undefined || bar.limit !== undefined || bar.tone !== undefined) && bar.layout !== "rows")
244
273
  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.");
274
+ if (
275
+ (bar.share !== undefined || bar.limit !== undefined || bar.tone !== undefined) &&
276
+ bar.data.some((d) => Number.isFinite(d.value) && d.value < 0)
277
+ )
278
+ issue("Share, limit and tone need nonnegative values.");
247
279
  if (bar.series) {
248
280
  if (!bar.x || bar.series.some((s) => s.data.length !== bar.x?.length)) issue("Bar series must have the same length as x.");
249
281
  if (bar.data.length) issue("Use data or aligned series, not both.");
250
282
  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")
283
+ } else if (bar.x || bar.compare || bar.layout === "grouped" || bar.layout === "stacked" || bar.layout === "nested")
252
284
  issue("This layout needs aligned x and series.");
253
285
  if (bar.layout === "stacked" && bar.yAxis?.scale === "log") issue("Stacked bars need a linear axis.");
254
286
  if (bar.normalize && bar.layout !== "stacked") issue("Normalized bars must be stacked.");
287
+ nestedDotOptions(bar, issue);
255
288
  if (bar.layout === "stacked" && bar.series?.some((s) => s.data.some((v) => v !== null && v < 0)))
256
289
  issue("Stacked bars require nonnegative values.");
257
- if (bar.compare && (bar.series?.length !== 1 || bar.compare.data.length !== bar.x?.length || bar.layout === "stacked"))
290
+ if (
291
+ bar.compare &&
292
+ (bar.series?.length !== 1 || bar.compare.data.length !== bar.x?.length || bar.layout === "stacked" || bar.layout === "nested")
293
+ )
258
294
  issue("Comparison needs one current series and aligned previous values.");
259
295
  }),
260
296
  z.object({
@@ -284,25 +320,78 @@ export const chartKinds = (limits?: ChartLimits) => {
284
320
  if (bar.rows.some((r) => r.values.length !== bar.series.length))
285
321
  ctx.addIssue({ code: "custom", message: "Horizontal bar values must match series." });
286
322
  }),
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
- }),
323
+ z
324
+ .object({
325
+ kind: z.literal("line"),
326
+ ...ChartKindCommon,
327
+ series: list(
328
+ ChartSeries(
329
+ limits
330
+ ? ChartLinePoints.min(2, "A line needs at least two points per series; show single values as a bar or scatter chart.")
331
+ : ChartLinePoints,
332
+ ).extend({ style: z.enum(["solid", "dashed", "dotted"]).optional() }),
333
+ 1,
334
+ limits?.maxSeries,
335
+ ),
336
+ xAxis: ChartAxis.optional(),
337
+ yAxis: ChartAxis.optional(),
338
+ legend: z.boolean().optional(),
339
+ area: z.boolean().optional(),
340
+ smooth: z.boolean().optional(),
341
+ step: z.enum(["after", "before", "middle"]).optional(),
342
+ zero: z.boolean().optional(),
343
+ legendValues: z.boolean().optional(),
344
+ forecast: z
345
+ .object({
346
+ from: ChartCoordinate,
347
+ band: list(z.tuple([z.number(), z.number()]), 0, limits?.maxValues).optional(),
348
+ })
349
+ .optional(),
350
+ threshold: z.object({ value: z.number(), label: ChartLabel }).optional(),
351
+ marker: z.object({ at: ChartCoordinate, label: ChartLabel }).optional(),
352
+ references: ChartReferences.optional(),
353
+ })
354
+ .superRefine((spec, ctx) => {
355
+ if (limits && !lineDetailsEnabled(spec))
356
+ spec.series.forEach((series, seriesIndex) => {
357
+ series.data.forEach((point, pointIndex) => {
358
+ if (!Number.isFinite(point.y))
359
+ ctx.addIssue({
360
+ code: "custom",
361
+ path: ["series", seriesIndex, "data", pointIndex, "y"],
362
+ message: "Null gaps require forecast, zero, threshold, marker or legendValues enabled.",
363
+ });
364
+ });
365
+ });
366
+ const coordinate = (x: number | string) => (typeof x === "number" ? x : chartDateTime(x));
367
+ const at = spec.marker && coordinate(spec.marker.at);
368
+ if (at !== undefined && spec.xAxis?.domain && (at < spec.xAxis.domain[0]! || at > spec.xAxis.domain[1]!))
369
+ ctx.addIssue({ code: "custom", path: ["marker", "at"], message: "Marker must be inside the explicit X domain." });
370
+ if (!spec.forecast) return;
371
+ const from = coordinate(spec.forecast.from);
372
+ const points = spec.series[0]?.data ?? [];
373
+ if (!points.some((point) => coordinate(point.x) === from)) {
374
+ ctx.addIssue({ code: "custom", path: ["forecast", "from"], message: "Forecast must start at an X value of the first series." });
375
+ }
376
+ const count = points.filter((point) => {
377
+ const x = coordinate(point.x);
378
+ return x !== undefined && from !== undefined && x >= from;
379
+ }).length;
380
+ if (spec.forecast.band && spec.forecast.band.length !== count)
381
+ ctx.addIssue({
382
+ code: "custom",
383
+ path: ["forecast", "band"],
384
+ message: "Forecast band must match the first series from forecast.from, ordered by X.",
385
+ });
386
+ spec.forecast.band?.forEach(([lo, hi], index) => {
387
+ if (lo > hi)
388
+ ctx.addIssue({
389
+ code: "custom",
390
+ path: ["forecast", "band", index],
391
+ message: "Forecast lower bound must not exceed its upper bound.",
392
+ });
393
+ });
394
+ }),
306
395
  z.object({
307
396
  kind: z.literal("scatter"),
308
397
  ...ChartKindCommon,
@@ -438,7 +527,11 @@ export const chartKinds = (limits?: ChartLimits) => {
438
527
  kind: z.literal("pareto"),
439
528
  ...ChartKindCommon,
440
529
  labels: z.tuple([ChartLabel, ChartLabel]),
441
- data: list(z.object({ label: ChartLabel, value: z.number().nonnegative(), prev: z.number().nonnegative() }), 1, limits?.maxValues),
530
+ data: list(
531
+ z.object({ label: ChartLabel, value: z.number().nonnegative(), prev: z.number().nonnegative(), rest: z.boolean().optional() }),
532
+ 1,
533
+ limits?.maxValues,
534
+ ),
442
535
  format: numberFormat.optional(),
443
536
  locale: chartLocaleSchema().optional(),
444
537
  })
@@ -446,6 +539,64 @@ export const chartKinds = (limits?: ChartLimits) => {
446
539
  if (!Number.isFinite(spec.data.reduce((sum, d) => sum + d.value, 0)))
447
540
  ctx.addIssue({ code: "custom", message: "Pareto total must be finite." });
448
541
  }),
542
+ z
543
+ .object({
544
+ kind: z.literal("balanceFlow"),
545
+ ...ChartKindCommon,
546
+ currency: z.string().regex(/^[A-Z]{3}$/),
547
+ locale: chartLocaleSchema().optional(),
548
+ periods: list(
549
+ z.object({
550
+ label: ChartLabel,
551
+ opening: z.number(),
552
+ inflows: list(z.object({ label: ChartLabel, value: z.number().min(0) }), 0, limits?.maxValues),
553
+ outflows: list(z.object({ label: ChartLabel, value: z.number().min(0) }), 0, limits?.maxValues),
554
+ closing: z.number(),
555
+ }),
556
+ 0,
557
+ limits?.maxValues,
558
+ ),
559
+ })
560
+ .superRefine((spec, ctx) => {
561
+ try {
562
+ validateBalanceFlow(spec.periods);
563
+ } catch (error) {
564
+ ctx.addIssue({
565
+ code: "custom",
566
+ path: error instanceof BalanceFlowError ? ["periods", error.period] : ["periods"],
567
+ message: error instanceof Error ? error.message : "Invalid balance flow.",
568
+ });
569
+ }
570
+ }),
571
+ z
572
+ .object({
573
+ kind: z.literal("sankey"),
574
+ ...ChartKindCommon,
575
+ nodes: list(
576
+ z.object({
577
+ id: z.string().min(1),
578
+ label: ChartLabel,
579
+ tone: z.enum(["in", "out", "muted", "blue", "green", "amber", "red", "violet", "tax"]).optional(),
580
+ }),
581
+ 1,
582
+ limits?.maxValues,
583
+ ),
584
+ links: list(z.object({ source: z.string(), target: z.string(), value: z.number().positive() }), 1, limits?.maxMarks),
585
+ legend: list(
586
+ z.object({ tone: z.enum(["in", "out", "muted", "blue", "green", "amber", "red", "violet", "tax"]), label: ChartLabel }),
587
+ 0,
588
+ limits?.maxSeries,
589
+ ).optional(),
590
+ format: numberFormat.optional(),
591
+ locale: chartLocaleSchema().optional(),
592
+ })
593
+ .superRefine((spec, ctx) => {
594
+ try {
595
+ sankeyGraph(spec);
596
+ } catch (error) {
597
+ ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : "Invalid Sankey graph." });
598
+ }
599
+ }),
449
600
  z
450
601
  .object({
451
602
  kind: z.literal("bubble"),