@aiquants/markdown-explorer 0.38.0 → 0.40.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +4 -2
  3. package/dist/{EditSurface-Dis52Iwq.cjs → EditSurface-DFHZLbWC.cjs} +2 -2
  4. package/dist/{EditSurface-BTrQ1viw.js → EditSurface-DV4FuQVx.js} +211 -211
  5. package/dist/{ExplorerSplit-Dq7HfNre.js → ExplorerSplit-DTkr0q2C.js} +407 -407
  6. package/dist/{ExplorerSplit-13nPIuf0.cjs → ExplorerSplit-DnuuUifU.cjs} +1 -1
  7. package/dist/{MultiLayout-B7RvBpCj.cjs → MultiLayout-CC0VPiFf.cjs} +1 -1
  8. package/dist/{MultiLayout-1rKm2Hzt.js → MultiLayout-S77I1xQr.js} +3 -3
  9. package/dist/{NativeScrollBar-D63-6AL1.cjs → NativeScrollBar-C2n-DzEJ.cjs} +1 -1
  10. package/dist/{NativeScrollBar-Bg05yuzM.js → NativeScrollBar-DMCPxFeR.js} +2 -2
  11. package/dist/{TreeLayout-9eEP62LF.js → TreeLayout-BGTzh0L4.js} +3 -3
  12. package/dist/{TreeLayout-CNE0XkWz.cjs → TreeLayout-DjJMAxWJ.cjs} +1 -1
  13. package/dist/core/config.d.cts +2 -0
  14. package/dist/core/config.d.ts +2 -0
  15. package/dist/core/geometry.d.cts +0 -1
  16. package/dist/core/geometry.d.ts +0 -1
  17. package/dist/{explorerCore-GCqatHTO.js → explorerCore-COhVrnGO.js} +1 -1
  18. package/dist/{explorerCore-5qeC3-gt.cjs → explorerCore-diILGZTv.cjs} +1 -1
  19. package/dist/{index-_XNluAcx.cjs → index-AfEbgYQI.cjs} +8 -8
  20. package/dist/{index-C52Nj37x.js → index-CWFyLa0N.js} +9 -8
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +15 -15
  23. package/dist/location-Csj3eAm_.cjs +1 -0
  24. package/dist/{location-CJvL6JNs.js → location-DFfbnUZ9.js} +95 -89
  25. package/dist/{merge-CnrrjXmc.js → merge-D-Oak4Xy.js} +1 -1
  26. package/dist/{merge-CKpFyeqR.cjs → merge-DvoikrFp.cjs} +1 -1
  27. package/dist/server.cjs +1 -1
  28. package/dist/server.js +3 -3
  29. package/dist/serverCore.cjs +1 -1
  30. package/dist/serverCore.js +3 -3
  31. package/dist/styles/markdown-explorer.css +1 -1
  32. package/dist/{tapScrollCircle-6etmzCb7.cjs → tapScrollCircle-CS3hbyGb.cjs} +1 -1
  33. package/dist/{tapScrollCircle-D-Lgzdxx.js → tapScrollCircle-DKoj17z6.js} +1 -1
  34. package/dist/{useSplitPersistence-CD_n1ivo.cjs → useSplitPersistence-C6s7a4Iu.cjs} +1 -1
  35. package/dist/{useSplitPersistence-tbTu3P5m.js → useSplitPersistence-CC9bx9iq.js} +1 -1
  36. package/package.json +5 -5
  37. package/dist/location-DOIG84V9.cjs +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,91 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Breaking
