@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.
@@ -1,30 +1,25 @@
1
- /**
2
- * Markup-hiding extension for CodeMirror.
3
- *
4
- * Hides markdown syntax markers when the cursor is not on the same line/range:
5
- * - Heading markers (# ## ### etc.) — hidden when cursor is on a different line
6
- * - Bold markers (**) — hidden when cursor is outside the bold range
7
- * - Italic markers (* or _) — hidden when cursor is outside the italic range
8
- * - Strikethrough markers (~~) — hidden when cursor is outside the range
9
- *
10
- * Also renders horizontal rules (--- / *** / ___) as visual lines.
11
- */
1
+ /** Hide Markdown markers outside the current selection, retaining unchanged blocks. Until the person acts in the editor,
2
+ * nothing is being edited and every marker stays hidden, also on the title line where the caret starts. */
12
3
  import { syntaxTree } from "@codemirror/language";
13
- import type { EditorState, Extension, Range } from "@codemirror/state";
14
- import { RangeSet, StateField } from "@codemirror/state";
15
- import type { DecorationSet } from "@codemirror/view";
16
- import { Decoration, EditorView, WidgetType } from "@codemirror/view";
17
- import { holdsDecorations, refreshMarkdownDecorationsEffect, treeOrDocChanged } from "./_lib/cursor-zone-field";
18
-
19
- // =============================================================================
20
- // Widgets
21
- // =============================================================================
4
+ import type { EditorSelection, EditorState, Extension, Range } from "@codemirror/state";
5
+ import { StateField } from "@codemirror/state";
6
+ import { Decoration, type DecorationSet, EditorView, WidgetType } from "@codemirror/view";
7
+ import {
8
+ changedMarkdownBlocks,
9
+ intersectsMarkdownSpans,
10
+ type MarkdownSpan,
11
+ markdownBlockAt,
12
+ mergeMarkdownSpans,
13
+ } from "./_lib/changed-blocks";
14
+ import {
15
+ holdsDecorations,
16
+ markdownEditorFocused,
17
+ placeMarkdownCaret,
18
+ refreshesMarkdownDecorations,
19
+ revealedSelection,
20
+ } from "./_lib/cursor-zone-field";
22
21
 
