@aiquants/markdown-explorer 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,975 @@
1
+ import { jsx as M, jsxs as te, Fragment as Xe } from "react/jsx-runtime";
2
+ import { useState as ne, useRef as D, useLayoutEffect as B, useEffectEvent as ve, useEffect as Pe, useImperativeHandle as Ye, useMemo as J, startTransition as Je, useCallback as j, useId as Qe } from "react";
3
+ import { v as re, g as me, h as Ze, u as le, i as et, l as tt, j as nt, k as De, m as rt, n as ot, o as it, p as st, E as lt, q as ct, s as at, t as we, w as be, A as ut, x as Ee, y as dt, z as ft, B as mt, G as pt } from "./index-0pnuyLUO.js";
4
+ import { fencedBodyAsRead as ht, planFencedBodyEdit as gt, fencedCodeLanguageOf as vt, SPREADSHEETS_LANGUAGE as wt, readFencedLine as bt, listItemWidthOn as Et, openingFenceOn as xt } from "@aiquants/markdown/code-blocks";
5
+ import { history as St, historyKeymap as yt, defaultKeymap as Tt, historyField as kt, redo as At, undo as It, isolateHistory as Lt } from "@codemirror/commands";
6
+ import { markdown as Ot, markdownLanguage as Ct } from "@codemirror/lang-markdown";
7
+ import { syntaxHighlighting as Mt, syntaxTreeAvailable as qt, HighlightStyle as Rt, ensureSyntaxTree as Be } from "@codemirror/language";
8
+ import { highlightSelectionMatches as _t, searchKeymap as Nt } from "@codemirror/search";
9
+ import { EditorState as Ve, EditorSelection as fe, StateField as Pt, RangeSetBuilder as Dt, MapMode as Bt } from "@codemirror/state";
10
+ import { EditorView as $, lineNumbers as Vt, highlightActiveLineGutter as Ht, drawSelection as zt, highlightActiveLine as Ft, keymap as Ut, ViewPlugin as Gt, Decoration as ce, WidgetType as Wt } from "@codemirror/view";
11
+ import { tags as N } from "@lezer/highlight";
12
+ import { MarkdownViewer as $t } from "@aiquants/markdown";
13
+ import { SOURCE_LINES_ATTRIBUTE as He, parseSourceLines as Kt } from "@aiquants/markdown/source-lines";
14
+ import { d as jt, f as oe, E as Xt } from "./dataRoute-CObbjNxG.js";
15
+ import { H as Yt, c as Jt, M as Qt } from "./sanitizePolicy-BWQtWhsL.js";
16
+ import Zt from "isomorphic-dompurify";
17
+ import { PanelGroup as en, Panel as xe, PanelResizeHandle as tn } from "@aiquants/resize-panels";
18
+ import { C as nn, F as rn, E as on, a as sn, b as ie, d as ln } from "./location-B-m9scLf.js";
19
+ import { u as cn, a as an } from "./useSplitPersistence-Cc4tDxB4.js";
20
+ const ze = { history: kt }, un = Rt.define([
21
+ { tag: [N.heading1, N.heading2, N.heading3, N.heading4, N.heading5, N.heading6, N.heading], color: "var(--aqmx-syntax-heading)", fontWeight: "700" },
22
+ { tag: N.strong, fontWeight: "700" },
23
+ { tag: N.emphasis, fontStyle: "italic" },
24
+ { tag: N.strikethrough, textDecoration: "line-through" },
25
+ { tag: N.link, color: "var(--aqmx-syntax-link)", textDecoration: "underline" },
26
+ { tag: N.url, color: "var(--aqmx-syntax-url)" },
27
+ { tag: N.monospace, color: "var(--aqmx-syntax-code)" },
28
+ { tag: N.quote, color: "var(--aqmx-syntax-quote)" },
29
+ { tag: [N.processingInstruction, N.contentSeparator, N.labelName, N.meta], color: "var(--aqmx-syntax-mark)" }
30
+ ]), dn = $.theme({
31
+ "&": { height: "100%", color: "var(--aqmx-text)", backgroundColor: "var(--aqmx-surface)", fontSize: "var(--aqmx-font-size-title)" },
32
+ "&.cm-focused": { outline: "none" },
33
+ ".cm-scroller": { fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace', lineHeight: "var(--aqmx-line-height-prose)" },
34
+ ".cm-content": { caretColor: "var(--aqmx-text)", paddingBlock: "var(--aqmx-space-6)" },
35
+ ".cm-line": { paddingInline: "var(--aqmx-space-6)" },
36
+ "&.cm-focused .cm-cursor": { borderLeftColor: "var(--aqmx-text)" },
37
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: "var(--aqmx-editor-selection)" },
38
+ ".cm-activeLine": { backgroundColor: "var(--aqmx-editor-active-line)" },
39
+ ".cm-gutters": { backgroundColor: "var(--aqmx-surface-raised)", color: "var(--aqmx-editor-gutter)", borderInlineEnd: "var(--aqmx-space-1) solid var(--aqmx-border)" },
40
+ ".cm-activeLineGutter": { backgroundColor: "var(--aqmx-editor-active-line)" },
41
+ ".cm-searchMatch": { outline: "var(--aqmx-space-1) solid var(--aqmx-border-strong)" },
42
+ ".cm-panels": { backgroundColor: "var(--aqmx-surface-raised)", color: "var(--aqmx-text)" }
43
+ }), Fe = "data-aqmx-conflict-actions", fn = ce.line({ attributes: { "data-aqmx-conflict-line": "marker" } }), mn = ce.line({ attributes: { "data-aqmx-conflict-line": "ours" } }), pn = ce.line({ attributes: { "data-aqmx-conflict-line": "theirs" } });
44
+ class hn extends Wt {
45
+ constructor(t, n) {
46
+ super(), this.index = t, this.labels = n;
47
+ }
48
+ index;
49
+ labels;
50
+ eq(t) {
51
+ return t.index === this.index && t.labels === this.labels;
52
+ }
53
+ toDOM(t) {
54
+ const n = document.createElement("div");
55
+ n.setAttribute(Fe, String(this.index));
56
+ for (const [r, s] of [
57
+ ["ours", this.labels.useOurs],
58
+ ["theirs", this.labels.useTheirs],
59
+ ["both", this.labels.keepBoth]
60
+ ]) {
61
+ const o = document.createElement("button");
62
+ o.type = "button", o.textContent = s, o.setAttribute("data-aqmx-conflict-choice", r), o.addEventListener("mousedown", (l) => l.preventDefault()), o.addEventListener("click", () => {
63
+ const l = ee(t.state.doc)[this.index];
64
+ l !== void 0 && (Ue(t, l, r), t.focus());
65
+ }), n.append(o);
66
+ }
67
+ return n;
68
+ }
69
+ ignoreEvent() {
70
+ return !0;
71
+ }
72
+ }
73
+ const ee = (e) => Ze(e.iterLines()), Se = (e, t) => {
74
+ const n = new Dt();
75
+ return ee(e).forEach((r, s) => {
76
+ const o = e.line(r.start);
77
+ n.add(o.from, o.from, ce.widget({ widget: new hn(s, t), block: !0, side: -1 }));
78
+ for (let l = r.start; l <= r.end; l += 1) {
79
+ const i = e.line(l).from, f = l === r.start || l === r.separator || l === r.end ? fn : l < r.separator ? mn : pn;
80
+ n.add(i, i, f);
81
+ }
82
+ }), n.finish();
83
+ }, gn = (e) => Pt.define({
84
+ create: (t) => Se(t.doc, e),
85
+ update: (t, n) => n.docChanged ? Se(n.state.doc, e) : t,
86
+ provide: (t) => $.decorations.from(t)
87
+ }), Ue = (e, t, n) => {
88
+ const { doc: r } = e.state, s = (y, c) => {
89
+ const w = [];
90
+ for (let u = y; u <= c; u += 1) w.push(r.line(u).text);
91
+ return w;
92
+ }, o = s(t.start + 1, t.separator - 1), l = s(t.separator + 1, t.end - 1), i = n === "ours" ? o : n === "theirs" ? l : [...o, ...l];
93
+ let f = r.line(t.start).from, d = r.line(t.end).to;
94
+ i.length === 0 && (t.end < r.lines ? d += 1 : t.start > 1 && (f -= 1));
95
+ const p = i.join(`
96
+ `);
97
+ e.dispatch({ changes: { from: f, to: d, insert: p }, selection: fe.cursor(f), scrollIntoView: !0, userEvent: "input.resolve" });
98
+ }, ye = "input.preview", vn = 20, wn = Gt.fromClass(
99
+ class {
100
+ constructor(e) {
101
+ this.view = e, this.schedule();
102
+ }
103
+ view;
104
+ cancel = null;
105
+ update(e) {
106
+ e.docChanged && this.schedule();
107
+ }
108
+ schedule() {
109
+ if (this.cancel !== null || qt(this.view.state)) return;
110
+ const e = this.view.dom.ownerDocument.defaultView;
111
+ if (e === null) return;
112
+ const t = () => {
113
+ this.cancel = null, Be(this.view.state, this.view.state.doc.length, vn), this.schedule();
114
+ };
115
+ if (typeof e.requestIdleCallback == "function") {
116
+ const n = e.requestIdleCallback(t);
117
+ this.cancel = () => e.cancelIdleCallback(n);
118
+ } else {
119
+ const n = e.setTimeout(t, 0);
120
+ this.cancel = () => e.clearTimeout(n);
121
+ }
122
+ }
123
+ destroy() {
124
+ this.cancel?.(), this.cancel = null;
125
+ }
126
+ }
127
+ ), bn = /`{3,}|~{3,}/u, Q = Object.freeze({ kind: "absent" }), ue = Object.freeze({ kind: "unreadable" }), En = (e, t, n) => {
128
+ const r = [];
129
+ for (let f = t.parent; f !== null; f = f.parent)
130
+ (f.name === "Blockquote" || f.name === "ListItem") && r.unshift(f);
131
+ const s = [], o = [], l = (f) => {
132
+ const d = o.indexOf(f);
133
+ return d === -1 ? o.length : d;
134
+ };
135
+ for (const f of r) {
136
+ const d = e.lineAt(f.from).number;
137
+ if (f.name === "ListItem") {
138
+ const p = Et(e.line(d).text, s, l(d));
139
+ if (p === null) return null;
140
+ s.push({ kind: "listItem", width: p });
141
+ } else
142
+ s.push({ kind: "quote" });
143
+ o.push(d);
144
+ }
145
+ const i = xt(n.text, s, l(n.number));
146
+ return i === null ? null : { containers: s, ...i };
147
+ }, xn = (e, t) => {
148
+ const { doc: n } = e;
149
+ let r = n.lineAt(t).to;
150
+ for (; ; ) {
151
+ const s = Be(e, r, Number.POSITIVE_INFINITY);
152
+ if (s === null) return null;
153
+ const o = s.resolveInner(t, 1), l = o.parent;
154
+ if (o.name !== "CodeMark" || l === null || l.name !== "FencedCode" || l.from !== o.from) return null;
155
+ if (l.to < r || r >= n.length) return l;
156
+ r = Math.min(n.length, l.to + Math.max(l.to - t, 1));
157
+ }
158
+ }, Te = (e, t) => {
159
+ const { doc: n } = e;
160
+ if (!Number.isInteger(t) || t < 1 || t > n.lines) return Q;
161
+ const r = n.line(t), s = bn.exec(r.text);
162
+ if (s === null) return Q;
163
+ const o = xn(e, r.from + s.index);
164
+ if (o === null) return Q;
165
+ const l = o.getChild("CodeInfo");
166
+ if (l === null) return Q;
167
+ const i = vt(n.sliceString(l.from, l.to));
168
+ if (i === null) return ue;
169
+ if (i !== wt) return Q;
170
+ const f = En(n, o, r);
171
+ if (f === null) return ue;
172
+ const [, ...d] = o.getChildren("CodeMark"), p = d.at(-1), y = p === void 0 ? n.lineAt(o.to).number : n.lineAt(p.from).number - 1, c = [];
173
+ let w = "";
174
+ for (let u = t + 1; u <= y; u += 1) {
175
+ const m = n.line(u).text, g = bt(m, f);
176
+ if (g === null) return ue;
177
+ c.push(m), w += u < n.lines ? `${g.content}
178
+ ` : g.content;
179
+ }
180
+ return { kind: "found", firstLine: t + 1, lines: c, layout: f, body: w };
181
+ }, Sn = ({ parent: e, scroll: t, text: n, saved: r, labels: s, revisions: o, onChange: l, onGeometry: i, onSave: f }) => {
182
+ let d = !1;
183
+ const p = [
184
+ $.scrollHandler.of((u, m, g) => (yn(u, m.head, g, t), !0)),
185
+ Vt(),
186
+ Ht(),
187
+ St(),
188
+ zt(),
189
+ Ft(),
190
+ _t(),
191
+ $.lineWrapping,
192
+ Ot({ base: Ct }),
193
+ wn,
194
+ Mt(un),
195
+ gn(s),
196
+ Ut.of([
197
+ {
198
+ key: "Mod-s",
199
+ preventDefault: !0,
200
+ run: () => (f(), !0)
201
+ },
202
+ ...Nt,
203
+ ...yt,
204
+ ...Tt
205
+ ]),
206
+ $.contentAttributes.of({ "aria-label": s.editor, "aria-multiline": "true" }),
207
+ $.updateListener.of((u) => {
208
+ for (const m of u.transactions) m.docChanged && o.record(m.changes, m.newDoc);
209
+ u.docChanged && l(u.transactions.every((m) => !m.docChanged || m.isUserEvent(ye))), (u.docChanged || u.heightChanged || u.geometryChanged) && i(u.docChanged && !d);
210
+ }),
211
+ dn
212
+ ], y = An(r, p) ?? Ve.create({ doc: n, extensions: p }), c = new $({ state: y, parent: e });
213
+ o.mount(c.state.doc);
214
+ const w = (u) => {
215
+ d = !0;
216
+ try {
217
+ u();
218
+ } finally {
219
+ d = !1;
220
+ }
221
+ };
222
+ return {
223
+ text: () => c.state.doc.toString(),
224
+ replaceText: (u) => {
225
+ const m = c.state.doc.toString();
226
+ if (m === u) return;
227
+ let g = 0;
228
+ const x = Math.min(m.length, u.length);
229
+ for (; g < x && m.charCodeAt(g) === u.charCodeAt(g); ) g += 1;
230
+ let h = 0;
231
+ for (; h < x - g && m.charCodeAt(m.length - 1 - h) === u.charCodeAt(u.length - 1 - h); ) h += 1;
232
+ c.dispatch({ changes: { from: g, to: m.length - h, insert: u.slice(g, u.length - h) }, userEvent: "input.replace" });
233
+ },
234
+ replaceBody: (u, m, g, x) => {
235
+ const { doc: h } = c.state, T = o.lineOf(x, u);
236
+ if (T === null) return "changed";
237
+ const I = Te(c.state, T);
238
+ if (I.kind === "absent") return "changed";
239
+ if (I.kind === "unreadable") return "unwritable";
240
+ if (I.body !== ht(m, I.layout)) return "changed";
241
+ const A = gt(I.lines, I.layout, g);
242
+ if (A.kind !== "edit") return A.kind;
243
+ if (A.from === A.to && A.lines.length === 0) return "written";
244
+ const _ = (H) => {
245
+ const V = I.firstLine + H;
246
+ return V <= h.lines ? h.line(V).from : h.length;
247
+ }, C = _(A.from), P = `${C === h.length && h.sliceString(h.length - 1) !== `
248
+ ` ? `
249
+ ` : ""}${A.lines.map((H) => `${H}
250
+ `).join("")}`;
251
+ return w(() => c.dispatch({ changes: { from: C, to: _(A.to), insert: P }, userEvent: ye, annotations: Lt.of("full") })), "written";
252
+ },
253
+ readBody: (u, m) => {
254
+ const g = o.lineOf(m, u);
255
+ if (g === null) return null;
256
+ const x = Te(c.state, g);
257
+ return x.kind === "found" ? x.body : null;
258
+ },
259
+ undo: () => w(() => It(c)),
260
+ redo: () => w(() => At(c)),
261
+ reveal: ({ line: u, column: m }, g) => {
262
+ const { doc: x } = c.state, h = x.line(Math.min(Math.max(u, 1), x.lines)), T = Math.min(h.from + m, h.to);
263
+ c.dispatch({ selection: fe.cursor(T), effects: ke(c, T, g, t) });
264
+ },
265
+ showLine: (u) => {
266
+ const { doc: m } = c.state, g = m.line(Math.min(Math.max(u, 1), m.lines)).from;
267
+ c.dispatch({ effects: ke(c, g, null, t) });
268
+ },
269
+ topLine: () => {
270
+ const u = t.scrollerOf(c.scrollDOM), m = re(u, c.contentDOM), g = me(u) + u.clientHeight, { documentTop: x } = c, { doc: h } = c.state;
271
+ let T = c.lineBlockAtHeight(Math.max(m - x, 0));
272
+ for (; h.lineAt(T.from).text.trim() === "" && T.to < h.length; ) {
273
+ const _ = c.lineBlockAt(T.to + 1);
274
+ if (x + _.top >= g) break;
275
+ T = _;
276
+ }
277
+ const I = c.coordsAtPos(T.from), A = I === null ? x + T.top : I.top;
278
+ return { line: c.state.doc.lineAt(T.from).number, clientTop: A, offset: A - m };
279
+ },
280
+ lineSpans: (u) => {
281
+ const m = c.scrollDOM, g = m.scrollTop + c.documentTop - re(m, c.contentDOM), { doc: x } = c.state, h = (T) => x.line(Math.min(Math.max(T, 1), x.lines)).from;
282
+ return u.map(({ first: T, last: I }) => ({ top: g + c.lineBlockAt(h(T)).top, bottom: g + c.lineBlockAt(h(I)).bottom }));
283
+ },
284
+ scrollElement: c.scrollDOM,
285
+ focus: () => c.focus(),
286
+ conflicts: () => ee(c.state.doc),
287
+ resolveAtCursor: (u) => {
288
+ const m = ee(c.state.doc), g = c.state.doc.lineAt(c.state.selection.main.head).number, x = m.find((h) => h.end >= g);
289
+ return x === void 0 ? !1 : (Ue(c, x, u), !0);
290
+ },
291
+ nextConflict: () => {
292
+ const u = ee(c.state.doc);
293
+ if (u[0] === void 0) return !1;
294
+ const g = c.state.doc.lineAt(c.state.selection.main.head).number, x = u.findIndex((A) => A.start > g), h = x < 0 ? 0 : x, T = c.state.doc.line(u[h].start).from;
295
+ c.dispatch({ selection: fe.cursor(T), effects: $.scrollIntoView(T, { y: "center" }) });
296
+ const I = c.contentDOM.querySelector(`[${Fe}="${String(h)}"] button`);
297
+ return I instanceof HTMLElement ? I.focus({ preventScroll: !0 }) : c.focus(), !0;
298
+ },
299
+ save: () => c.state.toJSON(ze),
300
+ destroy: () => c.destroy()
301
+ };
302
+ }, ke = (e, t, n, r) => {
303
+ const s = r.scrollerOf(e.scrollDOM), o = (n === null ? re(s, e.contentDOM) : n) - me(s);
304
+ return $.scrollIntoView(t, { y: "start", yMargin: o });
305
+ }, yn = (e, t, n, r) => {
306
+ const s = Tn(e, t), o = r.scrollerOf(e.scrollDOM), l = me(o), i = re(o, e.contentDOM), f = l + o.clientHeight;
307
+ let d = 0;
308
+ switch (n.y) {
309
+ case "start":
310
+ d = s.top - (l + n.yMargin);
311
+ break;
312
+ case "center":
313
+ d = (s.top + s.bottom) / 2 - (i + f) / 2;
314
+ break;
315
+ case "end":
316
+ d = s.bottom - (f - n.yMargin);
317
+ break;
318
+ default:
319
+ s.top < i + n.yMargin ? d = s.top - (i + n.yMargin) : s.bottom > f - n.yMargin && (d = Math.min(s.bottom - (f - n.yMargin), s.top - (i + n.yMargin)));
320
+ }
321
+ if (d !== 0 && (o.scrollTop += d), n.y === "start") return;
322
+ const p = kn(e, t);
323
+ p !== null && r.reveal(p);
324
+ }, Tn = (e, t) => {
325
+ const { node: n, offset: r } = e.domAtPos(t);
326
+ if (n.nodeType === Node.TEXT_NODE) {
327
+ const l = n.ownerDocument?.createRange();
328
+ if (l !== void 0) {
329
+ l.setStart(n, r), l.setEnd(n, r);
330
+ const [i] = l.getClientRects();
331
+ if (i !== void 0 && i.height > 0) return { top: i.top, bottom: i.bottom };
332
+ }
333
+ }
334
+ const s = e.lineBlockAt(t), o = e.documentTop + s.top;
335
+ return { top: o, bottom: o + s.height };
336
+ }, kn = (e, t) => {
337
+ const { node: n } = e.domAtPos(t);
338
+ for (let r = n instanceof Element ? n : n.parentElement; r !== null; r = r.parentElement)
339
+ if (r.parentElement === e.contentDOM) return r;
340
+ return null;
341
+ }, An = (e, t) => {
342
+ if (e == null) return null;
343
+ try {
344
+ return Ve.fromJSON(e, { extensions: t }, ze);
345
+ } catch {
346
+ return null;
347
+ }
348
+ }, In = 610, Ln = 987, Ae = Object.freeze({ kind: "unavailable" }), On = "true", Cn = "false", Mn = (e) => e === On ? !0 : e === Cn ? !1 : null, qn = (e) => {
349
+ const t = new DOMParser().parseFromString(e, "text/html"), n = [];
350
+ for (const r of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")) {
351
+ const s = r.localName === "img", o = r.getAttribute(s ? "data-asset-src" : "data-doc-path");
352
+ o !== null && n.push({ target: { kind: s ? "asset" : "doc", path: o }, exists: Mn(r.getAttribute(s ? "data-asset-exists" : "data-doc-exists")) });
353
+ }
354
+ return n;
355
+ }, Rn = ({ path: e, instant: t, preview: n, initial: r, onView: s }) => {
356
+ const o = new AbortController(), l = { asset: /* @__PURE__ */ new Map(), doc: /* @__PURE__ */ new Map() };
357
+ let i = r, f = null, d = !1, p = !1, y = null, c = null, w = [], u, m = !1, g, x = null;
358
+ const h = (v) => {
359
+ v.parsed === i.parsed && v.source === i.source && v.failure === i.failure && v.busy === i.busy && v.tier === i.tier || (i = v, s(v));
360
+ }, T = (v, S) => {
361
+ d || (d = !0, console.error(`[markdown-explorer] ${v}`, ...S === void 0 ? [] : [S]));
362
+ }, I = (v) => {
363
+ if (t !== null)
364
+ for (const { target: S, exists: O } of t.marksOf(v)) l[S.kind].set(S.path, O);
365
+ }, A = () => {
366
+ clearTimeout(g), g = void 0, x?.abort(), x = null;
367
+ }, _ = () => {
368
+ c = null, w = [], clearTimeout(u), u = void 0;
369
+ }, C = (v, S) => {
370
+ h({ ...i, failure: v, busy: !1, tier: S });
371
+ }, F = () => {
372
+ clearTimeout(u), u = w.length === 0 ? void 0 : setTimeout(H, Ln);
373
+ }, P = () => {
374
+ if (t === null || c === null) return;
375
+ const v = c, S = [], O = { asset: /* @__PURE__ */ new Set(), doc: /* @__PURE__ */ new Set() };
376
+ let G;
377
+ try {
378
+ G = t.sanitize(v.html, (E) => {
379
+ const q = l[E.kind].get(E.path);
380
+ return q === void 0 && !O[E.kind].has(E.path) && (O[E.kind].add(E.path), S.push(E)), q ?? void 0;
381
+ });
382
+ } catch (E) {
383
+ _(), E instanceof Yt ? C(oe("too-large"), "instant") : (T("the draft sanitizer failed", E), C(oe("failed"), "instant"));
384
+ return;
385
+ }
386
+ w = S;
387
+ const b = i.parsed !== null && i.parsed.htmlContent === G && i.parsed.headings === v.headings ? i.parsed : { htmlContent: G, headings: v.headings };
388
+ h({ parsed: b, source: v.draft, failure: null, busy: !1, tier: "instant" }), F();
389
+ }, H = () => {
390
+ if (u = void 0, m || c === null || w.length === 0) return;
391
+ m = !0;
392
+ const v = w;
393
+ n(e, c.draft.text, o.signal).then((S) => {
394
+ if (m = !1, !(o.signal.aborted || !("kind" in S))) {
395
+ S.kind === "preview" && I(S.htmlContent);
396
+ for (const O of v) l[O.kind].has(O.path) || l[O.kind].set(O.path, null);
397
+ P();
398
+ }
399
+ });
400
+ }, V = (v) => {
401
+ A(), _(), h({ ...i, busy: !0, tier: "server" });
402
+ const S = new AbortController();
403
+ x = S, g = setTimeout(() => {
404
+ g = void 0, n(e, v.text, S.signal).then((O) => {
405
+ if (!(S.signal.aborted || !("kind" in O))) {
406
+ if (x = null, O.kind === "failure") {
407
+ C(O.failure, "server");
408
+ return;
409
+ }
410
+ I(O.htmlContent), h({ parsed: { htmlContent: O.htmlContent, headings: O.headings }, source: v, failure: null, busy: !1, tier: "server" });
411
+ }
412
+ });
413
+ }, In);
414
+ }, a = async (v, S) => {
415
+ let O;
416
+ try {
417
+ O = await v.convert({ path: e, text: S }, o.signal);
418
+ } catch (b) {
419
+ return o.signal.aborted || T("the draft converter rejected a conversion, which its contract allows only once the signal aborted", b), Ae;
420
+ }
421
+ const G = jt(O);
422
+ return G === null ? O : (T(`the draft converter answered outside its contract: ${G}`), Ae);
423
+ }, k = (v, S) => {
424
+ switch (S.kind) {
425
+ case "preview":
426
+ if (A(), S.headings.length > Xt) {
427
+ _(), C(oe("too-large"), "instant");
428
+ return;
429
+ }
430
+ c = { draft: v, html: S.htmlContent, headings: S.headings.map(({ text: O, depth: G, id: b }) => ({ text: O, depth: G, id: b })) }, P();
431
+ return;
432
+ case "failure":
433
+ A(), _(), C(oe(S.failure.reason, S.failure.code), "instant");
434
+ return;
435
+ case "unavailable":
436
+ V(v);
437
+ return;
438
+ }
439
+ }, L = async (v) => {
440
+ p = !0;
441
+ try {
442
+ for (; y !== null && !o.signal.aborted; ) {
443
+ const S = y;
444
+ y = null;
445
+ const O = await a(v, S.text);
446
+ if (o.signal.aborted) return;
447
+ k(S, O);
448
+ }
449
+ } finally {
450
+ p = !1;
451
+ }
452
+ };
453
+ return t !== null && t.seed !== null && I(t.seed), {
454
+ update: (v) => {
455
+ if (!(o.signal.aborted || v.text === f?.text)) {
456
+ if (f = v, clearTimeout(u), u = void 0, t === null) {
457
+ V(v);
458
+ return;
459
+ }
460
+ y = v, p || L(t.converter);
461
+ }
462
+ },
463
+ dispose: () => {
464
+ o.abort(), y = null, clearTimeout(u), u = void 0, A();
465
+ }
466
+ };
467
+ }, _n = (e, t) => Jt(Zt(window), e, t, Qt), Nn = (e, t) => e.flatMap((n, r) => {
468
+ const s = t[r];
469
+ return s === void 0 ? [] : [
470
+ { editor: s.top, preview: n.top },
471
+ { editor: s.bottom, preview: n.bottom }
472
+ ];
473
+ }), K = (e, t) => {
474
+ const n = e[t];
475
+ if (n === void 0) throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length - 1)}; got ${String(t)}`);
476
+ return n;
477
+ }, Pn = (e) => {
478
+ const t = [];
479
+ for (const r of e) {
480
+ let s = 0, o = t.length;
481
+ for (; s < o; ) {
482
+ const l = s + o >> 1;
483
+ K(t, l).pair.preview <= r.preview ? s = l + 1 : o = l;
484
+ }
485
+ t[s] = { pair: r, before: s === 0 ? void 0 : K(t, s - 1) };
486
+ }
487
+ const n = [];
488
+ for (let r = t.at(-1); r !== void 0; r = r.before) n.push(r.pair);
489
+ return n.reverse();
490
+ }, Dn = (e, t) => {
491
+ const n = Math.max(t.editorMax, 0), r = Math.max(t.previewMax, 0), s = n - t.editorViewport, o = r - t.previewViewport, l = e.filter((d) => d.editor > 0 && d.editor < s && d.preview > 0 && d.preview < o).sort((d, p) => d.editor - p.editor || d.preview - p.preview);
492
+ let i = { editor: 0, preview: 0 };
493
+ const f = [i];
494
+ for (const d of Pn(l))
495
+ d.editor > i.editor && d.preview > i.preview && (f.push(d), i = d);
496
+ return f.push({ editor: n, preview: r }), {
497
+ toPreview: (d) => Ie(f, "editor", "preview", d),
498
+ toEditor: (d) => Ie(f, "preview", "editor", d)
499
+ };
500
+ }, Ie = (e, t, n, r) => {
501
+ const s = K(e, 0), o = K(e, e.length - 1);
502
+ if (Number.isNaN(r) || r <= s[t]) return s[n];
503
+ if (r >= o[t]) return o[n];
504
+ let l = 0, i = e.length - 1;
505
+ for (; i - l > 1; ) {
506
+ const p = l + i >> 1;
507
+ K(e, p)[t] <= r ? l = p : i = p;
508
+ }
509
+ const f = K(e, l), d = K(e, i);
510
+ return f[n] + (d[n] - f[n]) * (r - f[t]) / (d[t] - f[t]);
511
+ }, Bn = 610, Le = 89, Oe = 0.5, Vn = ({ editor: e, preview: t, previewBlocks: n, editorSpans: r, requestFrame: s, cancelFrame: o, now: l }) => {
512
+ let i = "editor", f = 0, d = null, p = null, y = !1, c = null, w = null;
513
+ const u = { editor: 0, preview: 0 }, m = { editor: null, preview: null };
514
+ let g = null, x = () => {
515
+ };
516
+ const h = (a) => {
517
+ d !== null && a !== d || (i = a, f = l() + Bn);
518
+ }, T = (a, k) => {
519
+ a !== i && d === null && l() >= f && !I(a, k) && (i = a), P();
520
+ }, I = (a, k) => {
521
+ const L = m[a];
522
+ return l() < u[a] || L !== null && Math.abs(k.position() - L) < Oe;
523
+ }, A = e.onScroll(() => T("editor", e)), _ = e.onIntent(() => h("editor")), C = () => {
524
+ const a = t();
525
+ return a !== g && (x(), g = a, x = a === null ? () => {
526
+ } : F(a)), a;
527
+ }, F = (a) => {
528
+ const k = a.onScroll(() => T("preview", a)), L = a.onIntent(() => h("preview"));
529
+ return () => {
530
+ k(), L();
531
+ };
532
+ }, P = () => {
533
+ !y && p === null && (p = s(H));
534
+ }, H = () => {
535
+ p = null;
536
+ const a = C();
537
+ a !== null && (c ??= n(), w ??= Dn(Nn(c, r(c)), { editorMax: e.max(), previewMax: a.max(), editorViewport: e.viewport(), previewViewport: a.viewport() }), i === "editor" ? V(a, "preview", w.toPreview(e.position())) : V(e, "editor", w.toEditor(a.position())));
538
+ }, V = (a, k, L) => {
539
+ if (Math.abs(a.position() - L) < Oe) {
540
+ m[k] = a.position();
541
+ return;
542
+ }
543
+ u[k] = l() + Le, m[k] = a.scrollTo(L);
544
+ };
545
+ return P(), {
546
+ editorChanged: (a) => {
547
+ w = null, a && h("editor"), P();
548
+ },
549
+ previewChanged: () => {
550
+ c = null, w = null, u.preview = l() + Le, P();
551
+ },
552
+ showAlone: (a) => {
553
+ d = a, !(a === null || a === i) && (i = a, f = 0, P());
554
+ },
555
+ dispose: () => {
556
+ y = !0, p !== null && o(p), p = null, A(), _(), x();
557
+ }
558
+ };
559
+ }, Ce = Object.freeze(["wheel", "pointerdown", "keydown", "focusin"]), Ge = (e) => ({
560
+ position: () => e.scrollTop,
561
+ max: () => Math.max(e.scrollHeight - e.clientHeight, 0),
562
+ viewport: () => e.clientHeight,
563
+ scrollTo: (t) => (e.scrollTo({ top: t, behavior: "instant" }), e.scrollTop),
564
+ onScroll: (t) => (e.addEventListener("scroll", t, { passive: !0 }), () => e.removeEventListener("scroll", t)),
565
+ onIntent: (t) => {
566
+ for (const n of Ce) e.addEventListener(n, t, { capture: !0, passive: !0 });
567
+ return () => {
568
+ for (const n of Ce) e.removeEventListener(n, t, { capture: !0 });
569
+ };
570
+ }
571
+ }), Z = "[data-aqmd-scroll-container]", Hn = "[data-aqmd-content]", zn = `[${He}]`, Fn = Object.freeze(["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8"]), We = (e, t) => {
572
+ const n = rt(e.peek(t));
573
+ return n !== null && n.document.kind === "markdown" ? { htmlContent: n.document.htmlContent, headings: n.document.headings } : null;
574
+ }, Un = (e, t, n, r, s) => {
575
+ if (n === void 0) return null;
576
+ let o;
577
+ try {
578
+ o = _n(e, t);
579
+ } catch (l) {
580
+ return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview", l), null;
581
+ }
582
+ return { converter: n, sanitize: o, marksOf: qn, seed: We(r, s)?.htmlContent ?? null };
583
+ }, Gn = (e) => {
584
+ const t = [];
585
+ let n = null;
586
+ for (const r of e.querySelectorAll(zn)) {
587
+ const s = Kt(r.getAttribute(He));
588
+ if (s === null || r.getClientRects().length === 0) continue;
589
+ n ??= e.scrollTop - re(e, r);
590
+ const { top: o, bottom: l } = r.getBoundingClientRect();
591
+ t.push({ first: s.first, last: s.last, top: n + o, bottom: n + l });
592
+ }
593
+ return t;
594
+ }, Wn = ({ path: e, readDraft: t, viewer: n, tables: r, concealed: s, onEditAt: o, onLayout: l, handleRef: i }) => {
595
+ const { config: f, data: d, documents: p, draftConverter: y, labels: c } = le(), [w, u] = ne(() => ({ parsed: We(p, e), source: null, failure: null, busy: !0, tier: y === void 0 ? "server" : "instant" })), m = D(null), g = D(null), x = D(w);
596
+ B(() => {
597
+ x.current = w;
598
+ });
599
+ const h = ve(() => t());
600
+ Pe(() => {
601
+ const a = Un(f.iframeHosts, f.dataPath, y, p, e), k = h(), L = Rn({ path: e, instant: a, preview: d.preview, initial: x.current, onView: (v) => Je(() => u(v)) });
602
+ return g.current = L, L.update(k), () => {
603
+ L.dispose(), g.current = null;
604
+ };
605
+ }, [f, d, p, y, e]);
606
+ const T = ve(() => l());
607
+ B(() => {
608
+ w.parsed !== null && T();
609
+ }, [w.parsed]);
610
+ const I = w.parsed !== null;
611
+ B(() => {
612
+ const a = I ? m.current?.querySelector(Z) : null;
613
+ if (!(a instanceof HTMLElement)) return;
614
+ a.tabIndex = 0;
615
+ const k = new ResizeObserver(() => T());
616
+ k.observe(a);
617
+ const L = a.querySelector(Hn);
618
+ return L !== null && k.observe(L), () => k.disconnect();
619
+ }, [I]);
620
+ const A = D(null);
621
+ Ye(
622
+ i,
623
+ () => ({
624
+ draft: (a) => {
625
+ g.current?.update(a);
626
+ },
627
+ scrollPort: () => {
628
+ const a = m.current?.querySelector(Z);
629
+ return a instanceof HTMLElement ? (A.current?.scroller !== a && (A.current = { scroller: a, port: Ge(a) }), A.current.port) : null;
630
+ },
631
+ blocks: () => {
632
+ const a = m.current?.querySelector(Z);
633
+ return a instanceof HTMLElement ? Gn(a) : [];
634
+ },
635
+ focus: () => {
636
+ const a = m.current?.querySelector(Z);
637
+ a instanceof HTMLElement && a.focus({ preventScroll: !0 });
638
+ },
639
+ anchor: (a) => {
640
+ const k = m.current, L = k?.querySelector(Z);
641
+ return k === null || !(L instanceof HTMLElement) ? null : nt(k, a(L));
642
+ },
643
+ place: ({ line: a, clientTop: k }, L) => {
644
+ const v = m.current, S = v === null ? null : et(v, a);
645
+ S !== null && (L(S).scrollTop += tt(S, a) - k);
646
+ }
647
+ }),
648
+ []
649
+ );
650
+ const _ = (a) => {
651
+ const k = m.current, { target: L } = a;
652
+ if (o === void 0 || k === null || !(L instanceof Element) || !ot(L)) return;
653
+ const v = it(L, k, k.ownerDocument.getSelection());
654
+ v !== null && o(v);
655
+ }, C = w.source === null ? null : w.source.revision, F = J(
656
+ () => C === null ? void 0 : {
657
+ write: (a) => r.write(C, a),
658
+ read: (a) => r.read(C, a),
659
+ undo: r.undo,
660
+ redo: r.redo,
661
+ subscribe: r.subscribe
662
+ },
663
+ [r, C]
664
+ ), P = J(() => ({ ...n.labels, spreadsheetReadOnly: c.previewTablePending }), [n.labels, c.previewTablePending]), H = J(
665
+ () => ({ ...n, labels: F === void 0 ? P : n.labels, showToc: !1, showStyle: !1, showAlign: !1, renderScrollBar: void 0, spreadsheetEditor: F }),
666
+ [n, P, F]
667
+ ), V = J(
668
+ () => w.parsed === null ? null : /* @__PURE__ */ M("div", { className: "aqmx-document-viewer", children: /* @__PURE__ */ M($t, { ...H, parseResult: w.parsed, content: null }) }),
669
+ [H, w.parsed]
670
+ );
671
+ return /* @__PURE__ */ te(
672
+ "section",
673
+ {
674
+ ref: m,
675
+ className: "aqmx-edit-preview",
676
+ "aria-label": c.previewRegion,
677
+ "aria-busy": w.busy,
678
+ inert: s !== null,
679
+ hidden: s === "removed",
680
+ "data-aqmx-preview-tier": w.tier,
681
+ "data-testid": "markdown-explorer-edit-preview",
682
+ onDoubleClick: o === void 0 ? void 0 : _,
683
+ children: [
684
+ w.failure === null ? null : /* @__PURE__ */ M("p", { className: "aqmx-callout aqmx-document-notice", "data-aqmx-tone": "warning", "data-testid": "markdown-explorer-edit-preview-failure", children: c.previewFailed(De(c, w.failure.reason)) }),
685
+ V ?? (w.failure === null ? /* @__PURE__ */ M("div", { className: "aqmx-skeleton", "aria-hidden": "true", "data-testid": "markdown-explorer-edit-preview-skeleton", children: Fn.map((a) => /* @__PURE__ */ M("span", {}, a)) }) : null),
686
+ w.busy ? /* @__PURE__ */ M("p", { className: "aqmx-sr-only", children: c.previewUpdating }) : null
687
+ ]
688
+ }
689
+ );
690
+ }, Me = "data-aqmx-edit-split", de = "--aqmx-edit-share", qe = "--aqmx-edit-gutter", $n = "data-aqmx-edit-split-probe", Kn = "aqmx-edit-split", jn = "aqmx-edit-editor", Xn = "aqmx-edit-preview", Re = { value: sn, unit: "percentage" }, _e = { value: on, unit: "percentage" }, Ne = (e) => {
691
+ if (e.length !== 2) return null;
692
+ const [t = 0, n = 0] = e, r = t + n;
693
+ return r > 0 ? t / r * 100 : null;
694
+ }, se = (e) => {
695
+ const t = e.current?.parentElement;
696
+ if (t == null) throw new Error("[markdown-explorer] the edit split is not mounted in its surface");
697
+ return t;
698
+ }, Yn = (e, t, n) => {
699
+ const [r, s] = ne(null);
700
+ return B(() => {
701
+ const o = e.current, l = t.current;
702
+ if (o === null || l === null) throw new Error("[markdown-explorer] the edit split is not mounted");
703
+ const i = { frame: o.getBoundingClientRect().width, measure: l.getBoundingClientRect().width }, f = () => {
704
+ i.frame > 0 && i.measure > 0 && s(ln(i.frame, i.measure, n));
705
+ };
706
+ f();
707
+ const d = new ResizeObserver((p) => {
708
+ for (const y of p) {
709
+ const [c] = y.borderBoxSize;
710
+ c !== void 0 && (y.target === o && (i.frame = c.inlineSize), y.target === l && (i.measure = c.inlineSize));
711
+ }
712
+ f();
713
+ });
714
+ return d.observe(o), d.observe(l), () => d.disconnect();
715
+ }, [e, t, n]), r;
716
+ }, Jn = ({ editorId: e }) => {
717
+ const { edits: t, labels: n } = le(), r = D(null), s = D(null), o = cn() ? nn : rn, l = Yn(r, s, o), [i] = ne(() => t.editorShare());
718
+ B(() => {
719
+ const p = se(r);
720
+ return p.style.setProperty(qe, `${String(o)}px`), () => {
721
+ p.style.removeProperty(qe);
722
+ };
723
+ }, [o]), B(() => {
724
+ const p = se(r);
725
+ return p.style.setProperty(de, `${String(i)}%`), () => {
726
+ p.style.removeProperty(de);
727
+ };
728
+ }, [i]), B(() => {
729
+ if (l === null) return;
730
+ const p = se(r);
731
+ return p.setAttribute(Me, l), () => p.removeAttribute(Me);
732
+ }, [l]);
733
+ const f = an(
734
+ j(
735
+ (p) => {
736
+ const y = Ne(p);
737
+ y !== null && t.setEditorShare(y);
738
+ },
739
+ [t]
740
+ )
741
+ ), d = j(
742
+ (p, y) => {
743
+ const c = Ne(p);
744
+ c !== null && se(r).style.setProperty(de, `${String(c)}%`), f.layoutChanged(p, y);
745
+ },
746
+ [f]
747
+ );
748
+ return /* @__PURE__ */ te("div", { ref: r, className: "aqmx-edit-split", "data-testid": "markdown-explorer-edit-split", children: [
749
+ /* @__PURE__ */ M("span", { ref: s, className: "aqmx-edit-split-probe", "aria-hidden": "true", [$n]: "" }),
750
+ l === null ? null : /* @__PURE__ */ te(en, { id: Kn, direction: l === "beside" ? "horizontal" : "vertical", onLayout: d, className: "aqmx-edit-split-group", children: [
751
+ /* @__PURE__ */ M(xe, { id: jn, defaultSize: { value: i, unit: "percentage" }, minSize: Re, maxSize: _e, contentOverflow: "hidden" }),
752
+ /* @__PURE__ */ M(
753
+ tn,
754
+ {
755
+ thickness: o,
756
+ indicator: { visible: !0, thickness: ie.gripThickness, length: ie.gripLength, barThickness: ie.barThickness, barLength: ie.barLength },
757
+ title: n.editViewSplitResize,
758
+ "aria-label": n.editViewSplitResize,
759
+ "aria-controls": e,
760
+ onDragging: f.draggingChanged,
761
+ className: "aqmx-split-handle aqmx-edit-split-handle"
762
+ }
763
+ ),
764
+ /* @__PURE__ */ M(xe, { id: Xn, defaultSize: { value: 100 - i, unit: "percentage" }, minSize: Re, maxSize: _e, contentOverflow: "hidden" })
765
+ ] })
766
+ ] });
767
+ }, Qn = 512, Zn = () => {
768
+ const e = [];
769
+ let t = 0, n = null;
770
+ const r = (s) => {
771
+ if (n === null || !Number.isInteger(s) || s < t) return null;
772
+ if (s === t + e.length) return n;
773
+ const o = e[s - t];
774
+ return o === void 0 ? null : o.before;
775
+ };
776
+ return {
777
+ revision: () => t + e.length,
778
+ mount: (s) => {
779
+ if (n !== null && (n === s || n.eq(s))) {
780
+ n = s;
781
+ return;
782
+ }
783
+ const o = t + e.length;
784
+ e.length = 0, t = n === null ? o : o + 1, n = s;
785
+ },
786
+ record: (s, o) => {
787
+ if (n === null) throw new Error("[markdown-explorer] a change of the editor's text was recorded before an editor mounted");
788
+ e.push({ before: n, changes: s }), n = o, e.length > Qn && (e.shift(), t += 1);
789
+ },
790
+ lineOf: (s, o) => {
791
+ const l = r(s);
792
+ if (l === null || n === null || !Number.isInteger(o) || o < 1 || o > l.lines) return null;
793
+ let i = l.line(o).from;
794
+ for (const f of e.slice(s - t)) {
795
+ const d = f.changes.mapPos(i, 1, Bt.TrackAfter);
796
+ if (d === null) return null;
797
+ i = d;
798
+ }
799
+ return n.lineAt(i).number;
800
+ }
801
+ };
802
+ }, er = 144, tr = "[data-aqmd-spreadsheet-fullscreen]", nr = Object.freeze(["e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8"]), rr = (e) => {
803
+ if (typeof e != "object" || e === null) return !1;
804
+ const { generation: t, topLine: n } = e;
805
+ return "state" in e && typeof t == "number" && typeof n == "number";
806
+ }, or = (e) => {
807
+ e.stopPropagation();
808
+ }, kr = (e) => {
809
+ const { path: t, name: n, session: r } = e, { edits: s, labels: o, announcer: l } = le(), { phase: i } = r, f = j(() => s.retry(t), [s, t]);
810
+ switch (Pe(() => {
811
+ i.kind === "failed" && l.announce(o.documentFailed(n, De(o, i.failure.reason)));
812
+ }, [i, l, o, n]), i.kind) {
813
+ case "opening":
814
+ return /* @__PURE__ */ te(Xe, { children: [
815
+ /* @__PURE__ */ M("div", { className: "aqmx-skeleton", "aria-hidden": "true", "data-testid": "markdown-explorer-edit-skeleton", children: nr.map((d) => /* @__PURE__ */ M("span", {}, d)) }),
816
+ /* @__PURE__ */ M("p", { className: "aqmx-sr-only", children: o.editLoading })
817
+ ] });
818
+ case "grant":
819
+ return /* @__PURE__ */ M("div", { className: "aqmx-edit-message", children: /* @__PURE__ */ M(lt, { href: i.href, onRetry: f, testId: "markdown-explorer-edit-grant" }) });
820
+ case "failed":
821
+ return /* @__PURE__ */ M("div", { className: "aqmx-edit-message", children: /* @__PURE__ */ M(st, { failure: i.failure, alert: !1, onRetry: f, testId: "markdown-explorer-edit-failure" }) });
822
+ case "editing":
823
+ return /* @__PURE__ */ M(ir, { ...e });
824
+ }
825
+ }, ir = ({ path: e, name: t, session: n, layout: r, viewer: s, region: o, paneScroll: l }) => {
826
+ const { edits: i, labels: f } = le(), d = D(null), p = Qe(), y = D(null), [c] = ne(() => /* @__PURE__ */ new Set()), [w] = ne(Zn), u = D(null), m = D(null), g = r === "fill", x = ct(), h = at(n, x, g), T = h !== "editor" || n.previewPrepared, I = T && g, A = D({ layout: r, region: o, paneScroll: l });
827
+ B(() => {
828
+ A.current = { layout: r, region: o, paneScroll: l };
829
+ });
830
+ const _ = D(n.generation);
831
+ B(() => {
832
+ _.current = n.generation;
833
+ });
834
+ const C = D({ view: h, previewMounted: T });
835
+ B(() => {
836
+ C.current = { view: h, previewMounted: T };
837
+ });
838
+ const F = D(null), P = D(null), H = D(!1), V = J(() => ({ editor: f.editorLabel(t), useOurs: f.conflictUseOurs, useTheirs: f.conflictUseTheirs, keepBoth: f.conflictKeepBoth }), [f, t]), a = j((b) => {
839
+ const { region: E, paneScroll: q } = A.current, z = E();
840
+ return z === null ? b : q.scrollerOf(z, b);
841
+ }, []);
842
+ B(() => {
843
+ const b = d.current, E = i.draft(e);
844
+ if (b === null || E === null) return;
845
+ const q = i.editorState.get(e), z = rr(q) && q.generation === _.current ? q : null;
846
+ let W = null, X = null;
847
+ const ae = () => {
848
+ W !== null && clearTimeout(W), W = null, X !== null && i.setDraft(e, X.text());
849
+ }, U = Sn({
850
+ parent: b,
851
+ scroll: {
852
+ scrollerOf: (R) => {
853
+ const { layout: Y, region: Ke, paneScroll: je } = A.current, ge = Ke();
854
+ return Y === "fill" || ge === null ? R : je.scrollerOf(ge, R);
855
+ },
856
+ reveal: (R) => A.current.paneScroll.reveal(R)
857
+ },
858
+ text: E,
859
+ saved: z === null ? void 0 : z.state,
860
+ labels: V,
861
+ revisions: w,
862
+ onGeometry: (R) => m.current?.editorChanged(R),
863
+ onChange: (R) => {
864
+ if (W ??= setTimeout(ae, er), !R)
865
+ for (const Y of [...c]) Y();
866
+ C.current.previewMounted && X !== null && u.current?.draft({ text: X.text(), revision: w.revision() });
867
+ },
868
+ onSave: () => {
869
+ i.save(e);
870
+ }
871
+ });
872
+ X = U, y.current = U;
873
+ const pe = () => {
874
+ const R = U.topLine();
875
+ return { line: R.line, clientTop: R.clientTop };
876
+ }, he = () => u.current?.anchor(a) ?? null, $e = i.bindEditor(e, {
877
+ flush: ae,
878
+ adopt: (R) => U.replaceText(R),
879
+ returnPoint: () => {
880
+ const R = C.current.view === "preview" && A.current.layout === "content" ? he() : null;
881
+ return R === null ? pe() : { line: R.lines.first, clientTop: R.clientTop };
882
+ },
883
+ nextConflict: () => C.current.view !== "preview" ? U.nextConflict() : U.conflicts().length === 0 ? !1 : (H.current = !0, i.setView(e, "editor"), !0),
884
+ beforeView: (R) => {
885
+ if (A.current.layout === "fill") return;
886
+ if (R === "preview") {
887
+ F.current = { to: "preview", point: pe() };
888
+ return;
889
+ }
890
+ const Y = he();
891
+ F.current = Y === null ? null : { to: "editor", anchor: Y };
892
+ }
893
+ });
894
+ return z !== null && U.showLine(z.topLine), () => {
895
+ ae(), i.editorState.set(e, { state: U.save(), generation: _.current, topLine: U.topLine().line }), $e(), U.destroy(), X = null, y.current = null;
896
+ };
897
+ }, [i, e, V, a, c, w]);
898
+ const { request: k } = n;
899
+ B(() => {
900
+ const b = y.current, E = i.draft(e);
901
+ b === null || E === null || k === null || (k.anchor !== null && b.reveal(we(E, k.anchor), k.anchor.clientTop), b.focus(), i.consumeRequest(e));
902
+ }, [i, e, k, V]), B(() => {
903
+ h !== "editor" && !n.previewPrepared && i.preparePreview(e);
904
+ }, [i, e, h, n.previewPrepared]), B(() => {
905
+ const b = F.current, E = P.current, q = H.current;
906
+ F.current = null, P.current = null, H.current = !1;
907
+ const z = y.current;
908
+ if (b?.to === "preview") u.current?.place(b.point, a);
909
+ else if (b?.to === "editor" && z !== null) {
910
+ const W = i.draft(e);
911
+ W !== null && z.reveal(we(W, b.anchor), b.anchor.clientTop);
912
+ }
913
+ q ? z?.nextConflict() : E === "editor" ? z?.focus() : E === "preview" && u.current?.focus();
914
+ }, [i, e, h, a]);
915
+ const L = J(() => {
916
+ const b = () => {
917
+ const E = y.current;
918
+ if (E === null) throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");
919
+ return E;
920
+ };
921
+ return {
922
+ write: (E, { fenceLine: q, expected: z, text: W }) => b().replaceBody(q, z, W, E),
923
+ read: (E, q) => b().readBody(q, E),
924
+ undo: () => b().undo(),
925
+ redo: () => b().redo(),
926
+ subscribe: (E) => (c.add(E), () => {
927
+ c.delete(E);
928
+ })
929
+ };
930
+ }, [c]), v = j(() => {
931
+ const b = y.current;
932
+ if (b === null) throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");
933
+ return { text: b.text(), revision: w.revision() };
934
+ }, [w]);
935
+ B(() => {
936
+ const b = y.current;
937
+ if (!I || b === null) return;
938
+ const E = Vn({
939
+ editor: Ge(b.scrollElement),
940
+ preview: () => u.current?.scrollPort() ?? null,
941
+ previewBlocks: () => u.current?.blocks() ?? [],
942
+ editorSpans: (q) => b.lineSpans(q),
943
+ requestFrame: (q) => requestAnimationFrame(q),
944
+ cancelFrame: (q) => cancelAnimationFrame(q),
945
+ now: () => performance.now()
946
+ });
947
+ return E.showAlone(be(C.current.view)), m.current = E, () => {
948
+ E.dispose(), m.current = null;
949
+ };
950
+ }, [I, i, e, V]), B(() => {
951
+ m.current?.showAlone(be(h));
952
+ }, [h]);
953
+ const S = j(() => m.current?.previewChanged(), []), O = j((b) => i.start(e, b), [i, e]);
954
+ return (
955
+ /* @__PURE__ */ te("div", { className: "aqmx-edit", "data-aqmx-edit-layout": r, "data-aqmx-edit-view": h, "data-testid": "markdown-explorer-edit", onKeyDown: (b) => {
956
+ if (b.target instanceof Element && b.target.closest(tr) !== null) return;
957
+ if (b.key === "Escape") {
958
+ Ee(b);
959
+ return;
960
+ }
961
+ if (!dt(b.nativeEvent, ft(navigator.platform))) return;
962
+ Ee(b);
963
+ const E = pt(h);
964
+ P.current = E, mt(i, e, E, g);
965
+ }, onDoubleClick: or, children: [
966
+ /* @__PURE__ */ M("div", { ref: d, id: p, className: "aqmx-edit-editor", "data-testid": "markdown-explorer-editor", inert: h === "preview", hidden: h === "preview" && !g, ...ut }),
967
+ h === "split" ? /* @__PURE__ */ M(Jn, { editorId: p }) : null,
968
+ T ? /* @__PURE__ */ M(Wn, { path: e, readDraft: v, viewer: s, tables: L, concealed: h !== "editor" ? null : g ? "overlay" : "removed", onEditAt: h === "preview" ? O : void 0, onLayout: S, handleRef: u }) : null
969
+ ] })
970
+ );
971
+ };
972
+ export {
973
+ er as DRAFT_WRITE_INTERVAL_MS,
974
+ kr as default
975
+ };