@aiquants/markdown-explorer 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.1 (2026-10-15)
4
+
5
+ ### Fixed
6
+
7
+ - **The editor and its preview scroll together** (patch): scrolling the editor no longer makes the preview move back and forth at every line, and the ends meet. The preview used to keep the editor's top line at the same pixel offset, so it moved one to one with the editor inside a line and jumped by the difference of the two line heights at each new line (back while scrolling down: 12 steps back over 1,600 px of the demo's long notes, up to 64 px; 35 over a draft with images), and it was not tied to either end.
8
+ The two panes now scroll together, both ways, through a map of the converter's blocks: the top of each block's first source line goes with the top of its box and the bottom of its last line with the bottom of its box, positions in between are linear, both tops and both bottoms are pinned together, and blocks whose place differs between the source and the rendering (footnotes) are left out. Either pane moves continuously and on whenever the other does, crossing a block taller on its side (an image, a heading) faster; the same measurements now find no step back, and both ends meet.
9
+ The pane the reader works in (the wheel, a pointer press, a key, the focus moving in, typing) leads at once, so a single jump such as Ctrl+End is never lost, and for 610 ms after that input the other pane's scrolls (the sync's own moves, the editor's corrections while it draws new lines, the browser clamping a preview that shrank, the tail of an earlier scroll animation) never take the lead; a scroll without input, such as a find in page, takes it once the input ended.
10
+ The map is measured again when the preview renders anew or changes size (an image or a diagram finishing) and when the editor's text or line heights change, and the preview's scroller no longer anchors its scroll to its content (`overflow-anchor: none`).
11
+
3
12
  ## 0.12.0 (2026-10-15)
4
13
 
5
14
  ### Added
package/README.md CHANGED
@@ -411,7 +411,7 @@ editMaxBytes: 2 * 1024 * 1024, // the largest source and draft, the default
411
411
  - **Limits.** A draft (`save`, `preview`) is read before any port is called: `text/markdown` with no charset or `utf-8`, at most `editMaxBytes` bytes (`too-large`, 413), valid UTF-8 without NUL (`invalid`, 400). A source, a conflict's text or a revision longer than `editMaxBytes` breaks the contract (logged, `failed`); refuse such a document in `source` with `ExplorerError("too-large")` instead.
412
412
  - **Grants.** Answer `{ kind: "grant", href }` from `source` or `save` when the reader must first allow writing (an OAuth consent for a wider scope, for example); `href` is a root-relative address of your own. The explorer shows a notice whose action calls `<MarkdownExplorer onEditGrant>` with it, or, without that prop, links to it in a new tab beside Try again.
413
413
  - **Operations.** The data route answers `GET <dataPath>/edit?path=`, `POST <dataPath>/save?path=&base=<version>`, `POST <dataPath>/preview?path=`, `GET <dataPath>/revisions?path=` and `GET <dataPath>/revision?path=&revision=<id>`. `save` and `preview` carry `X-Markdown-Explorer: edit` and must pass the shared cross-origin check, like a refresh. Without `edit`, these operations answer as unknown ones (404), and `editMaxBytes` alone throws.
414
- - **Source lines.** The editor opens at the place the reader was reading, or at the word they double-clicked, and the preview follows the editor, through the source lines your converter writes on every block: `data-source-lines="<first>-<last>"` (1-based, both inclusive), `@aiquants/markdown`'s `includeSourceLines`. Without them the editor opens at the start of the document; the sanitizer keeps the attribute only in that form.
414
+ - **Source lines.** The editor opens at the place the reader was reading, or at the word they double-clicked, and the editor and the preview scroll together block by block, through the source lines your converter writes on every block: `data-source-lines="<first>-<last>"` (1-based, both inclusive), `@aiquants/markdown`'s `includeSourceLines`. Without them the editor opens at the start of the document and the two panes scroll together by the ratio of their lengths alone; the sanitizer keeps the attribute only in that form.
415
415
 
416
416
  ### Revealing the open document
417
417
 
@@ -655,7 +655,7 @@ While a document is edited, the bar shows the draft's status on one line and the
655
655
  The editor (CodeMirror 6, loaded when the reader first points at or focuses Edit) fills the pane where it can and grows with its text in a panel that is not maximized; Escape inside it is consumed, so a maximized panel stays maximized, and Tab leaves it.
656
656
  A save writes the draft back with the line endings of the file it opened (`\r\n` when the file held one, `\n` otherwise), so editing never rewrites the lines the reader left alone; a file that already mixed endings is saved with `\r\n` throughout.
657
657
  A save that meets changes saved elsewhere merges them line by line: changes on different lines are saved at once; lines both sides changed differently are written between git-style markers with buttons above each conflict (keep my lines, the saved lines, or both), and Next conflict moves the focus to those buttons. A draft with markers left is not saved.
