@monster-orange/den-ui 0.7.4 → 0.7.5

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,1122 @@
1
+ /**
2
+ * den-ui: the Markdown editor (0.7.5). CodeMirror 6 on the Markdown TEXT:
3
+ * the document is the string that is stored, character for character, and
4
+ * the live preview is drawn in place, as decoration only. Nothing is ever
5
+ * converted to HTML and back, and there is no preview pane. Framework-free:
6
+ *
7
+ * import { mountMarkdownEditor } from "@monster-orange/den-ui/markdown-editor";
8
+ * // and @monster-orange/den-ui/markdown-editor.css, after tokens.css
9
+ * const ed = mountMarkdownEditor(el, {
10
+ * value: "", onChange: (text) => save(text),
11
+ * label: "Notes", the editor's name (or labelledBy)
12
+ * mode: "full", "full": a form field with a toolbar;
13
+ * "lite": a chat box, no toolbar
14
+ * onSubmit: () => send(), full: ⌘/Ctrl+Enter; lite: Enter
15
+ * });
16
+ * ed.setValue(""); ed.focus(); ed.destroy();
17
+ *
18
+ * Every option and method is in markdown-editor.d.ts.
19
+ *
20
+ * Lazy: this file imports no CodeMirror. On mount it loads the packages
21
+ * with import(), so a consumer's bundler puts them in their own chunk, and
22
+ * a plain textarea (the stand-in) takes the typing until they arrive. The
23
+ * toolbar works on the stand-in too. When the editor arrives it goes on
24
+ * from the stand-in's text, focus, caret and selection, so nothing typed
25
+ * is lost and what is typed next lands where the caret was.
26
+ *
27
+ * The preview (livePreview below): on a line the caret is NOT on, the
28
+ * markers hide (`**`, `_`, `` ` ``, `~~`, `#`, `>`, the `[`/`](url)` around
29
+ * a link's words, a backslash escape) and the words show formatted; `- `
30
+ * becomes a bullet. On the line being edited every marker stays visible,
31
+ * muted, so the caret never lands inside something hidden. Unfocused, the
32
+ * whole field reads as the preview. The subset is CommonMark without the
33
+ * parts a safe renderer leaves as plain text (setext headings, indented
34
+ * code, HTML, entities, reference links, images, autolinks), plus
35
+ * strikethrough; only an http(s) link is drawn as a link.
36
+ *
37
+ * IME: CodeMirror ignores key events during a composition, and on top of
38
+ * that every Enter here checks `view.composing`, the keydown's own
39
+ * isComposing / keyCode 229, and a confirming Enter that lands within
40
+ * COMPOSITION_GRACE_MS of `compositionend` (Safari fires that keydown after
41
+ * compositionend, isComposing already false). The preview's ranges are
42
+ * frozen (mapped, not rebuilt) while a composition is open, and the line
43
+ * being edited never has markers hidden, so the DOM around an open
44
+ * composition is never rewritten. The length limit never cuts one.
45
+ *
46
+ * Words: the toolbar's are the kit's (strings.js, kit.md.*), in the
47
+ * `uiLang` option's language, else the page's (<html lang>). Its look is
48
+ * markdown-editor.css: tokens only. Under a strict style-src, pass the
49
+ * page's `nonce`: CodeMirror writes its own base styles into a <style>.
50
+ *
51
+ * Ported from an existing editor, value for value.
52
+ */
53
+ import { kitT } from "./strings.js";
54
+
55
+ // ------------------------------------------------------------- Enter and the IME
56
+
57
+ /** True while the key belongs to an IME composition: leave it to the IME. */
58
+ export function composingKey(e) {
59
+ return !!e.isComposing || e.keyCode === 229;
60
+ }
61
+
62
+ /** Within this long after `compositionend`, an Enter is the composition's, not a send (Safari). */
63
+ export const COMPOSITION_GRACE_MS = 100;
64
+
65
+ /**
66
+ * What Enter does. `lite` (a chat): Enter sends, Shift+Enter (or
67
+ * Alt+Enter) is a new line. `full` (a form field): Enter is a new line,
68
+ * ⌘/Ctrl+Enter submits. Never while composing: "ime".
69
+ */
70
+ export function enterAction(e, mode, composing = false) {
71
+ if (e.key !== "Enter") return null;
72
+ if (composing || composingKey(e)) return "ime";
73
+ if (mode === "lite") return e.shiftKey || e.altKey ? "newline" : "submit";
74
+ return e.metaKey || e.ctrlKey ? "submit" : "newline";
75
+ }
76
+
77
+ // ------------------------------------------------------------------ the commands
78
+ // The formatting commands as pure text edits. Each takes the Markdown source
79
+ // and the selection and returns the edit to make: the markers typed into the
80
+ // source exactly as a person would type them. The toolbar, ⌘B/⌘I/⌘E/⌘K,
81
+ // ⌘⇧X and Enter in a list all go through here, so a formatted word is stored
82
+ // as `**word**`, never as HTML. An edit is { changes: [{ from, to, insert }],
83
+ // anchor, head }: changes in the OLD text's positions, the selection in the
84
+ // new one.
85
+
86
+ const MARKER = { bold: "**", italic: "*", code: "`", strike: "~~" };
87
+
88
+ /**
89
+ * Wrap the selection in the format's markers, or unwrap it when it is
90
+ * already wrapped. An empty selection gets the pair with the caret between.
91
+ */
92
+ export function toggleInline(doc, from, to, format) {
93
+ const m = MARKER[format];
94
+ const n = m.length;
95
+ const inner = doc.slice(from, to);
96
+ // `**word**` with the markers just outside the selection.
97
+ if (
98
+ doc.slice(from - n, from) === m &&
99
+ doc.slice(to, to + n) === m &&
100
+ !(
101
+ format === "italic" &&
102
+ doc.slice(from - 2, from) === "**" &&
103
+ doc.slice(from - 3, from) !== "***"
104
+ )
105
+ ) {
106
+ return {
107
+ changes: [
108
+ { from: from - n, to: from, insert: "" },
109
+ { from: to, to: to + n, insert: "" },
110
+ ],
111
+ anchor: from - n,
112
+ head: to - n,
113
+ };
114
+ }
115
+ // The selection includes the markers.
116
+ if (inner.length >= 2 * n && inner.startsWith(m) && inner.endsWith(m)) {
117
+ return {
118
+ changes: [{ from, to, insert: inner.slice(n, inner.length - n) }],
119
+ anchor: from,
120
+ head: to - 2 * n,
121
+ };
122
+ }
123
+ // Leading/trailing spaces stay outside the markers (`** word**` would not be bold).
124
+ const lead = /^\s*/.exec(inner)[0].length;
125
+ const trail = inner.length > lead ? /\s*$/.exec(inner)[0].length : 0;
126
+ const a = from + lead,
127
+ b = to - trail;
128
+ return {
129
+ changes: [
130
+ { from: a, to: a, insert: m },
131
+ { from: b, to: b, insert: m },
132
+ ],
133
+ anchor: a + n,
134
+ head: b + n,
135
+ };
136
+ }
137
+
138
+ /**
139
+ * `[words](https://)`: the selection becomes the words and the address is
140
+ * selected to type over; with nothing selected, the words placeholder is
141
+ * selected first. A selected address becomes the address.
142
+ */
143
+ export function insertLink(doc, from, to, placeholder = "text") {
144
+ const sel = doc.slice(from, to);
145
+ if (/^https?:\/\/\S+$/.test(sel)) {
146
+ const insert = `[${placeholder}](${sel})`;
147
+ return {
148
+ changes: [{ from, to, insert }],
149
+ anchor: from + 1,
150
+ head: from + 1 + placeholder.length,
151
+ };
152
+ }
153
+ const words = sel || placeholder;
154
+ const insert = `[${words}](https://)`;
155
+ if (!sel)
156
+ return {
157
+ changes: [{ from, to, insert }],
158
+ anchor: from + 1,
159
+ head: from + 1 + words.length,
160
+ };
161
+ const url = from + words.length + 3;
162
+ return {
163
+ changes: [{ from, to, insert }],
164
+ anchor: url,
165
+ head: url + "https://".length,
166
+ };
167
+ }
168
+
169
+ const BLOCK_PREFIX = /^(\s{0,3})(#{1,6}\s+|[-*+]\s+|\d{1,9}[.)]\s+|>\s?)?/;
170
+ const IS = {
171
+ heading: /^#{1,6}\s+$/,
172
+ bullet: /^[-*+]\s+$/,
173
+ ordered: /^\d{1,9}[.)]\s+$/,
174
+ quote: /^>\s?$/,
175
+ };
176
+
177
+ /**
178
+ * Turn every line the selection touches into the block (`## `, `- `,
179
+ * `1. `, `> `), replacing another block prefix; when every line already is
180
+ * that block, take the prefix off.
181
+ */
182
+ export function toggleBlock(doc, from, to, format) {
183
+ const start = doc.lastIndexOf("\n", from - 1) + 1;
184
+ let end = doc.indexOf("\n", to);
185
+ if (end < 0) end = doc.length;
186
+ const lines = doc.slice(start, end).split("\n");
187
+ const prefixes = lines.map((l) => BLOCK_PREFIX.exec(l));
188
+ const all = prefixes.every((p) => p[2] && IS[format].test(p[2]));
189
+ const changes = [];
190
+ let at = start,
191
+ shiftFrom = 0,
192
+ shiftTo = 0,
193
+ n = 0;
194
+ lines.forEach((line, i) => {
195
+ const p = prefixes[i];
196
+ const cut = p[0].length;
197
+ const blank = !line.trim();
198
+ let insert = p[1];
199
+ if (!all && !(blank && lines.length > 1)) {
200
+ n += 1;
201
+ insert +=
202
+ format === "heading"
203
+ ? "## "
204
+ : format === "bullet"
205
+ ? "- "
206
+ : format === "ordered"
207
+ ? `${n}. `
208
+ : "> ";
209
+ }
210
+ if (insert !== p[0]) changes.push({ from: at, to: at + cut, insert });
211
+ const delta = insert.length - cut;
212
+ if (at <= from) shiftFrom += delta;
213
+ shiftTo += delta;
214
+ at += line.length + 1;
215
+ });
216
+ return {
217
+ changes,
218
+ anchor: Math.max(start, from + shiftFrom),
219
+ head: Math.max(start, to + shiftTo),
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Enter inside a list or a quote: the next line gets the same marker (a
225
+ * numbered list counts on). Enter on an empty item ends the list (its
226
+ * marker is removed). Null when the line is neither, and the caller
227
+ * inserts a plain newline.
228
+ */
229
+ export function continueBlock(doc, pos) {
230
+ const start = doc.lastIndexOf("\n", pos - 1) + 1;
231
+ const line = doc.slice(start, pos);
232
+ const m =
233
+ /^(\s*)([-*+]|\d{1,9}[.)]|>)(\s+)(.*)$/.exec(line) ??
234
+ /^(\s*)(>)()(.*)$/.exec(line);
235
+ if (!m) return null;
236
+ const [, indent, mark, space, rest] = m;
237
+ if (
238
+ !rest.trim() &&
239
+ doc
240
+ .slice(pos, (doc.indexOf("\n", pos) + 1 || doc.length + 1) - 1)
241
+ .trim() === ""
242
+ ) {
243
+ return {
244
+ changes: [{ from: start, to: pos, insert: "" }],
245
+ anchor: start,
246
+ head: start,
247
+ };
248
+ }
249
+ const ord = /^(\d{1,9})([.)])$/.exec(mark);
250
+ const next = ord ? `${Number(ord[1]) + 1}${ord[2]}` : mark;
251
+ const insert = `\n${indent}${next}${space || " "}`;
252
+ return {
253
+ changes: [{ from: pos, to: pos, insert }],
254
+ anchor: pos + insert.length,
255
+ head: pos + insert.length,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Put a block (a snippet, a card) where the caret is, replacing any
261
+ * selection, on lines of its own: a blank line before and after unless the
262
+ * text there already gives one. The caret lands after the block.
263
+ */
264
+ export function insertBlock(doc, from, to, block) {
265
+ const before = doc.slice(0, from),
266
+ after = doc.slice(to);
267
+ const lead =
268
+ before === "" || before.endsWith("\n\n")
269
+ ? ""
270
+ : before.endsWith("\n")
271
+ ? "\n"
272
+ : "\n\n";
273
+ const tail =
274
+ after === ""
275
+ ? "\n"
276
+ : after.startsWith("\n\n")
277
+ ? ""
278
+ : after.startsWith("\n")
279
+ ? "\n"
280
+ : "\n\n";
281
+ const insert = lead + block + tail;
282
+ const caret = from + lead.length + block.length;
283
+ return { changes: [{ from, to, insert }], anchor: caret, head: caret };
284
+ }
285
+
286
+ /**
287
+ * A link to `url` where the caret is, replacing the selection: the
288
+ * selected words become the link's words (else `label`, else the URL),
289
+ * brackets and line breaks flattened so the Markdown stays one link. The
290
+ * caret lands after it.
291
+ */
292
+ export function insertLinkTo(doc, from, to, label, url) {
293
+ const flat = (s) =>
294
+ s
295
+ .replace(/[[\]\n\r]+/g, " ")
296
+ .replace(/\s+/g, " ")
297
+ .trim();
298
+ const words = flat(doc.slice(from, to)) || flat(label) || url;
299
+ const safe = url.replace(
300
+ /[()\s]/g,
301
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`,
302
+ );
303
+ const insert = `[${words}](${safe})`;
304
+ const caret = from + insert.length;
305
+ return { changes: [{ from, to, insert }], anchor: caret, head: caret };
306
+ }
307
+
308
+ /** Apply an edit to a string (tests and the stand-in). Changes do not overlap. */
309
+ export function applyEdit(doc, edit) {
310
+ let out = doc;
311
+ for (const c of [...edit.changes].sort((a, b) => b.from - a.from))
312
+ out = out.slice(0, c.from) + c.insert + out.slice(c.to);
313
+ return out;
314
+ }
315
+
316
+ // --------------------------------------------------------------- the live preview
317
+
318
+ const parsers = new WeakMap();
319
+
320
+ /** The preview's Markdown parser, from the @lezer/markdown module given. */
321
+ export function markdownParser(md) {
322
+ let p = parsers.get(md);
323
+ if (!p) {
324
+ p = md.parser.configure([
325
+ md.Strikethrough,
326
+ {
327
+ remove: [
328
+ "SetextHeading",
329
+ "IndentedCode",
330
+ "HTMLBlock",
331
+ "HTMLTag",
332
+ "Entity",
333
+ "LinkReference",
334
+ "Image",
335
+ "Autolink",
336
+ "Comment",
337
+ "ProcessingInstruction",
338
+ ],
339
+ },
340
+ ]);
341
+ parsers.set(md, p);
342
+ }
343
+ return p;
344
+ }
345
+
346
+ const INLINE = {
347
+ StrongEmphasis: "md-strong",
348
+ Emphasis: "md-em",
349
+ InlineCode: "md-code",
350
+ Strikethrough: "md-del",
351
+ };
352
+ const MARKS = new Set(["EmphasisMark", "CodeMark", "StrikethroughMark"]);
353
+ const rank = (r) => (r.kind === "line" ? 0 : r.kind === "mark" ? 1 : 2);
354
+
355
+ /**
356
+ * Every drawing instruction for `text`, given the selection ranges
357
+ * (`[from, to]`) whose lines are being edited. `hide` and `bullet` replace
358
+ * their range; `mark` styles it; `line` styles the whole line that starts
359
+ * at `from`. Sorted by `from`; replacing ranges never overlap. Nothing here
360
+ * changes the text.
361
+ */
362
+ export function livePreview(text, selection, parser) {
363
+ const starts = [0];
364
+ for (let i = 0; i < text.length; i++)
365
+ if (text.charCodeAt(i) === 10) starts.push(i + 1);
366
+ const lineOf = (pos) => {
367
+ let lo = 0,
368
+ hi = starts.length - 1;
369
+ while (lo < hi) {
370
+ const mid = (lo + hi + 1) >> 1;
371
+ if (starts[mid] <= pos) lo = mid;
372
+ else hi = mid - 1;
373
+ }
374
+ return lo;
375
+ };
376
+ const activeLines = new Set();
377
+ for (const [a, b] of selection)
378
+ for (let l = lineOf(Math.min(a, b)); l <= lineOf(Math.max(a, b)); l++)
379
+ activeLines.add(l);
380
+ const active = (from, to) => {
381
+ for (let l = lineOf(from); l <= lineOf(Math.max(from, to - 1)); l++)
382
+ if (activeLines.has(l)) return true;
383
+ return false;
384
+ };
385
+
386
+ const out = [];
387
+ const hide = (from, to) => {
388
+ if (to <= from) return;
389
+ if (active(from, to)) {
390
+ out.push({ kind: "mark", from, to, cls: "md-marker" });
391
+ return;
392
+ }
393
+ out.push({ kind: "hide", from, to });
394
+ };
395
+ const lineDeco = (from, to, cls) => {
396
+ for (let l = lineOf(from); l <= lineOf(Math.max(from, to - 1)); l++)
397
+ out.push({ kind: "line", from: starts[l], cls });
398
+ };
399
+
400
+ parser.parse(text).iterate({
401
+ enter(node) {
402
+ const { name, from, to } = node;
403
+ if (name in INLINE)
404
+ out.push({ kind: "mark", from, to, cls: INLINE[name] });
405
+ if (MARKS.has(name)) {
406
+ hide(from, to);
407
+ return;
408
+ }
409
+ const heading = /^ATXHeading([1-6])$/.exec(name);
410
+ if (heading) {
411
+ lineDeco(from, to, `md-h md-h${Math.min(Number(heading[1]), 3)}`);
412
+ return;
413
+ }
414
+ switch (name) {
415
+ case "HeaderMark": {
416
+ // The `##` and the one space after it.
417
+ const end = text[to] === " " ? to + 1 : to;
418
+ if (
419
+ node.node.parent?.name.startsWith("ATXHeading") &&
420
+ from === node.node.parent.from
421
+ )
422
+ hide(from, end);
423
+ else hide(from, to); // a closing `##`
424
+ return;
425
+ }
426
+ case "Blockquote":
427
+ lineDeco(from, to, "md-quote");
428
+ return;
429
+ case "QuoteMark":
430
+ hide(from, text[to] === " " ? to + 1 : to);
431
+ return;
432
+ case "FencedCode":
433
+ lineDeco(from, to, "md-fence");
434
+ return false;
435
+ case "HorizontalRule":
436
+ lineDeco(from, to, "md-hr");
437
+ out.push({ kind: "mark", from, to, cls: "md-marker" });
438
+ return;
439
+ case "ListMark": {
440
+ const mark = text.slice(from, to);
441
+ if (/^[-*+]$/.test(mark) && !active(from, to))
442
+ out.push({ kind: "bullet", from, to });
443
+ else out.push({ kind: "mark", from, to, cls: "md-listmark" });
444
+ return;
445
+ }
446
+ case "Escape":
447
+ hide(from, from + 1);
448
+ return;
449
+ case "Link": {
450
+ const url = node.node.getChild("URL");
451
+ // Only an http(s) address is a link to the reader; anything else stays as typed.
452
+ if (!url || !/^https?:\/\//.test(text.slice(url.from, url.to)))
453
+ return false;
454
+ const marks = node.node.getChildren("LinkMark");
455
+ const close = marks.find((m) => text.slice(m.from, m.to) === "]");
456
+ if (!close || marks[0].from !== from) return false;
457
+ out.push({
458
+ kind: "mark",
459
+ from: from + 1,
460
+ to: close.from,
461
+ cls: "md-link",
462
+ });
463
+ hide(from, from + 1);
464
+ hide(close.from, to);
465
+ return;
466
+ }
467
+ }
468
+ },
469
+ });
470
+ return out.sort((a, b) => a.from - b.from || rank(a) - rank(b));
471
+ }
472
+
473
+ // ------------------------------------------------------------------ the lazy chunk
474
+
475
+ let loading = null;
476
+
477
+ /**
478
+ * Loads CodeMirror (once; every editor shares it). mountMarkdownEditor
479
+ * calls it; call it earlier to warm the chunk before a field is shown.
480
+ */
481
+ export function loadMarkdownEditor() {
482
+ return chunk().then(() => undefined);
483
+ }
484
+
485
+ /** The loaded modules, built once. */
486
+ function chunk() {
487
+ if (!loading) {
488
+ loading = Promise.all([
489
+ import("@codemirror/state"),
490
+ import("@codemirror/view"),
491
+ import("@codemirror/commands"),
492
+ import("@lezer/markdown"),
493
+ ]).then(([state, view, commands, md]) => build(state, view, commands, md));
494
+ // A chunk that failed to load is tried again by the next editor.
495
+ loading.catch(() => {
496
+ loading = null;
497
+ });
498
+ }
499
+ return loading;
500
+ }
501
+
502
+ /** What the editors share, made once from the loaded modules. */
503
+ function build(state, cmView, commands, md) {
504
+ const { EditorView, Decoration, ViewPlugin, WidgetType } = cmView;
505
+ const parser = markdownParser(md);
506
+
507
+ class BulletWidget extends WidgetType {
508
+ eq() {
509
+ return true;
510
+ }
511
+ toDOM() {
512
+ const span = document.createElement("span");
513
+ span.className = "md-bullet";
514
+ span.setAttribute("aria-hidden", "true");
515
+ span.textContent = "•";
516
+ return span;
517
+ }
518
+ ignoreEvent() {
519
+ return false;
520
+ }
521
+ }
522
+ const BULLET = new BulletWidget();
523
+ const HIDE = Decoration.replace({});
524
+
525
+ function decorate(view) {
526
+ // Unfocused, the whole field reads as the preview; focused, the caret's lines show their markers.
527
+ const sel = view.hasFocus
528
+ ? view.state.selection.ranges.map((r) => [r.from, r.to])
529
+ : [];
530
+ const ranges = livePreview(view.state.doc.toString(), sel, parser).map(
531
+ (r) => {
532
+ switch (r.kind) {
533
+ case "hide":
534
+ return HIDE.range(r.from, r.to);
535
+ case "mark":
536
+ return Decoration.mark({ class: r.cls }).range(r.from, r.to);
537
+ case "line":
538
+ return Decoration.line({ class: r.cls }).range(r.from);
539
+ case "bullet":
540
+ return Decoration.replace({ widget: BULLET }).range(r.from, r.to);
541
+ }
542
+ },
543
+ );
544
+ return Decoration.set(ranges, true);
545
+ }
546
+
547
+ const livePreviewPlugin = ViewPlugin.fromClass(
548
+ class {
549
+ constructor(view) {
550
+ this.decorations = decorate(view);
551
+ }
552
+ update(u) {
553
+ if (u.view.composing || u.view.compositionStarted) {
554
+ this.decorations = this.decorations.map(u.changes);
555
+ return;
556
+ }
557
+ if (u.docChanged || u.selectionSet || u.focusChanged)
558
+ this.decorations = decorate(u.view);
559
+ }
560
+ },
561
+ { decorations: (p) => p.decorations },
562
+ );
563
+
564
+ return {
565
+ ...state,
566
+ ...cmView,
567
+ ...commands,
568
+ /** A change that came from setValue, not from the person typing. */
569
+ External: state.Annotation.define(),
570
+ livePreviewPlugin,
571
+ };
572
+ }
573
+
574
+ // ------------------------------------------------------------------------- mount
575
+
576
+ const isMac =
577
+ typeof navigator !== "undefined" &&
578
+ /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
579
+ const MOD = isMac ? "⌘" : "Ctrl+";
580
+
581
+ const svg = (d) =>
582
+ '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">' +
583
+ d +
584
+ "</svg>";
585
+
586
+ const TOOLS = [
587
+ {
588
+ format: "bold",
589
+ label: "kit.md.bold",
590
+ key: "B",
591
+ icon: '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>',
592
+ },
593
+ {
594
+ format: "italic",
595
+ label: "kit.md.italic",
596
+ key: "I",
597
+ icon: '<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>',
598
+ },
599
+ {
600
+ format: "code",
601
+ label: "kit.md.code",
602
+ key: "E",
603
+ icon: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',
604
+ },
605
+ {
606
+ format: "link",
607
+ label: "kit.md.link",
608
+ key: "K",
609
+ icon: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
610
+ },
611
+ "sep",
612
+ {
613
+ format: "heading",
614
+ label: "kit.md.heading",
615
+ icon: '<path d="M6 12h12"/><path d="M6 20V4"/><path d="M18 20V4"/>',
616
+ },
617
+ {
618
+ format: "bullet",
619
+ label: "kit.md.bulleted",
620
+ icon: '<path d="M3 12h.01"/><path d="M3 18h.01"/><path d="M3 6h.01"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M8 6h13"/>',
621
+ },
622
+ {
623
+ format: "ordered",
624
+ label: "kit.md.numbered",
625
+ icon: '<path d="M10 12h11"/><path d="M10 18h11"/><path d="M10 6h11"/><path d="M4 10h2"/><path d="M4 6h1v4"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>',
626
+ },
627
+ {
628
+ format: "quote",
629
+ label: "kit.md.quote",
630
+ icon: '<path d="M17 6H3"/><path d="M21 12H8"/><path d="M21 18H8"/><path d="M3 12v6"/>',
631
+ },
632
+ ];
633
+
634
+ /** The edit a format makes (the editor and the stand-in share it). */
635
+ function formatEdit(doc, from, to, format, linkText) {
636
+ return format === "link"
637
+ ? insertLink(doc, from, to, linkText)
638
+ : format === "heading" ||
639
+ format === "bullet" ||
640
+ format === "ordered" ||
641
+ format === "quote"
642
+ ? toggleBlock(doc, from, to, format)
643
+ : toggleInline(doc, from, to, format);
644
+ }
645
+
646
+ /** Two strings as one replacement (shared prefix and suffix kept). */
647
+ function diff(a, b) {
648
+ let s = 0;
649
+ while (s < a.length && s < b.length && a[s] === b[s]) s++;
650
+ let e = 0;
651
+ while (
652
+ e < a.length - s &&
653
+ e < b.length - s &&
654
+ a[a.length - 1 - e] === b[b.length - 1 - e]
655
+ )
656
+ e++;
657
+ return { from: s, to: a.length - e, insert: b.slice(s, b.length - e) };
658
+ }
659
+
660
+ let seq = 0;
661
+
662
+ /**
663
+ * Mounts a Markdown editor in `el` (appended to what is there). See
664
+ * markdown-editor.d.ts for the options and the handle.
665
+ */
666
+ export function mountMarkdownEditor(el, options) {
667
+ const o = { ...options };
668
+ const mode = o.mode === "lite" ? "lite" : "full";
669
+ const lite = mode === "lite";
670
+ const id = o.id || `md-editor-${++seq}`;
671
+ const lang = () =>
672
+ o.uiLang ||
673
+ (typeof document !== "undefined" &&
674
+ document.documentElement.lang?.slice(0, 2)) ||
675
+ "en";
676
+ const word = (key, vars) => kitT(lang(), key, vars);
677
+ const linkText = () => word("kit.md.linkText");
678
+
679
+ let cm = null;
680
+ let view = null;
681
+ let destroyed = false;
682
+ let swapping = false;
683
+ let dyn = null;
684
+ let onKeyRec = null;
685
+
686
+ // The field's box: a form field's look (full) or a chat's (lite).
687
+ const box = document.createElement("div");
688
+ box.className = lite ? "md-field md-lite" : "md-field";
689
+ for (const c of String(o.className || "").split(/\s+/))
690
+ if (c) box.classList.add(c);
691
+ box.setAttribute(lite ? "data-markdown-lite" : "data-markdown-field", "");
692
+ if (!lite)
693
+ box.style.setProperty(
694
+ "--md-min-height",
695
+ `${(o.rows ?? 3) * 1.5 * 15 + 20}px`,
696
+ );
697
+ const paint = () => {
698
+ if (!lite && o.invalid) box.setAttribute("data-invalid", "true");
699
+ else box.removeAttribute("data-invalid");
700
+ if (o.disabled) box.setAttribute("data-disabled", "true");
701
+ else box.removeAttribute("data-disabled");
702
+ };
703
+ paint();
704
+ // Focus left the field, the toolbar included.
705
+ box.addEventListener("focusout", (e) => {
706
+ if (swapping || !o.onBlur) return;
707
+ if (!box.contains(e.relatedTarget)) o.onBlur();
708
+ });
709
+ // Escape inside is the editor's (a dialog around it stays open).
710
+ box.addEventListener("keydown", (e) => {
711
+ if (e.key === "Escape" && o.onEscape) e.stopPropagation();
712
+ });
713
+
714
+ // The toolbar (full only): it works on the stand-in too.
715
+ let bar = null;
716
+ const drawToolbar = () => {
717
+ bar?.remove();
718
+ bar = null;
719
+ if (lite || o.readOnly || o.toolbar === false) return;
720
+ bar = document.createElement("div");
721
+ bar.className = "md-toolbar";
722
+ bar.setAttribute("role", "toolbar");
723
+ bar.setAttribute("aria-label", word("kit.md.toolbar"));
724
+ bar.setAttribute("aria-controls", id);
725
+ for (const tool of TOOLS) {
726
+ if (tool !== "sep" && o.noLinks && tool.format === "link") continue;
727
+ if (tool === "sep") {
728
+ const s = document.createElement("span");
729
+ s.className = "md-toolbar-sep";
730
+ s.setAttribute("aria-hidden", "true");
731
+ bar.append(s);
732
+ continue;
733
+ }
734
+ const name = tool.key
735
+ ? word("kit.md.toolKey", {
736
+ name: word(tool.label),
737
+ key: MOD + tool.key,
738
+ })
739
+ : word(tool.label);
740
+ const b = document.createElement("button");
741
+ b.type = "button";
742
+ b.className = "md-tool";
743
+ b.disabled = !!o.disabled;
744
+ b.setAttribute("aria-label", name);
745
+ b.title = name;
746
+ b.innerHTML = svg(tool.icon);
747
+ // A toolbar press keeps the caret in the text.
748
+ b.addEventListener("mousedown", (e) => e.preventDefault());
749
+ b.addEventListener("click", () => run(tool.format));
750
+ bar.append(b);
751
+ }
752
+ box.prepend(bar);
753
+ };
754
+ drawToolbar();
755
+
756
+ // The stand-in: a plain textarea with the same value, names and limit.
757
+ const area = document.createElement("textarea");
758
+ area.id = id;
759
+ area.className = "md-fallback";
760
+ area.rows = lite ? 1 : (o.rows ?? 3);
761
+ area.value = String(o.value ?? "");
762
+ area.setAttribute("data-md-editor", mode);
763
+ const paintArea = () => {
764
+ const set = (k, v) =>
765
+ v === undefined || v === null || v === false
766
+ ? area.removeAttribute(k)
767
+ : area.setAttribute(k, v === true ? "" : String(v));
768
+ set("placeholder", o.placeholder);
769
+ set("maxlength", o.maxLength);
770
+ set("disabled", !!o.disabled);
771
+ set("readonly", !lite && !!o.readOnly);
772
+ set("required", !!o.required);
773
+ set("lang", o.lang);
774
+ set("aria-label", o.label);
775
+ set("aria-labelledby", o.labelledBy);
776
+ set("aria-describedby", o.describedBy);
777
+ set("aria-invalid", !!o.invalid && "true");
778
+ };
779
+ paintArea();
780
+ area.addEventListener("input", () => o.onChange?.(area.value));
781
+ area.addEventListener("keydown", (e) => {
782
+ const act = enterAction(
783
+ {
784
+ key: e.key,
785
+ shiftKey: e.shiftKey,
786
+ altKey: e.altKey,
787
+ metaKey: e.metaKey,
788
+ ctrlKey: e.ctrlKey,
789
+ isComposing: e.isComposing,
790
+ keyCode: e.keyCode,
791
+ },
792
+ mode,
793
+ );
794
+ if (act === "submit" && o.onSubmit) {
795
+ e.preventDefault();
796
+ o.onSubmit();
797
+ } else if (act === "submit" && lite) e.preventDefault();
798
+ else if (e.key === "Escape" && o.onEscape) {
799
+ e.preventDefault();
800
+ o.onEscape();
801
+ }
802
+ });
803
+ box.append(area);
804
+ el.append(box);
805
+ if (o.autoFocus) area.focus();
806
+
807
+ /** An edit on the stand-in, as the person would make it. */
808
+ const standInEdit = (edit) => {
809
+ area.value = applyEdit(area.value, edit);
810
+ o.onChange?.(area.value);
811
+ requestAnimationFrame(() => {
812
+ area.focus();
813
+ area.setSelectionRange(edit.anchor, edit.head);
814
+ });
815
+ };
816
+ const apply = (edit, userEvent) =>
817
+ view.dispatch({
818
+ changes: edit.changes,
819
+ selection: cm.EditorSelection.single(edit.anchor, edit.head),
820
+ userEvent,
821
+ scrollIntoView: true,
822
+ });
823
+ const runFormat = (v, format) => {
824
+ if (!v.state.facet(cm.EditorView.editable) || v.state.readOnly)
825
+ return false;
826
+ const { from, to } = v.state.selection.main;
827
+ apply(
828
+ formatEdit(v.state.doc.toString(), from, to, format, linkText()),
829
+ "input.format",
830
+ );
831
+ return true;
832
+ };
833
+ const newline = (v) => {
834
+ if (v.state.readOnly) return false;
835
+ const { from, to } = v.state.selection.main;
836
+ const edit =
837
+ from === to ? continueBlock(v.state.doc.toString(), from) : null;
838
+ if (edit) apply(edit, "input");
839
+ else
840
+ v.dispatch(v.state.replaceSelection("\n"), {
841
+ userEvent: "input",
842
+ scrollIntoView: true,
843
+ });
844
+ return true;
845
+ };
846
+
847
+ function run(format) {
848
+ if (view) {
849
+ runFormat(view, format);
850
+ view.focus();
851
+ return;
852
+ }
853
+ standInEdit(
854
+ formatEdit(
855
+ area.value,
856
+ area.selectionStart,
857
+ area.selectionEnd,
858
+ format,
859
+ linkText(),
860
+ ),
861
+ );
862
+ }
863
+ /** From outside (a button): the editor when it has loaded, else the stand-in's caret. */
864
+ const atCaret = (make) => {
865
+ if (view) {
866
+ // The selection survives the blur a click outside causes: this is where the person last was.
867
+ const { from, to } = view.state.selection.main;
868
+ const edit = make(view.state.doc.toString(), from, to);
869
+ view.dispatch({
870
+ changes: edit.changes,
871
+ selection: { anchor: edit.anchor, head: edit.head },
872
+ scrollIntoView: true,
873
+ });
874
+ view.focus();
875
+ return;
876
+ }
877
+ standInEdit(make(area.value, area.selectionStart, area.selectionEnd));
878
+ };
879
+
880
+ // The editor's own attributes and state, reconfigured by update().
881
+ const dynamic = () => {
882
+ const attrs = {
883
+ id,
884
+ tabindex: o.disabled ? "-1" : "0",
885
+ "aria-multiline": "true",
886
+ role: "textbox",
887
+ "data-md-editor": mode,
888
+ autocapitalize: "sentences",
889
+ autocorrect: "on",
890
+ spellcheck: "true",
891
+ };
892
+ if (o.label) attrs["aria-label"] = o.label;
893
+ if (o.labelledBy) attrs["aria-labelledby"] = o.labelledBy;
894
+ if (o.describedBy) attrs["aria-describedby"] = o.describedBy;
895
+ if (o.invalid) attrs["aria-invalid"] = "true";
896
+ if (o.required) attrs["aria-required"] = "true";
897
+ if (o.disabled) attrs["aria-disabled"] = "true";
898
+ if (o.readOnly) attrs["aria-readonly"] = "true";
899
+ if (o.lang) attrs.lang = o.lang;
900
+ return [
901
+ cm.EditorView.editable.of(!o.disabled),
902
+ cm.EditorState.readOnly.of(!!o.disabled || !!o.readOnly),
903
+ cm.EditorView.contentAttributes.of(attrs),
904
+ o.placeholder ? cm.placeholder(o.placeholder) : [],
905
+ ];
906
+ };
907
+
908
+ function start(loaded) {
909
+ cm = loaded;
910
+ const { EditorState, EditorView, Prec, Transaction, keymap } = cm;
911
+ let compositionEnded = 0;
912
+ let lastKey = { isComposing: false, keyCode: 0 };
913
+ const imeEnter = (view) =>
914
+ view.composing ||
915
+ composingKey(lastKey) ||
916
+ Date.now() - compositionEnded < COMPOSITION_GRACE_MS;
917
+ const submit = () => {
918
+ const fn = o.onSubmit;
919
+ if (!fn) return false;
920
+ fn();
921
+ return true;
922
+ };
923
+ const keys = [
924
+ { key: "Mod-b", run: (v) => runFormat(v, "bold") },
925
+ { key: "Mod-i", run: (v) => runFormat(v, "italic") },
926
+ { key: "Mod-e", run: (v) => runFormat(v, "code") },
927
+ { key: "Mod-k", run: (v) => runFormat(v, "link") },
928
+ { key: "Mod-Shift-x", run: (v) => runFormat(v, "strike") },
929
+ // An Enter that belongs to the IME is swallowed here (true), so no lower keymap inserts a line either.
930
+ lite
931
+ ? { key: "Enter", run: (v) => imeEnter(v) || submit() || newline(v) }
932
+ : { key: "Enter", run: (v) => imeEnter(v) || newline(v) },
933
+ { key: "Shift-Enter", run: (v) => imeEnter(v) || newline(v) },
934
+ { key: "Alt-Enter", run: (v) => imeEnter(v) || newline(v) },
935
+ { key: "Mod-Enter", run: (v) => imeEnter(v) || submit() || true },
936
+ {
937
+ key: "Escape",
938
+ run: () => {
939
+ const fn = o.onEscape;
940
+ if (!fn) return false;
941
+ fn();
942
+ return true;
943
+ },
944
+ },
945
+ ];
946
+
947
+ const limit = EditorState.transactionFilter.of((tr) => {
948
+ const max = o.maxLength;
949
+ if (
950
+ !max ||
951
+ !tr.docChanged ||
952
+ tr.annotation(cm.External) ||
953
+ !tr.annotation(Transaction.userEvent)
954
+ )
955
+ return tr;
956
+ if (
957
+ tr.newDoc.length <= max ||
958
+ tr.newDoc.length <= tr.startState.doc.length
959
+ )
960
+ return tr;
961
+ // Never cut an open IME composition: a count beside the field says it is over.
962
+ if (tr.isUserEvent("input.type.compose")) return tr;
963
+ const changes = [];
964
+ tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) =>
965
+ changes.push({ from: fromA, to: toA, insert: inserted.toString() }),
966
+ );
967
+ if (changes.length !== 1) return [];
968
+ const c = changes[0];
969
+ let insert = c.insert.slice(
970
+ 0,
971
+ c.insert.length - (tr.newDoc.length - max),
972
+ );
973
+ if (/[\ud800-\udbff]$/.test(insert)) insert = insert.slice(0, -1);
974
+ if (!insert) return [];
975
+ return {
976
+ changes: { from: c.from, to: c.to, insert },
977
+ selection: { anchor: c.from + insert.length },
978
+ userEvent: tr.annotation(Transaction.userEvent),
979
+ };
980
+ });
981
+
982
+ // The stand-in hands over its text, focus, caret and selection as they are now.
983
+ const doc = area.value;
984
+ const handed = {
985
+ focus: document.activeElement === area,
986
+ caret: area.selectionStart,
987
+ end: area.selectionEnd,
988
+ };
989
+ const opened = doc;
990
+ const focus = o.autoFocus || handed.focus;
991
+ const caret = o.initialCaret ?? (handed.focus ? handed.caret : undefined);
992
+ // a selection in the stand-in comes over whole (anchor at its start, head at its end)
993
+ const end =
994
+ o.initialCaret === undefined && handed.focus ? handed.end : undefined;
995
+ dyn = new cm.Compartment();
996
+ const host = document.createElement("div");
997
+ host.className = `md-editor-host md-editor-${mode}`;
998
+ area.before(host);
999
+ view = new EditorView({
1000
+ parent: host,
1001
+ state: EditorState.create({
1002
+ doc,
1003
+ selection:
1004
+ caret !== undefined
1005
+ ? {
1006
+ anchor: Math.min(caret, doc.length),
1007
+ head: Math.min(end ?? caret, doc.length),
1008
+ }
1009
+ : undefined,
1010
+ extensions: [
1011
+ o.nonce ? EditorView.cspNonce.of(o.nonce) : [],
1012
+ cm.history(),
1013
+ Prec.highest(keymap.of(keys)),
1014
+ keymap.of([...cm.standardKeymap, ...cm.historyKeymap]),
1015
+ EditorView.lineWrapping,
1016
+ cm.livePreviewPlugin,
1017
+ limit,
1018
+ EditorView.domEventHandlers({
1019
+ compositionend() {
1020
+ compositionEnded = Date.now();
1021
+ return false;
1022
+ },
1023
+ }),
1024
+ EditorView.updateListener.of((u) => {
1025
+ if (!u.docChanged) return;
1026
+ const text = u.state.doc.toString();
1027
+ if (!u.transactions.some((tr) => tr.annotation(cm.External)))
1028
+ o.onChange?.(text);
1029
+ // Unsaved typing, for an update notice's "reload anyway?".
1030
+ if (text !== opened && text.trim())
1031
+ u.view.contentDOM.setAttribute("data-md-dirty", "");
1032
+ else u.view.contentDOM.removeAttribute("data-md-dirty");
1033
+ }),
1034
+ dyn.of(dynamic()),
1035
+ ],
1036
+ }),
1037
+ });
1038
+ // Record the keydown before CodeMirror's handlers see it (keyCode 229 = an IME's key).
1039
+ onKeyRec = (e) => {
1040
+ lastKey = { isComposing: e.isComposing, keyCode: e.keyCode };
1041
+ };
1042
+ view.dom.addEventListener("keydown", onKeyRec, true);
1043
+ swapping = true;
1044
+ area.remove();
1045
+ swapping = false;
1046
+ if (focus) {
1047
+ view.focus();
1048
+ if (caret === undefined)
1049
+ view.dispatch({ selection: { anchor: view.state.doc.length } });
1050
+ }
1051
+ }
1052
+
1053
+ const ready = chunk().then((loaded) => {
1054
+ if (!destroyed) start(loaded);
1055
+ });
1056
+ ready.catch(() => {
1057
+ /* the stand-in stays: a plain textarea that still works */
1058
+ });
1059
+
1060
+ return {
1061
+ ready,
1062
+ getValue: () => (view ? view.state.doc.toString() : area.value),
1063
+ setValue(v) {
1064
+ const next = String(v ?? "");
1065
+ if (!view) {
1066
+ area.value = next;
1067
+ return;
1068
+ }
1069
+ const doc = view.state.doc.toString();
1070
+ if (next === doc) return;
1071
+ view.dispatch({
1072
+ changes: diff(doc, next),
1073
+ annotations: cm.External.of(true),
1074
+ });
1075
+ // A value set from outside (a send cleared it, a save answered) is the new baseline.
1076
+ view.contentDOM.removeAttribute("data-md-dirty");
1077
+ },
1078
+ focus: () => (view ? view.focus() : area.focus()),
1079
+ run,
1080
+ insertBlock: (block) =>
1081
+ atCaret((doc, from, to) => insertBlock(doc, from, to, block)),
1082
+ insertLinkTo: (label, url) =>
1083
+ atCaret((doc, from, to) => insertLinkTo(doc, from, to, label, url)),
1084
+ replaceEnd(count, text) {
1085
+ if (view) {
1086
+ const end = view.state.doc.length,
1087
+ from = Math.max(0, end - count);
1088
+ view.dispatch({
1089
+ changes: { from, to: end, insert: text },
1090
+ selection: { anchor: from + text.length },
1091
+ scrollIntoView: true,
1092
+ });
1093
+ view.focus();
1094
+ return;
1095
+ }
1096
+ const next =
1097
+ area.value.slice(0, Math.max(0, area.value.length - count)) + text;
1098
+ area.value = next;
1099
+ o.onChange?.(next);
1100
+ requestAnimationFrame(() => {
1101
+ area.focus();
1102
+ area.setSelectionRange(next.length, next.length);
1103
+ });
1104
+ },
1105
+ update(next) {
1106
+ Object.assign(o, next ?? {});
1107
+ paint();
1108
+ paintArea();
1109
+ drawToolbar();
1110
+ view?.dispatch({ effects: dyn.reconfigure(dynamic()) });
1111
+ },
1112
+ destroy() {
1113
+ destroyed = true;
1114
+ if (view) {
1115
+ view.dom.removeEventListener("keydown", onKeyRec, true);
1116
+ view.destroy();
1117
+ view = null;
1118
+ }
1119
+ box.remove();
1120
+ },
1121
+ };
1122
+ }