@k2b/editor 0.10.0 → 0.11.1

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,7 +1,8 @@
1
1
  import type { EditorState, Extension, Range, Transaction } from "@codemirror/state";
2
2
  import { StateField } from "@codemirror/state";
3
3
  import { Decoration, type DecorationSet, EditorView, ViewPlugin, WidgetType } from "@codemirror/view";
4
- import { treeOrDocChanged } from "./_lib/cursor-zone-field";
4
+ import { changedMarkdownBlocks, intersectsMarkdownSpans } from "./_lib/changed-blocks";
5
+ import { markdownEditorFocused, revealedSelection, treeOrDocChanged } from "./_lib/cursor-zone-field";
5
6
  import {
6
7
  type ExcludedSpan,
7
8
  excludedSpans,
@@ -81,7 +82,9 @@ const decorated = (state: EditorState, item: ListItem): boolean =>
81
82
  : /[ \t]/.test(state.sliceDoc(item.markerTo, item.markerTo + 1));
82
83
 
83
84
  const selectionParent = (state: EditorState, structure: ListStructure): number => {
84
- const index = listItemAtLine(structure, state.doc.lineAt(state.selection.main.head).number);
85
+ const cursor = revealedSelection(state)?.main;
86
+ if (!cursor) return -1;
87
+ const index = listItemAtLine(structure, state.doc.lineAt(cursor.head).number);
85
88
  return structure.items[index]?.parent ?? -1;
86
89
  };
87
90
 
@@ -106,13 +109,44 @@ type ListState = {
106
109
  parent: number;
107
110
  };
108
111
 
109
- const build = (state: EditorState, cached?: readonly ExcludedSpan[]): ListState => {
112
+ const build = (state: EditorState, cached?: readonly ExcludedSpan[], incremental?: { value: ListState; tr: Transaction }): ListState => {
110
113
  let excluded = cached;
114
+ const spans = incremental ? changedMarkdownBlocks(incremental.tr) : undefined;
111
115
  // Notebook blocks are outside Markdown's grammar. Read their source only when lists exist.
112
- const structure = listStructure(state, () => (excluded ??= excludedSpans(state)));
116
+ const readExcluded = () => (excluded ??= excludedSpans(state));
117
+ let structure: ListStructure;
118
+ if (incremental && spans) {
119
+ const map = (position: number) => incremental.tr.changes.mapPos(position);
120
+ const items: ListItem[] = incremental.value.structure.items
121
+ .filter((item) => !intersectsMarkdownSpans(spans, map(item.markerFrom), map(item.markerTo)))
122
+ .map((item) => ({
123
+ ...item,
124
+ from: map(item.from),
125
+ to: map(item.to),
126
+ line: state.doc.lineAt(map(item.from)).number,
127
+ markerFrom: map(item.markerFrom),
128
+ markerTo: map(item.markerTo),
129
+ contentFrom: map(item.contentFrom),
130
+ taskFrom: item.taskFrom === null ? null : map(item.taskFrom),
131
+ taskTo: item.taskTo === null ? null : map(item.taskTo),
132
+ listFrom: map(item.listFrom),
133
+ }));
134
+ for (const span of spans) items.push(...listStructure(state, readExcluded, span).items);
135
+ items.sort((a, b) => a.from - b.from);
136
+ const parents: number[] = [];
137
+ for (let index = 0; index < items.length; index++) {
138
+ const item = items[index]!;
139
+ while (parents.length > item.depth) items[parents.pop()!]!.subtreeEnd = index;
140
+ item.parent = parents.at(-1) ?? -1;
141
+ parents.push(index);
142
+ }
143
+ for (const index of parents) items[index]!.subtreeEnd = items.length;
144
+ structure = { items };
145
+ } else structure = listStructure(state, readExcluded);
113
146
  const ranges: Range<Decoration>[] = [];
114
147
  const atomic: Range<Decoration>[] = [];
115
148
  for (const item of structure.items) {
149
+ if (spans && !intersectsMarkdownSpans(spans, item.from, item.contentFrom)) continue;
116
150
  if (!decorated(state, item)) continue;
117
151
  ranges.push(
118
152
  Decoration.line({
@@ -131,11 +165,21 @@ const build = (state: EditorState, cached?: readonly ExcludedSpan[]): ListState
131
165
  atomic.push(gutter);
132
166
  }
133
167
  const parent = selectionParent(state, structure);
168
+ const update = (previous: DecorationSet, add: Range<Decoration>[]) => {
169
+ let result = previous.map(incremental!.tr.changes);
170
+ if (spans!.length)
171
+ result = result.update({
172
+ filterFrom: spans![0]!.from,
173
+ filterTo: spans!.at(-1)!.to,
174
+ filter: (from, to) => !intersectsMarkdownSpans(spans!, from, from === to ? from + 1 : to),
175
+ });
176
+ return result.update({ add, sort: true });
177
+ };
134
178
  return {
135
179
  excluded,
136
180
  structure,
137
- decorations: Decoration.set(ranges, true),
138
- atomicRanges: Decoration.set(atomic, true),
181
+ decorations: incremental ? update(incremental.value.decorations, ranges) : Decoration.set(ranges, true),
182
+ atomicRanges: incremental ? update(incremental.value.atomicRanges, atomic) : Decoration.set(atomic, true),
139
183
  active: activeGuides(state, structure, parent),
140
184
  parent,
141
185
  };
@@ -179,10 +223,10 @@ export const listStateField = StateField.define<ListState>({
179
223
  from: tr.changes.mapPos(span.from, -1),
180
224
  to: tr.changes.mapPos(span.to, 1),
181
225
  }));
182
- return build(tr.state, exclusionsChanged(tr) ? undefined : excluded);
226
+ return exclusionsChanged(tr) ? build(tr.state) : build(tr.state, excluded, { value, tr });
183
227
  }
184
228
  // Parser progress changes the list tree, but not the source-scanned spans.
185
- if (treeOrDocChanged(tr)) return build(tr.state, value.excluded);
229
+ if (treeOrDocChanged(tr)) return build(tr.state, value.excluded, { value, tr });
186
230
  const parent = selectionParent(tr.state, value.structure);
187
231
  return {
188
232
  ...value,
@@ -194,6 +238,7 @@ export const listStateField = StateField.define<ListState>({
194
238
  },
195
239
  provide(field) {
196
240
  return [
241
+ markdownEditorFocused,
197
242
  EditorView.decorations.from(field, (value) => value.decorations),
198
243
  EditorView.decorations.from(field, (value) => value.active),
199
244
  EditorView.atomicRanges.of((view) => view.state.field(field).atomicRanges),
@@ -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)) {