6
+
7
+ - **The `@aiquants/markdown` peer floor rises from `^13.3.0` to `^13.4.0`.** The new `documentFontFamily` option is passed
8
+ through to `@aiquants/markdown`'s viewer, whose `documentFontFamily` prop ships in 13.4.0, so a host on an older markdown
9
+ cannot apply a document font. `@aiquants/markdown-explorer-host` raises its own explorer peer floor to `^0.40.0` to
10
+ match, released together with this version.
11
+
12
+ ### Added
13
+
14
+ - **A host sets a document's text font through the `documentFontFamily` configuration option.** The explorer passes the
15
+ value through to `@aiquants/markdown`'s viewer verbatim, which sets `--aqmd-document-font-family` on the document root
16
+ and reads it through `font-family`, overriding the display style's font; omitted or `undefined`, the document keeps its
17
+ display style's font. The explorer never sanitizes the value — the host passes an already-safe CSS `font-family`,
18
+ resolved and sanitized from a person's choice with `@aiquants/fonts`, so a stack's unquoted generic fallback (the
19
+ `sans-serif` in `"Noto Sans JP", sans-serif`) is kept intact rather than corrupted by re-sanitizing. A blank or
20
+ whitespace-only string throws a `RangeError` (omit it for the display style's font); anything but a string a `TypeError`.
21
+ - **The explorer chrome's font is settable through `--aqmx-ui-font-family`.** The explorer's tree, toolbars and menus take
22
+ `font-family: var(--aqmx-ui-font-family, inherit)` on the root; the property is left undeclared, so without it the chrome
23
+ inherits the page's font as before, and a value set on `:root` (or an ancestor of the explorer) applies it. A document's
24
+ own text is separate (its display style and `documentFontFamily`), and the editor and other monospace surfaces keep
25
+ their own fonts.
26
+
27
+ ## 0.39.0 (2026-11-16) — A 44 px resize divider, prose line heights and an opt-in document floor (WCAG 2.2); the auth-core peer floor rises to ^0.9.0
28
+
29
+ ### Breaking
30
+
31
+ - **The `@aiquants/auth-core` peer floor rises from `^0.8.0` to `^0.9.0`.** auth-core 0.9.0's access-failure policy now
32
+ requires `signedIn`: a policy is `{ signedIn: true; keepsWork: boolean }` or `{ signedIn: false; keepsWork: false }`, and
33
+ `accessFailureView` throws a `RangeError` on `signedIn: false` with `keepsWork: true` (a policy without a sign-in cannot
34
+ keep work). Hosts that pass a policy to `accessFailureView` must add `signedIn` — `signedIn: true` for the explorer,
35
+ which keeps the reader's unsaved drafts — so the demo and README examples now pass `{ signedIn: true, keepsWork: true }`.
36
+
37
+ ### Added
38
+
39
+ - **An opt-in `--aqmx-document-min-block-size` floor for the single view's document scroll box (WCAG 2.2 1.4.10).** The
40
+ neutral token (default `0px`, the host writes it) sets the `min-block-size` of the single view's document scroll boxes
41
+ (the viewer, `DocumentScrollArea` and the editor's preview), which also `contain: size` so a tall document does not
42
+ stretch them. It is a scroll-box minimum, not a page-growth mechanism: the explorer root is `block-size: 100%` (it
43
+ fills the host's container), so a host that wants the floor to show must size the explorer's container to at least the
44
+ bar plus the floor — a shorter container clips the floored box. §6.2's `F_d` is `calc(5 * 1rem * φ)`, the golden ratio
45
+ φ (≈ 129.4 px at a 16 px root).
46
+
47
+ ### Changed
48
+
49
+ - **The explorer/content resize divider is a 44 px hit band under every pointer (WCAG 2.2 2.5.5).** `ExplorerSplit` and
50
+ `EditSplit` size the handle to `COARSE_TARGET_PIXELS` (44 px, one control) for every pointer, not 24 px for a fine
51
+ pointer; the visible grip is unchanged and the band insets its neighbours by half its width (22 px), so it covers
52
+ neither the tree's scroll bar nor the content's edge. The edit split's side-by-side threshold rises by 20 px to match,
53
+ and `FINE_TARGET_PIXELS` is gone.
54
+ - **Multi-line text blocks take the prose line height (WCAG 2.2 1.4.8).** Notices, failure sentences, toasts, the tree
55
+ and edit messages and the dialog bodies use `--aqmx-line-height-prose` (the golden ratio φ ≈ 1.618); single-line
56
+ controls, titles and bars keep the compact `1.382`.
57
+
58
+ ### Tests
59
+
60
+ - The target-size E2E no longer exempts the resize divider (it measures 44 × 44), and the divider threshold tests assert
61
+ 44 px under every pointer. A new `document-floor` E2E checks, in a window too short to hold it, that the floor holds the
62
+ single view's document scroll box at `F_d` and that the default `0px` leaves it collapsed.
63
+
64
+ ## 0.38.0 (2026-11-16) — A config option names the mermaid pan and zoom modifier key
65
+
66
+ ### Added
67
+
68
+ - **`mermaidModifier` config option for the mermaid pan and zoom modifier key.** `defineExplorerConfig` now takes
69
+ `mermaidModifier?: "ctrl" | "shift"` and passes it through to `@aiquants/markdown`'s viewer, so a plain mouse drag
70
+ stays for text selection and node clicks and only a drag or wheel held with the modifier pans and zooms the diagram.
71
+ Omitted or `undefined`, the value is passed through unchanged and the viewer applies its own
72
+ `DEFAULT_PAN_ZOOM_MODIFIER` (`"ctrl"`), keeping the default's single source of truth in the viewer; a value that is
73
+ not `"ctrl"` or `"shift"` throws a `RangeError` naming them. The package ships this as a component option with no UI
74
+ of its own — a host app surfaces the choice in its own settings — and the diagram's mode labels take the viewer's
75
+ neutral form (`"修飾キー+ドラッグ"` / `"modifier+drag"`) so the app names the key.
76
+
77
+ ### Changed
78
+
79
+ - **The `@aiquants/markdown` peer floor rises from `^13.0.0` to `^13.3.0`.** The pass-through needs 13.3.0's
80
+ `PanZoomModifier` type, the viewer's `mermaidModifier` prop and the neutral mermaid mode labels.
81
+
82
+ ### Tests
83
+
84
+ - `tests/unit/settings.test.ts`: `defineExplorerConfig` resolves `"ctrl"` and `"shift"` to themselves and an omitted
85
+ or `undefined` `mermaidModifier` to `undefined` (the viewer applies its default), and rejects a value that is not one
86
+ of them with a `RangeError`; `revalidateExplorerConfig` round-trips `"shift"` and rejects `"alt"`; the sorted option
87
+ keys and the options string include `mermaidModifier`.
88
+
3
89
  ## 0.37.1 (2026-11-15) — Access failures: a 401 keeps the page and the reader's work, and each failure gets its own node
4
90
 
5
91
  ### Fixed
package/README.md CHANGED
@@ -50,7 +50,7 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
50
50
 
51
51
  - React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
52
52
  - Node.js 22.22 or later (the floor React Router 8 declares). The package ships ES modules and CommonJS; the CommonJS entries load the ESM-only `react-router` through `require(esm)`.
53
- - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/auth-core` ^0.8.0 (the access failure contract: the occurrence the host's presenter draws, and the 403 refusal of the page loader, `accessFailureResponse`), `@aiquants/markdown` ^13.3.0 (document rendering;
53
+ - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/auth-core` ^0.9.0 (the access failure contract: the occurrence the host's presenter draws, and the 403 refusal of the page loader, `accessFailureResponse`), `@aiquants/markdown` ^13.4.0 (document rendering;
54
54
  the column width and colour pair a reader picks in its display popover (`CONTENT_MEASURES` and `CONTENT_COLORS` of `@aiquants/markdown/viewer-settings`) and the labels of the popover's sections and of a diagram's notices, a document's language for its content (`contentLang`) apart from the UI language of the labels the explorer passes (`labelsLang`), and the size of a document table's tap-scroll circle (`spreadsheetTapScrollCircle`'s `size`);
55
55
  the gutter its scroll container keeps beside the explorer's bar for the tap-scroll circle (`scrollBarGutter`, given as a custom property that a media query sets), code blocks whose Copy button sits in a header row above the code, and documents whose front matter does not render; the Source toggle of a storage SVG image that stands alone in a paragraph, read through `imageSource`, and a Copy that copies the image as a PNG image or its source, the source readable in every display style, a notice in place of a block that cannot render and plain text for a fence in a language it does not know;
56
56
  the full screen of its tables, Mermaid diagrams and SVG images, which every block marks with the same DOM hook (`data-aqmd-fullscreen`), and `DEFAULT_MARKDOWN_STYLE`, the style a document starts in by default; its components' stylesheet without utilities,
@@ -116,6 +116,7 @@ The source ids are not part of it: they are the ids of the server's `sources` (a
116
116
  | `documentStyles?` | `readonly { name, className }[]` | Document styles, in the order the style section of the viewer's display popover lists them; `@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLES` (None, GitHub, Zenn; also exported without React from `@aiquants/markdown/viewer-settings`) when omitted. |
117
117
  | `defaultDocumentStyle?` | `string` | The style a document starts in while neither the URL (`style`) nor the reader's saved preference names one: the name of one of `documentStyles`, matched exactly (`"zenn"` is not `"Zenn"`). `@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE` (`"Zenn"`, also exported from `@aiquants/markdown/viewer-settings`) when omitted, also when given as `undefined`; it never falls back to the first style, so a host whose `documentStyles` leave Zenn out names its own, or the configuration throws. A name that is not one of `documentStyles` throws a `RangeError` naming the styles, and anything but a string a `TypeError`. |
118
118
  | `mermaidModifier?` | `PanZoomModifier` | The modifier key that gates a mermaid diagram's pan and zoom with the mouse (drag and wheel), so a plain drag still selects text and clicks nodes: `"ctrl"` or `"shift"`. The explorer passes it through to `@aiquants/markdown`'s viewer, which gates on it and keeps the diagram's mode label neutral so the app names the key in its own setting; the viewer applies `DEFAULT_PAN_ZOOM_MODIFIER` (`"ctrl"`) when this is omitted or `undefined`. A value that is not `"ctrl"` or `"shift"` throws a `RangeError` naming them. |
119
+ | `documentFontFamily?` | `string` | The CSS `font-family` for a document's text. The explorer passes it through to `@aiquants/markdown`'s viewer verbatim, which sets `--aqmd-document-font-family` on the document root to this value and reads it through `font-family`, overriding the display style's font; omitted or `undefined`, the document keeps its display style's font. The explorer never sanitizes the value — pass an already-safe CSS `font-family`, resolved and sanitized from a person's choice with `@aiquants/fonts`, because re-sanitizing here would corrupt a stack's unquoted generic fallback (such as the `sans-serif` in `"Noto Sans JP", sans-serif`). A blank or whitespace-only string throws a `RangeError` (omit it for the display style's font), and anything but a string a `TypeError`. This sets a document's own text; the explorer chrome's font is the separate `--aqmx-ui-font-family` (see [Styling](#5-load-the-styles)). |
119
120
  | `iframeHosts?` | `readonly string[]` | Host names whose `https:` iframes written in documents may load (exact match); none when omitted. They gate only iframes written in documents; provider frames come from `embeds`, and no iframe of the page's own origin ever renders, whatever is listed. |
120
121
  | `appOrigins?` | `readonly string[]` | The origins the app's own pages are served from, as the browser writes them (`scheme://host[:port]`, such as `http://wails.localhost` or `wails://localhost`): a document's absolute URL of one of them is the app's own, like a relative or path-absolute one, and stays only under the paths its use allows (see [Security](docs/behavior/security.md#html)). None by default. |
121
122
  | `mediaDataPath?` | `string` | An absolute `http:` or `https:` URL, of an origin and a mount path, that the asset URLs of videos, audio and PDF documents are built on instead of the data route (a separate media server's data route, for example); a document's `video`, `audio` and `source` may then use it too. None by default (see [Hosting](docs/behavior/hosting.md#the-apps-own-urls-apporigins-and-mediadatapath)). |
@@ -242,7 +243,7 @@ const follow = (action: AccessFailureAction, retry: (() => void) | null): void =
242
243
 
243
244
  // The explorer keeps the reader's unsaved drafts in the page, so it keeps work.
244
245
  export const presentAccessFailure: AccessFailurePresenter<ReactNode> = (occurrence) => {
245
- const view = accessFailureView(occurrence, { keepsWork: true }, labels)
246
+ const view = accessFailureView(occurrence, { signedIn: true, keepsWork: true }, labels)
246
247
  return (
247
248
  <div role={view.politeness}>
248
249
  <p>{view.title}</p>
@@ -353,6 +354,7 @@ to; load it when your documents contain math.
353
354
  - A maximized multi-view panel and the tree view's maximized document cover the viewport inside the explorer's maximize insets, `--aqmx-maximize-top`, `--aqmx-maximize-right`, `--aqmx-maximize-bottom` and `--aqmx-maximize-left` (all `0px` by default; the stage hands them to drag-drop-panels' `--aqdd-maximize-*`), so one binding in your layout keeps your own header or menu visible in both views. Everything of the explorer they cover (the explorer and its handle, the rail of a closed explorer or the sheet's bar, and the other panels) is inert until the panel or the document is restored.
354
355
  Your own chrome is not: whatever of it they cover stays in the Tab order and in the accessibility tree, so either bind the insets so they leave it uncovered, or make it inert (or `visibility: hidden`) while something is maximized — the maximized panel's frame and the tree view's maximized document column carry `data-aqmx-maximized="true"`, the split's frame carries `data-aqmx-content-covers-page="true"` in both cases (`:has([data-aqmx-content-covers-page="true"])`), and the URL carries `maximized`.
355
356
  - The tree and single views' document bar touches the page's top inline-end corner, where a host may float a control of its own (a menu switch). The bar keeps `--aqmx-page-bar-inset-inline-end` (`0px` by default) free at the end of its button row, beside the focus ring's room, so its last button (Edit while a document is edited, Refresh document otherwise) never sits under that control. The explorer leaves the property undeclared, so a value set on `:root` (or any ancestor of the explorer) reaches the bar.
357
+ - The explorer's chrome (its tree, toolbars and menus) takes its font from `--aqmx-ui-font-family`. The explorer leaves the property undeclared and falls back to `inherit`, so without it the chrome inherits the page's font (as before); a value set on `:root` (or any ancestor of the explorer) applies it. A document's own text is governed instead by its display style and the `documentFontFamily` option, and the editor and other monospace surfaces keep their own fonts.
356
358
 
357
359
  ## Views and URLs
358
360
 
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),m=require("react"),b=require("./index-_XNluAcx.cjs"),Z=require("@aiquants/markdown/code-blocks"),J=require("@codemirror/commands"),we=require("@codemirror/lang-markdown"),ie=require("@codemirror/language"),Ee=require("@codemirror/search"),K=require("@codemirror/state"),_=require("@codemirror/view"),D=require("@lezer/highlight"),Ge=require("@aiquants/markdown"),me=require("@aiquants/markdown/source-lines"),ne=require("./ownUrls-BTPGNhBt.cjs"),pe=require("./sanitizePolicy-C-ehd0J_.cjs"),We=require("isomorphic-dompurify"),X=require("./location-DOIG84V9.cjs"),Xe=require("./describeValue-Ccvhbt36.cjs"),ce=require("@aiquants/resize-panels"),be=require("./useSplitPersistence-CD_n1ivo.cjs"),Pe={history:J.historyField},$e=ie.HighlightStyle.define([{tag:[D.tags.heading1,D.tags.heading2,D.tags.heading3,D.tags.heading4,D.tags.heading5,D.tags.heading6,D.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:D.tags.strong,fontWeight:"700"},{tag:D.tags.emphasis,fontStyle:"italic"},{tag:D.tags.strikethrough,textDecoration:"line-through"},{tag:D.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:D.tags.url,color:"var(--aqmx-syntax-url)"},{tag:D.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:D.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[D.tags.processingInstruction,D.tags.contentSeparator,D.tags.labelName,D.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ke=_.EditorView.theme({"&":{height:"100%",color:"var(--aqmx-text)",backgroundColor:"var(--aqmx-surface)",fontSize:"var(--aqmx-font-size-title)"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',lineHeight:"var(--aqmx-line-height-prose)"},".cm-content":{caretColor:"var(--aqmx-text)",paddingBlock:"var(--aqmx-space-6)"},".cm-line":{paddingInline:"var(--aqmx-space-6)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--aqmx-text)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--aqmx-editor-selection)"},".cm-activeLine":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-gutters":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-editor-gutter)",borderInlineEnd:"var(--aqmx-space-1) solid var(--aqmx-border)"},".cm-activeLineGutter":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-searchMatch":{outline:"var(--aqmx-space-1) solid var(--aqmx-border-strong)"},".cm-panels":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-text)"}}),Ne="data-aqmx-conflict-actions",Ye=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Je=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),Qe=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class Ze extends _.WidgetType{constructor(t,n){super(),this.index=t,this.labels=n}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const n=document.createElement("div");n.setAttribute(Ne,String(this.index));for(const[o,s]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const r=document.createElement("button");r.type="button",r.textContent=s,r.setAttribute("data-aqmx-conflict-choice",o),r.addEventListener("mousedown",l=>l.preventDefault()),r.addEventListener("click",()=>{const l=se(t.state.doc)[this.index];l!==void 0&&(De(t,l,o),t.focus())}),n.append(r)}return n}ignoreEvent(){return!0}}const se=e=>b.findConflictsInLines(e.iterLines()),xe=(e,t)=>{const n=new K.RangeSetBuilder;return se(e).forEach((o,s)=>{const r=e.line(o.start);n.add(r.from,r.from,_.Decoration.widget({widget:new Ze(s,t),block:!0,side:-1}));for(let l=o.start;l<=o.end;l+=1){const i=e.line(l).from,f=l===o.start||l===o.separator||l===o.end?Ye:l<o.separator?Je:Qe;n.add(i,i,f)}}),n.finish()},et=e=>K.StateField.define({create:t=>xe(t.doc,e),update:(t,n)=>n.docChanged?xe(n.state.doc,e):t,provide:t=>_.EditorView.decorations.from(t)}),De=(e,t,n)=>{const{doc:o}=e.state,s=(E,c)=>{const w=[];for(let u=E;u<=c;u+=1)w.push(o.line(u).text);return w},r=s(t.start+1,t.separator-1),l=s(t.separator+1,t.end-1),i=n==="ours"?r:n==="theirs"?l:[...r,...l];let f=o.line(t.start).from,d=o.line(t.end).to;i.length===0&&(t.end<o.lines?d+=1:t.start>1&&(f-=1));const x=i.join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),m=require("react"),b=require("./index-AfEbgYQI.cjs"),Z=require("@aiquants/markdown/code-blocks"),J=require("@codemirror/commands"),we=require("@codemirror/lang-markdown"),ie=require("@codemirror/language"),Ee=require("@codemirror/search"),K=require("@codemirror/state"),_=require("@codemirror/view"),D=require("@lezer/highlight"),Ge=require("@aiquants/markdown"),me=require("@aiquants/markdown/source-lines"),ne=require("./ownUrls-BTPGNhBt.cjs"),pe=require("./sanitizePolicy-C-ehd0J_.cjs"),We=require("isomorphic-dompurify"),$=require("./location-Csj3eAm_.cjs"),Xe=require("./describeValue-Ccvhbt36.cjs"),ce=require("@aiquants/resize-panels"),be=require("./useSplitPersistence-C6s7a4Iu.cjs"),Pe={history:J.historyField},$e=ie.HighlightStyle.define([{tag:[D.tags.heading1,D.tags.heading2,D.tags.heading3,D.tags.heading4,D.tags.heading5,D.tags.heading6,D.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:D.tags.strong,fontWeight:"700"},{tag:D.tags.emphasis,fontStyle:"italic"},{tag:D.tags.strikethrough,textDecoration:"line-through"},{tag:D.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:D.tags.url,color:"var(--aqmx-syntax-url)"},{tag:D.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:D.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[D.tags.processingInstruction,D.tags.contentSeparator,D.tags.labelName,D.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ke=_.EditorView.theme({"&":{height:"100%",color:"var(--aqmx-text)",backgroundColor:"var(--aqmx-surface)",fontSize:"var(--aqmx-font-size-title)"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',lineHeight:"var(--aqmx-line-height-prose)"},".cm-content":{caretColor:"var(--aqmx-text)",paddingBlock:"var(--aqmx-space-6)"},".cm-line":{paddingInline:"var(--aqmx-space-6)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--aqmx-text)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--aqmx-editor-selection)"},".cm-activeLine":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-gutters":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-editor-gutter)",borderInlineEnd:"var(--aqmx-space-1) solid var(--aqmx-border)"},".cm-activeLineGutter":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-searchMatch":{outline:"var(--aqmx-space-1) solid var(--aqmx-border-strong)"},".cm-panels":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-text)"}}),Ne="data-aqmx-conflict-actions",Ye=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Je=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),Qe=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class Ze extends _.WidgetType{constructor(t,n){super(),this.index=t,this.labels=n}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const n=document.createElement("div");n.setAttribute(Ne,String(this.index));for(const[o,s]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const r=document.createElement("button");r.type="button",r.textContent=s,r.setAttribute("data-aqmx-conflict-choice",o),r.addEventListener("mousedown",l=>l.preventDefault()),r.addEventListener("click",()=>{const l=se(t.state.doc)[this.index];l!==void 0&&(De(t,l,o),t.focus())}),n.append(r)}return n}ignoreEvent(){return!0}}const se=e=>b.findConflictsInLines(e.iterLines()),xe=(e,t)=>{const n=new K.RangeSetBuilder;return se(e).forEach((o,s)=>{const r=e.line(o.start);n.add(r.from,r.from,_.Decoration.widget({widget:new Ze(s,t),block:!0,side:-1}));for(let l=o.start;l<=o.end;l+=1){const i=e.line(l).from,f=l===o.start||l===o.separator||l===o.end?Ye:l<o.separator?Je:Qe;n.add(i,i,f)}}),n.finish()},et=e=>K.StateField.define({create:t=>xe(t.doc,e),update:(t,n)=>n.docChanged?xe(n.state.doc,e):t,provide:t=>_.EditorView.decorations.from(t)}),De=(e,t,n)=>{const{doc:o}=e.state,s=(E,c)=>{const w=[];for(let u=E;u<=c;u+=1)w.push(o.line(u).text);return w},r=s(t.start+1,t.separator-1),l=s(t.separator+1,t.end-1),i=n==="ours"?r:n==="theirs"?l:[...r,...l];let f=o.line(t.start).from,d=o.line(t.end).to;i.length===0&&(t.end<o.lines?d+=1:t.start>1&&(f-=1));const x=i.join(`
2
2
  `);e.dispatch({changes:{from:f,to:d,insert:x},selection:K.EditorSelection.cursor(f),scrollIntoView:!0,userEvent:"input.resolve"})},Se="input.preview",tt=20,nt=_.ViewPlugin.fromClass(class{constructor(e){this.view=e,this.schedule()}view;cancel=null;update(e){e.docChanged&&this.schedule()}schedule(){if(this.cancel!==null||ie.syntaxTreeAvailable(this.view.state))return;const e=this.view.dom.ownerDocument.defaultView;if(e===null)return;const t=()=>{this.cancel=null,ie.ensureSyntaxTree(this.view.state,this.view.state.doc.length,tt),this.schedule()};if(typeof e.requestIdleCallback=="function"){const n=e.requestIdleCallback(t);this.cancel=()=>e.cancelIdleCallback(n)}else{const n=e.setTimeout(t,0);this.cancel=()=>e.clearTimeout(n)}}destroy(){this.cancel?.(),this.cancel=null}}),rt=/`{3,}|~{3,}/u,re=Object.freeze({kind:"absent"}),de=Object.freeze({kind:"unreadable"}),ot=(e,t,n)=>{const o=[];for(let f=t.parent;f!==null;f=f.parent)(f.name==="Blockquote"||f.name==="ListItem")&&o.unshift(f);const s=[],r=[],l=f=>{const d=r.indexOf(f);return d===-1?r.length:d};for(const f of o){const d=e.lineAt(f.from).number;if(f.name==="ListItem"){const x=Z.listItemWidthOn(e.line(d).text,s,l(d));if(x===null)return null;s.push({kind:"listItem",width:x})}else s.push({kind:"quote"});r.push(d)}const i=Z.openingFenceOn(n.text,s,l(n.number));return i===null?null:{containers:s,...i}},st=(e,t)=>{const{doc:n}=e;let o=n.lineAt(t).to;for(;;){const s=ie.ensureSyntaxTree(e,o,Number.POSITIVE_INFINITY);if(s===null)return null;const r=s.resolveInner(t,1),l=r.parent;if(r.name!=="CodeMark"||l===null||l.name!=="FencedCode"||l.from!==r.from)return null;if(l.to<o||o>=n.length)return l;o=Math.min(n.length,l.to+Math.max(l.to-t,1))}},ye=(e,t)=>{const{doc:n}=e;if(!Number.isInteger(t)||t<1||t>n.lines)return re;const o=n.line(t),s=rt.exec(o.text);if(s===null)return re;const r=st(e,o.from+s.index);if(r===null)return re;const l=r.getChild("CodeInfo");if(l===null)return re;const i=Z.fencedCodeLanguageOf(n.sliceString(l.from,l.to));if(i===null)return de;if(i!==Z.SPREADSHEETS_LANGUAGE)return re;const f=ot(n,r,o);if(f===null)return de;const[,...d]=r.getChildren("CodeMark"),x=d.at(-1),E=x===void 0?n.lineAt(r.to).number:n.lineAt(x.from).number-1,c=[];let w="";for(let u=t+1;u<=E;u+=1){const p=n.line(u).text,g=Z.readFencedLine(p,f);if(g===null)return de;c.push(p),w+=u<n.lines?`${g.content}
3
3
  `:g.content}return{kind:"found",firstLine:t+1,lines:c,layout:f,body:w}},it=({parent:e,scroll:t,text:n,saved:o,labels:s,revisions:r,onChange:l,onGeometry:i,onSave:f})=>{let d=!1;const x=[_.EditorView.scrollHandler.of((u,p,g)=>(lt(u,p.head,g,t),!0)),_.lineNumbers(),_.highlightActiveLineGutter(),J.history(),_.drawSelection(),_.highlightActiveLine(),Ee.highlightSelectionMatches(),_.EditorView.lineWrapping,we.markdown({base:we.markdownLanguage}),nt,ie.syntaxHighlighting($e),et(s),_.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(f(),!0)},...Ee.searchKeymap,...J.historyKeymap,...J.defaultKeymap]),_.EditorView.contentAttributes.of({"aria-label":s.editor,"aria-multiline":"true"}),_.EditorView.updateListener.of(u=>{for(const p of u.transactions)p.docChanged&&r.record(p.changes,p.newDoc);u.docChanged&&l(u.transactions.every(p=>!p.docChanged||p.isUserEvent(Se))),(u.docChanged||u.heightChanged||u.geometryChanged)&&i(u.docChanged&&!d)}),Ke],E=ut(o,x)??K.EditorState.create({doc:n,extensions:x}),c=new _.EditorView({state:E,parent:e});r.mount(c.state.doc);const w=u=>{d=!0;try{u()}finally{d=!1}};return{text:()=>c.state.doc.toString(),replaceText:u=>{const p=c.state.doc.toString();if(p===u)return;let g=0;const y=Math.min(p.length,u.length);for(;g<y&&p.charCodeAt(g)===u.charCodeAt(g);)g+=1;let h=0;for(;h<y-g&&p.charCodeAt(p.length-1-h)===u.charCodeAt(u.length-1-h);)h+=1;c.dispatch({changes:{from:g,to:p.length-h,insert:u.slice(g,u.length-h)},userEvent:"input.replace"})},replaceBody:(u,p,g,y)=>{const{doc:h}=c.state,T=r.lineOf(y,u);if(T===null)return"changed";const O=ye(c.state,T);if(O.kind==="absent")return"changed";if(O.kind==="unreadable")return"unwritable";if(O.body!==Z.fencedBodyAsRead(p,O.layout))return"changed";const L=Z.planFencedBodyEdit(O.lines,O.layout,g);if(L.kind!=="edit")return L.kind;if(L.from===L.to&&L.lines.length===0)return"written";const N=F=>{const j=O.firstLine+F;return j<=h.lines?h.line(j).from:h.length},M=N(L.from),B=`${M===h.length&&h.sliceString(h.length-1)!==`
4
4
  `?`
5
5
  `:""}${L.lines.map(F=>`${F}
6
- `).join("")}`;return w(()=>c.dispatch({changes:{from:M,to:N(L.to),insert:B},userEvent:Se,annotations:J.isolateHistory.of("full")})),"written"},readBody:(u,p)=>{const g=r.lineOf(p,u);if(g===null)return null;const y=ye(c.state,g);return y.kind==="found"?y.body:null},undo:()=>w(()=>J.undo(c)),redo:()=>w(()=>J.redo(c)),reveal:({line:u,column:p},g)=>{const{doc:y}=c.state,h=y.line(Math.min(Math.max(u,1),y.lines)),T=Math.min(h.from+p,h.to);c.dispatch({selection:K.EditorSelection.cursor(T),effects:Te(c,T,g,t)})},showLine:u=>{const{doc:p}=c.state,g=p.line(Math.min(Math.max(u,1),p.lines)).from;c.dispatch({effects:Te(c,g,null,t)})},topLine:()=>{const u=t.scrollerOf(c.scrollDOM),p=b.visibleTopOf(u,c.contentDOM),g=b.frameTopOf(u)+u.clientHeight,{documentTop:y}=c,{doc:h}=c.state;let T=c.lineBlockAtHeight(Math.max(p-y,0));for(;h.lineAt(T.from).text.trim()===""&&T.to<h.length;){const N=c.lineBlockAt(T.to+1);if(y+N.top>=g)break;T=N}const O=c.coordsAtPos(T.from),L=O===null?y+T.top:O.top;return{line:c.state.doc.lineAt(T.from).number,clientTop:L,offset:L-p}},lineSpans:u=>{const p=c.scrollDOM,g=p.scrollTop+c.documentTop-b.visibleTopOf(p,c.contentDOM),{doc:y}=c.state,h=T=>y.line(Math.min(Math.max(T,1),y.lines)).from;return u.map(({first:T,last:O})=>({top:g+c.lineBlockAt(h(T)).top,bottom:g+c.lineBlockAt(h(O)).bottom}))},scrollElement:c.scrollDOM,focus:()=>c.focus(),conflicts:()=>se(c.state.doc),resolveAtCursor:u=>{const p=se(c.state.doc),g=c.state.doc.lineAt(c.state.selection.main.head).number,y=p.find(h=>h.end>=g);return y===void 0?!1:(De(c,y,u),!0)},nextConflict:()=>{const u=se(c.state.doc);if(u[0]===void 0)return!1;const g=c.state.doc.lineAt(c.state.selection.main.head).number,y=u.findIndex(L=>L.start>g),h=y<0?0:y,T=c.state.doc.line(u[h].start).from;c.dispatch({selection:K.EditorSelection.cursor(T),effects:_.EditorView.scrollIntoView(T,{y:"center"})});const O=c.contentDOM.querySelector(`[${Ne}="${String(h)}"] button`);return O instanceof HTMLElement?O.focus({preventScroll:!0}):c.focus(),!0},save:()=>c.state.toJSON(Pe),destroy:()=>c.destroy()}},Te=(e,t,n,o)=>{const s=o.scrollerOf(e.scrollDOM),r=(n===null?b.visibleTopOf(s,e.contentDOM):n)-b.frameTopOf(s);return _.EditorView.scrollIntoView(t,{y:"start",yMargin:r})},lt=(e,t,n,o)=>{const s=ct(e,t),r=o.scrollerOf(e.scrollDOM),l=b.frameTopOf(r),i=b.visibleTopOf(r,e.contentDOM),f=l+r.clientHeight;let d=0;switch(n.y){case"start":d=s.top-(l+n.yMargin);break;case"center":d=(s.top+s.bottom)/2-(i+f)/2;break;case"end":d=s.bottom-(f-n.yMargin);break;default: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)))}if(d!==0&&(r.scrollTop+=d),n.y==="start")return;const x=at(e,t);x!==null&&o.reveal(x)},ct=(e,t)=>{const{node:n,offset:o}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,o),l.setEnd(n,o);const[i]=l.getClientRects();if(i!==void 0&&i.height>0)return{top:i.top,bottom:i.bottom}}}const s=e.lineBlockAt(t),r=e.documentTop+s.top;return{top:r,bottom:r+s.height}},at=(e,t)=>{const{node:n}=e.domAtPos(t);for(let o=n instanceof Element?n:n.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},ut=(e,t)=>{if(e==null)return null;try{return K.EditorState.fromJSON(e,{extensions:t},Pe)}catch{return null}},dt=610,ft=987,ke=Object.freeze({kind:"unavailable"}),mt="true",pt="false",ht=e=>e===mt?!0:e===pt?!1:null,gt=e=>{const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const s=o.localName==="img",r=o.getAttribute(s?"data-asset-src":"data-doc-path");r!==null&&n.push({target:{kind:s?"asset":"doc",path:r},exists:ht(o.getAttribute(s?"data-asset-exists":"data-doc-exists"))})}return n},vt=({path:e,instant:t,preview:n,initial:o,onView:s})=>{const r=new AbortController,l={asset:new Map,doc:new Map};let i=o,f=null,d=!1,x=!1,E=null,c=null,w=[],u,p=!1,g,y=null;const h=v=>{v.parsed===i.parsed&&v.source===i.source&&v.failure===i.failure&&v.busy===i.busy&&v.tier===i.tier||(i=v,s(v))},T=(v,S)=>{d||(d=!0,console.error(`[markdown-explorer] ${v}`,...S===void 0?[]:[S]))},O=v=>{if(t!==null)for(const{target:S,exists:C}of t.marksOf(v))l[S.kind].set(S.path,C)},L=()=>{clearTimeout(g),g=void 0,y?.abort(),y=null},N=()=>{c=null,w=[],clearTimeout(u),u=void 0},M=(v,S)=>{h({...i,failure:v,busy:!1,tier:S})},U=()=>{clearTimeout(u),u=w.length===0?void 0:setTimeout(F,ft)},B=()=>{if(t===null||c===null)return;const v=c,S=[],C={asset:new Set,doc:new Set};let G;try{G=t.sanitize(v.html,z=>{const le=l[z.kind].get(z.path);return le===void 0&&!C[z.kind].has(z.path)&&(C[z.kind].add(z.path),S.push(z)),le??void 0})}catch(z){N(),z instanceof pe.HtmlNestingLimitError?M(ne.failureOf("too-large"),"instant"):(T("the draft sanitizer failed",z),M(ne.failureOf("failed"),"instant"));return}w=S;const Y=i.parsed!==null&&i.parsed.htmlContent===G&&i.parsed.headings===v.headings?i.parsed:{htmlContent:G,headings:v.headings};h({parsed:Y,source:v.draft,failure:null,busy:!1,tier:"instant"}),U()},F=()=>{if(u=void 0,p||c===null||w.length===0)return;p=!0;const v=w;n(e,c.draft.text,r.signal).then(S=>{if(p=!1,!(r.signal.aborted||!("kind"in S))){S.kind==="preview"&&O(S.htmlContent);for(const C of v)l[C.kind].has(C.path)||l[C.kind].set(C.path,null);B()}})},j=v=>{L(),N(),h({...i,busy:!0,tier:"server"});const S=new AbortController;y=S,g=setTimeout(()=>{g=void 0,n(e,v.text,S.signal).then(C=>{if(!(S.signal.aborted||!("kind"in C))){if(y=null,C.kind==="failure"){M(C.failure,"server");return}O(C.htmlContent),h({parsed:{htmlContent:C.htmlContent,headings:C.headings},source:v,failure:null,busy:!1,tier:"server"})}})},dt)},a=async(v,S)=>{let C;try{C=await v.convert({path:e,text:S},r.signal)}catch(Y){return r.signal.aborted||T("the draft converter rejected a conversion, which its contract allows only once the signal aborted",Y),ke}const G=ne.draftAnswerViolation(C);return G===null?C:(T(`the draft converter answered outside its contract: ${G}`),ke)},A=(v,S)=>{switch(S.kind){case"preview":if(L(),S.headings.length>ne.EXPLORER_MAX_HEADINGS){N(),M(ne.failureOf("too-large"),"instant");return}c={draft:v,html:S.htmlContent,headings:S.headings.map(({text:C,depth:G,id:Y})=>({text:C,depth:G,id:Y}))},B();return;case"failure":L(),N(),M(ne.failureOf(S.failure.reason,S.failure.code),"instant");return;case"unavailable":j(v);return}},I=async v=>{x=!0;try{for(;E!==null&&!r.signal.aborted;){const S=E;E=null;const C=await a(v,S.text);if(r.signal.aborted)return;A(S,C)}}finally{x=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:v=>{if(!(r.signal.aborted||v.text===f?.text)){if(f=v,clearTimeout(u),u=void 0,t===null){j(v);return}E=v,x||I(t.converter)}},dispose:()=>{r.abort(),E=null,clearTimeout(u),u=void 0,L()}}},wt=e=>pe.createHtmlSanitizer(We(window),e.iframeHosts,e.dataPath,pe.MAX_HTML_NESTING_DEPTH,X.ownUrlsOf(e)),Et=(e,t)=>e.flatMap((n,o)=>{const s=t[o];return s===void 0?[]:[{editor:s.top,preview:n.top},{editor:s.bottom,preview:n.bottom}]}),Q=(e,t)=>{const n=e[t];if(n===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${Xe.describeValue(t)}`);return n},bt=e=>{const t=[];for(const o of e){let s=0,r=t.length;for(;s<r;){const l=s+r>>1;Q(t,l).pair.preview<=o.preview?s=l+1:r=l}t[s]={pair:o,before:s===0?void 0:Q(t,s-1)}}const n=[];for(let o=t.at(-1);o!==void 0;o=o.before)n.push(o.pair);return n.reverse()},xt=(e,t)=>{const n=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),s=n-t.editorViewport,r=o-t.previewViewport,l=e.filter(d=>d.editor>0&&d.editor<s&&d.preview>0&&d.preview<r).sort((d,x)=>d.editor-x.editor||d.preview-x.preview);let i={editor:0,preview:0};const f=[i];for(const d of bt(l))d.editor>i.editor&&d.preview>i.preview&&(f.push(d),i=d);return f.push({editor:n,preview:o}),{toPreview:d=>Le(f,"editor","preview",d),toEditor:d=>Le(f,"preview","editor",d)}},Le=(e,t,n,o)=>{const s=Q(e,0),r=Q(e,e.length-1);if(Number.isNaN(o)||o<=s[t])return s[n];if(o>=r[t])return r[n];let l=0,i=e.length-1;for(;i-l>1;){const x=l+i>>1;Q(e,x)[t]<=o?l=x:i=x}const f=Q(e,l),d=Q(e,i);return f[n]+(d[n]-f[n])*(o-f[t])/(d[t]-f[t])},St=610,Ae=89,Ie=.5,yt=({editor:e,preview:t,previewBlocks:n,editorSpans:o,requestFrame:s,cancelFrame:r,now:l})=>{let i="editor",f=0,d=null,x=null,E=!1,c=null,w=null;const u={editor:0,preview:0},p={editor:null,preview:null};let g=null,y=()=>{};const h=a=>{d!==null&&a!==d||(i=a,f=l()+St)},T=(a,A)=>{a!==i&&d===null&&l()>=f&&!O(a,A)&&(i=a),B()},O=(a,A)=>{const I=p[a];return l()<u[a]||I!==null&&Math.abs(A.position()-I)<Ie},L=e.onScroll(()=>T("editor",e)),N=e.onIntent(()=>h("editor")),M=()=>{const a=t();return a!==g&&(y(),g=a,y=a===null?()=>{}:U(a)),a},U=a=>{const A=a.onScroll(()=>T("preview",a)),I=a.onIntent(()=>h("preview"));return()=>{A(),I()}},B=()=>{!E&&x===null&&(x=s(F))},F=()=>{x=null;const a=M();a!==null&&(c??=n(),w??=xt(Et(c,o(c)),{editorMax:e.max(),previewMax:a.max(),editorViewport:e.viewport(),previewViewport:a.viewport()}),i==="editor"?j(a,"preview",w.toPreview(e.position())):j(e,"editor",w.toEditor(a.position())))},j=(a,A,I)=>{if(Math.abs(a.position()-I)<Ie){p[A]=a.position();return}u[A]=l()+Ae,p[A]=a.scrollTo(I)};return B(),{editorChanged:a=>{w=null,a&&h("editor"),B()},previewChanged:()=>{c=null,w=null,u.preview=l()+Ae,B()},showAlone:a=>{d=a,!(a===null||a===i)&&(i=a,f=0,B())},dispose:()=>{E=!0,x!==null&&r(x),x=null,L(),N(),y()}}},Oe=Object.freeze(["wheel","pointerdown","keydown","focusin"]),Ve=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const n of Oe)e.addEventListener(n,t,{capture:!0,passive:!0});return()=>{for(const n of Oe)e.removeEventListener(n,t,{capture:!0})}}}),oe="[data-aqmd-scroll-container]",Tt="[data-aqmd-content]",kt=`[${me.SOURCE_LINES_ATTRIBUTE}]`,Lt=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Be=(e,t)=>{const n=b.loadedOf(e.peek(t));return n!==null&&n.document.kind==="markdown"?{htmlContent:n.document.htmlContent,headings:n.document.headings}:null},At=(e,t,n,o)=>{if(t===void 0)return null;let s;try{s=wt(e)}catch(r){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",r),null}return{converter:t,sanitize:s,marksOf:gt,seed:Be(n,o)?.htmlContent??null}},It=e=>{const t=[];let n=null;for(const o of e.querySelectorAll(kt)){const s=me.parseSourceLines(o.getAttribute(me.SOURCE_LINES_ATTRIBUTE));if(s===null||o.getClientRects().length===0)continue;n??=e.scrollTop-b.visibleTopOf(e,o);const{top:r,bottom:l}=o.getBoundingClientRect();t.push({first:s.first,last:s.last,top:n+r,bottom:n+l})}return t},Ot=({path:e,readDraft:t,viewer:n,tables:o,concealed:s,onEditAt:r,onLayout:l,handleRef:i})=>{const{config:f,data:d,documents:x,draftConverter:E,labels:c}=b.useExplorer(),[w,u]=m.useState(()=>({parsed:Be(x,e),source:null,failure:null,busy:!0,tier:E===void 0?"server":"instant"})),p=m.useRef(null),g=m.useRef(null),y=m.useRef(w);m.useLayoutEffect(()=>{y.current=w});const h=m.useEffectEvent(()=>t());m.useEffect(()=>{const a=At(f,E,x,e),A=h(),I=vt({path:e,instant:a,preview:d.preview,initial:y.current,onView:v=>m.startTransition(()=>u(v))});return g.current=I,I.update(A),()=>{I.dispose(),g.current=null}},[f,d,x,E,e]);const T=m.useEffectEvent(()=>l());m.useLayoutEffect(()=>{w.parsed!==null&&T()},[w.parsed]);const O=w.parsed!==null;m.useLayoutEffect(()=>{const a=O?p.current?.querySelector(oe):null;if(!(a instanceof HTMLElement))return;a.tabIndex=0;const A=new ResizeObserver(()=>T());A.observe(a);const I=a.querySelector(Tt);return I!==null&&A.observe(I),()=>A.disconnect()},[O]);const L=m.useRef(null);m.useImperativeHandle(i,()=>({draft:a=>{g.current?.update(a)},scrollPort:()=>{const a=p.current?.querySelector(oe);return a instanceof HTMLElement?(L.current?.scroller!==a&&(L.current={scroller:a,port:Ve(a)}),L.current.port):null},blocks:()=>{const a=p.current?.querySelector(oe);return a instanceof HTMLElement?It(a):[]},focus:()=>{const a=p.current?.querySelector(oe);a instanceof HTMLElement&&a.focus({preventScroll:!0})},anchor:a=>{const A=p.current,I=A?.querySelector(oe);return A===null||!(I instanceof HTMLElement)?null:b.anchorOfView(A,a(I))},place:({line:a,clientTop:A},I)=>{const v=p.current,S=v===null?null:b.blockAtLine(v,a);S!==null&&(I(S).scrollTop+=b.lineTopIn(S,a)-A)}}),[]);const N=a=>{const A=p.current,{target:I}=a;if(r===void 0||A===null||!(I instanceof Element)||!b.isEditingDoubleClick(I))return;const v=b.anchorOfDoubleClick(I,A,A.ownerDocument.getSelection());v!==null&&r(v)},M=w.source===null?null:w.source.revision,U=m.useMemo(()=>M===null?void 0:{write:a=>o.write(M,a),read:a=>o.read(M,a),undo:o.undo,redo:o.redo,subscribe:o.subscribe},[o,M]),B=m.useMemo(()=>({...n.labels,spreadsheetReadOnly:c.previewTablePending}),[n.labels,c.previewTablePending]),F=m.useMemo(()=>({...n,labels:U===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,showMeasure:!1,showContentColors:!1,renderScrollBar:void 0,scrollBarGutter:void 0,scrollBarInlineSize:void 0,spreadsheetEditor:U}),[n,B,U]),j=m.useMemo(()=>w.parsed===null?null:q.jsx("div",{className:"aqmx-document-viewer",children:q.jsx(Ge.MarkdownViewer,{...F,parseResult:w.parsed,content:null})}),[F,w.parsed]);return q.jsxs("section",{ref:p,className:"aqmx-edit-preview","aria-label":c.previewRegion,"aria-busy":w.busy,inert:s!==null,hidden:s==="removed","data-aqmx-preview-tier":w.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:r===void 0?void 0:N,children:[w.failure===null?null:q.jsx(Rt,{failure:w.failure}),j??(w.failure===null?q.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:Lt.map(a=>q.jsx("span",{},a))}):null),w.busy?q.jsx("p",{className:"aqmx-sr-only",children:c.previewUpdating}):null]})},Rt=({failure:e})=>{const{labels:t}=b.useExplorer(),{reason:n}=e;return b.isAccessFailureReason(n)?q.jsx(b.AccessFailureNotice,{failure:e,place:"read",deniedSentence:null,retry:null,testId:"markdown-explorer-edit-preview-failure"}):q.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:t.previewFailed(b.failureTitleOf(t,n))})},Re="data-aqmx-edit-split",fe="--aqmx-edit-share",qe="--aqmx-edit-gutter",qt="data-aqmx-edit-split-probe",Ct="aqmx-edit-split",Mt="aqmx-edit-editor",_t="aqmx-edit-preview",Ce={value:X.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},Me={value:X.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},_e=e=>{if(e.length!==2)return null;const[t=0,n=0]=e,o=t+n;return o>0?t/o*100:null},ae=e=>{const t=e.current?.parentElement;if(t==null)throw new Error("[markdown-explorer] the edit split is not mounted in its surface");return t},Pt=(e,t,n)=>{const[o,s]=m.useState(null);return m.useLayoutEffect(()=>{const r=e.current,l=t.current;if(r===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const i={frame:r.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},f=()=>{i.frame>0&&i.measure>0&&s(X.editSplitOrientation(i.frame,i.measure,n))};f();const d=new ResizeObserver(x=>{for(const E of x){const[c]=E.borderBoxSize;c!==void 0&&(E.target===r&&(i.frame=c.inlineSize),E.target===l&&(i.measure=c.inlineSize))}f()});return d.observe(r),d.observe(l),()=>d.disconnect()},[e,t,n]),o},Nt=({editorId:e})=>{const{edits:t,labels:n}=b.useExplorer(),o=m.useMemo(()=>be.toPanelGroupLabels(n),[n]),s=m.useRef(null),r=m.useRef(null),l=b.useCoarsePointer()?X.COARSE_TARGET_PIXELS:X.FINE_TARGET_PIXELS,i=Pt(s,r,l),[f]=m.useState(()=>t.editorShare());m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(qe,`${String(l)}px`),()=>{E.style.removeProperty(qe)}},[l]),m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(fe,`${String(f)}%`),()=>{E.style.removeProperty(fe)}},[f]),m.useLayoutEffect(()=>{if(i===null)return;const E=ae(s);return E.setAttribute(Re,i),()=>E.removeAttribute(Re)},[i]);const d=be.useSplitPersistence(m.useCallback(E=>{const c=_e(E);c!==null&&t.setEditorShare(c)},[t])),x=m.useCallback((E,c)=>{const w=_e(E);w!==null&&ae(s).style.setProperty(fe,`${String(w)}%`),d.layoutChanged(E,c)},[d]);return q.jsxs("div",{ref:s,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[q.jsx("span",{ref:r,className:"aqmx-edit-split-probe","aria-hidden":"true",[qt]:""}),i===null?null:q.jsxs(ce.PanelGroup,{id:Ct,direction:i==="beside"?"horizontal":"vertical",onLayout:x,labels:o,className:"aqmx-edit-split-group",children:[q.jsx(ce.Panel,{id:Mt,defaultSize:{value:f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"}),q.jsx(ce.PanelResizeHandle,{thickness:l,indicator:{visible:!0,thickness:X.SPLIT_HANDLE_PIXELS.gripThickness,length:X.SPLIT_HANDLE_PIXELS.gripLength,barThickness:X.SPLIT_HANDLE_PIXELS.barThickness,barLength:X.SPLIT_HANDLE_PIXELS.barLength},title:n.editViewSplitResize,"aria-label":n.editViewSplitResize,"aria-controls":e,onDragging:d.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),q.jsx(ce.Panel,{id:_t,defaultSize:{value:100-f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"})]})]})},Dt=512,Vt=()=>{const e=[];let t=0,n=null;const o=s=>{if(n===null||!Number.isInteger(s)||s<t)return null;if(s===t+e.length)return n;const r=e[s-t];return r===void 0?null:r.before};return{revision:()=>t+e.length,mount:s=>{if(n!==null&&(n===s||n.eq(s))){n=s;return}const r=t+e.length;e.length=0,t=n===null?r:r+1,n=s},record:(s,r)=>{if(n===null)throw new Error("[markdown-explorer] a change of the editor's text was recorded before an editor mounted");e.push({before:n,changes:s}),n=r,e.length>Dt&&(e.shift(),t+=1)},lineOf:(s,r)=>{const l=o(s);if(l===null||n===null||!Number.isInteger(r)||r<1||r>l.lines)return null;let i=l.line(r).from;for(const f of e.slice(s-t)){const d=f.changes.mapPos(i,1,K.MapMode.TrackAfter);if(d===null)return null;i=d}return n.lineAt(i).number}}},je=144,Bt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:n}=e;return"state"in e&&typeof t=="number"&&typeof n=="number"},jt=e=>{e.stopPropagation()},Ht=e=>{const{path:t,name:n,session:o}=e,{edits:s,labels:r,announcer:l}=b.useExplorer(),{phase:i}=o,f=m.useCallback(()=>s.retry(t),[s,t]);switch(m.useEffect(()=>{if(i.kind!=="failed")return;const{reason:d}=i.failure;b.isAccessFailureReason(d)||l.announce(r.documentFailed(n,b.failureTitleOf(r,d)))},[i,l,r,n]),i.kind){case"opening":return q.jsx(b.ContentSkeleton,{label:r.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(b.EditGrantNotice,{href:i.href,onRetry:f,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(b.FailureView,{failure:i.failure,alert:!1,onRetry:f,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Ft,{...e})}},Ft=({path:e,name:t,session:n,layout:o,viewer:s,region:r,paneScroll:l})=>{const{edits:i,labels:f}=b.useExplorer(),d=m.useRef(null),x=m.useId(),E=m.useRef(null),[c]=m.useState(()=>new Set),[w]=m.useState(Vt),u=m.useRef(null),p=m.useRef(null),g=o==="fill",y=b.useSideBySide(),h=b.editViewOf(n,y,g),T=h!=="editor"||n.previewPrepared,O=T&&g,L=m.useRef({layout:o,region:r,paneScroll:l});m.useLayoutEffect(()=>{L.current={layout:o,region:r,paneScroll:l}});const N=m.useRef(n.generation);m.useLayoutEffect(()=>{N.current=n.generation});const M=m.useRef({view:h,previewMounted:T});m.useLayoutEffect(()=>{M.current={view:h,previewMounted:T}});const{requestSave:U,confirmation:B}=b.useSaveRequest(e),F=m.useRef(U);m.useLayoutEffect(()=>{F.current=U});const j=m.useRef(null),a=m.useRef(null),A=m.useRef(!1),I=m.useMemo(()=>({editor:f.editorLabel(t),useOurs:f.conflictUseOurs,useTheirs:f.conflictUseTheirs,keepBoth:f.conflictKeepBoth}),[f,t]),v=m.useCallback(k=>{const{region:R,paneScroll:V}=L.current,H=R();return H===null?k:V.scrollerOf(H,k)},[]);m.useLayoutEffect(()=>{const k=d.current,R=i.draft(e);if(k===null||R===null)return;const V=i.editorState.get(e),H=Bt(V)&&V.generation===N.current?V:null;let $=null,ee=null;const ue=()=>{$!==null&&clearTimeout($),$=null,ee!==null&&i.setDraft(e,ee.text())},W=it({parent:k,scroll:{scrollerOf:P=>{const{layout:te,region:ze,paneScroll:Ue}=L.current,ve=ze();return te==="fill"||ve===null?P:Ue.scrollerOf(ve,P)},reveal:P=>L.current.paneScroll.reveal(P)},text:R,saved:H===null?void 0:H.state,labels:I,revisions:w,onGeometry:P=>p.current?.editorChanged(P),onChange:P=>{if($??=setTimeout(ue,je),!P)for(const te of[...c])te();M.current.previewMounted&&ee!==null&&u.current?.draft({text:ee.text(),revision:w.revision()})},onSave:()=>F.current()});ee=W,E.current=W;const he=()=>{const P=W.topLine();return{line:P.line,clientTop:P.clientTop}},ge=()=>u.current?.anchor(v)??null,Fe=i.bindEditor(e,{flush:ue,adopt:P=>W.replaceText(P),returnPoint:()=>{const P=M.current.view==="preview"&&L.current.layout==="content"?ge():null;return P===null?he():{line:P.lines.first,clientTop:P.clientTop}},nextConflict:()=>M.current.view!=="preview"?W.nextConflict():W.conflicts().length===0?!1:(A.current=!0,i.setView(e,"editor"),!0),beforeView:P=>{if(L.current.layout==="fill")return;if(P==="preview"){j.current={to:"preview",point:he()};return}const te=ge();j.current=te===null?null:{to:"editor",anchor:te}}});return H!==null&&W.showLine(H.topLine),()=>{ue(),i.editorState.set(e,{state:W.save(),generation:N.current,topLine:W.topLine().line}),Fe(),W.destroy(),ee=null,E.current=null}},[i,e,I,v,c,w]);const{request:S}=n;m.useLayoutEffect(()=>{const k=E.current,R=i.draft(e);k===null||R===null||S===null||(S.anchor!==null&&k.reveal(b.positionInSource(R,S.anchor),S.anchor.clientTop),k.focus(),i.consumeRequest(e))},[i,e,S,I]),m.useLayoutEffect(()=>{h!=="editor"&&!n.previewPrepared&&i.preparePreview(e)},[i,e,h,n.previewPrepared]),m.useLayoutEffect(()=>{const k=j.current,R=a.current,V=A.current;j.current=null,a.current=null,A.current=!1;const H=E.current;if(k?.to==="preview")u.current?.place(k.point,v);else if(k?.to==="editor"&&H!==null){const $=i.draft(e);$!==null&&H.reveal(b.positionInSource($,k.anchor),k.anchor.clientTop)}V?H?.nextConflict():R==="editor"?H?.focus():R==="preview"&&u.current?.focus()},[i,e,h,v]);const C=m.useMemo(()=>{const k=()=>{const R=E.current;if(R===null)throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");return R};return{write:(R,{fenceLine:V,expected:H,text:$})=>k().replaceBody(V,H,$,R),read:(R,V)=>k().readBody(V,R),undo:()=>k().undo(),redo:()=>k().redo(),subscribe:R=>(c.add(R),()=>{c.delete(R)})}},[c]),G=m.useCallback(()=>{const k=E.current;if(k===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return{text:k.text(),revision:w.revision()}},[w]);m.useLayoutEffect(()=>{const k=E.current;if(!O||k===null)return;const R=yt({editor:Ve(k.scrollElement),preview:()=>u.current?.scrollPort()??null,previewBlocks:()=>u.current?.blocks()??[],editorSpans:V=>k.lineSpans(V),requestFrame:V=>requestAnimationFrame(V),cancelFrame:V=>cancelAnimationFrame(V),now:()=>performance.now()});return R.showAlone(b.paneShownAlone(M.current.view)),p.current=R,()=>{R.dispose(),p.current=null}},[O,i,e,I]),m.useLayoutEffect(()=>{p.current?.showAlone(b.paneShownAlone(h))},[h]);const Y=m.useCallback(()=>p.current?.previewChanged(),[]),z=m.useCallback(k=>i.start(e,k),[i,e]),le=k=>{if(b.isInFullscreenBlock(k.target))return;if(k.key==="Escape"){b.consumeKey(k);return}if(!b.isEditViewShortcut(k.nativeEvent,b.isApplePlatform(navigator.platform)))return;b.consumeKey(k);const R=b.toggledEditView(h);a.current=R,b.chooseEditView(i,e,R,g)},He=q.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":h,"data-testid":"markdown-explorer-edit",onKeyDown:le,onDoubleClick:jt,children:[q.jsx("div",{ref:d,id:x,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:h==="preview",hidden:h==="preview"&&!g,...b.ALLOW_KEY_REPEAT}),h==="split"?q.jsx(Nt,{editorId:x}):null,T?q.jsx(Ot,{path:e,readDraft:G,viewer:s,tables:C,concealed:h!=="editor"?null:g?"overlay":"removed",onEditAt:h==="preview"?z:void 0,onLayout:Y,handleRef:u}):null]});return q.jsxs(q.Fragment,{children:[He,B]})};exports.DRAFT_WRITE_INTERVAL_MS=je;exports.default=Ht;
6
+ `).join("")}`;return w(()=>c.dispatch({changes:{from:M,to:N(L.to),insert:B},userEvent:Se,annotations:J.isolateHistory.of("full")})),"written"},readBody:(u,p)=>{const g=r.lineOf(p,u);if(g===null)return null;const y=ye(c.state,g);return y.kind==="found"?y.body:null},undo:()=>w(()=>J.undo(c)),redo:()=>w(()=>J.redo(c)),reveal:({line:u,column:p},g)=>{const{doc:y}=c.state,h=y.line(Math.min(Math.max(u,1),y.lines)),T=Math.min(h.from+p,h.to);c.dispatch({selection:K.EditorSelection.cursor(T),effects:Te(c,T,g,t)})},showLine:u=>{const{doc:p}=c.state,g=p.line(Math.min(Math.max(u,1),p.lines)).from;c.dispatch({effects:Te(c,g,null,t)})},topLine:()=>{const u=t.scrollerOf(c.scrollDOM),p=b.visibleTopOf(u,c.contentDOM),g=b.frameTopOf(u)+u.clientHeight,{documentTop:y}=c,{doc:h}=c.state;let T=c.lineBlockAtHeight(Math.max(p-y,0));for(;h.lineAt(T.from).text.trim()===""&&T.to<h.length;){const N=c.lineBlockAt(T.to+1);if(y+N.top>=g)break;T=N}const O=c.coordsAtPos(T.from),L=O===null?y+T.top:O.top;return{line:c.state.doc.lineAt(T.from).number,clientTop:L,offset:L-p}},lineSpans:u=>{const p=c.scrollDOM,g=p.scrollTop+c.documentTop-b.visibleTopOf(p,c.contentDOM),{doc:y}=c.state,h=T=>y.line(Math.min(Math.max(T,1),y.lines)).from;return u.map(({first:T,last:O})=>({top:g+c.lineBlockAt(h(T)).top,bottom:g+c.lineBlockAt(h(O)).bottom}))},scrollElement:c.scrollDOM,focus:()=>c.focus(),conflicts:()=>se(c.state.doc),resolveAtCursor:u=>{const p=se(c.state.doc),g=c.state.doc.lineAt(c.state.selection.main.head).number,y=p.find(h=>h.end>=g);return y===void 0?!1:(De(c,y,u),!0)},nextConflict:()=>{const u=se(c.state.doc);if(u[0]===void 0)return!1;const g=c.state.doc.lineAt(c.state.selection.main.head).number,y=u.findIndex(L=>L.start>g),h=y<0?0:y,T=c.state.doc.line(u[h].start).from;c.dispatch({selection:K.EditorSelection.cursor(T),effects:_.EditorView.scrollIntoView(T,{y:"center"})});const O=c.contentDOM.querySelector(`[${Ne}="${String(h)}"] button`);return O instanceof HTMLElement?O.focus({preventScroll:!0}):c.focus(),!0},save:()=>c.state.toJSON(Pe),destroy:()=>c.destroy()}},Te=(e,t,n,o)=>{const s=o.scrollerOf(e.scrollDOM),r=(n===null?b.visibleTopOf(s,e.contentDOM):n)-b.frameTopOf(s);return _.EditorView.scrollIntoView(t,{y:"start",yMargin:r})},lt=(e,t,n,o)=>{const s=ct(e,t),r=o.scrollerOf(e.scrollDOM),l=b.frameTopOf(r),i=b.visibleTopOf(r,e.contentDOM),f=l+r.clientHeight;let d=0;switch(n.y){case"start":d=s.top-(l+n.yMargin);break;case"center":d=(s.top+s.bottom)/2-(i+f)/2;break;case"end":d=s.bottom-(f-n.yMargin);break;default: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)))}if(d!==0&&(r.scrollTop+=d),n.y==="start")return;const x=at(e,t);x!==null&&o.reveal(x)},ct=(e,t)=>{const{node:n,offset:o}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,o),l.setEnd(n,o);const[i]=l.getClientRects();if(i!==void 0&&i.height>0)return{top:i.top,bottom:i.bottom}}}const s=e.lineBlockAt(t),r=e.documentTop+s.top;return{top:r,bottom:r+s.height}},at=(e,t)=>{const{node:n}=e.domAtPos(t);for(let o=n instanceof Element?n:n.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},ut=(e,t)=>{if(e==null)return null;try{return K.EditorState.fromJSON(e,{extensions:t},Pe)}catch{return null}},dt=610,ft=987,ke=Object.freeze({kind:"unavailable"}),mt="true",pt="false",ht=e=>e===mt?!0:e===pt?!1:null,gt=e=>{const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const s=o.localName==="img",r=o.getAttribute(s?"data-asset-src":"data-doc-path");r!==null&&n.push({target:{kind:s?"asset":"doc",path:r},exists:ht(o.getAttribute(s?"data-asset-exists":"data-doc-exists"))})}return n},vt=({path:e,instant:t,preview:n,initial:o,onView:s})=>{const r=new AbortController,l={asset:new Map,doc:new Map};let i=o,f=null,d=!1,x=!1,E=null,c=null,w=[],u,p=!1,g,y=null;const h=v=>{v.parsed===i.parsed&&v.source===i.source&&v.failure===i.failure&&v.busy===i.busy&&v.tier===i.tier||(i=v,s(v))},T=(v,S)=>{d||(d=!0,console.error(`[markdown-explorer] ${v}`,...S===void 0?[]:[S]))},O=v=>{if(t!==null)for(const{target:S,exists:C}of t.marksOf(v))l[S.kind].set(S.path,C)},L=()=>{clearTimeout(g),g=void 0,y?.abort(),y=null},N=()=>{c=null,w=[],clearTimeout(u),u=void 0},M=(v,S)=>{h({...i,failure:v,busy:!1,tier:S})},U=()=>{clearTimeout(u),u=w.length===0?void 0:setTimeout(F,ft)},B=()=>{if(t===null||c===null)return;const v=c,S=[],C={asset:new Set,doc:new Set};let G;try{G=t.sanitize(v.html,z=>{const le=l[z.kind].get(z.path);return le===void 0&&!C[z.kind].has(z.path)&&(C[z.kind].add(z.path),S.push(z)),le??void 0})}catch(z){N(),z instanceof pe.HtmlNestingLimitError?M(ne.failureOf("too-large"),"instant"):(T("the draft sanitizer failed",z),M(ne.failureOf("failed"),"instant"));return}w=S;const Y=i.parsed!==null&&i.parsed.htmlContent===G&&i.parsed.headings===v.headings?i.parsed:{htmlContent:G,headings:v.headings};h({parsed:Y,source:v.draft,failure:null,busy:!1,tier:"instant"}),U()},F=()=>{if(u=void 0,p||c===null||w.length===0)return;p=!0;const v=w;n(e,c.draft.text,r.signal).then(S=>{if(p=!1,!(r.signal.aborted||!("kind"in S))){S.kind==="preview"&&O(S.htmlContent);for(const C of v)l[C.kind].has(C.path)||l[C.kind].set(C.path,null);B()}})},j=v=>{L(),N(),h({...i,busy:!0,tier:"server"});const S=new AbortController;y=S,g=setTimeout(()=>{g=void 0,n(e,v.text,S.signal).then(C=>{if(!(S.signal.aborted||!("kind"in C))){if(y=null,C.kind==="failure"){M(C.failure,"server");return}O(C.htmlContent),h({parsed:{htmlContent:C.htmlContent,headings:C.headings},source:v,failure:null,busy:!1,tier:"server"})}})},dt)},a=async(v,S)=>{let C;try{C=await v.convert({path:e,text:S},r.signal)}catch(Y){return r.signal.aborted||T("the draft converter rejected a conversion, which its contract allows only once the signal aborted",Y),ke}const G=ne.draftAnswerViolation(C);return G===null?C:(T(`the draft converter answered outside its contract: ${G}`),ke)},A=(v,S)=>{switch(S.kind){case"preview":if(L(),S.headings.length>ne.EXPLORER_MAX_HEADINGS){N(),M(ne.failureOf("too-large"),"instant");return}c={draft:v,html:S.htmlContent,headings:S.headings.map(({text:C,depth:G,id:Y})=>({text:C,depth:G,id:Y}))},B();return;case"failure":L(),N(),M(ne.failureOf(S.failure.reason,S.failure.code),"instant");return;case"unavailable":j(v);return}},I=async v=>{x=!0;try{for(;E!==null&&!r.signal.aborted;){const S=E;E=null;const C=await a(v,S.text);if(r.signal.aborted)return;A(S,C)}}finally{x=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:v=>{if(!(r.signal.aborted||v.text===f?.text)){if(f=v,clearTimeout(u),u=void 0,t===null){j(v);return}E=v,x||I(t.converter)}},dispose:()=>{r.abort(),E=null,clearTimeout(u),u=void 0,L()}}},wt=e=>pe.createHtmlSanitizer(We(window),e.iframeHosts,e.dataPath,pe.MAX_HTML_NESTING_DEPTH,$.ownUrlsOf(e)),Et=(e,t)=>e.flatMap((n,o)=>{const s=t[o];return s===void 0?[]:[{editor:s.top,preview:n.top},{editor:s.bottom,preview:n.bottom}]}),Q=(e,t)=>{const n=e[t];if(n===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${Xe.describeValue(t)}`);return n},bt=e=>{const t=[];for(const o of e){let s=0,r=t.length;for(;s<r;){const l=s+r>>1;Q(t,l).pair.preview<=o.preview?s=l+1:r=l}t[s]={pair:o,before:s===0?void 0:Q(t,s-1)}}const n=[];for(let o=t.at(-1);o!==void 0;o=o.before)n.push(o.pair);return n.reverse()},xt=(e,t)=>{const n=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),s=n-t.editorViewport,r=o-t.previewViewport,l=e.filter(d=>d.editor>0&&d.editor<s&&d.preview>0&&d.preview<r).sort((d,x)=>d.editor-x.editor||d.preview-x.preview);let i={editor:0,preview:0};const f=[i];for(const d of bt(l))d.editor>i.editor&&d.preview>i.preview&&(f.push(d),i=d);return f.push({editor:n,preview:o}),{toPreview:d=>Le(f,"editor","preview",d),toEditor:d=>Le(f,"preview","editor",d)}},Le=(e,t,n,o)=>{const s=Q(e,0),r=Q(e,e.length-1);if(Number.isNaN(o)||o<=s[t])return s[n];if(o>=r[t])return r[n];let l=0,i=e.length-1;for(;i-l>1;){const x=l+i>>1;Q(e,x)[t]<=o?l=x:i=x}const f=Q(e,l),d=Q(e,i);return f[n]+(d[n]-f[n])*(o-f[t])/(d[t]-f[t])},St=610,Ae=89,Ie=.5,yt=({editor:e,preview:t,previewBlocks:n,editorSpans:o,requestFrame:s,cancelFrame:r,now:l})=>{let i="editor",f=0,d=null,x=null,E=!1,c=null,w=null;const u={editor:0,preview:0},p={editor:null,preview:null};let g=null,y=()=>{};const h=a=>{d!==null&&a!==d||(i=a,f=l()+St)},T=(a,A)=>{a!==i&&d===null&&l()>=f&&!O(a,A)&&(i=a),B()},O=(a,A)=>{const I=p[a];return l()<u[a]||I!==null&&Math.abs(A.position()-I)<Ie},L=e.onScroll(()=>T("editor",e)),N=e.onIntent(()=>h("editor")),M=()=>{const a=t();return a!==g&&(y(),g=a,y=a===null?()=>{}:U(a)),a},U=a=>{const A=a.onScroll(()=>T("preview",a)),I=a.onIntent(()=>h("preview"));return()=>{A(),I()}},B=()=>{!E&&x===null&&(x=s(F))},F=()=>{x=null;const a=M();a!==null&&(c??=n(),w??=xt(Et(c,o(c)),{editorMax:e.max(),previewMax:a.max(),editorViewport:e.viewport(),previewViewport:a.viewport()}),i==="editor"?j(a,"preview",w.toPreview(e.position())):j(e,"editor",w.toEditor(a.position())))},j=(a,A,I)=>{if(Math.abs(a.position()-I)<Ie){p[A]=a.position();return}u[A]=l()+Ae,p[A]=a.scrollTo(I)};return B(),{editorChanged:a=>{w=null,a&&h("editor"),B()},previewChanged:()=>{c=null,w=null,u.preview=l()+Ae,B()},showAlone:a=>{d=a,!(a===null||a===i)&&(i=a,f=0,B())},dispose:()=>{E=!0,x!==null&&r(x),x=null,L(),N(),y()}}},Oe=Object.freeze(["wheel","pointerdown","keydown","focusin"]),Ve=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const n of Oe)e.addEventListener(n,t,{capture:!0,passive:!0});return()=>{for(const n of Oe)e.removeEventListener(n,t,{capture:!0})}}}),oe="[data-aqmd-scroll-container]",Tt="[data-aqmd-content]",kt=`[${me.SOURCE_LINES_ATTRIBUTE}]`,Lt=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Be=(e,t)=>{const n=b.loadedOf(e.peek(t));return n!==null&&n.document.kind==="markdown"?{htmlContent:n.document.htmlContent,headings:n.document.headings}:null},At=(e,t,n,o)=>{if(t===void 0)return null;let s;try{s=wt(e)}catch(r){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",r),null}return{converter:t,sanitize:s,marksOf:gt,seed:Be(n,o)?.htmlContent??null}},It=e=>{const t=[];let n=null;for(const o of e.querySelectorAll(kt)){const s=me.parseSourceLines(o.getAttribute(me.SOURCE_LINES_ATTRIBUTE));if(s===null||o.getClientRects().length===0)continue;n??=e.scrollTop-b.visibleTopOf(e,o);const{top:r,bottom:l}=o.getBoundingClientRect();t.push({first:s.first,last:s.last,top:n+r,bottom:n+l})}return t},Ot=({path:e,readDraft:t,viewer:n,tables:o,concealed:s,onEditAt:r,onLayout:l,handleRef:i})=>{const{config:f,data:d,documents:x,draftConverter:E,labels:c}=b.useExplorer(),[w,u]=m.useState(()=>({parsed:Be(x,e),source:null,failure:null,busy:!0,tier:E===void 0?"server":"instant"})),p=m.useRef(null),g=m.useRef(null),y=m.useRef(w);m.useLayoutEffect(()=>{y.current=w});const h=m.useEffectEvent(()=>t());m.useEffect(()=>{const a=At(f,E,x,e),A=h(),I=vt({path:e,instant:a,preview:d.preview,initial:y.current,onView:v=>m.startTransition(()=>u(v))});return g.current=I,I.update(A),()=>{I.dispose(),g.current=null}},[f,d,x,E,e]);const T=m.useEffectEvent(()=>l());m.useLayoutEffect(()=>{w.parsed!==null&&T()},[w.parsed]);const O=w.parsed!==null;m.useLayoutEffect(()=>{const a=O?p.current?.querySelector(oe):null;if(!(a instanceof HTMLElement))return;a.tabIndex=0;const A=new ResizeObserver(()=>T());A.observe(a);const I=a.querySelector(Tt);return I!==null&&A.observe(I),()=>A.disconnect()},[O]);const L=m.useRef(null);m.useImperativeHandle(i,()=>({draft:a=>{g.current?.update(a)},scrollPort:()=>{const a=p.current?.querySelector(oe);return a instanceof HTMLElement?(L.current?.scroller!==a&&(L.current={scroller:a,port:Ve(a)}),L.current.port):null},blocks:()=>{const a=p.current?.querySelector(oe);return a instanceof HTMLElement?It(a):[]},focus:()=>{const a=p.current?.querySelector(oe);a instanceof HTMLElement&&a.focus({preventScroll:!0})},anchor:a=>{const A=p.current,I=A?.querySelector(oe);return A===null||!(I instanceof HTMLElement)?null:b.anchorOfView(A,a(I))},place:({line:a,clientTop:A},I)=>{const v=p.current,S=v===null?null:b.blockAtLine(v,a);S!==null&&(I(S).scrollTop+=b.lineTopIn(S,a)-A)}}),[]);const N=a=>{const A=p.current,{target:I}=a;if(r===void 0||A===null||!(I instanceof Element)||!b.isEditingDoubleClick(I))return;const v=b.anchorOfDoubleClick(I,A,A.ownerDocument.getSelection());v!==null&&r(v)},M=w.source===null?null:w.source.revision,U=m.useMemo(()=>M===null?void 0:{write:a=>o.write(M,a),read:a=>o.read(M,a),undo:o.undo,redo:o.redo,subscribe:o.subscribe},[o,M]),B=m.useMemo(()=>({...n.labels,spreadsheetReadOnly:c.previewTablePending}),[n.labels,c.previewTablePending]),F=m.useMemo(()=>({...n,labels:U===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,showMeasure:!1,showContentColors:!1,renderScrollBar:void 0,scrollBarGutter:void 0,scrollBarInlineSize:void 0,spreadsheetEditor:U}),[n,B,U]),j=m.useMemo(()=>w.parsed===null?null:q.jsx("div",{className:"aqmx-document-viewer",children:q.jsx(Ge.MarkdownViewer,{...F,parseResult:w.parsed,content:null})}),[F,w.parsed]);return q.jsxs("section",{ref:p,className:"aqmx-edit-preview","aria-label":c.previewRegion,"aria-busy":w.busy,inert:s!==null,hidden:s==="removed","data-aqmx-preview-tier":w.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:r===void 0?void 0:N,children:[w.failure===null?null:q.jsx(Rt,{failure:w.failure}),j??(w.failure===null?q.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:Lt.map(a=>q.jsx("span",{},a))}):null),w.busy?q.jsx("p",{className:"aqmx-sr-only",children:c.previewUpdating}):null]})},Rt=({failure:e})=>{const{labels:t}=b.useExplorer(),{reason:n}=e;return b.isAccessFailureReason(n)?q.jsx(b.AccessFailureNotice,{failure:e,place:"read",deniedSentence:null,retry:null,testId:"markdown-explorer-edit-preview-failure"}):q.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:t.previewFailed(b.failureTitleOf(t,n))})},Re="data-aqmx-edit-split",fe="--aqmx-edit-share",qe="--aqmx-edit-gutter",qt="data-aqmx-edit-split-probe",Ct="aqmx-edit-split",Mt="aqmx-edit-editor",_t="aqmx-edit-preview",Ce={value:$.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},Me={value:$.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},_e=e=>{if(e.length!==2)return null;const[t=0,n=0]=e,o=t+n;return o>0?t/o*100:null},ae=e=>{const t=e.current?.parentElement;if(t==null)throw new Error("[markdown-explorer] the edit split is not mounted in its surface");return t},Pt=(e,t,n)=>{const[o,s]=m.useState(null);return m.useLayoutEffect(()=>{const r=e.current,l=t.current;if(r===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const i={frame:r.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},f=()=>{i.frame>0&&i.measure>0&&s($.editSplitOrientation(i.frame,i.measure,n))};f();const d=new ResizeObserver(x=>{for(const E of x){const[c]=E.borderBoxSize;c!==void 0&&(E.target===r&&(i.frame=c.inlineSize),E.target===l&&(i.measure=c.inlineSize))}f()});return d.observe(r),d.observe(l),()=>d.disconnect()},[e,t,n]),o},Nt=({editorId:e})=>{const{edits:t,labels:n}=b.useExplorer(),o=m.useMemo(()=>be.toPanelGroupLabels(n),[n]),s=m.useRef(null),r=m.useRef(null),l=$.COARSE_TARGET_PIXELS,i=Pt(s,r,l),[f]=m.useState(()=>t.editorShare());m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(qe,`${String(l)}px`),()=>{E.style.removeProperty(qe)}},[l]),m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(fe,`${String(f)}%`),()=>{E.style.removeProperty(fe)}},[f]),m.useLayoutEffect(()=>{if(i===null)return;const E=ae(s);return E.setAttribute(Re,i),()=>E.removeAttribute(Re)},[i]);const d=be.useSplitPersistence(m.useCallback(E=>{const c=_e(E);c!==null&&t.setEditorShare(c)},[t])),x=m.useCallback((E,c)=>{const w=_e(E);w!==null&&ae(s).style.setProperty(fe,`${String(w)}%`),d.layoutChanged(E,c)},[d]);return q.jsxs("div",{ref:s,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[q.jsx("span",{ref:r,className:"aqmx-edit-split-probe","aria-hidden":"true",[qt]:""}),i===null?null:q.jsxs(ce.PanelGroup,{id:Ct,direction:i==="beside"?"horizontal":"vertical",onLayout:x,labels:o,className:"aqmx-edit-split-group",children:[q.jsx(ce.Panel,{id:Mt,defaultSize:{value:f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"}),q.jsx(ce.PanelResizeHandle,{thickness:l,indicator:{visible:!0,thickness:$.SPLIT_HANDLE_PIXELS.gripThickness,length:$.SPLIT_HANDLE_PIXELS.gripLength,barThickness:$.SPLIT_HANDLE_PIXELS.barThickness,barLength:$.SPLIT_HANDLE_PIXELS.barLength},title:n.editViewSplitResize,"aria-label":n.editViewSplitResize,"aria-controls":e,onDragging:d.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),q.jsx(ce.Panel,{id:_t,defaultSize:{value:100-f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"})]})]})},Dt=512,Vt=()=>{const e=[];let t=0,n=null;const o=s=>{if(n===null||!Number.isInteger(s)||s<t)return null;if(s===t+e.length)return n;const r=e[s-t];return r===void 0?null:r.before};return{revision:()=>t+e.length,mount:s=>{if(n!==null&&(n===s||n.eq(s))){n=s;return}const r=t+e.length;e.length=0,t=n===null?r:r+1,n=s},record:(s,r)=>{if(n===null)throw new Error("[markdown-explorer] a change of the editor's text was recorded before an editor mounted");e.push({before:n,changes:s}),n=r,e.length>Dt&&(e.shift(),t+=1)},lineOf:(s,r)=>{const l=o(s);if(l===null||n===null||!Number.isInteger(r)||r<1||r>l.lines)return null;let i=l.line(r).from;for(const f of e.slice(s-t)){const d=f.changes.mapPos(i,1,K.MapMode.TrackAfter);if(d===null)return null;i=d}return n.lineAt(i).number}}},je=144,Bt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:n}=e;return"state"in e&&typeof t=="number"&&typeof n=="number"},jt=e=>{e.stopPropagation()},Ht=e=>{const{path:t,name:n,session:o}=e,{edits:s,labels:r,announcer:l}=b.useExplorer(),{phase:i}=o,f=m.useCallback(()=>s.retry(t),[s,t]);switch(m.useEffect(()=>{if(i.kind!=="failed")return;const{reason:d}=i.failure;b.isAccessFailureReason(d)||l.announce(r.documentFailed(n,b.failureTitleOf(r,d)))},[i,l,r,n]),i.kind){case"opening":return q.jsx(b.ContentSkeleton,{label:r.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(b.EditGrantNotice,{href:i.href,onRetry:f,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(b.FailureView,{failure:i.failure,alert:!1,onRetry:f,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Ft,{...e})}},Ft=({path:e,name:t,session:n,layout:o,viewer:s,region:r,paneScroll:l})=>{const{edits:i,labels:f}=b.useExplorer(),d=m.useRef(null),x=m.useId(),E=m.useRef(null),[c]=m.useState(()=>new Set),[w]=m.useState(Vt),u=m.useRef(null),p=m.useRef(null),g=o==="fill",y=b.useSideBySide(),h=b.editViewOf(n,y,g),T=h!=="editor"||n.previewPrepared,O=T&&g,L=m.useRef({layout:o,region:r,paneScroll:l});m.useLayoutEffect(()=>{L.current={layout:o,region:r,paneScroll:l}});const N=m.useRef(n.generation);m.useLayoutEffect(()=>{N.current=n.generation});const M=m.useRef({view:h,previewMounted:T});m.useLayoutEffect(()=>{M.current={view:h,previewMounted:T}});const{requestSave:U,confirmation:B}=b.useSaveRequest(e),F=m.useRef(U);m.useLayoutEffect(()=>{F.current=U});const j=m.useRef(null),a=m.useRef(null),A=m.useRef(!1),I=m.useMemo(()=>({editor:f.editorLabel(t),useOurs:f.conflictUseOurs,useTheirs:f.conflictUseTheirs,keepBoth:f.conflictKeepBoth}),[f,t]),v=m.useCallback(k=>{const{region:R,paneScroll:V}=L.current,H=R();return H===null?k:V.scrollerOf(H,k)},[]);m.useLayoutEffect(()=>{const k=d.current,R=i.draft(e);if(k===null||R===null)return;const V=i.editorState.get(e),H=Bt(V)&&V.generation===N.current?V:null;let X=null,ee=null;const ue=()=>{X!==null&&clearTimeout(X),X=null,ee!==null&&i.setDraft(e,ee.text())},W=it({parent:k,scroll:{scrollerOf:P=>{const{layout:te,region:ze,paneScroll:Ue}=L.current,ve=ze();return te==="fill"||ve===null?P:Ue.scrollerOf(ve,P)},reveal:P=>L.current.paneScroll.reveal(P)},text:R,saved:H===null?void 0:H.state,labels:I,revisions:w,onGeometry:P=>p.current?.editorChanged(P),onChange:P=>{if(X??=setTimeout(ue,je),!P)for(const te of[...c])te();M.current.previewMounted&&ee!==null&&u.current?.draft({text:ee.text(),revision:w.revision()})},onSave:()=>F.current()});ee=W,E.current=W;const he=()=>{const P=W.topLine();return{line:P.line,clientTop:P.clientTop}},ge=()=>u.current?.anchor(v)??null,Fe=i.bindEditor(e,{flush:ue,adopt:P=>W.replaceText(P),returnPoint:()=>{const P=M.current.view==="preview"&&L.current.layout==="content"?ge():null;return P===null?he():{line:P.lines.first,clientTop:P.clientTop}},nextConflict:()=>M.current.view!=="preview"?W.nextConflict():W.conflicts().length===0?!1:(A.current=!0,i.setView(e,"editor"),!0),beforeView:P=>{if(L.current.layout==="fill")return;if(P==="preview"){j.current={to:"preview",point:he()};return}const te=ge();j.current=te===null?null:{to:"editor",anchor:te}}});return H!==null&&W.showLine(H.topLine),()=>{ue(),i.editorState.set(e,{state:W.save(),generation:N.current,topLine:W.topLine().line}),Fe(),W.destroy(),ee=null,E.current=null}},[i,e,I,v,c,w]);const{request:S}=n;m.useLayoutEffect(()=>{const k=E.current,R=i.draft(e);k===null||R===null||S===null||(S.anchor!==null&&k.reveal(b.positionInSource(R,S.anchor),S.anchor.clientTop),k.focus(),i.consumeRequest(e))},[i,e,S,I]),m.useLayoutEffect(()=>{h!=="editor"&&!n.previewPrepared&&i.preparePreview(e)},[i,e,h,n.previewPrepared]),m.useLayoutEffect(()=>{const k=j.current,R=a.current,V=A.current;j.current=null,a.current=null,A.current=!1;const H=E.current;if(k?.to==="preview")u.current?.place(k.point,v);else if(k?.to==="editor"&&H!==null){const X=i.draft(e);X!==null&&H.reveal(b.positionInSource(X,k.anchor),k.anchor.clientTop)}V?H?.nextConflict():R==="editor"?H?.focus():R==="preview"&&u.current?.focus()},[i,e,h,v]);const C=m.useMemo(()=>{const k=()=>{const R=E.current;if(R===null)throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");return R};return{write:(R,{fenceLine:V,expected:H,text:X})=>k().replaceBody(V,H,X,R),read:(R,V)=>k().readBody(V,R),undo:()=>k().undo(),redo:()=>k().redo(),subscribe:R=>(c.add(R),()=>{c.delete(R)})}},[c]),G=m.useCallback(()=>{const k=E.current;if(k===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return{text:k.text(),revision:w.revision()}},[w]);m.useLayoutEffect(()=>{const k=E.current;if(!O||k===null)return;const R=yt({editor:Ve(k.scrollElement),preview:()=>u.current?.scrollPort()??null,previewBlocks:()=>u.current?.blocks()??[],editorSpans:V=>k.lineSpans(V),requestFrame:V=>requestAnimationFrame(V),cancelFrame:V=>cancelAnimationFrame(V),now:()=>performance.now()});return R.showAlone(b.paneShownAlone(M.current.view)),p.current=R,()=>{R.dispose(),p.current=null}},[O,i,e,I]),m.useLayoutEffect(()=>{p.current?.showAlone(b.paneShownAlone(h))},[h]);const Y=m.useCallback(()=>p.current?.previewChanged(),[]),z=m.useCallback(k=>i.start(e,k),[i,e]),le=k=>{if(b.isInFullscreenBlock(k.target))return;if(k.key==="Escape"){b.consumeKey(k);return}if(!b.isEditViewShortcut(k.nativeEvent,b.isApplePlatform(navigator.platform)))return;b.consumeKey(k);const R=b.toggledEditView(h);a.current=R,b.chooseEditView(i,e,R,g)},He=q.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":h,"data-testid":"markdown-explorer-edit",onKeyDown:le,onDoubleClick:jt,children:[q.jsx("div",{ref:d,id:x,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:h==="preview",hidden:h==="preview"&&!g,...b.ALLOW_KEY_REPEAT}),h==="split"?q.jsx(Nt,{editorId:x}):null,T?q.jsx(Ot,{path:e,readDraft:G,viewer:s,tables:C,concealed:h!=="editor"?null:g?"overlay":"removed",onEditAt:h==="preview"?z:void 0,onLayout:Y,handleRef:u}):null]});return q.jsxs(q.Fragment,{children:[He,B]})};exports.DRAFT_WRITE_INTERVAL_MS=je;exports.default=Ht;