23
22
  class HorizontalRuleWidget extends WidgetType {
24
- constructor(private fromPos: number) {
25
- super();
26
- }
27
-
28
23
  override toDOM(view: EditorView) {
29
24
  const hr = document.createElement("div");
30
25
  hr.className = "cm-hr-widget";
@@ -32,354 +27,129 @@ class HorizontalRuleWidget extends WidgetType {
32
27
  hr.onmousedown = (event) => {
33
28
  event.preventDefault();
34
29
  event.stopPropagation();
35
- view.dispatch({ selection: { anchor: this.fromPos }, scrollIntoView: true });
30
+ view.dispatch({ selection: { anchor: view.posAtDOM(hr) }, scrollIntoView: true, effects: placeMarkdownCaret.of() });
36
31
  view.focus();
37
32
  };
38
33
  return hr;
39
34
  }
40
-
41
35
  override eq(other: WidgetType) {
42
- return other instanceof HorizontalRuleWidget && other.fromPos === this.fromPos;
36
+ return other instanceof HorizontalRuleWidget;
43
37
  }
44
-
45
38
  override ignoreEvent() {
46
39
  return true;
47
40
  }
48
41
  }
49
42
 
50
- // =============================================================================
51
- // Decoration builders
52
- // =============================================================================
53
-
54
- /**
55
- * Check if the cursor is on a given line.
56
- */
57
- const cursorOnLine = (state: EditorState, lineFrom: number, lineTo: number): boolean => {
58
- for (const range of state.selection.ranges) {
59
- const rLineFrom = state.doc.lineAt(range.from).number;
60
- const rLineTo = state.doc.lineAt(range.to).number;
61
- const targetLineFrom = state.doc.lineAt(lineFrom).number;
62
- const targetLineTo = state.doc.lineAt(lineTo).number;
63
- if (rLineFrom <= targetLineTo && rLineTo >= targetLineFrom) return true;
64
- }
65
- return false;
66
- };
67
-
68
- /**
69
- * Check if the cursor is inside a range (inclusive).
70
- */
71
- const cursorInRange = (state: EditorState, from: number, to: number): boolean => {
72
- for (const range of state.selection.ranges) {
73
- if (range.from <= to && range.to >= from) return true;
74
- }
75
- return false;
76
- };
77
-
78
- /**
79
- * Collect all code ranges to avoid decorating inside code blocks.
80
- */
81
- const getCodeRanges = (state: EditorState): { from: number; to: number }[] => {
82
- const ranges: { from: number; to: number }[] = [];
83
- syntaxTree(state).iterate({
84
- enter: (node) => {
85
- if (node.type.name === "FencedCode" || node.type.name === "InlineCode" || node.type.name === "CodeBlock") {
86
- ranges.push({ from: node.from, to: node.to });
87
- }
88
- },
89
- });
90
- return ranges;
91
- };
92
-
93
- const isInsideCode = (codeRanges: { from: number; to: number }[], from: number, to: number): boolean =>
94
- codeRanges.some((r) => from >= r.from && to <= r.to);
95
-
96
- /**
97
- * Walk the syntax tree once to collect:
98
- * - Line numbers of every line that hosts a heading / HR
99
- * (cursor-on-line decisions depend on these).
100
- * - Source ranges of every emphasis / strong / strikethrough /
101
- * codespan node (cursor-in-range decisions depend on these).
102
- *
103
- * Cached in the StateField value so subsequent selection-only
104
- * transactions can decide whether to rebuild WITHOUT another
105
- * walk: if the cursor neither changed lines (for line-based
106
- * decorations) nor crossed any tracked range boundary (for
107
- * range-based decorations), nothing's changed and we keep the
108
- * existing decoration set.
109
- */
110
- const collectMarkupTrackedRanges = (state: EditorState): { lines: Set<number>; ranges: Array<{ from: number; to: number }> } => {
111
- const lines = new Set<number>();
112
- const ranges: Array<{ from: number; to: number }> = [];
113
- syntaxTree(state).iterate({
114
- enter: (node) => {
115
- const { name, from, to } = node;
116
- if (name.startsWith("ATXHeading") || name === "HorizontalRule" || name === "SetextHeading") {
117
- const fromLine = state.doc.lineAt(from).number;
118
- const toLine = state.doc.lineAt(to).number;
119
- for (let l = fromLine; l <= toLine; l++) lines.add(l);
120
- return;
121
- }
122
- if (name === "Emphasis" || name === "StrongEmphasis" || name === "Strikethrough" || name === "InlineCode") {
123
- ranges.push({ from, to });
124
- }
125
- },
126
- });
127
- return { lines, ranges };
43
+ const cursorOnLine = (state: EditorState, from: number, to: number): boolean => {
44
+ const first = state.doc.lineAt(from).from;
45
+ const last = state.doc.lineAt(to).to;
46
+ return (revealedSelection(state)?.ranges ?? []).some((range) => range.from <= last && range.to >= first);
128
47
  };
48
+ const cursorInRange = (state: EditorState, from: number, to: number): boolean =>
49
+ (revealedSelection(state)?.ranges ?? []).some((range) => range.from <= to && range.to >= from);
129
50
 
130
- /**
131
- * Build all decorations for markup hiding and horizontal rules.
132
- */
133
- const buildDecorations = (state: EditorState): Range<Decoration>[] => {
51
+ /** `selection` is the selection the decorations reveal around: `null` while the person is not editing. */
52
+ type MarkupState = { decorations: DecorationSet; atomicDecorations: DecorationSet; selection: EditorSelection | null };
53
+ const build = (state: EditorState, span?: MarkdownSpan): MarkupState => {
134
54
  const decorations: Range<Decoration>[] = [];
135
- const codeRanges = getCodeRanges(state);
136
-
55
+ const atomic: Range<Decoration>[] = [];
137
56
  syntaxTree(state).iterate({
138
- enter: (node) => {
57
+ from: span?.from,
58
+ to: span?.to,
59
+ enter(node) {
139
60
  const { name, from, to } = node;
140
-
141
- // ---------------------------------------------------------------
142
- // Headings: hide the "# " marker when cursor is on another line
143
- // ---------------------------------------------------------------
61
+ if (span && (from >= span.to || to <= span.from)) return false;
62
+ // A code subtree is literal; do not search a separate list of code ranges per node.
63
+ if (name === "FencedCode" || name === "CodeBlock" || name === "InlineCode") return false;
144
64
  if (name.startsWith("ATXHeading")) {
145
- if (isInsideCode(codeRanges, from, to)) return;
146
65
  if (cursorOnLine(state, from, to)) return;
147
-
148
- // Find the HeaderMark node (the # characters)
149
- let markEnd = from;
150
- const nodeRef = node.node;
151
- const markCursor = nodeRef.cursor();
152
- if (markCursor.firstChild()) {
153
- do {
154
- if (markCursor.name === "HeaderMark") {
155
- // Include the space after the #
156
- markEnd = markCursor.to;
157
- const afterMark = state.doc.sliceString(markEnd, markEnd + 1);
158
- if (afterMark === " ") markEnd++;
159
- break;
160
- }
161
- } while (markCursor.nextSibling());
162
- }
163
-
164
- if (markEnd > from) {
165
- decorations.push(Decoration.replace({}).range(from, markEnd));
166
- }
167
- return;
168
- }
169
-
170
- // ---------------------------------------------------------------
171
- // Bold: hide ** or __ markers
172
- // ---------------------------------------------------------------
173
- if (name === "StrongEmphasis") {
174
- if (isInsideCode(codeRanges, from, to)) return;
175
- if (cursorInRange(state, from, to)) return;
176
-
177
- const text = state.doc.sliceString(from, to);
178
- const marker = text.startsWith("**") ? "**" : text.startsWith("__") ? "__" : null;
179
- if (!marker) return;
180
-
181
- const markerLen = marker.length;
182
- // Hide opening marker
183
- decorations.push(Decoration.replace({}).range(from, from + markerLen));
184
- // Hide closing marker
185
- decorations.push(Decoration.replace({}).range(to - markerLen, to));
186
- return;
187
- }
188
-
189
- // ---------------------------------------------------------------
190
- // Italic: hide * or _ markers
191
- // ---------------------------------------------------------------
192
- if (name === "Emphasis") {
193
- if (isInsideCode(codeRanges, from, to)) return;
66
+ const mark = node.node.getChild("HeaderMark");
67
+ if (mark) decorations.push(Decoration.replace({}).range(from, mark.to + Number(state.sliceDoc(mark.to, mark.to + 1) === " ")));
68
+ } else if (name === "StrongEmphasis" || name === "Emphasis" || name === "Strikethrough") {
194
69
  if (cursorInRange(state, from, to)) return;
195
-
196
- const text = state.doc.sliceString(from, to);
197
- const marker = text.startsWith("*") ? "*" : text.startsWith("_") ? "_" : null;
198
- if (!marker) return;
199
-
200
- const markerLen = marker.length;
201
- // Hide opening marker
202
- decorations.push(Decoration.replace({}).range(from, from + markerLen));
203
- // Hide closing marker
204
- decorations.push(Decoration.replace({}).range(to - markerLen, to));
205
- return;
206
- }
207
-
208
- // ---------------------------------------------------------------
209
- // Strikethrough: hide ~~ markers
210
- // ---------------------------------------------------------------
211
- if (name === "Strikethrough") {
212
- if (isInsideCode(codeRanges, from, to)) return;
213
- if (cursorInRange(state, from, to)) return;
214
-
215
- // Hide opening ~~
216
- decorations.push(Decoration.replace({}).range(from, from + 2));
217
- // Hide closing ~~
218
- decorations.push(Decoration.replace({}).range(to - 2, to));
219
- return;
220
- }
221
-
222
- // ---------------------------------------------------------------
223
- // Horizontal Rule: replace --- / *** / ___ with a visual line
224
- // ---------------------------------------------------------------
225
- if (name === "HorizontalRule") {
226
- if (cursorOnLine(state, from, to)) return;
227
-
228
- decorations.push(
229
- Decoration.replace({
230
- widget: new HorizontalRuleWidget(from),
231
- block: true,
232
- }).range(from, to),
233
- );
234
- return;
70
+ const size = name === "Emphasis" ? 1 : 2;
71
+ decorations.push(Decoration.replace({}).range(from, from + size), Decoration.replace({}).range(to - size, to));
72
+ } else if (name === "HorizontalRule" && !cursorOnLine(state, from, to)) {
73
+ const rule = Decoration.replace({ widget: new HorizontalRuleWidget(), block: true }).range(from, to);
74
+ decorations.push(rule);
75
+ atomic.push(rule);
235
76
  }
236
77
  },
237
78
  });
238
-
239
- return decorations;
79
+ return {
80
+ decorations: Decoration.set(decorations, true),
81
+ atomicDecorations: Decoration.set(atomic, true),
82
+ selection: revealedSelection(state),
83
+ };
240
84
  };
241
85
 
242
- const buildAtomicDecorations = (state: EditorState): Range<Decoration>[] => {
243
- const decorations: Range<Decoration>[] = [];
244
- syntaxTree(state).iterate({
245
- enter: ({ name, from, to }) => {
246
- if (name !== "HorizontalRule") return;
247
- if (cursorOnLine(state, from, to)) return;
248
- decorations.push(
249
- Decoration.replace({
250
- widget: new HorizontalRuleWidget(from),
251
- block: true,
252
- }).range(from, to),
253
- );
254
- },
86
+ const replaceBlocks = (previous: DecorationSet, additions: readonly DecorationSet[], spans: readonly MarkdownSpan[]): DecorationSet => {
87
+ if (!spans.length) return previous;
88
+ const add: Range<Decoration>[] = [];
89
+ for (const set of additions)
90
+ for (let cursor = set.iter(); cursor.value; cursor.next()) add.push(cursor.value.range(cursor.from, cursor.to));
91
+ return previous.update({
92
+ filterFrom: spans[0]!.from,
93
+ filterTo: spans.at(-1)!.to,
94
+ filter: (from, to) => from < to && !intersectsMarkdownSpans(spans, from, to),
95
+ add,
96
+ sort: true,
255
97
  });
256
- return decorations;
257
- };
258
-
259
- // =============================================================================
260
- // Extension
261
- // =============================================================================
262
-
263
- /** All decoration-affecting ranges discovered during the last
264
- * rebuild. Markup makes two kinds of cursor-sensitive decisions:
265
- *
266
- * - LINE-BASED (`cursorOnLine`): headings + HRs. Rebuild needed
267
- * when the cursor moves to a different line.
268
- *
269
- * - RANGE-BASED (`cursorInRange`): emphasis / strong markers.
270
- * Rebuild needed when the cursor's containment status changes
271
- * for any tracked range (entered or left any of them).
272
- *
273
- * We cache both so the `update()` can decide whether to rebuild
274
- * by comparing the new cursor's relationship to these ranges
275
- * against the old state's. */
276
- type MarkupState = {
277
- decorations: DecorationSet;
278
- atomicDecorations: DecorationSet;
279
- /** Line numbers of every line that has a cursor-sensitive
280
- * decoration (heading, HR). If the cursor crosses any of these
281
- * lines, we rebuild. */
282
- cursorSensitiveLines: Set<number>;
283
- /** Emphasis / strong ranges — decisions depend on `cursorInRange`. */
284
- cursorSensitiveRanges: Array<{ from: number; to: number }>;
285
- /** Cached current cursor signature so we can compare across
286
- * transactions cheaply. */
287
- cursorLine: number;
288
- cursorRangeKey: string;
289
- };
290
-
291
- const cursorLineNumber = (state: EditorState): number => state.doc.lineAt(state.selection.main.head).number;
292
-
293
- /** Compact "set of ranges the cursor is inside" identifier. We use
294
- * a sorted comma-separated index string so equality is a cheap
295
- * string compare. */
296
- const computeCursorRangeKey = (state: EditorState, ranges: Array<{ from: number; to: number }>): string => {
297
- const cursor = state.selection.main;
298
- const hits: number[] = [];
299
- for (let i = 0; i < ranges.length; i++) {
300
- const r = ranges[i]!;
301
- if (cursor.from <= r.to && cursor.to >= r.from) hits.push(i);
302
- }
303
- return hits.join(",");
304
98
  };
305
99
 
306
100
  export const markupExtension = (): Extension => {
307
- const stateField = StateField.define<MarkupState>({
308
- create(state) {
309
- const tracked = collectMarkupTrackedRanges(state);
310
- return {
311
- decorations: RangeSet.of(buildDecorations(state), true),
312
- atomicDecorations: RangeSet.of(buildAtomicDecorations(state), true),
313
- cursorSensitiveLines: tracked.lines,
314
- cursorSensitiveRanges: tracked.ranges,
315
- cursorLine: cursorLineNumber(state),
316
- cursorRangeKey: computeCursorRangeKey(state, tracked.ranges),
317
- };
318
- },
101
+ const field = StateField.define<MarkupState>({
102
+ create: build,
319
103
  update(value, tr) {
320
- if (treeOrDocChanged(tr) || tr.effects.some((effect) => effect.is(refreshMarkdownDecorationsEffect))) {
321
- // Keep cached cursor signatures consistent with the rebuilt decorations.
322
- const tracked = collectMarkupTrackedRanges(tr.state);
323
- return {
324
- decorations: RangeSet.of(buildDecorations(tr.state), true),
325
- atomicDecorations: RangeSet.of(buildAtomicDecorations(tr.state), true),
326
- cursorSensitiveLines: tracked.lines,
327
- cursorSensitiveRanges: tracked.ranges,
328
- cursorLine: cursorLineNumber(tr.state),
329
- cursorRangeKey: computeCursorRangeKey(tr.state, tracked.ranges),
330
- };
331
- }
332
- if (holdsDecorations(tr)) return value;
333
- if (!tr.selection) {
334
- return value;
335
- }
336
- // Selection moved. Two checks:
337
- // 1. Cursor changed line AND old or new line had a markup
338
- // decoration (heading / HR). Rebuild.
339
- // 2. Cursor crossed an emphasis/strong range boundary
340
- // (entered or left). Rebuild.
341
- const newLine = cursorLineNumber(tr.state);
342
- const lineChangedAndMatters =
343
- newLine !== value.cursorLine && (value.cursorSensitiveLines.has(value.cursorLine) || value.cursorSensitiveLines.has(newLine));
344
- const newRangeKey = computeCursorRangeKey(tr.state, value.cursorSensitiveRanges);
345
- const rangesChanged = newRangeKey !== value.cursorRangeKey;
346
- if (!lineChangedAndMatters && !rangesChanged) {
347
- // Selection moved but didn't affect any markup decision —
348
- // skip the rebuild. This is the common case for typing
349
- // within a plain paragraph: lots of cursor moves with no
350
- // decoration impact.
351
- return { ...value, cursorLine: newLine };
104
+ // An explicit refresh, or the person starting or stopping to edit, redraws the blocks around the selection too.
105
+ const refresh = refreshesMarkdownDecorations(tr);
106
+ const spans = [...changedMarkdownBlocks(tr)];
107
+ if ((!holdsDecorations(tr) && tr.selection) || refresh) {
108
+ for (const range of value.selection?.ranges ?? []) {
109
+ const block = markdownBlockAt(syntaxTree(tr.startState), range.from);
110
+ const end = markdownBlockAt(syntaxTree(tr.startState), range.to);
111
+ spans.push({ from: tr.changes.mapPos(block.from, -1), to: tr.changes.mapPos(end.to, 1) });
112
+ }
113
+ for (const range of revealedSelection(tr.state)?.ranges ?? []) {
114
+ spans.push({
115
+ from: markdownBlockAt(syntaxTree(tr.state), range.from).from,
116
+ to: markdownBlockAt(syntaxTree(tr.state), range.to).to,
117
+ });
118
+ }
352
119
  }
353
- const tracked = collectMarkupTrackedRanges(tr.state);
120
+ const merged = mergeMarkdownSpans(spans);
121
+ const additions = merged.map((span) => build(tr.state, span));
354
122
  return {
355
- decorations: RangeSet.of(buildDecorations(tr.state), true),
356
- atomicDecorations: RangeSet.of(buildAtomicDecorations(tr.state), true),
357
- cursorSensitiveLines: tracked.lines,
358
- cursorSensitiveRanges: tracked.ranges,
359
- cursorLine: newLine,
360
- cursorRangeKey: computeCursorRangeKey(tr.state, tracked.ranges),
123
+ decorations: replaceBlocks(
124
+ value.decorations.map(tr.changes),
125
+ additions.map((next) => next.decorations),
126
+ merged,
127
+ ),
128
+ atomicDecorations: replaceBlocks(
129
+ value.atomicDecorations.map(tr.changes),
130
+ additions.map((next) => next.atomicDecorations),
131
+ merged,
132
+ ),
133
+ selection: holdsDecorations(tr) ? (value.selection?.map(tr.changes) ?? null) : revealedSelection(tr.state),
361
134
  };
362
135
  },
363
- provide(field) {
364
- return [
365
- EditorView.decorations.from(field, (v) => v.decorations),
366
- EditorView.atomicRanges.of((view) => view.state.field(field).atomicDecorations),
367
- ];
368
- },
136
+ provide: (field) => [
137
+ EditorView.decorations.from(field, (value) => value.decorations),
138
+ EditorView.atomicRanges.of((view) => view.state.field(field).atomicDecorations),
139
+ ],
369
140
  });
370
-
371
- const theme = EditorView.theme({
372
- ".cm-hr-widget": {
373
- borderTop: "2px solid",
374
- borderColor: "var(--color-zinc-300)",
375
- margin: "0 !important",
376
- padding: "0.75em 0 0",
377
- boxSizing: "border-box",
378
- },
379
- ".dark .cm-hr-widget": {
380
- borderColor: "var(--color-zinc-600)",
381
- },
382
- });
383
-
384
- return [stateField, theme];
141
+ return [
142
+ markdownEditorFocused,
143
+ field,
144
+ EditorView.theme({
145
+ ".cm-hr-widget": {
146
+ borderTop: "2px solid",
147
+ borderColor: "var(--color-zinc-300)",
148
+ margin: "0 !important",
149
+ padding: "0.75em 0 0",
150
+ boxSizing: "border-box",
151
+ },
152
+ ".dark .cm-hr-widget": { borderColor: "var(--color-zinc-600)" },
153
+ }),
154
+ ];
385
155
  };
@@ -9,6 +9,8 @@ import {
9
9
  blockWidgetLineNavigationExtension,
10
10
  type CursorZoneState,
11
11
  cursorZoneStateField,
12
+ placeMarkdownCaret,
13
+ revealedSelection,
12
14
  selectionIntersectsRange,
13
15
  } from "./_lib/cursor-zone-field";
14
16
  import { codeFenceLanguage } from "./lib/markdown-fences";
@@ -80,7 +82,7 @@ class MermaidWidget extends WidgetType {
80
82
  container.className = "cm-mermaid-widget !m-0";
81
83
  container.setAttribute("contenteditable", "false");
82
84
  const edit = () => {
83
- view.dispatch({ selection: { anchor: this.fromPos }, scrollIntoView: true });
85
+ view.dispatch({ selection: { anchor: this.fromPos }, scrollIntoView: true, effects: placeMarkdownCaret.of() });
84
86
  view.focus();
85
87
  };
86
88
  // At fit a press edits the source, as it always has. Zoomed in, a press
@@ -195,7 +197,7 @@ export const mermaidExtension = (options: MermaidOptions): Extension => {
195
197
  const decorations: Range<Decoration>[] = [];
196
198
  const atomicDecorations: Range<Decoration>[] = [];
197
199
  const ranges: { from: number; to: number }[] = [];
198
- const cursor = state.selection.main;
200
+ const cursor = revealedSelection(state)?.main;
199
201
  let widgetId = 0;
200
202
 
201
203
  syntaxTree(state).iterate({
@@ -4,6 +4,8 @@ import {
4
4
  blockWidgetLineNavigationExtension,
5
5
  type CursorZoneState,
6
6
  cursorZoneStateField,
7
+ placeMarkdownCaret,
8
+ revealedSelection,
7
9
  selectionIntersectsRange,
8
10
  } from "./_lib/cursor-zone-field";
9
11
  import { extractNamedBlocks } from "./lib/named-blocks";
@@ -32,7 +34,7 @@ class NamedBlockHandleWidget extends WidgetType {
32
34
  el.onmousedown = (event) => {
33
35
  event.preventDefault();
34
36
  event.stopPropagation();
35
- view.dispatch({ selection: { anchor: this.fromPos }, scrollIntoView: true });
37
+ view.dispatch({ selection: { anchor: this.fromPos }, scrollIntoView: true, effects: placeMarkdownCaret.of() });
36
38
  view.focus();
37
39
  };
38
40
  return el;
@@ -52,7 +54,7 @@ export const namedBlocksExtension = (): Extension => {
52
54
  const decorations: Range<Decoration>[] = [];
53
55
  const atomicDecorations: Range<Decoration>[] = [];
54
56
  const ranges: { from: number; to: number }[] = [];
55
- const cursor = state.selection.main;
57
+ const cursor = revealedSelection(state)?.main;
56
58
  const text = state.doc.toString();
57
59
 
58
60
  for (const block of extractNamedBlocks(text)) {
@@ -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, mountBalanceFlow, 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
  });
@@ -106,6 +106,8 @@ function ChartControls(props: { figure: HTMLElement; viewport: HTMLElement; draw
106
106
  */
107
107
  export function enhanceNotebookCharts(root: HTMLElement, locale: string, options: Pick<MarkdownChartOptions, "schema">): () => void {
108
108
  const cleanups: (() => void)[] = [];
109
+ for (const frame of root.querySelectorAll<HTMLElement>("[data-balance-flow]:not([data-balance-mounted])"))
110
+ cleanups.push(mountBalanceFlow(frame, { locale }));
109
111
  for (const figure of root.querySelectorAll<HTMLElement>("figure.notebook-book-chart[data-chart]:not([data-enhanced])")) {
110
112
  const chart = figure.querySelector<HTMLElement>(".notebook-book-chart__viewport > .k2b-chart");
111
113
  const viewport = chart?.parentElement;
@@ -125,7 +127,12 @@ export function enhanceNotebookCharts(root: HTMLElement, locale: string, options
125
127
  if (input.kind === "heatmap" && input.layout === "calendar") cleanups.push(mountCalendarScroll(chart));
126
128
  const inspection = inspectChart(chart, {
127
129
  kind: input.kind,
128
- nav: input.kind === "heatmap" && input.layout === "calendar" ? calendarInspectionNavigation : undefined,
130
+ nav:
131
+ input.kind === "sankey"
132
+ ? sankeyInspectionNavigation
133
+ : input.kind === "heatmap" && input.layout === "calendar"
134
+ ? calendarInspectionNavigation
135
+ : undefined,
129
136
  locale,
130
137
  legend: figure,
131
138
  format: ({ datum }) => lazy().tooltips.get(chartMarkKey(datum)) ?? { rows: [] },
@@ -58,7 +58,15 @@ import { Decoration, type DecorationSet, EditorView, keymap, WidgetType } from "
58
58
  import { i18n } from "@k2b/stdlib";
59
59
  import { clipboard } from "@k2b/stdlib/browser";
60
60
  import { type EvalContext, type EvalResult, evaluateFormula, isFormula } from "../formula";
61
- import { holdsDecorations, refreshMarkdownDecorationsEffect, selectionIntersectsRange, treeOrDocChanged } from "./_lib/cursor-zone-field";
61
+ import {
62
+ holdsDecorations,
63
+ markdownEditorFocused,
64
+ placeMarkdownCaret,
65
+ refreshesMarkdownDecorations,
66
+ revealedSelection,
67
+ selectionIntersectsRange,
68
+ treeOrDocChanged,
69
+ } from "./_lib/cursor-zone-field";
62
70
  import { splitTableLineCells, tableCellText } from "./_lib/table-cell";
63
71
  import { isNamedBlockHandle } from "./lib/named-blocks";
64
72
  import { applyLigatures } from "./ligatures";
@@ -322,7 +330,7 @@ class TableWidget extends WidgetType {
322
330
  }
323
331
  event.preventDefault();
324
332
  event.stopPropagation();
325
- view.dispatch({ selection: { anchor: this.fromPos } });
333
+ view.dispatch({ selection: { anchor: this.fromPos }, effects: placeMarkdownCaret.of() });
326
334
  view.focus();
327
335
  };
328
336
  // CM's default `dblclick` handler runs INDEPENDENTLY of mousedown.
@@ -423,8 +431,8 @@ type TablesState = {
423
431
  * This makes the table behave consistently regardless of approach
424
432
  * direction. */
425
433
  const cursorTableKey = (state: EditorState, ranges: TableRange[]): string | null => {
426
- if (ranges.length === 0) return null;
427
- const cursor = state.selection.main;
434
+ const cursor = revealedSelection(state)?.main;
435
+ if (ranges.length === 0 || !cursor) return null;
428
436
  const hits: number[] = [];
429
437
  for (const r of ranges) {
430
438
  const prevLineStart = state.doc.lineAt(Math.max(r.from - 1, 0)).from;
@@ -444,7 +452,7 @@ const scanTables = (state: EditorState, presentation: PrettyTableOptions): Table
444
452
  const decorations: Range<Decoration>[] = [];
445
453
  const blockWidgetDecorations: Range<Decoration>[] = [];
446
454
  const tableRanges: TableRange[] = [];
447
- const cursor = state.selection.main;
455
+ const cursor = revealedSelection(state)?.main;
448
456
 
449
457
  syntaxTree(state).iterate({
450
458
  enter: (node) => {
@@ -504,7 +512,7 @@ export const tablesExtension = (presentation: PrettyTableOptions = {}): Extensio
504
512
  return scanTables(state, presentation);
505
513
  },
506
514
  update(value, tr) {
507
- if (tr.effects.some((effect) => effect.is(refreshMarkdownDecorationsEffect))) {
515
+ if (refreshesMarkdownDecorations(tr)) {
508
516
  return scanTables(tr.state, presentation);
509
517
  }
510
518
  // Doc or syntax tree changed → tables may have appeared /
@@ -677,7 +685,7 @@ export const tablesExtension = (presentation: PrettyTableOptions = {}): Extensio
677
685
  // No view-level mousedown handler — the widget's own onmousedown
678
686
  // captures the click + stopPropagation prevents CM's internal
679
687
  // logic from running posAtDOM against widget-DOM targets.
680
- return [stateField, theme, tableNavKeymap];
688
+ return [markdownEditorFocused, stateField, theme, tableNavKeymap];
681
689
  };
682
690
 
683
691
  /** Check whether the document range [from, to] is covered by a