658
- The preview renders the draft as the document would be, beside the editor (below it on a narrow pane), and keeps the block of the editor's top line level with it: on every keystroke with a `draftConverter`, else once the reader pauses typing (SERVER_PREVIEW_DELAY_MS, 610 ms). Until its first rendering lands it shows the document's own rendering (the skeleton when the document is not loaded), and afterwards the last rendering stays until the next one lands, so it never flashes empty. Whether it shows is the reader's choice, kept in browser storage under `storageNamespace` (default off). History lists the revisions, shows the one picked and puts it into the draft, to be saved like any draft.
658
+ The preview renders the draft as the document would be, beside the editor (below it on a narrow pane): on every keystroke with a `draftConverter`, else once the reader pauses typing (SERVER_PREVIEW_DELAY_MS, 610 ms). The two scroll together, both ways: the pane the reader works in (the wheel, a press, a key, typing) leads, and the other keeps the same blocks at the top of its view, moving on continuously — a block taller on one side, such as an image or a heading, is crossed faster there, never with a jump or a step back — and both reach their tops and their bottoms together. Until its first rendering lands it shows the document's own rendering (the skeleton when the document is not loaded), and afterwards the last rendering stays until the next one lands, so it never flashes empty. Whether it shows is the reader's choice, kept in browser storage under `storageNamespace` (default off). History lists the revisions, shows the one picked and puts it into the draft, to be saved like any draft.
659
659
  Drafts last while the explorer is mounted, across view switches and remounted panels. A navigation that would take a document with an unsaved draft off the page asks first (the explorer holds the router's one blocker, so render one explorer per router), and leaving the page asks through `beforeunload` while a document is edited.
660
660
 
661
661
  #### Rendering drafts in the browser
@@ -0,0 +1,633 @@
1
+ import { jsx as C, jsxs as J, Fragment as ge } from "react/jsx-runtime";
2
+ import { useState as we, useRef as D, useLayoutEffect as B, useEffectEvent as te, useEffect as U, useImperativeHandle as be, useMemo as X, startTransition as Ee, useCallback as $ } from "react";
3
+ import { v as G, f as Q, g as xe, u as Z, h as ce, l as Se, F as ye, E as ke, i as Te, p as Me, A as Le, j as Ce } from "./index-CjCr8czx.js";
4
+ import { history as qe, historyKeymap as Oe, defaultKeymap as Ae, historyField as Ie } from "@codemirror/commands";
5
+ import { markdown as Ne, markdownLanguage as Re } from "@codemirror/lang-markdown";
6
+ import { syntaxHighlighting as De, HighlightStyle as _e } from "@codemirror/language";
7
+ import { highlightSelectionMatches as He, searchKeymap as Pe } from "@codemirror/search";
8
+ import { EditorState as ue, EditorSelection as Y, StateField as Ve, RangeSetBuilder as Be } from "@codemirror/state";
9
+ import { EditorView as V, lineNumbers as Fe, highlightActiveLineGutter as ze, drawSelection as Ge, highlightActiveLine as Ke, keymap as We, Decoration as W, WidgetType as je } from "@codemirror/view";
10
+ import { tags as L } from "@lezer/highlight";
11
+ import { MarkdownViewer as Ue } from "@aiquants/markdown";
12
+ import { SOURCE_LINES_ATTRIBUTE as de, parseSourceLines as Xe } from "@aiquants/markdown/source-lines";
13
+ import { d as $e, f as K, E as Ye } from "./dataRoute-Pm_0ue_4.js";
14
+ import { H as Je, c as Qe, M as Ze } from "./sanitizePolicy-djLC3fRN.js";
15
+ import et from "isomorphic-dompurify";
16
+ const fe = { history: Ie }, tt = _e.define([
17
+ { tag: [L.heading1, L.heading2, L.heading3, L.heading4, L.heading5, L.heading6, L.heading], color: "var(--aqmx-syntax-heading)", fontWeight: "700" },
18
+ { tag: L.strong, fontWeight: "700" },
19
+ { tag: L.emphasis, fontStyle: "italic" },
20
+ { tag: L.strikethrough, textDecoration: "line-through" },
21
+ { tag: L.link, color: "var(--aqmx-syntax-link)", textDecoration: "underline" },
22
+ { tag: L.url, color: "var(--aqmx-syntax-url)" },
23
+ { tag: L.monospace, color: "var(--aqmx-syntax-code)" },
24
+ { tag: L.quote, color: "var(--aqmx-syntax-quote)" },
25
+ { tag: [L.processingInstruction, L.contentSeparator, L.labelName, L.meta], color: "var(--aqmx-syntax-mark)" }
26
+ ]), rt = V.theme({
27
+ "&": { height: "100%", color: "var(--aqmx-text)", backgroundColor: "var(--aqmx-surface)", fontSize: "var(--aqmx-font-size-title)" },
28
+ "&.cm-focused": { outline: "none" },
29
+ ".cm-scroller": { fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace', lineHeight: "var(--aqmx-line-height-prose)" },
30
+ ".cm-content": { caretColor: "var(--aqmx-text)", paddingBlock: "var(--aqmx-space-6)" },
31
+ ".cm-line": { paddingInline: "var(--aqmx-space-6)" },
32
+ "&.cm-focused .cm-cursor": { borderLeftColor: "var(--aqmx-text)" },
33
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: "var(--aqmx-editor-selection)" },
34
+ ".cm-activeLine": { backgroundColor: "var(--aqmx-editor-active-line)" },
35
+ ".cm-gutters": { backgroundColor: "var(--aqmx-surface-raised)", color: "var(--aqmx-editor-gutter)", borderInlineEnd: "var(--aqmx-space-1) solid var(--aqmx-border)" },
36
+ ".cm-activeLineGutter": { backgroundColor: "var(--aqmx-editor-active-line)" },
37
+ ".cm-searchMatch": { outline: "var(--aqmx-space-1) solid var(--aqmx-border-strong)" },
38
+ ".cm-panels": { backgroundColor: "var(--aqmx-surface-raised)", color: "var(--aqmx-text)" }
39
+ }), me = "data-aqmx-conflict-actions", nt = W.line({ attributes: { "data-aqmx-conflict-line": "marker" } }), ot = W.line({ attributes: { "data-aqmx-conflict-line": "ours" } }), st = W.line({ attributes: { "data-aqmx-conflict-line": "theirs" } });
40
+ class it extends je {
41
+ constructor(t, r) {
42
+ super(), this.index = t, this.labels = r;
43
+ }
44
+ index;
45
+ labels;
46
+ eq(t) {
47
+ return t.index === this.index && t.labels === this.labels;
48
+ }
49
+ toDOM(t) {
50
+ const r = document.createElement("div");
51
+ r.setAttribute(me, String(this.index));
52
+ for (const [s, l] of [
53
+ ["ours", this.labels.useOurs],
54
+ ["theirs", this.labels.useTheirs],
55
+ ["both", this.labels.keepBoth]
56
+ ]) {
57
+ const i = document.createElement("button");
58
+ i.type = "button", i.textContent = l, i.setAttribute("data-aqmx-conflict-choice", s), i.addEventListener("mousedown", (a) => a.preventDefault()), i.addEventListener("click", () => {
59
+ const a = z(t.state.doc)[this.index];
60
+ a !== void 0 && (pe(t, a, s), t.focus());
61
+ }), r.append(i);
62
+ }
63
+ return r;
64
+ }
65
+ ignoreEvent() {
66
+ return !0;
67
+ }
68
+ }
69
+ const z = (e) => xe(e.iterLines()), re = (e, t) => {
70
+ const r = new Be();
71
+ return z(e).forEach((s, l) => {
72
+ const i = e.line(s.start);
73
+ r.add(i.from, i.from, W.widget({ widget: new it(l, t), block: !0, side: -1 }));
74
+ for (let a = s.start; a <= s.end; a += 1) {
75
+ const o = e.line(a).from, c = a === s.start || a === s.separator || a === s.end ? nt : a < s.separator ? ot : st;
76
+ r.add(o, o, c);
77
+ }
78
+ }), r.finish();
79
+ }, lt = (e) => Ve.define({
80
+ create: (t) => re(t.doc, e),
81
+ update: (t, r) => r.docChanged ? re(r.state.doc, e) : t,
82
+ provide: (t) => V.decorations.from(t)
83
+ }), pe = (e, t, r) => {
84
+ const { doc: s } = e.state, l = (u, d) => {
85
+ const f = [];
86
+ for (let m = u; m <= d; m += 1) f.push(s.line(m).text);
87
+ return f;
88
+ }, i = l(t.start + 1, t.separator - 1), a = l(t.separator + 1, t.end - 1), o = r === "ours" ? i : r === "theirs" ? a : [...i, ...a];
89
+ let c = s.line(t.start).from, p = s.line(t.end).to;
90
+ o.length === 0 && (t.end < s.lines ? p += 1 : t.start > 1 && (c -= 1));
91
+ const n = o.join(`
92
+ `);
93
+ e.dispatch({ changes: { from: c, to: p, insert: n }, selection: Y.cursor(c), scrollIntoView: !0, userEvent: "input.resolve" });
94
+ }, at = ({ parent: e, scroll: t, text: r, saved: s, labels: l, onChange: i, onGeometry: a, onSave: o }) => {
95
+ const c = [
96
+ V.scrollHandler.of((u, d, f) => (ct(u, d.head, f, t), !0)),
97
+ Fe(),
98
+ ze(),
99
+ qe(),
100
+ Ge(),
101
+ Ke(),
102
+ He(),
103
+ V.lineWrapping,
104
+ Ne({ base: Re }),
105
+ De(tt),
106
+ lt(l),
107
+ We.of([
108
+ {
109
+ key: "Mod-s",
110
+ preventDefault: !0,
111
+ run: () => (o(), !0)
112
+ },
113
+ ...Pe,
114
+ ...Oe,
115
+ ...Ae
116
+ ]),
117
+ V.contentAttributes.of({ "aria-label": l.editor, "aria-multiline": "true" }),
118
+ V.updateListener.of((u) => {
119
+ u.docChanged && i(), (u.docChanged || u.heightChanged || u.geometryChanged) && a(u.docChanged);
120
+ }),
121
+ rt
122
+ ], p = ft(s, c) ?? ue.create({ doc: r, extensions: c }), n = new V({ state: p, parent: e });
123
+ return {
124
+ text: () => n.state.doc.toString(),
125
+ replaceText: (u) => {
126
+ const d = n.state.doc.toString();
127
+ if (d === u) return;
128
+ let f = 0;
129
+ const m = Math.min(d.length, u.length);
130
+ for (; f < m && d.charCodeAt(f) === u.charCodeAt(f); ) f += 1;
131
+ let w = 0;
132
+ for (; w < m - f && d.charCodeAt(d.length - 1 - w) === u.charCodeAt(u.length - 1 - w); ) w += 1;
133
+ n.dispatch({ changes: { from: f, to: d.length - w, insert: u.slice(f, u.length - w) }, userEvent: "input.replace" });
134
+ },
135
+ reveal: ({ line: u, column: d }, f) => {
136
+ const { doc: m } = n.state, w = m.line(Math.min(Math.max(u, 1), m.lines)), b = Math.min(w.from + d, w.to);
137
+ n.dispatch({ selection: Y.cursor(b), effects: ne(n, b, f, t) });
138
+ },
139
+ showLine: (u) => {
140
+ const { doc: d } = n.state, f = d.line(Math.min(Math.max(u, 1), d.lines)).from;
141
+ n.dispatch({ effects: ne(n, f, null, t) });
142
+ },
143
+ topLine: () => {
144
+ const u = t.scrollerOf(n.scrollDOM), d = G(u, n.contentDOM), f = Q(u) + u.clientHeight, { documentTop: m } = n, { doc: w } = n.state;
145
+ let b = n.lineBlockAtHeight(Math.max(d - m, 0));
146
+ for (; w.lineAt(b.from).text.trim() === "" && b.to < w.length; ) {
147
+ const q = n.lineBlockAt(b.to + 1);
148
+ if (m + q.top >= f) break;
149
+ b = q;
150
+ }
151
+ const S = n.coordsAtPos(b.from), k = S === null ? m + b.top : S.top;
152
+ return { line: n.state.doc.lineAt(b.from).number, clientTop: k, offset: k - d };
153
+ },
154
+ lineSpans: (u) => {
155
+ const d = n.scrollDOM, f = d.scrollTop + n.documentTop - G(d, n.contentDOM), { doc: m } = n.state, w = (b) => m.line(Math.min(Math.max(b, 1), m.lines)).from;
156
+ return u.map(({ first: b, last: S }) => ({ top: f + n.lineBlockAt(w(b)).top, bottom: f + n.lineBlockAt(w(S)).bottom }));
157
+ },
158
+ scrollElement: n.scrollDOM,
159
+ focus: () => n.focus(),
160
+ conflicts: () => z(n.state.doc),
161
+ resolveAtCursor: (u) => {
162
+ const d = z(n.state.doc), f = n.state.doc.lineAt(n.state.selection.main.head).number, m = d.find((w) => w.end >= f);
163
+ return m === void 0 ? !1 : (pe(n, m, u), !0);
164
+ },
165
+ nextConflict: () => {
166
+ const u = z(n.state.doc);
167
+ if (u[0] === void 0) return !1;
168
+ const f = n.state.doc.lineAt(n.state.selection.main.head).number, m = u.findIndex((k) => k.start > f), w = m < 0 ? 0 : m, b = n.state.doc.line(u[w].start).from;
169
+ n.dispatch({ selection: Y.cursor(b), effects: V.scrollIntoView(b, { y: "center" }) });
170
+ const S = n.contentDOM.querySelector(`[${me}="${String(w)}"] button`);
171
+ return S instanceof HTMLElement ? S.focus({ preventScroll: !0 }) : n.focus(), !0;
172
+ },
173
+ save: () => n.state.toJSON(fe),
174
+ destroy: () => n.destroy()
175
+ };
176
+ }, ne = (e, t, r, s) => {
177
+ const l = s.scrollerOf(e.scrollDOM), i = (r === null ? G(l, e.contentDOM) : r) - Q(l);
178
+ return V.scrollIntoView(t, { y: "start", yMargin: i });
179
+ }, ct = (e, t, r, s) => {
180
+ const l = ut(e, t), i = s.scrollerOf(e.scrollDOM), a = Q(i), o = G(i, e.contentDOM), c = a + i.clientHeight;
181
+ let p = 0;
182
+ switch (r.y) {
183
+ case "start":
184
+ p = l.top - (a + r.yMargin);
185
+ break;
186
+ case "center":
187
+ p = (l.top + l.bottom) / 2 - (o + c) / 2;
188
+ break;
189
+ case "end":
190
+ p = l.bottom - (c - r.yMargin);
191
+ break;
192
+ default:
193
+ l.top < o + r.yMargin ? p = l.top - (o + r.yMargin) : l.bottom > c - r.yMargin && (p = Math.min(l.bottom - (c - r.yMargin), l.top - (o + r.yMargin)));
194
+ }
195
+ if (p !== 0 && (i.scrollTop += p), r.y === "start") return;
196
+ const n = dt(e, t);
197
+ n !== null && s.reveal(n);
198
+ }, ut = (e, t) => {
199
+ const { node: r, offset: s } = e.domAtPos(t);
200
+ if (r.nodeType === Node.TEXT_NODE) {
201
+ const a = r.ownerDocument?.createRange();
202
+ if (a !== void 0) {
203
+ a.setStart(r, s), a.setEnd(r, s);
204
+ const [o] = a.getClientRects();
205
+ if (o !== void 0 && o.height > 0) return { top: o.top, bottom: o.bottom };
206
+ }
207
+ }
208
+ const l = e.lineBlockAt(t), i = e.documentTop + l.top;
209
+ return { top: i, bottom: i + l.height };
210
+ }, dt = (e, t) => {
211
+ const { node: r } = e.domAtPos(t);
212
+ for (let s = r instanceof Element ? r : r.parentElement; s !== null; s = s.parentElement)
213
+ if (s.parentElement === e.contentDOM) return s;
214
+ return null;
215
+ }, ft = (e, t) => {
216
+ if (e == null) return null;
217
+ try {
218
+ return ue.fromJSON(e, { extensions: t }, fe);
219
+ } catch {
220
+ return null;
221
+ }
222
+ }, mt = 610, pt = 987, oe = Object.freeze({ kind: "unavailable" }), ht = "true", vt = "false", gt = (e) => e === ht ? !0 : e === vt ? !1 : null, wt = (e) => {
223
+ const t = new DOMParser().parseFromString(e, "text/html"), r = [];
224
+ for (const s of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")) {
225
+ const l = s.localName === "img", i = s.getAttribute(l ? "data-asset-src" : "data-doc-path");
226
+ i !== null && r.push({ target: { kind: l ? "asset" : "doc", path: i }, exists: gt(s.getAttribute(l ? "data-asset-exists" : "data-doc-exists")) });
227
+ }
228
+ return r;
229
+ }, bt = ({ path: e, instant: t, preview: r, initial: s, onView: l }) => {
230
+ const i = new AbortController(), a = { asset: /* @__PURE__ */ new Map(), doc: /* @__PURE__ */ new Map() };
231
+ let o = s, c = null, p = !1, n = !1, u = null, d = null, f = [], m, w = !1, b, S = null;
232
+ const k = (g) => {
233
+ g.parsed === o.parsed && g.failure === o.failure && g.busy === o.busy && g.tier === o.tier || (o = g, l(g));
234
+ }, q = (g, E) => {
235
+ p || (p = !0, console.error(`[markdown-explorer] ${g}`, ...E === void 0 ? [] : [E]));
236
+ }, H = (g) => {
237
+ if (t !== null)
238
+ for (const { target: E, exists: x } of t.marksOf(g)) a[E.kind].set(E.path, x);
239
+ }, h = () => {
240
+ clearTimeout(b), b = void 0, S?.abort(), S = null;
241
+ }, y = () => {
242
+ d = null, f = [], clearTimeout(m), m = void 0;
243
+ }, T = (g, E) => {
244
+ k({ parsed: o.parsed, failure: g, busy: !1, tier: E });
245
+ }, A = () => {
246
+ clearTimeout(m), m = f.length === 0 ? void 0 : setTimeout(I, pt);
247
+ }, P = () => {
248
+ if (t === null || d === null) return;
249
+ const g = d, E = [], x = { asset: /* @__PURE__ */ new Set(), doc: /* @__PURE__ */ new Set() };
250
+ let R;
251
+ try {
252
+ R = t.sanitize(g.html, (_) => {
253
+ const ee = a[_.kind].get(_.path);
254
+ return ee === void 0 && !x[_.kind].has(_.path) && (x[_.kind].add(_.path), E.push(_)), ee ?? void 0;
255
+ });
256
+ } catch (_) {
257
+ y(), _ instanceof Je ? T(K("too-large"), "instant") : (q("the draft sanitizer failed", _), T(K("failed"), "instant"));
258
+ return;
259
+ }
260
+ f = E;
261
+ const F = o.parsed !== null && o.parsed.htmlContent === R && o.parsed.headings === g.headings ? o.parsed : { htmlContent: R, headings: g.headings };
262
+ k({ parsed: F, failure: null, busy: !1, tier: "instant" }), A();
263
+ }, I = () => {
264
+ if (m = void 0, w || d === null || f.length === 0) return;
265
+ w = !0;
266
+ const g = f;
267
+ r(e, d.text, i.signal).then((E) => {
268
+ if (w = !1, !(i.signal.aborted || !("kind" in E))) {
269
+ E.kind === "preview" && H(E.htmlContent);
270
+ for (const x of g) a[x.kind].has(x.path) || a[x.kind].set(x.path, null);
271
+ P();
272
+ }
273
+ });
274
+ }, v = (g) => {
275
+ h(), y(), k({ ...o, busy: !0, tier: "server" });
276
+ const E = new AbortController();
277
+ S = E, b = setTimeout(() => {
278
+ b = void 0, r(e, g, E.signal).then((x) => {
279
+ if (!(E.signal.aborted || !("kind" in x))) {
280
+ if (S = null, x.kind === "failure") {
281
+ T(x.failure, "server");
282
+ return;
283
+ }
284
+ H(x.htmlContent), k({ parsed: { htmlContent: x.htmlContent, headings: x.headings }, failure: null, busy: !1, tier: "server" });
285
+ }
286
+ });
287
+ }, mt);
288
+ }, M = async (g, E) => {
289
+ let x;
290
+ try {
291
+ x = await g.convert({ path: e, text: E }, i.signal);
292
+ } catch (F) {
293
+ return i.signal.aborted || q("the draft converter rejected a conversion, which its contract allows only once the signal aborted", F), oe;
294
+ }
295
+ const R = $e(x);
296
+ return R === null ? x : (q(`the draft converter answered outside its contract: ${R}`), oe);
297
+ }, N = (g, E) => {
298
+ switch (E.kind) {
299
+ case "preview":
300
+ if (h(), E.headings.length > Ye) {
301
+ y(), T(K("too-large"), "instant");
302
+ return;
303
+ }
304
+ d = { text: g, html: E.htmlContent, headings: E.headings.map(({ text: x, depth: R, id: F }) => ({ text: x, depth: R, id: F })) }, P();
305
+ return;
306
+ case "failure":
307
+ h(), y(), T(K(E.failure.reason, E.failure.code), "instant");
308
+ return;
309
+ case "unavailable":
310
+ v(g);
311
+ return;
312
+ }
313
+ }, O = async (g) => {
314
+ n = !0;
315
+ try {
316
+ for (; u !== null && !i.signal.aborted; ) {
317
+ const E = u;
318
+ u = null;
319
+ const x = await M(g, E);
320
+ if (i.signal.aborted) return;
321
+ N(E, x);
322
+ }
323
+ } finally {
324
+ n = !1;
325
+ }
326
+ };
327
+ return t !== null && t.seed !== null && H(t.seed), {
328
+ update: (g) => {
329
+ if (!(i.signal.aborted || g === c)) {
330
+ if (c = g, clearTimeout(m), m = void 0, t === null) {
331
+ v(g);
332
+ return;
333
+ }
334
+ u = g, n || O(t.converter);
335
+ }
336
+ },
337
+ dispose: () => {
338
+ i.abort(), u = null, clearTimeout(m), m = void 0, h();
339
+ }
340
+ };
341
+ }, Et = (e, t) => Qe(et(window), e, t, Ze), xt = (e, t) => e.flatMap((r, s) => {
342
+ const l = t[s];
343
+ return l === void 0 ? [] : [
344
+ { editor: l.top, preview: r.top },
345
+ { editor: l.bottom, preview: r.bottom }
346
+ ];
347
+ }), St = (e) => {
348
+ const t = [], r = [];
349
+ e.forEach((l, i) => {
350
+ let a = 0, o = t.length;
351
+ for (; a < o; ) {
352
+ const c = a + o >> 1;
353
+ (e[t[c] ?? 0]?.preview ?? 0) <= l.preview ? a = c + 1 : o = c;
354
+ }
355
+ r[i] = a > 0 ? t[a - 1] ?? -1 : -1, t[a] = i;
356
+ });
357
+ const s = [];
358
+ for (let l = t.at(-1) ?? -1; l >= 0; l = r[l] ?? -1) {
359
+ const i = e[l];
360
+ i !== void 0 && s.push(i);
361
+ }
362
+ return s.reverse();
363
+ }, yt = (e, t) => {
364
+ const r = Math.max(t.editorMax, 0), s = Math.max(t.previewMax, 0), l = r - t.editorViewport, i = s - t.previewViewport, a = e.filter((c) => c.editor > 0 && c.editor < l && c.preview > 0 && c.preview < i).sort((c, p) => c.editor - p.editor || c.preview - p.preview), o = [{ editor: 0, preview: 0 }];
365
+ for (const c of St(a)) {
366
+ const p = o.at(-1);
367
+ (p === void 0 || c.editor > p.editor && c.preview > p.preview) && o.push(c);
368
+ }
369
+ return o.push({ editor: r, preview: s }), {
370
+ toPreview: (c) => se(o, "editor", "preview", c),
371
+ toEditor: (c) => se(o, "preview", "editor", c)
372
+ };
373
+ }, se = (e, t, r, s) => {
374
+ const l = e[0], i = e.at(-1);
375
+ if (l === void 0 || i === void 0 || Number.isNaN(s) || s <= l[t]) return l?.[r] ?? 0;
376
+ if (s >= i[t]) return i[r];
377
+ let a = 0, o = e.length - 1;
378
+ for (; o - a > 1; ) {
379
+ const n = a + o >> 1;
380
+ (e[n]?.[t] ?? 0) <= s ? a = n : o = n;
381
+ }
382
+ const c = e[a] ?? l, p = e[o] ?? i;
383
+ return c[r] + (p[r] - c[r]) * (s - c[t]) / (p[t] - c[t]);
384
+ }, kt = 610, ie = 89, le = 0.5, Tt = ({ editor: e, preview: t, previewBlocks: r, editorSpans: s, requestFrame: l, cancelFrame: i, now: a }) => {
385
+ let o = "editor", c = 0, p = null, n = !1, u = null, d = null;
386
+ const f = { editor: 0, preview: 0 }, m = { editor: null, preview: null };
387
+ let w = null, b = () => {
388
+ };
389
+ const S = (v) => {
390
+ o = v, c = a() + kt;
391
+ }, k = (v, M) => {
392
+ v !== o && a() >= c && !q(v, M) && (o = v), A();
393
+ }, q = (v, M) => {
394
+ const N = m[v];
395
+ return a() < f[v] || N !== null && Math.abs(M.position() - N) < le;
396
+ }, H = e.onScroll(() => k("editor", e)), h = e.onIntent(() => S("editor")), y = () => {
397
+ const v = t();
398
+ return v !== w && (b(), w = v, b = v === null ? () => {
399
+ } : T(v)), v;
400
+ }, T = (v) => {
401
+ const M = v.onScroll(() => k("preview", v)), N = v.onIntent(() => S("preview"));
402
+ return () => {
403
+ M(), N();
404
+ };
405
+ }, A = () => {
406
+ !n && p === null && (p = l(P));
407
+ }, P = () => {
408
+ p = null;
409
+ const v = y();
410
+ v !== null && (u ??= r(), d ??= yt(xt(u, s(u)), { editorMax: e.max(), previewMax: v.max(), editorViewport: e.viewport(), previewViewport: v.viewport() }), o === "editor" ? I(v, "preview", d.toPreview(e.position())) : I(e, "editor", d.toEditor(v.position())));
411
+ }, I = (v, M, N) => {
412
+ if (Math.abs(v.position() - N) < le) {
413
+ m[M] = v.position();
414
+ return;
415
+ }
416
+ f[M] = a() + ie, m[M] = v.scrollTo(N);
417
+ };
418
+ return A(), {
419
+ editorChanged: (v) => {
420
+ d = null, v && S("editor"), A();
421
+ },
422
+ previewChanged: () => {
423
+ u = null, d = null, f.preview = a() + ie, A();
424
+ },
425
+ dispose: () => {
426
+ n = !0, p !== null && i(p), p = null, H(), h(), b();
427
+ }
428
+ };
429
+ }, ae = Object.freeze(["wheel", "pointerdown", "keydown", "focusin"]), he = (e) => ({
430
+ position: () => e.scrollTop,
431
+ max: () => Math.max(e.scrollHeight - e.clientHeight, 0),
432
+ viewport: () => e.clientHeight,
433
+ scrollTo: (t) => (e.scrollTo({ top: t, behavior: "instant" }), e.scrollTop),
434
+ onScroll: (t) => (e.addEventListener("scroll", t, { passive: !0 }), () => e.removeEventListener("scroll", t)),
435
+ onIntent: (t) => {
436
+ for (const r of ae) e.addEventListener(r, t, { capture: !0, passive: !0 });
437
+ return () => {
438
+ for (const r of ae) e.removeEventListener(r, t, { capture: !0 });
439
+ };
440
+ }
441
+ }), j = "[data-aqmd-scroll-container]", Mt = "[data-aqmd-content]", Lt = `[${de}]`, Ct = Object.freeze(["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8"]), ve = (e, t) => {
442
+ const r = Se(e.peek(t));
443
+ return r !== null && r.document.kind === "markdown" ? { htmlContent: r.document.htmlContent, headings: r.document.headings } : null;
444
+ }, qt = (e, t, r, s, l) => {
445
+ if (r === void 0) return null;
446
+ let i;
447
+ try {
448
+ i = Et(e, t);
449
+ } catch (a) {
450
+ return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview", a), null;
451
+ }
452
+ return { converter: r, sanitize: i, marksOf: wt, seed: ve(s, l)?.htmlContent ?? null };
453
+ }, Ot = (e) => {
454
+ const t = [];
455
+ let r = null;
456
+ for (const s of e.querySelectorAll(Lt)) {
457
+ const l = Xe(s.getAttribute(de));
458
+ if (l === null || s.getClientRects().length === 0) continue;
459
+ r ??= e.scrollTop - G(e, s);
460
+ const { top: i, bottom: a } = s.getBoundingClientRect();
461
+ t.push({ first: l.first, last: l.last, top: r + i, bottom: r + a });
462
+ }
463
+ return t;
464
+ }, At = ({ path: e, readDraft: t, viewer: r, onLayout: s, handleRef: l }) => {
465
+ const { config: i, data: a, documents: o, draftConverter: c, labels: p } = Z(), [n, u] = we(() => ({ parsed: ve(o, e), failure: null, busy: !0, tier: c === void 0 ? "server" : "instant" })), d = D(null), f = D(null), m = D(n);
466
+ B(() => {
467
+ m.current = n;
468
+ });
469
+ const w = te(() => t());
470
+ U(() => {
471
+ const h = qt(i.iframeHosts, i.dataPath, c, o, e), y = bt({ path: e, instant: h, preview: a.preview, initial: m.current, onView: (T) => Ee(() => u(T)) });
472
+ return f.current = y, y.update(w()), () => {
473
+ y.dispose(), f.current = null;
474
+ };
475
+ }, [i, a, o, c, e]);
476
+ const b = te(() => s());
477
+ B(() => {
478
+ n.parsed !== null && b();
479
+ }, [n.parsed]);
480
+ const S = n.parsed !== null;
481
+ U(() => {
482
+ const h = S ? d.current?.querySelector(j) : null;
483
+ if (!(h instanceof HTMLElement)) return;
484
+ const y = new ResizeObserver(() => b());
485
+ y.observe(h);
486
+ const T = h.querySelector(Mt);
487
+ return T !== null && y.observe(T), () => y.disconnect();
488
+ }, [S]);
489
+ const k = D(null);
490
+ be(
491
+ l,
492
+ () => ({
493
+ draft: (h) => {
494
+ f.current?.update(h);
495
+ },
496
+ scrollPort: () => {
497
+ const h = d.current?.querySelector(j);
498
+ return h instanceof HTMLElement ? (k.current?.scroller !== h && (k.current = { scroller: h, port: he(h) }), k.current.port) : null;
499
+ },
500
+ blocks: () => {
501
+ const h = d.current?.querySelector(j);
502
+ return h instanceof HTMLElement ? Ot(h) : [];
503
+ }
504
+ }),
505
+ []
506
+ );
507
+ const q = X(() => ({ ...r, showToc: !1, showStyle: !1, showAlign: !1, renderScrollBar: void 0 }), [r]), H = X(
508
+ () => n.parsed === null ? null : /* @__PURE__ */ C("div", { className: "aqmx-document-viewer", children: /* @__PURE__ */ C(Ue, { ...q, parseResult: n.parsed, content: null }) }),
509
+ [q, n.parsed]
510
+ );
511
+ return /* @__PURE__ */ J("section", { ref: d, className: "aqmx-edit-preview", "aria-label": p.previewRegion, "aria-busy": n.busy, "data-aqmx-preview-tier": n.tier, "data-testid": "markdown-explorer-edit-preview", children: [
512
+ n.failure === null ? null : /* @__PURE__ */ C("p", { className: "aqmx-callout aqmx-document-notice", "data-aqmx-tone": "warning", "data-testid": "markdown-explorer-edit-preview-failure", children: p.previewFailed(ce(p, n.failure.reason)) }),
513
+ H ?? (n.failure === null ? /* @__PURE__ */ C("div", { className: "aqmx-skeleton", "aria-hidden": "true", "data-testid": "markdown-explorer-edit-preview-skeleton", children: Ct.map((h) => /* @__PURE__ */ C("span", {}, h)) }) : null),
514
+ n.busy ? /* @__PURE__ */ C("p", { className: "aqmx-sr-only", children: p.previewUpdating }) : null
515
+ ] });
516
+ }, It = 144, Nt = Object.freeze(["e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8"]), Rt = (e) => {
517
+ if (typeof e != "object" || e === null) return !1;
518
+ const { generation: t, topLine: r } = e;
519
+ return "state" in e && typeof t == "number" && typeof r == "number";
520
+ }, Dt = (e) => {
521
+ e.key === "Escape" && Ce(e);
522
+ }, _t = (e) => {
523
+ e.stopPropagation();
524
+ }, Zt = (e) => {
525
+ const { path: t, name: r, session: s } = e, { edits: l, labels: i, announcer: a } = Z(), { phase: o } = s, c = $(() => l.retry(t), [l, t]);
526
+ switch (U(() => {
527
+ o.kind === "failed" && a.announce(i.documentFailed(r, ce(i, o.failure.reason)));
528
+ }, [o, a, i, r]), o.kind) {
529
+ case "opening":
530
+ return /* @__PURE__ */ J(ge, { children: [
531
+ /* @__PURE__ */ C("div", { className: "aqmx-skeleton", "aria-hidden": "true", "data-testid": "markdown-explorer-edit-skeleton", children: Nt.map((p) => /* @__PURE__ */ C("span", {}, p)) }),
532
+ /* @__PURE__ */ C("p", { className: "aqmx-sr-only", children: i.editLoading })
533
+ ] });
534
+ case "grant":
535
+ return /* @__PURE__ */ C("div", { className: "aqmx-edit-message", children: /* @__PURE__ */ C(ke, { href: o.href, onRetry: c, testId: "markdown-explorer-edit-grant" }) });
536
+ case "failed":
537
+ return /* @__PURE__ */ C("div", { className: "aqmx-edit-message", children: /* @__PURE__ */ C(ye, { failure: o.failure, alert: !1, onRetry: c, testId: "markdown-explorer-edit-failure" }) });
538
+ case "editing":
539
+ return /* @__PURE__ */ C(Ht, { ...e });
540
+ }
541
+ }, Ht = ({ path: e, name: t, session: r, layout: s, viewer: l, region: i, paneScroll: a }) => {
542
+ const { edits: o, labels: c } = Z(), p = D(null), n = D(null), u = D(null), d = D(null), f = Te() && s === "fill", m = D({ layout: s, region: i, paneScroll: a });
543
+ B(() => {
544
+ m.current = { layout: s, region: i, paneScroll: a };
545
+ });
546
+ const w = D(r.generation);
547
+ B(() => {
548
+ w.current = r.generation;
549
+ });
550
+ const b = D(f);
551
+ B(() => {
552
+ b.current = f;
553
+ });
554
+ const S = X(() => ({ editor: c.editorLabel(t), useOurs: c.conflictUseOurs, useTheirs: c.conflictUseTheirs, keepBoth: c.conflictKeepBoth }), [c, t]);
555
+ B(() => {
556
+ const h = p.current, y = o.draft(e);
557
+ if (h === null || y === null) return;
558
+ const T = o.editorState.get(e), A = Rt(T) && T.generation === w.current ? T : null;
559
+ let P = null, I = null;
560
+ const v = () => {
561
+ P !== null && clearTimeout(P), P = null, I !== null && o.setDraft(e, I.text());
562
+ }, M = at({
563
+ parent: h,
564
+ scroll: {
565
+ scrollerOf: (O) => {
566
+ const { layout: g, region: E, paneScroll: x } = m.current, R = E();
567
+ return g === "fill" || R === null ? O : x.scrollerOf(R, O);
568
+ },
569
+ reveal: (O) => m.current.paneScroll.reveal(O)
570
+ },
571
+ text: y,
572
+ saved: A === null ? void 0 : A.state,
573
+ labels: S,
574
+ onGeometry: (O) => d.current?.editorChanged(O),
575
+ onChange: () => {
576
+ P ??= setTimeout(v, It), b.current && I !== null && u.current?.draft(I.text());
577
+ },
578
+ onSave: () => {
579
+ o.save(e);
580
+ }
581
+ });
582
+ I = M, n.current = M;
583
+ const N = o.bindEditor(e, {
584
+ flush: v,
585
+ adopt: (O) => M.replaceText(O),
586
+ returnPoint: () => {
587
+ const O = M.topLine();
588
+ return { line: O.line, clientTop: O.clientTop };
589
+ },
590
+ nextConflict: () => M.nextConflict()
591
+ });
592
+ return A !== null && M.showLine(A.topLine), () => {
593
+ v(), o.editorState.set(e, { state: M.save(), generation: w.current, topLine: M.topLine().line }), N(), M.destroy(), I = null, n.current = null;
594
+ };
595
+ }, [o, e, S]);
596
+ const { request: k } = r;
597
+ B(() => {
598
+ const h = n.current, y = o.draft(e);
599
+ h === null || y === null || k === null || (k.anchor !== null && h.reveal(Me(y, k.anchor), k.anchor.clientTop), h.focus(), o.consumeRequest(e));
600
+ }, [o, e, k, S]);
601
+ const q = $(() => {
602
+ const h = n.current;
603
+ if (h === null) throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");
604
+ return h.text();
605
+ }, []);
606
+ B(() => {
607
+ const h = n.current;
608
+ if (!f || h === null) return;
609
+ const y = Tt({
610
+ editor: he(h.scrollElement),
611
+ preview: () => u.current?.scrollPort() ?? null,
612
+ previewBlocks: () => u.current?.blocks() ?? [],
613
+ editorSpans: (T) => h.lineSpans(T),
614
+ requestFrame: (T) => requestAnimationFrame(T),
615
+ cancelFrame: (T) => cancelAnimationFrame(T),
616
+ now: () => performance.now()
617
+ });
618
+ return d.current = y, () => {
619
+ y.dispose(), d.current = null;
620
+ };
621
+ }, [f, o, e, S]);
622
+ const H = $(() => d.current?.previewChanged(), []);
623
+ return (
624
+ /* @__PURE__ */ J("div", { className: "aqmx-edit", "data-aqmx-edit-layout": s, "data-testid": "markdown-explorer-edit", onKeyDown: Dt, onDoubleClick: _t, children: [
625
+ /* @__PURE__ */ C("div", { ref: p, className: "aqmx-edit-editor", "data-testid": "markdown-explorer-editor", ...Le }),
626
+ f ? /* @__PURE__ */ C(At, { path: e, readDraft: q, viewer: l, onLayout: H, handleRef: u }) : null
627
+ ] })
628
+ );
629
+ };
630
+ export {
631
+ It as DRAFT_WRITE_INTERVAL_MS,
632
+ Zt as default
633
+ };