@mdbase-dev/ui 0.1.0-beta.164 → 0.1.0-beta.166

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.
@@ -0,0 +1,418 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { Decoration, EditorView, ViewPlugin, WidgetType } from "@codemirror/view";
3
+ import { i18n as _i18n } from "@lingui/core";
4
+ import { calloutHeader } from "./blocks.js";
5
+ import { isRevealed, revealChanged } from "./reveal.js";
6
+ const hide = Decoration.replace({});
7
+ const muted = Decoration.mark({
8
+ class: "cm-lp-mark"
9
+ });
10
+ const styles = {
11
+ Emphasis: Decoration.mark({
12
+ class: "cm-lp-em"
13
+ }),
14
+ StrongEmphasis: Decoration.mark({
15
+ class: "cm-lp-strong"
16
+ }),
17
+ Strikethrough: Decoration.mark({
18
+ class: "cm-lp-strike"
19
+ }),
20
+ InlineCode: Decoration.mark({
21
+ class: "cm-lp-code"
22
+ })
23
+ };
24
+ const inlineMarks = {
25
+ Emphasis: "EmphasisMark",
26
+ StrongEmphasis: "EmphasisMark",
27
+ Strikethrough: "StrikethroughMark",
28
+ InlineCode: "CodeMark"
29
+ };
30
+ const headingLines = Array.from({
31
+ length: 6
32
+ }, (_, index) => Decoration.line({
33
+ class: `cm-lp-heading cm-lp-h${index + 1}`
34
+ }));
35
+ const headingMark = Decoration.mark({
36
+ class: "cm-lp-mark cm-lp-outdent"
37
+ });
38
+ const quoteMark = Decoration.mark({
39
+ class: "cm-lp-mark cm-lp-outdent"
40
+ });
41
+ const escaped = Decoration.mark({
42
+ class: "cm-lp-escaped"
43
+ });
44
+ const ruleLine = Decoration.line({
45
+ class: "cm-lp-rule"
46
+ });
47
+ /** A list item's indent, bullet or number and task box as one box, as wide as its revealed source. */
48
+ class ListPrefixWidget extends WidgetType {
49
+ prefix;
50
+ constructor(prefix) {
51
+ super();
52
+ this.prefix = prefix;
53
+ }
54
+ eq(other) {
55
+ const a = this.prefix,
56
+ b = other.prefix;
57
+ return a.leading === b.leading && a.width === b.width && a.marker === b.marker && a.markerWidth === b.markerWidth && a.depth === b.depth && a.task?.from === b.task?.from && a.task?.checked === b.task?.checked;
58
+ }
59
+ toDOM() {
60
+ const {
61
+ leading,
62
+ width,
63
+ marker,
64
+ markerWidth,
65
+ depth,
66
+ task
67
+ } = this.prefix;
68
+ const box = document.createElement("span");
69
+ box.className = "cm-lp-list-prefix";
70
+ box.style.paddingLeft = `${leading}ch`;
71
+ const bullet = /^[-+*]$/.test(marker);
72
+ // A task's checkbox takes its bullet's place.
73
+ if (!(bullet && task)) {
74
+ const mark = document.createElement("span");
75
+ mark.className = bullet ? `cm-lp-bullet cm-lp-bullet-${depth % 3}` : "cm-lp-ordinal";
76
+ if (bullet) mark.setAttribute("aria-hidden", "true");else mark.textContent = marker;
77
+ mark.style.width = `${markerWidth + 1}ch`;
78
+ box.append(mark);
79
+ }
80
+ if (task) box.append(taskBox(task.from, task.checked));
81
+ box.style.width = `${width}ch`;
82
+ return box;
83
+ }
84
+ ignoreEvent() {
85
+ return false;
86
+ }
87
+ }
88
+ function taskBox(from, checked) {
89
+ const box = document.createElement("button");
90
+ box.type = "button";
91
+ box.className = "cm-lp-task mdbase-checkbox";
92
+ box.dataset.taskFrom = String(from);
93
+ box.setAttribute("role", "checkbox");
94
+ box.setAttribute("aria-checked", String(checked));
95
+ const label = checked ? _i18n._(
96
+ /** i18n */
97
+ {
98
+ id: "7aCOX4",
99
+ message: "Mark task incomplete"
100
+ }) : _i18n._(
101
+ /** i18n */
102
+ {
103
+ id: "rb0pGu",
104
+ message: "Mark task complete"
105
+ });
106
+ box.setAttribute("aria-label", label);
107
+ box.title = label;
108
+ return box;
109
+ }
110
+ /** Rendered Markdown: markers hide away from the selection, and lists, tasks and links read as written. */
111
+ export function inlinePreview(options) {
112
+ return ViewPlugin.fromClass(class {
113
+ decorations;
114
+ atomic;
115
+ constructor(view) {
116
+ ({
117
+ decorations: this.decorations,
118
+ atomic: this.atomic
119
+ } = build(view, options));
120
+ }
121
+ update(update) {
122
+ if (update.docChanged || update.viewportChanged || revealChanged(update) || syntaxTree(update.startState) !== syntaxTree(update.state) || update.transactions.some(transaction => transaction.reconfigured) || options.refresh?.(update)) {
123
+ ({
124
+ decorations: this.decorations,
125
+ atomic: this.atomic
126
+ } = build(update.view, options));
127
+ }
128
+ }
129
+ }, {
130
+ decorations: plugin => plugin.decorations,
131
+ provide: plugin => EditorView.atomicRanges.of(view => view.plugin(plugin)?.atomic ?? Decoration.none)
132
+ });
133
+ }
134
+ function build(view, options) {
135
+ return buildRanges(view.state, options, view.visibleRanges);
136
+ }
137
+ function buildRanges(state, options, visibleRanges) {
138
+ const ranges = [];
139
+ const hidden = [];
140
+ const conceal = (from, to) => {
141
+ if (from >= to) return;
142
+ ranges.push(hide.range(from, to));
143
+ hidden.push(hide.range(from, to));
144
+ };
145
+ const line = position => state.doc.lineAt(position);
146
+ const lineRevealed = position => {
147
+ const current = line(position);
148
+ return isRevealed(state, current.from, current.to);
149
+ };
150
+ for (const visible of visibleRanges) {
151
+ syntaxTree(state).iterate({
152
+ from: visible.from,
153
+ to: visible.to,
154
+ enter(node) {
155
+ const name = node.name;
156
+ if (name === "Image" || name === "FencedCode" || name === "CodeBlock" || name === "HTMLBlock") return false;
157
+ const heading = /^ATXHeading([1-6])$/.exec(name);
158
+ if (heading) {
159
+ ranges.push(headingLines[Number(heading[1]) - 1].range(line(node.from).from));
160
+ const revealed = lineRevealed(node.from);
161
+ for (const mark of children(node, "HeaderMark")) {
162
+ if (revealed) {
163
+ ranges.push((mark.from === node.from ? headingMark : muted).range(mark.from, mark.to));
164
+ } else {
165
+ // The opening mark takes its space with it; a closing mark the space before it.
166
+ const opening = mark.from === node.from;
167
+ const from = opening ? mark.from : trimStart(state, node.from, mark.from);
168
+ const to = opening ? skipSpaces(state, mark.to, node.to) : mark.to;
169
+ conceal(from, to);
170
+ }
171
+ }
172
+ return;
173
+ }
174
+ if (name in inlineMarks) {
175
+ ranges.push(styles[name].range(node.from, node.to));
176
+ const revealed = isRevealed(state, node.from, node.to);
177
+ for (const mark of children(node, inlineMarks[name])) {
178
+ if (revealed) ranges.push(muted.range(mark.from, mark.to));else conceal(mark.from, mark.to);
179
+ }
180
+ return name === "InlineCode" ? false : undefined;
181
+ }
182
+ if (name === "Link") {
183
+ if (/^\[\^[^\]\s]+\]$/.test(state.sliceDoc(node.from, node.to))) return false;
184
+ renderLink(state, node, options, ranges, conceal);
185
+ return false;
186
+ }
187
+ if (name === "URL" && node.node.parent?.name !== "Link" && node.node.parent?.name !== "LinkReference") {
188
+ ranges.push(linkMark(node.from, state.sliceDoc(node.from, node.to), "markdown", false).range(node.from, node.to));
189
+ return;
190
+ }
191
+ if (name === "Escape") {
192
+ if (!isRevealed(state, node.from, node.to)) {
193
+ conceal(node.from, node.from + 1);
194
+ ranges.push(escaped.range(node.from + 1, node.to));
195
+ }
196
+ return;
197
+ }
198
+ if (name === "Blockquote") {
199
+ renderQuote(state, node, ranges);
200
+ return;
201
+ }
202
+ if (name === "QuoteMark") {
203
+ const current = line(node.from);
204
+ if (calloutHeader(current.text)) return;
205
+ if (isRevealed(state, current.from, current.to)) ranges.push(quoteMark.range(node.from, node.to));else conceal(node.from, skipSpaces(state, node.to, current.to, 1));
206
+ return;
207
+ }
208
+ if (name === "ListMark") {
209
+ renderListMark(state, node, ranges, hidden);
210
+ return;
211
+ }
212
+ if (name === "HorizontalRule") {
213
+ if (lineRevealed(node.from)) ranges.push(muted.range(node.from, node.to));else {
214
+ ranges.push(ruleLine.range(line(node.from).from));
215
+ conceal(node.from, node.to);
216
+ }
217
+ return;
218
+ }
219
+ }
220
+ });
221
+ }
222
+ return {
223
+ decorations: Decoration.set(ranges, true),
224
+ atomic: Decoration.set(hidden, true)
225
+ };
226
+ }
227
+ function renderLink(state, node, options, ranges, conceal) {
228
+ const url = node.node.getChild("URL");
229
+ // The Markdown grammar reads [[target]] as a Link around [target].
230
+ const wiki = !url && node.from > 0 && state.sliceDoc(node.from - 1, node.from) === "[" && state.sliceDoc(node.to, node.to + 1) === "]";
231
+ const from = wiki ? node.from - 1 : node.from;
232
+ const to = wiki ? node.to + 1 : node.to;
233
+ const revealed = isRevealed(state, from, to);
234
+ const marks = children(node, "LinkMark");
235
+ if (wiki) {
236
+ const inner = state.sliceDoc(from + 2, to - 2);
237
+ const pipe = inner.indexOf("|");
238
+ const target = (pipe < 0 ? inner : inner.slice(0, pipe)).trim();
239
+ const textFrom = pipe < 0 ? from + 2 : from + 3 + pipe;
240
+ const missing = options.linkMissing?.(state, {
241
+ from,
242
+ to,
243
+ target,
244
+ format: "wikilink"
245
+ }) ?? false;
246
+ if (textFrom < to - 2) ranges.push(linkMark(from, target, "wikilink", missing).range(textFrom, to - 2));
247
+ if (revealed) {
248
+ ranges.push(muted.range(from, textFrom));
249
+ ranges.push(muted.range(to - 2, to));
250
+ } else {
251
+ conceal(from, textFrom);
252
+ conceal(to - 2, to);
253
+ }
254
+ return;
255
+ }
256
+ const close = marks.find(mark => state.sliceDoc(mark.from, mark.to) === "]");
257
+ // A bare [text] is a link only with a matching definition, which a note rarely has.
258
+ if (!close || !marks.length || !url && !node.node.getChild("LinkLabel")) return;
259
+ const textFrom = marks[0].to;
260
+ const target = url ? state.sliceDoc(url.from, url.to) : "";
261
+ const missing = url ? options.linkMissing?.(state, {
262
+ from,
263
+ to,
264
+ target,
265
+ format: "markdown"
266
+ }) ?? false : false;
267
+ if (textFrom < close.from) ranges.push(linkMark(from, target, "markdown", missing).range(textFrom, close.from));
268
+ if (revealed) {
269
+ ranges.push(muted.range(from, textFrom));
270
+ ranges.push(muted.range(close.from, to));
271
+ } else {
272
+ conceal(from, textFrom);
273
+ // A reference link [text][label] or a bare [text] keeps no trailing source either.
274
+ conceal(close.from, to);
275
+ }
276
+ }
277
+ function linkMark(from, target, format, missing) {
278
+ return Decoration.mark({
279
+ class: missing ? "cm-lp-link cm-lp-link-missing" : "cm-lp-link",
280
+ attributes: {
281
+ role: "link",
282
+ "data-link-from": String(from),
283
+ "data-link-format": format,
284
+ ...(missing ? {
285
+ title: _i18n._(
286
+ /** i18n */
287
+ {
288
+ id: "bBQYl1",
289
+ message: "No note or file matches \u201C{target}\u201D.",
290
+ values: {
291
+ target: target
292
+ }
293
+ })
294
+ } : {})
295
+ }
296
+ });
297
+ }
298
+ function renderQuote(state, node, ranges) {
299
+ if (calloutHeader(state.doc.lineAt(node.from).text)) return;
300
+ // A nested quote's lines belong to its outermost quote, which marks each line's depth.
301
+ if (ancestors(node, "Blockquote") > 1) return;
302
+ const first = state.doc.lineAt(node.from).number;
303
+ const last = state.doc.lineAt(node.to).number;
304
+ for (let number = first; number <= last; number += 1) {
305
+ const current = state.doc.line(number);
306
+ const depth = Math.max(1, (/^\s*((?:>\s?)+)/.exec(current.text)?.[1].match(/>/g) ?? []).length);
307
+ const edge = `${number === first ? " cm-lp-quote-first" : ""}${number === last ? " cm-lp-quote-last" : ""}${depth > 1 ? " cm-lp-quote-nested" : ""}${depth > 2 ? " cm-lp-quote-deep" : ""}`;
308
+ ranges.push(Decoration.line({
309
+ class: `cm-lp-quote${edge}`,
310
+ attributes: {
311
+ style: `--lp-quote-depth: ${depth}`
312
+ }
313
+ }).range(current.from));
314
+ }
315
+ }
316
+ function renderListMark(state, node, ranges, hidden) {
317
+ const current = state.doc.lineAt(node.from);
318
+ // Only the item's first line carries its marker.
319
+ if (current.from !== state.doc.lineAt(node.node.parent?.from ?? node.from).from) return;
320
+ const taskMarker = node.node.parent?.getChild("Task")?.getChild("TaskMarker");
321
+ const afterMark = skipSpaces(state, node.to, current.to);
322
+ const task = taskMarker && taskMarker.from === afterMark ? taskMarker : undefined;
323
+ const prefixEnd = task ? skipSpaces(state, task.to, current.to) : afterMark;
324
+ const list = node.node.parent?.parent;
325
+ const marker = state.sliceDoc(node.from, node.to);
326
+ const markerWidth = list?.name === "OrderedList" ? widestMarker(list) : marker.length;
327
+ // A task's checkbox and gap take about the width of its source "[x] ";
328
+ // a bulleted task shows only the checkbox.
329
+ const width = task ? node.from - current.from + (/^[-+*]$/.test(marker) ? 0 : markerWidth + 1) + 3.5 : prefixEnd - current.from + markerWidth - marker.length;
330
+ const checked = task ? /x/i.test(state.sliceDoc(task.from, task.to)) : false;
331
+ // Wrapped lines hang under the item's text: the prefix box is exactly the indent.
332
+ ranges.push(Decoration.line({
333
+ class: checked ? "cm-lp-list cm-lp-task-done" : "cm-lp-list",
334
+ attributes: {
335
+ style: `--lp-list-indent: ${width}ch`
336
+ }
337
+ }).range(current.from));
338
+ renderContinuations(state, node.node.parent, current.to, width, ranges, hidden);
339
+ // The prefix shows its source only while the selection is in it, not at the text after it.
340
+ const revealed = isRevealed(state, node.from, prefixEnd, false);
341
+ if (revealed) {
342
+ ranges.push(Decoration.mark({
343
+ class: "cm-lp-list-prefix cm-lp-mark"
344
+ }).range(current.from, prefixEnd));
345
+ return;
346
+ }
347
+ const widget = Decoration.replace({
348
+ widget: new ListPrefixWidget({
349
+ leading: node.from - current.from,
350
+ width,
351
+ marker,
352
+ markerWidth,
353
+ depth: ancestors(node, "BulletList") + ancestors(node, "OrderedList") - 1,
354
+ task: task ? {
355
+ from: task.from,
356
+ checked
357
+ } : undefined
358
+ })
359
+ }).range(current.from, prefixEnd);
360
+ ranges.push(widget);
361
+ hidden.push(widget);
362
+ }
363
+ /** Later lines of an item's own paragraphs hang under its text, whatever their source indent. */
364
+ function renderContinuations(state, item, after, width, ranges, hidden) {
365
+ const indent = Decoration.line({
366
+ class: "cm-lp-list-continue",
367
+ attributes: {
368
+ style: `--lp-list-indent: ${width}ch`
369
+ }
370
+ });
371
+ for (let child = item.firstChild; child; child = child.nextSibling) {
372
+ if (child.name !== "Paragraph" && child.name !== "Task" || child.to <= after) continue;
373
+ for (let position = Math.max(child.from, after + 1); position <= child.to;) {
374
+ const current = state.doc.lineAt(position);
375
+ ranges.push(indent.range(current.from));
376
+ const text = skipSpaces(state, current.from, current.to);
377
+ if (text > current.from) {
378
+ const spaces = Decoration.replace({}).range(current.from, text);
379
+ ranges.push(spaces);
380
+ hidden.push(spaces);
381
+ }
382
+ position = current.to + 1;
383
+ }
384
+ }
385
+ }
386
+ function widestMarker(list) {
387
+ let widest = 0;
388
+ for (let item = list.firstChild; item; item = item.nextSibling) {
389
+ const mark = item.getChild("ListMark");
390
+ if (mark) widest = Math.max(widest, mark.to - mark.from);
391
+ }
392
+ return widest;
393
+ }
394
+ function children(node, name) {
395
+ const found = [];
396
+ const cursor = node.node.cursor();
397
+ if (!cursor.firstChild()) return found;
398
+ do if (cursor.name === name) found.push({
399
+ from: cursor.from,
400
+ to: cursor.to
401
+ }); while (cursor.nextSibling());
402
+ return found;
403
+ }
404
+ function ancestors(node, name) {
405
+ let count = 0;
406
+ for (let current = node.node; current; current = current.parent) if (current.name === name) count += 1;
407
+ return count;
408
+ }
409
+ function skipSpaces(state, from, limit, maximum = Infinity) {
410
+ let position = from;
411
+ while (position < limit && position - from < maximum && /[ \t]/.test(state.sliceDoc(position, position + 1))) position += 1;
412
+ return position;
413
+ }
414
+ function trimStart(state, limit, to) {
415
+ let position = to;
416
+ while (position > limit && /[ \t]/.test(state.sliceDoc(position - 1, position))) position -= 1;
417
+ return position;
418
+ }
@@ -0,0 +1,7 @@
1
+ import { type Extension } from "@codemirror/state";
2
+ import { EditorView } from "@codemirror/view";
3
+ export declare const livePreviewKeys: Extension;
4
+ /** Tab in a list: nest the item under the one before it, at that item's text column. */
5
+ export declare function indentListItem(view: EditorView): boolean;
6
+ /** Shift-Tab in a list: lift the item out to its parent item's column. */
7
+ export declare function outdentListItem(view: EditorView): boolean;
@@ -0,0 +1,143 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { EditorSelection, Prec } from "@codemirror/state";
3
+ import { keymap } from "@codemirror/view";
4
+ const prefixMarks = new Set(["HeaderMark", "QuoteMark", "ListMark", "TaskMarker"]);
5
+ /** Where a line's text starts after its quote, list, task and heading markers. */
6
+ function textStart(state, position) {
7
+ const line = state.doc.lineAt(position);
8
+ const tree = syntaxTree(state);
9
+ let at = line.from;
10
+ for (;;) {
11
+ while (at < line.to && /[ \t]/.test(state.sliceDoc(at, at + 1))) at += 1;
12
+ const node = tree.resolveInner(at, 1);
13
+ if (at >= line.to || !prefixMarks.has(node.name) || node.from !== at || node.to > line.to) return at;
14
+ at = node.to;
15
+ }
16
+ }
17
+ /**
18
+ * Home goes to where the line's text starts, as in a word processor, and from
19
+ * there (or from a wrapped row) to the start of the row as usual.
20
+ */
21
+ function home(view, extend) {
22
+ const {
23
+ state
24
+ } = view;
25
+ view.dispatch(state.update({
26
+ selection: EditorSelection.create(state.selection.ranges.map(range => {
27
+ const start = textStart(state, range.head);
28
+ const row = view.moveToLineBoundary(range, false);
29
+ const head = range.head > start && row.head <= start ? start : row.head;
30
+ return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);
31
+ }), state.selection.mainIndex),
32
+ scrollIntoView: true,
33
+ userEvent: "select"
34
+ }));
35
+ return true;
36
+ }
37
+ export const livePreviewKeys = Prec.high(keymap.of([{
38
+ key: "Home",
39
+ run: view => home(view, false),
40
+ shift: view => home(view, true)
41
+ }]));
42
+ /** The list item whose marker starts the line at `position`, if any. */
43
+ function itemAt(state, position) {
44
+ const line = state.doc.lineAt(position);
45
+ let at = line.from;
46
+ while (at < line.to && /[ \t]/.test(state.sliceDoc(at, at + 1))) at += 1;
47
+ const mark = syntaxTree(state).resolveInner(at, 1);
48
+ return mark.name === "ListMark" && mark.from === at && mark.parent?.name === "ListItem" ? mark.parent : null;
49
+ }
50
+ /** The items whose first lines the selection touches, outermost only: an item moves with its children. */
51
+ function selectedItems(state) {
52
+ const items = [];
53
+ for (const range of state.selection.ranges) {
54
+ const last = state.doc.lineAt(range.to).number;
55
+ for (let number = state.doc.lineAt(range.from).number; number <= last; number += 1) {
56
+ const item = itemAt(state, state.doc.line(number).from);
57
+ if (item && !items.some(other => other.from <= item.from && item.to <= other.to)) items.push(item);
58
+ }
59
+ }
60
+ return items;
61
+ }
62
+ function markOf(item) {
63
+ const mark = item.getChild("ListMark");
64
+ if (!mark) throw new Error("A list item has no marker.");
65
+ return mark;
66
+ }
67
+ function column(state, position) {
68
+ return position - state.doc.lineAt(position).from;
69
+ }
70
+ /** Shift every line of an item, renumbering its marker if it is ordered. */
71
+ function shiftItem(state, item, delta, number) {
72
+ const changes = [];
73
+ const last = state.doc.lineAt(item.to).number;
74
+ for (let index = state.doc.lineAt(item.from).number; index <= last; index += 1) {
75
+ const line = state.doc.line(index);
76
+ if (!line.text.trim()) continue;
77
+ const leading = /^[ \t]*/.exec(line.text)[0].length;
78
+ if (delta > 0) changes.push({
79
+ from: line.from,
80
+ insert: " ".repeat(delta)
81
+ });else if (delta < 0) changes.push({
82
+ from: line.from,
83
+ to: line.from + Math.min(leading, -delta)
84
+ });
85
+ }
86
+ const mark = markOf(item);
87
+ const ordinal = /^(\d+)([.)])$/.exec(state.sliceDoc(mark.from, mark.to));
88
+ if (ordinal && number !== null) changes.push({
89
+ from: mark.from,
90
+ to: mark.to,
91
+ insert: `${number}${ordinal[2]}`
92
+ });
93
+ return changes;
94
+ }
95
+ function ordinalOf(state, item) {
96
+ if (!item) return null;
97
+ const mark = markOf(item);
98
+ const ordinal = /^(\d+)/.exec(state.sliceDoc(mark.from, mark.to));
99
+ return ordinal ? Number(ordinal[1]) : null;
100
+ }
101
+ /** Tab in a list: nest the item under the one before it, at that item's text column. */
102
+ export function indentListItem(view) {
103
+ const {
104
+ state
105
+ } = view;
106
+ const items = selectedItems(state);
107
+ if (!items.length || state.readOnly) return false;
108
+ const changes = items.flatMap(item => {
109
+ const previous = item.prevSibling;
110
+ if (previous?.name !== "ListItem") return [];
111
+ const previousMark = markOf(previous);
112
+ let text = previousMark.to;
113
+ while (text < previous.to && text - previousMark.to < 4 && state.sliceDoc(text, text + 1) === " ") text += 1;
114
+ const sublist = previous.lastChild?.name === "OrderedList" ? previous.lastChild : null;
115
+ const number = sublist ? (ordinalOf(state, sublist.lastChild) ?? 0) + 1 : 1;
116
+ return shiftItem(state, item, column(state, text) - column(state, markOf(item).from), number);
117
+ });
118
+ // An item with nothing before it to nest under stays put, and Tab stays in the editor.
119
+ if (changes.length) view.dispatch({
120
+ changes,
121
+ userEvent: "input.indent"
122
+ });
123
+ return true;
124
+ }
125
+ /** Shift-Tab in a list: lift the item out to its parent item's column. */
126
+ export function outdentListItem(view) {
127
+ const {
128
+ state
129
+ } = view;
130
+ const items = selectedItems(state);
131
+ if (!items.length || state.readOnly) return false;
132
+ const changes = items.flatMap(item => {
133
+ const parent = item.parent?.parent;
134
+ if (parent?.name !== "ListItem") return [];
135
+ const parentNumber = ordinalOf(state, parent);
136
+ return shiftItem(state, item, column(state, markOf(parent).from) - column(state, markOf(item).from), parentNumber === null ? null : parentNumber + 1);
137
+ });
138
+ if (changes.length) view.dispatch({
139
+ changes,
140
+ userEvent: "delete.dedent"
141
+ });
142
+ return true;
143
+ }
@@ -0,0 +1,29 @@
1
+ import { StateField, type EditorSelection, type EditorState, type Extension } from "@codemirror/state";
2
+ import { type ViewUpdate } from "@codemirror/view";
3
+ /**
4
+ * Which Markdown source is shown raw. Source is revealed only where a focused
5
+ * selection touches it, so an unfocused note always reads as rendered text.
6
+ *
7
+ * While a mouse button is held, the revealed selection stays where it was:
8
+ * revealing markers under a press would move the text the pointer is on and
9
+ * turn a click into a stray drag. The reveal catches up on release.
10
+ *
11
+ * A block of table cells reveals nothing: it selects cells, not their text.
12
+ */
13
+ interface RevealState {
14
+ focused: boolean;
15
+ pointer: boolean;
16
+ cells: boolean;
17
+ selection: EditorSelection;
18
+ }
19
+ /** What is revealed, as a dependency for `EditorView.decorations.compute`. */
20
+ export declare const revealField: StateField<RevealState>;
21
+ export declare function revealTracking(): Extension;
22
+ /**
23
+ * Whether a focused selection touches [from, to]. Both edges count unless
24
+ * `touchEnd` is false, for source whose end is where the text after it starts.
25
+ */
26
+ export declare function isRevealed(state: EditorState, from: number, to: number, touchEnd?: boolean): boolean;
27
+ /** Whether a view update changed what is revealed, so decorations must be rebuilt. */
28
+ export declare function revealChanged(update: ViewUpdate): boolean;
29
+ export {};
@@ -0,0 +1,97 @@
1
+ import { StateEffect, StateField } from "@codemirror/state";
2
+ import { EditorView, ViewPlugin } from "@codemirror/view";
3
+ import { cellRange } from "./table-model.js";
4
+ const focusEffect = StateEffect.define();
5
+ const pointerEffect = StateEffect.define();
6
+ /** What is revealed, as a dependency for `EditorView.decorations.compute`. */
7
+ export const revealField = StateField.define({
8
+ create: state => ({
9
+ focused: false,
10
+ pointer: false,
11
+ cells: false,
12
+ selection: state.selection
13
+ }),
14
+ update(value, transaction) {
15
+ let {
16
+ focused,
17
+ pointer
18
+ } = value;
19
+ for (const effect of transaction.effects) {
20
+ if (effect.is(focusEffect) && !pointer) focused = effect.value;
21
+ if (effect.is(pointerEffect)) pointer = effect.value;
22
+ }
23
+ const selection = pointer ? transaction.docChanged ? value.selection.map(transaction.changes) : value.selection : transaction.state.selection;
24
+ const cells = pointer || !transaction.docChanged && selection.eq(value.selection) ? value.cells : !!cellRange(transaction.state);
25
+ if (focused === value.focused && pointer === value.pointer && cells === value.cells && selection.eq(value.selection)) {
26
+ return transaction.docChanged ? {
27
+ focused,
28
+ pointer,
29
+ cells,
30
+ selection
31
+ } : value;
32
+ }
33
+ return {
34
+ focused,
35
+ pointer,
36
+ cells,
37
+ selection
38
+ };
39
+ }
40
+ });
41
+ export function revealTracking() {
42
+ return [revealField, EditorView.focusChangeEffect.of((_state, focusing) => focusEffect.of(focusing)),
43
+ // A field created while the view already has focus (a new view, a new
44
+ // state, or a reconfiguration) never sees a focus change, so catch it up.
45
+ ViewPlugin.define(view => {
46
+ let pending = false;
47
+ const sync = () => {
48
+ const reveal = view.state.field(revealField);
49
+ // A held pointer settles focus on release.
50
+ if (pending || reveal.pointer || view.hasFocus === reveal.focused) return;
51
+ pending = true;
52
+ queueMicrotask(() => {
53
+ pending = false;
54
+ const focused = view.hasFocus;
55
+ const current = view.state.field(revealField);
56
+ if (view.dom.isConnected && !current.pointer && focused !== current.focused) view.dispatch({
57
+ effects: focusEffect.of(focused)
58
+ });
59
+ });
60
+ };
61
+ sync();
62
+ return {
63
+ update: sync
64
+ };
65
+ }), EditorView.domEventHandlers({
66
+ pointerdown(event, view) {
67
+ if (event.pointerType !== "mouse" || event.button !== 0) return false;
68
+ const release = () => {
69
+ window.removeEventListener("pointerup", release, true);
70
+ window.removeEventListener("pointercancel", release, true);
71
+ // The release can follow a view teardown or a document swap.
72
+ if (view.dom.isConnected) view.dispatch({
73
+ effects: [pointerEffect.of(false), focusEffect.of(view.hasFocus)]
74
+ });
75
+ };
76
+ window.addEventListener("pointerup", release, true);
77
+ window.addEventListener("pointercancel", release, true);
78
+ view.dispatch({
79
+ effects: pointerEffect.of(true)
80
+ });
81
+ return false;
82
+ }
83
+ })];
84
+ }
85
+ /**
86
+ * Whether a focused selection touches [from, to]. Both edges count unless
87
+ * `touchEnd` is false, for source whose end is where the text after it starts.
88
+ */
89
+ export function isRevealed(state, from, to, touchEnd = true) {
90
+ const reveal = state.field(revealField, false);
91
+ if (!reveal?.focused || reveal.cells) return false;
92
+ return reveal.selection.ranges.some(range => range.to >= from && (touchEnd ? range.from <= to : range.from < to));
93
+ }
94
+ /** Whether a view update changed what is revealed, so decorations must be rebuilt. */
95
+ export function revealChanged(update) {
96
+ return update.startState.field(revealField, false) !== update.state.field(revealField, false);
97
+ }