@aiquants/markdown-explorer 0.12.1 → 0.14.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 (44) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README.md +21 -12
  3. package/dist/EditSurface-BLlu5zEt.cjs +2 -0
  4. package/dist/EditSurface-CF2io496.js +705 -0
  5. package/dist/{ExplorerSplit-BjjqNRtj.js → ExplorerSplit-BPLECNpv.js} +109 -109
  6. package/dist/{ExplorerSplit-CqmbUSZ7.cjs → ExplorerSplit-Cjvy0JHP.cjs} +1 -1
  7. package/dist/{MultiLayout-BZbEl73E.cjs → MultiLayout-BjA0k-5n.cjs} +1 -1
  8. package/dist/{MultiLayout-BYXoD1aS.js → MultiLayout-D8F0BfxA.js} +25 -25
  9. package/dist/{NativeScrollBar-RP37nwmY.js → NativeScrollBar-BFF12oEd.js} +1 -1
  10. package/dist/{NativeScrollBar-B7jTbQmn.cjs → NativeScrollBar-BUWXPvTV.cjs} +1 -1
  11. package/dist/{TreeLayout-CEp5oKly.cjs → TreeLayout-CQUpgsxz.cjs} +1 -1
  12. package/dist/{TreeLayout-Uo6RG7lq.js → TreeLayout-rhyVTfrI.js} +3 -3
  13. package/dist/core/contracts.d.cts +7 -1
  14. package/dist/core/contracts.d.ts +7 -1
  15. package/dist/core/labels.d.cts +14 -1
  16. package/dist/core/labels.d.ts +14 -1
  17. package/dist/core/revalidation.d.cts +1 -2
  18. package/dist/core/revalidation.d.ts +1 -2
  19. package/dist/{dataRoute-CH3yOKR0.cjs → dataRoute-BONacTPi.cjs} +1 -1
  20. package/dist/{dataRoute-Pm_0ue_4.js → dataRoute-CObbjNxG.js} +14 -12
  21. package/dist/index-Dn7cYy-4.cjs +13 -0
  22. package/dist/index-v997iKxe.js +3464 -0
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +21 -21
  25. package/dist/{location-BUNWJ4eB.cjs → location-D6RE3wAN.cjs} +1 -1
  26. package/dist/{location-DWd6SQhN.js → location-IRD9h42r.js} +1 -1
  27. package/dist/{merge-DRGBbLuR.cjs → merge-BFk7nT59.cjs} +1 -1
  28. package/dist/{merge-q-5i8qsn.js → merge-Bi2VedIr.js} +1 -1
  29. package/dist/{sanitizePolicy-djLC3fRN.js → sanitizePolicy-DlrakwA4.js} +1 -1
  30. package/dist/{sanitizePolicy-BfUlXI5E.cjs → sanitizePolicy-DrIMuYCb.cjs} +1 -1
  31. package/dist/sanitizeWorker.cjs +1 -1
  32. package/dist/sanitizeWorker.js +1 -1
  33. package/dist/server/ports.d.cts +3 -0
  34. package/dist/server/ports.d.ts +3 -0
  35. package/dist/server.cjs +1 -1
  36. package/dist/server.js +93 -83
  37. package/dist/styles/markdown-explorer.css +1 -1
  38. package/docs/behavior/dom-hooks.md +6 -5
  39. package/docs/behavior/layout.md +10 -3
  40. package/package.json +6 -5
  41. package/dist/EditSurface-By6NPcD7.js +0 -633
  42. package/dist/EditSurface-BztcpQPW.cjs +0 -2
  43. package/dist/index-CGBl3fYT.cjs +0 -13
  44. package/dist/index-CjCr8czx.js +0 -3356
package/CHANGELOG.md CHANGED
@@ -1,12 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0 (2026-10-16)
4
+
5
+ ### Breaking
6
+
7
+ - **The peer floors of `@aiquants/markdown` and `@aiquants/virtualscroll` rise to `^6.4.1` and `^3.18.0`**, the versions this release is built and tested with (0.13.0: `^6.4.0` and `^3.17.0`). The other peers are unchanged.
8
+ Migration: upgrade both packages to those versions or later.
9
+
10
+ ### Changed
11
+
12
+ - **`shouldRevalidateExplorer` is built with `@aiquants/route-revalidation`** (a new dependency), the rule every route of the host can share. It decides as before: a submission, another path under the splat, another query and a navigation that drops the hash never run the page loader, and the unchanged URL keeps React Router's decision.
13
+ Its type is that package's `RouteShouldRevalidate`, which takes React Router's `ShouldRevalidateFunctionArgs` as they are and the same arguments the previous type took.
14
+
15
+ ## 0.13.0 (2026-10-15)
16
+
17
+ ### Breaking
18
+
19
+ - **The view switch replaces the preview toggle**: the bar's `markdown-explorer-edit-preview-toggle` and the label key `previewToggle` are gone; the view switch (`markdown-explorer-edit-view`, below) takes their place, and a host overriding `previewToggle` gets the unknown-key `RangeError`. The side-by-side setting keeps its storage key (`<storageNamespace>:edit-preview`, `on`/`off`).
20
+ - **`ExplorerDocumentEdit` gains `draft`** (below): a host's exhaustive switch over a document's `edit`, or over what `edit.source` answers (`ExplorerHostEditSource`), needs the new case.
21
+
22
+ ### Added
23
+
24
+ - **The editor and the preview in one place** (minor): the document bar's view switch, native radios named `editView` (`editViewNamed` in a panel), shows the editor alone, the two side by side where the pane fills (a page view, a maximized panel), or the preview alone; Ctrl+E (⌘E on Apple's platforms) switches between the editor and the preview from the editor, the preview or the switch, and moves the focus to the pane shown.
25
+ In a page view and a maximized panel both panes share one grid cell: the hidden pane stays laid out, invisible and inert, and the scroll sync keeps it at the shown pane's place, so switching shows the same block at the top by the next frame (about 10 ms in Chromium); while one pane shows alone, it alone leads the sync. A panel that is not maximized shows one pane at a time, the preview growing with its content like the panel's document, and puts the next pane at the same place on screen.
26
+ A double-click on a word of the preview shown alone opens the editor at that word, and Next conflict shows the editor first. The preview's scroller is a Tab stop and takes the focus on a click, so the keys scroll it and the shortcut reaches it. Where the bar is narrower than two reading columns (a phone), the switch shows its icons alone and keeps its 44 px targets.
27
+ The surface carries `data-aqmx-edit-view` (`editor`, `split` or `preview`). Side by side stays the reader's setting; otherwise each session starts with the editor. New labels: `editView`, `editViewNamed`, `editViewEditor`, `editViewEditorTooltip`, `editViewSplit`, `editViewSplitTooltip`, `editViewPreview` and `editViewPreviewTooltip`.
28
+ - **Editing without saving** (minor): a markdown document's `edit` may be `{ kind: "draft" }`, for a document the reader may change in the explorer's editor and try in the preview but not save. The `edit.source` port answers it with `{ kind: "draft", text }`, the text alone, and that answer decides the session; like `inline`, a `draft` edit needs the server's edit ports, and the explorer never calls `save`, `revisions` or `revision` for a draft session.
29
+ A draft session shows "Draft, not saved" as its status (`draftStatus`, `data-aqmx-save="draft"`) and neither Save nor History; Ctrl/⌘+S saves nothing and the announcer says so (`draftNotSaved`), and closing a changed draft or leaving its document asks with the draft's words (`draftDiscardTitle`, `draftDiscardBody`). The Edit toggle's tooltip and its name in a panel say the document is edited without saving (`editDraftDocument`, `editDraftDocumentNamed`).
30
+
3
31
  ## 0.12.1 (2026-10-15)
4
32
 
5
33
  ### Fixed
6
34
 
7
35
  - **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
36
  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.
37
+ 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.
38
+ A scroll without input, such as a find in page, takes the lead once the input ended, unless it comes from the sync or from a new rendering: the pane still stands where the sync left it, or the sync moved it or the preview changed less than 89 ms before.
10
39
  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
40
 
12
41
  ## 0.12.0 (2026-10-15)
package/README.md CHANGED
@@ -26,9 +26,9 @@ the tree and multi views carry it; another document opens rendered.
26
26
  With the server's `edit` ports, a Markdown document also offers **Edit**: the reader edits its Markdown in place
27
27
  (CodeMirror, loaded on demand), from where they were reading or from the word they double-clicked, saves over the
28
28
  version the draft started from (changes saved elsewhere are merged line by line, and conflicts are resolved in the
29
- editor), previews the draft beside the editor (on every keystroke with a browser converter, such as
30
- `@aiquants/markdown`'s Go converter compiled to WebAssembly), brings back an older revision, and is asked before an
31
- unsaved draft is lost (see [Editing](#editing)).
29
+ editor), previews the draft beside the editor or in its place, switching at once with Ctrl+E (on every keystroke with
30
+ a browser converter, such as `@aiquants/markdown`'s Go converter compiled to WebAssembly), brings back an older
31
+ revision, and is asked before an unsaved draft is lost (see [Editing](#editing)).
32
32
  A single-view (embedding) page never downloads the tree and multi-panel views, which load on demand.
33
33
  - **Embeds and link cards** — with `embeds` in the configuration, a link alone in a paragraph shows its post or video from up to ten providers (YouTube, X, Instagram, Threads, TikTok, Bluesky, LinkedIn, Reddit, note and niconico) in a cross-origin frame, with no provider script in the page, or a link card the explorer's own data route reads (`{dataPath}/link-card`, through `@aiquants/markdown`'s link-card handler: internal addresses never become cards); the link itself always stays, under the frame, as the card or as the paragraph.
34
34
  - **Secure by default** — Markdown HTML is sanitized on the server with an allow-list (scripts, event handlers, `srcdoc` and foreign iframes never reach the browser), and the document viewer applies its own on every render (a document keeps only the converter's class tokens, and ids only on headings, footnotes and `user-content-…` targets); document paths are validated, and deny rules hide environment files, keys and version-control metadata through up to three percent-decoding levels; tokens, principals, server paths and raw error messages never leave the server.
@@ -184,6 +184,7 @@ export const action = explorer.dataAction
184
184
  - Take the content folder from configuration (an environment variable here), not from `import.meta.url`: after `react-router build` the server module runs from `build/server/index.js`, so a path relative to the module would point into `build/`.
185
185
  - The page route needs its own `ErrorBoundary`: React Router stops carrying `headers` at the boundary that renders an error, so without one the default 403 answer loses its `Cache-Control: private, no-store`.
186
186
  - The data route module must not have a default export; with one it becomes a UI route and the JSON answers are rendered as a page.
187
+ - `shouldRevalidateExplorer` keeps React Router from running the page loader again on a submission, a move to another document, view or source (another path under the splat, another query) and a navigation that drops the hash; the unchanged URL (a `revalidate()` call, a link to the current page) keeps React Router's decision. It is built with `@aiquants/route-revalidation`.
187
188
  - The explorer adds no `main` landmark in any view (its own landmarks — the explorer `nav`, the document region, the multi view's columns — sit inside yours), so the page places it in its own `<main>`.
188
189
 
189
190
  ### 5. Load the styles
@@ -367,7 +368,8 @@ This is the document the browser receives. Your `document` port answers `Explore
367
368
  `version` is an opaque validator of 1 to 256 visible ASCII characters other than `"`, the same one your `asset` port reports for the file; the explorer writes the document's `url` as its own asset URL with that version (`<dataPath>/asset?path=…&v=<version>`, see [URL contract](docs/behavior/url-contract.md#asset-urls)).
368
369
  An answer of those kinds that carries a `url` key, or lacks a valid `version`, breaks the contract: it is logged and the reader sees `failed`.
369
370
  `failureDocument(reason, code?)` returns an `ExplorerFailureDocument`, which both unions accept.
370
- A markdown document says how the reader may edit it in `edit` (`ExplorerDocumentEdit`), which every markdown answer must carry: `null` (no editing), `{ kind: "inline" }` (in the explorer, through the server's `edit` ports; without them the answer breaks the contract) or `{ kind: "external", href }` (the document's own editor, an absolute `https:` URL the bar opens in a new tab). Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
371
+ A markdown document says how the reader may edit it in `edit` (`ExplorerDocumentEdit`), which every markdown answer must carry: `null` (no editing), `{ kind: "inline" }` (in the explorer, through the server's `edit` ports; without them the answer breaks the contract), `{ kind: "draft" }` (in the explorer without saving, to try changes in the preview: the ports' `source` and `preview` only, and the same contract) or `{ kind: "external", href }` (the document's own editor, an absolute `https:` URL the bar opens in a new tab).
372
+ Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
371
373
  A `text` document shows the beginning of a file under the file header (its name, Copy the text — offered only when the whole file was read, so the clipboard never gets part of a file — Open in a new tab, which shows the whole file as UTF-8 plain text, and Download, so a truncated preview can still be fetched whole); a `file` document is a file the explorer cannot show, which every view (single, tree, the multi view's panels) shows as a download view: the file header over a note (the label `fileNotShown`) with a download link.
372
374
 
373
375
  A markdown document lists at most `EXPLORER_MAX_HEADINGS` (10,000) headings; one that lists more is answered `too-large`, because every listed heading travels with the document (in the data response, the browser's document cache and the viewer's table of contents, one entry each) and a parser can list headings its HTML never renders (`#` lines inside a math block), so none of the HTML's limits bounds the list. A cache of your parser's results can rely on the same bound.
@@ -389,12 +391,13 @@ The deny rules are checked on the document's path only: a parser that expands in
389
391
 
390
392
  ### Editing
391
393
 
392
- Give `createMarkdownExplorer` the editor's ports as `edit` (`ExplorerEditPorts`) and answer `edit: { kind: "inline" }` for the markdown documents a reader may edit. Each port receives the context, the document path and the admitting source's `readPath`, after the deny rules (a refusal is logged) and the same admission as a document; refuse with `ExplorerError` as anywhere else, and check in every port that this reader may edit this document, since a request can name any path.
394
+ Give `createMarkdownExplorer` the editor's ports as `edit` (`ExplorerEditPorts`) and answer `edit: { kind: "inline" }` for the markdown documents a reader may edit, or `edit: { kind: "draft" }` for those they may edit but not save: `source` answers those with `{ kind: "draft", text }`, the text alone, and such a session never calls `save`, `revisions` or `revision` (refuse them there all the same).
395
+ The answer of `source` decides the session, whatever the document's `edit` said. Each port receives the context, the document path and the admitting source's `readPath`, after the deny rules (a refusal is logged) and the same admission as a document; refuse with `ExplorerError` as anywhere else, and check in every port that this reader may edit this document, since a request can name any path.
393
396
 
394
397
  ```ts
395
398
  edit: {
396
399
  // The whole source and its version (an opaque token naming this content), or a grant to ask for first
397
- source: async (context, path, readPath) => ({ kind: "edit", text, version, history: true }), // or { kind: "grant", href: "/auth/consent?grant=edit" }
400
+ source: async (context, path, readPath) => ({ kind: "edit", text, version, history: true }), // or { kind: "draft", text } (not saved) / { kind: "grant", href: "/auth/consent?grant=edit" }
398
401
  // Write only if the document still has draft.baseVersion; otherwise write nothing and answer the current content
399
402
  save: async (context, path, readPath, draft) => ({ kind: "saved", version: newVersion }), // or { kind: "conflict", version, text } / a grant
400
403
  // Render the draft exactly as the document would be (the explorer sanitizes it like a document)
@@ -411,7 +414,7 @@ editMaxBytes: 2 * 1024 * 1024, // the largest source and draft, the default
411
414
  - **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
415
  - **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
416
  - **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 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.
417
+ - **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 in proportion alone, top with top and bottom with bottom; the sanitizer keeps the attribute only in that form.
415
418
 
416
419
  ### Revealing the open document
417
420
 
@@ -648,14 +651,20 @@ A folder met again among its own ancestors (a shortcut inside its own target, or
648
651
 
649
652
  #### The editor
650
653
 
651
- A markdown document whose `edit` is `inline` gets an **Edit** toggle (`aria-pressed`) in the document bar, between Source and Refresh document: labelled beside a page view's pane, icon-only and named after the document in a multi-view panel. One whose `edit` is `external` gets a link to its own editor in a new tab instead.
654
+ A markdown document whose `edit` is `inline` gets an **Edit** toggle (`aria-pressed`) in the document bar, between Source and Refresh document: labelled beside a page view's pane, icon-only and named after the document in a multi-view panel. One whose `edit` is `draft` gets the same toggle, its tooltip and its name in a panel saying the document is edited without saving. One whose `edit` is `external` gets a link to its own editor in a new tab instead.
652
655
  Pressing Edit opens the editor with the block at the top of the reader's view at the same place on screen; a double-click on a word of the rendered document opens it with the cursor on that word, which stays where it was, in the tree and single views and in a maximized panel (a panel that is not maximized maximizes on its first double-click, as before; links, controls, media and drawings keep their own double-click). Pressed again, Edit closes the editor — asking first when the draft is unsaved — and the rendered document shows the editor's top line at the same place.
653
656
  The toggle is one element in both states, so the focus stays on it.
654
- While a document is edited, the bar shows the draft's status on one line and the editor's actions instead of Source and Refresh document: Next conflict while conflicts wait, Preview where the pane has room (a page view or a maximized panel), History when the host keeps revisions, and Save (Ctrl/⌘+S in the editor), which is `aria-disabled` until the draft changes; the announcer speaks each save's outcome.
657
+ While a document is edited, the bar shows the draft's status on one line and the editor's actions instead of Source and Refresh document: Next conflict while conflicts wait, the view switch (Editor, Side by side where the pane has room — a page view or a maximized panel —, and Preview), History when the host keeps revisions, and Save (Ctrl/⌘+S in the editor), which is `aria-disabled` until the draft changes; the announcer speaks each save's outcome.
655
658
  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
659
  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
660
  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): 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.
661
+ The preview renders the draft as the document would be: on every keystroke with a `draftConverter`, else once the reader pauses typing (SERVER_PREVIEW_DELAY_MS, 610 ms).
662
+ The view switch shows the editor alone, the two side by side (the preview below the editor on a narrow pane), or the preview alone; Ctrl+E (⌘E on a Mac) switches between the editor and the preview from the editor, the preview or the switch and moves the focus there, and a double-click on a word of the preview shown alone opens the editor at that word.
663
+ Switching is instant: the hidden pane stays rendered and in step, so the block at the top of the view stays the same; a panel that is not maximized shows one pane at a time and puts the next one at the same place on screen. Where the bar is narrower than two reading columns (a phone), the switch shows its icons alone, keeping its 44 px targets.
664
+ The two scroll together, both ways: the pane the reader works in (the wheel, a press, a key, the focus, typing) leads — the shown one alone while the other is hidden —, 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.
665
+ 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.
666
+ Whether the preview shows side by side is the reader's choice, kept in browser storage under `storageNamespace` (default off); otherwise the session shows the editor or the preview, starting with the editor. History lists the revisions, shows the one picked and puts it into the draft, to be saved like any draft.
667
+ A draft session (`source` answered `draft`) shows "Draft, not saved" as its status (`data-aqmx-save="draft"`) and neither Save nor History; Ctrl/⌘+S saves nothing and the announcer says the draft is not saved, and closing a changed draft or leaving its document asks with the draft's words, since its changes are lost.
659
668
  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
669
 
661
670
  #### Rendering drafts in the browser
@@ -707,7 +716,7 @@ export const draftConverter: ExplorerDraftConverter = {
707
716
  ```
708
717
 
709
718
  - **The contract.** `convert(draft, signal)` receives the document's path as the explorer names it and the draft's text, and resolves to `{ kind: "preview", htmlContent, headings }` (unsanitized, without existence marks), a failure document (shown over the last rendering, as a failed preview is; more than `EXPLORER_MAX_HEADINGS` headings is `too-large`, as on the server), or `{ kind: "unavailable" }` when the converter cannot run, for which the server renders that draft. It rejects only with the signal's reason once the signal aborted. Any other rejection, or an answer outside the contract, is a bug: the explorer reports it once on the console and treats it as `unavailable`.
710
- - **Loading ahead.** `prepare()`, when given, is called when the reader is about to see the preview — they point at or focus Edit while the preview is on and fits the pane, or point at or focus the preview toggle — so the worker and its WebAssembly (about 0.4 s to start in Chromium) load before the first draft. The explorer may call it many times: return at once and do the work once.
719
+ - **Loading ahead.** `prepare()`, when given, is called when the reader is about to see the preview — they point at or focus Edit while the preview shows side by side and fits the pane, or point at or focus the view switch's Preview — so the worker and its WebAssembly (about 0.4 s to start in Chromium) load before the first draft. The explorer may call it many times: return at once and do the work once.
711
720
  - **One draft at a time.** The explorer converts the first draft at once; a draft that arrives while another converts waits, and only the latest waiting draft is converted next (a WebAssembly call cannot be interrupted, so the running one is never aborted). It aborts the signal only when the preview goes away. A rendering is shown without `aria-busy`, through a React transition, so typing goes ahead of it.
712
721
  - **The server's rules.** Each rendering is sanitized in the browser with the allow-list rules the server applies to every document (the same module, on a DOMPurify instance of the preview's own from `isomorphic-dompurify`'s browser build, part of the editing chunk), so the instant preview shows what the saved document will.
713
722
  - **Which targets exist.** Only the server can tell whether an image or a linked document exists. The preview keeps a table of the marks the server answered (`data-asset-exists`, `data-doc-exists`, or none), seeded from the document's own rendering, and writes the known ones onto every rendering. When a rendering names a target the table does not hold, the preview asks the data route's `preview` operation about the newest draft once the reader has paused for VERIFY_DELAY_MS (987 ms), one request at a time, learns the marks of the answer, remembers every asked target the answer left unmarked (or a failed answer did not reach) as having none, and renders the newest draft again. So the server is asked about a target once, and a draft that adds no new image or link causes no request at all; a missing image the reader just added shows as a broken image until the answer lands, then as the viewer's missing-image placeholder.
@@ -779,7 +788,7 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
779
788
  ## Known limitations
780
789
 
781
790
  - One explorer per page: the drag-and-drop layout looks up its panels document-wide.
782
- - Merges are line-based (node-diff3): changes on adjacent lines, or on the same line, conflict even when they would combine. A panel that is not maximized shows no preview; maximize it to see one.
791
+ - Merges are line-based (node-diff3): changes on adjacent lines, or on the same line, conflict even when they would combine. A panel that is not maximized shows the editor or the preview, never both; maximize it to see them side by side.
783
792
  - The browser applies the server sanitizer's allow-list rules and nesting limit (512 levels, which Chromium's own parser never exceeds), but not its other resource limits (parsed nodes, attributes, worker heap, time): the host's converter bounds a draft's HTML with `maxHtmlBytes` instead. The existence marks of a target the reader just added arrive about a second after they pause, so until then a new image that does not exist shows as a broken image, and a new link to a missing document as an ordinary link.
784
793
  - A held Enter acts once on every control inside the explorer, those of other packages included (the tree's rows, the panel headers' buttons, the document viewer's toolbar and the controls inside a document), except Zoom in and Zoom out, which keep stepping while a press that began on them is held (see [Held keys](docs/behavior/layout.md#held-keys)): a press that hands the focus to them, such as following a link to an image, does not step them. The repeated keydowns end at the explorer's root, so a keydown listener the host attaches outside the explorer for the bubbling phase does not receive them either.
785
794
  - A loop row (a folder met again among its own ancestors) shows an expand glyph and `aria-expanded="false"` like any closed folder, because `@aiquants/directory-tree` has no row that cannot expand; it never opens. The 4 listings in flight are counted per explorer, not across browser tabs.
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("react/jsx-runtime"),E=require("react"),y=require("./index-Dn7cYy-4.cjs"),J=require("@codemirror/commands"),ne=require("@codemirror/lang-markdown"),fe=require("@codemirror/language"),oe=require("@codemirror/search"),U=require("@codemirror/state"),A=require("@codemirror/view"),C=require("@lezer/highlight"),ye=require("@aiquants/markdown"),Q=require("@aiquants/markdown/source-lines"),G=require("./dataRoute-BONacTPi.cjs"),Z=require("./sanitizePolicy-DrIMuYCb.cjs"),Se=require("isomorphic-dompurify"),pe={history:J.historyField},ke=fe.HighlightStyle.define([{tag:[C.tags.heading1,C.tags.heading2,C.tags.heading3,C.tags.heading4,C.tags.heading5,C.tags.heading6,C.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:C.tags.strong,fontWeight:"700"},{tag:C.tags.emphasis,fontStyle:"italic"},{tag:C.tags.strikethrough,textDecoration:"line-through"},{tag:C.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:C.tags.url,color:"var(--aqmx-syntax-url)"},{tag:C.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:C.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[C.tags.processingInstruction,C.tags.contentSeparator,C.tags.labelName,C.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Te=A.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)"}}),me="data-aqmx-conflict-actions",Le=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Me=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),qe=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class Oe extends A.WidgetType{constructor(t,r){super(),this.index=t,this.labels=r}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const r=document.createElement("div");r.setAttribute(me,String(this.index));for(const[o,s]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const l=document.createElement("button");l.type="button",l.textContent=s,l.setAttribute("data-aqmx-conflict-choice",o),l.addEventListener("mousedown",a=>a.preventDefault()),l.addEventListener("click",()=>{const a=X(t.state.doc)[this.index];a!==void 0&&(he(t,a,o),t.focus())}),r.append(l)}return r}ignoreEvent(){return!0}}const X=e=>y.findConflictsInLines(e.iterLines()),ie=(e,t)=>{const r=new U.RangeSetBuilder;return X(e).forEach((o,s)=>{const l=e.line(o.start);r.add(l.from,l.from,A.Decoration.widget({widget:new Oe(s,t),block:!0,side:-1}));for(let a=o.start;a<=o.end;a+=1){const n=e.line(a).from,w=a===o.start||a===o.separator||a===o.end?Le:a<o.separator?Me:qe;r.add(n,n,w)}}),r.finish()},Ae=e=>U.StateField.define({create:t=>ie(t.doc,e),update:(t,r)=>r.docChanged?ie(r.state.doc,e):t,provide:t=>A.EditorView.decorations.from(t)}),he=(e,t,r)=>{const{doc:o}=e.state,s=(d,u)=>{const v=[];for(let m=d;m<=u;m+=1)v.push(o.line(m).text);return v},l=s(t.start+1,t.separator-1),a=s(t.separator+1,t.end-1),n=r==="ours"?l:r==="theirs"?a:[...l,...a];let w=o.line(t.start).from,f=o.line(t.end).to;n.length===0&&(t.end<o.lines?f+=1:t.start>1&&(w-=1));const i=n.join(`
2
+ `);e.dispatch({changes:{from:w,to:f,insert:i},selection:U.EditorSelection.cursor(w),scrollIntoView:!0,userEvent:"input.resolve"})},Ce=({parent:e,scroll:t,text:r,saved:o,labels:s,onChange:l,onGeometry:a,onSave:n})=>{const w=[A.EditorView.scrollHandler.of((d,u,v)=>(Re(d,u.head,v,t),!0)),A.lineNumbers(),A.highlightActiveLineGutter(),J.history(),A.drawSelection(),A.highlightActiveLine(),oe.highlightSelectionMatches(),A.EditorView.lineWrapping,ne.markdown({base:ne.markdownLanguage}),fe.syntaxHighlighting(ke),Ae(s),A.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(n(),!0)},...oe.searchKeymap,...J.historyKeymap,...J.defaultKeymap]),A.EditorView.contentAttributes.of({"aria-label":s.editor,"aria-multiline":"true"}),A.EditorView.updateListener.of(d=>{d.docChanged&&l(),(d.docChanged||d.heightChanged||d.geometryChanged)&&a(d.docChanged)}),Te],f=De(o,w)??U.EditorState.create({doc:r,extensions:w}),i=new A.EditorView({state:f,parent:e});return{text:()=>i.state.doc.toString(),replaceText:d=>{const u=i.state.doc.toString();if(u===d)return;let v=0;const m=Math.min(u.length,d.length);for(;v<m&&u.charCodeAt(v)===d.charCodeAt(v);)v+=1;let h=0;for(;h<m-v&&u.charCodeAt(u.length-1-h)===d.charCodeAt(d.length-1-h);)h+=1;i.dispatch({changes:{from:v,to:u.length-h,insert:d.slice(v,d.length-h)},userEvent:"input.replace"})},reveal:({line:d,column:u},v)=>{const{doc:m}=i.state,h=m.line(Math.min(Math.max(d,1),m.lines)),S=Math.min(h.from+u,h.to);i.dispatch({selection:U.EditorSelection.cursor(S),effects:se(i,S,v,t)})},showLine:d=>{const{doc:u}=i.state,v=u.line(Math.min(Math.max(d,1),u.lines)).from;i.dispatch({effects:se(i,v,null,t)})},topLine:()=>{const d=t.scrollerOf(i.scrollDOM),u=y.visibleTopOf(d,i.contentDOM),v=y.frameTopOf(d)+d.clientHeight,{documentTop:m}=i,{doc:h}=i.state;let S=i.lineBlockAtHeight(Math.max(u-m,0));for(;h.lineAt(S.from).text.trim()===""&&S.to<h.length;){const N=i.lineBlockAt(S.to+1);if(m+N.top>=v)break;S=N}const M=i.coordsAtPos(S.from),T=M===null?m+S.top:M.top;return{line:i.state.doc.lineAt(S.from).number,clientTop:T,offset:T-u}},lineSpans:d=>{const u=i.scrollDOM,v=u.scrollTop+i.documentTop-y.visibleTopOf(u,i.contentDOM),{doc:m}=i.state,h=S=>m.line(Math.min(Math.max(S,1),m.lines)).from;return d.map(({first:S,last:M})=>({top:v+i.lineBlockAt(h(S)).top,bottom:v+i.lineBlockAt(h(M)).bottom}))},scrollElement:i.scrollDOM,focus:()=>i.focus(),conflicts:()=>X(i.state.doc),resolveAtCursor:d=>{const u=X(i.state.doc),v=i.state.doc.lineAt(i.state.selection.main.head).number,m=u.find(h=>h.end>=v);return m===void 0?!1:(he(i,m,d),!0)},nextConflict:()=>{const d=X(i.state.doc);if(d[0]===void 0)return!1;const v=i.state.doc.lineAt(i.state.selection.main.head).number,m=d.findIndex(T=>T.start>v),h=m<0?0:m,S=i.state.doc.line(d[h].start).from;i.dispatch({selection:U.EditorSelection.cursor(S),effects:A.EditorView.scrollIntoView(S,{y:"center"})});const M=i.contentDOM.querySelector(`[${me}="${String(h)}"] button`);return M instanceof HTMLElement?M.focus({preventScroll:!0}):i.focus(),!0},save:()=>i.state.toJSON(pe),destroy:()=>i.destroy()}},se=(e,t,r,o)=>{const s=o.scrollerOf(e.scrollDOM),l=(r===null?y.visibleTopOf(s,e.contentDOM):r)-y.frameTopOf(s);return A.EditorView.scrollIntoView(t,{y:"start",yMargin:l})},Re=(e,t,r,o)=>{const s=Ie(e,t),l=o.scrollerOf(e.scrollDOM),a=y.frameTopOf(l),n=y.visibleTopOf(l,e.contentDOM),w=a+l.clientHeight;let f=0;switch(r.y){case"start":f=s.top-(a+r.yMargin);break;case"center":f=(s.top+s.bottom)/2-(n+w)/2;break;case"end":f=s.bottom-(w-r.yMargin);break;default:s.top<n+r.yMargin?f=s.top-(n+r.yMargin):s.bottom>w-r.yMargin&&(f=Math.min(s.bottom-(w-r.yMargin),s.top-(n+r.yMargin)))}if(f!==0&&(l.scrollTop+=f),r.y==="start")return;const i=Ne(e,t);i!==null&&o.reveal(i)},Ie=(e,t)=>{const{node:r,offset:o}=e.domAtPos(t);if(r.nodeType===Node.TEXT_NODE){const a=r.ownerDocument?.createRange();if(a!==void 0){a.setStart(r,o),a.setEnd(r,o);const[n]=a.getClientRects();if(n!==void 0&&n.height>0)return{top:n.top,bottom:n.bottom}}}const s=e.lineBlockAt(t),l=e.documentTop+s.top;return{top:l,bottom:l+s.height}},Ne=(e,t)=>{const{node:r}=e.domAtPos(t);for(let o=r instanceof Element?r:r.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},De=(e,t)=>{if(e==null)return null;try{return U.EditorState.fromJSON(e,{extensions:t},pe)}catch{return null}},_e=610,Ve=987,le=Object.freeze({kind:"unavailable"}),Pe="true",je="false",He=e=>e===Pe?!0:e===je?!1:null,Be=e=>{const t=new DOMParser().parseFromString(e,"text/html"),r=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const s=o.localName==="img",l=o.getAttribute(s?"data-asset-src":"data-doc-path");l!==null&&r.push({target:{kind:s?"asset":"doc",path:l},exists:He(o.getAttribute(s?"data-asset-exists":"data-doc-exists"))})}return r},Fe=({path:e,instant:t,preview:r,initial:o,onView:s})=>{const l=new AbortController,a={asset:new Map,doc:new Map};let n=o,w=null,f=!1,i=!1,d=null,u=null,v=[],m,h=!1,S,M=null;const T=c=>{c.parsed===n.parsed&&c.failure===n.failure&&c.busy===n.busy&&c.tier===n.tier||(n=c,s(c))},N=(c,p)=>{f||(f=!0,console.error(`[markdown-explorer] ${c}`,...p===void 0?[]:[p]))},D=c=>{if(t!==null)for(const{target:p,exists:b}of t.marksOf(c))a[p.kind].set(p.path,b)},_=()=>{clearTimeout(S),S=void 0,M?.abort(),M=null},V=()=>{u=null,v=[],clearTimeout(m),m=void 0},P=(c,p)=>{T({parsed:n.parsed,failure:c,busy:!1,tier:p})},x=()=>{clearTimeout(m),m=v.length===0?void 0:setTimeout(L,Ve)},k=()=>{if(t===null||u===null)return;const c=u,p=[],b={asset:new Set,doc:new Set};let q;try{q=t.sanitize(c.html,R=>{const W=a[R.kind].get(R.path);return W===void 0&&!b[R.kind].has(R.path)&&(b[R.kind].add(R.path),p.push(R)),W??void 0})}catch(R){V(),R instanceof Z.HtmlNestingLimitError?P(G.failureOf("too-large"),"instant"):(N("the draft sanitizer failed",R),P(G.failureOf("failed"),"instant"));return}v=p;const B=n.parsed!==null&&n.parsed.htmlContent===q&&n.parsed.headings===c.headings?n.parsed:{htmlContent:q,headings:c.headings};T({parsed:B,failure:null,busy:!1,tier:"instant"}),x()},L=()=>{if(m=void 0,h||u===null||v.length===0)return;h=!0;const c=v;r(e,u.text,l.signal).then(p=>{if(h=!1,!(l.signal.aborted||!("kind"in p))){p.kind==="preview"&&D(p.htmlContent);for(const b of c)a[b.kind].has(b.path)||a[b.kind].set(b.path,null);k()}})},j=c=>{_(),V(),T({...n,busy:!0,tier:"server"});const p=new AbortController;M=p,S=setTimeout(()=>{S=void 0,r(e,c,p.signal).then(b=>{if(!(p.signal.aborted||!("kind"in b))){if(M=null,b.kind==="failure"){P(b.failure,"server");return}D(b.htmlContent),T({parsed:{htmlContent:b.htmlContent,headings:b.headings},failure:null,busy:!1,tier:"server"})}})},_e)},g=async(c,p)=>{let b;try{b=await c.convert({path:e,text:p},l.signal)}catch(B){return l.signal.aborted||N("the draft converter rejected a conversion, which its contract allows only once the signal aborted",B),le}const q=G.draftAnswerViolation(b);return q===null?b:(N(`the draft converter answered outside its contract: ${q}`),le)},H=(c,p)=>{switch(p.kind){case"preview":if(_(),p.headings.length>G.EXPLORER_MAX_HEADINGS){V(),P(G.failureOf("too-large"),"instant");return}u={text:c,html:p.htmlContent,headings:p.headings.map(({text:b,depth:q,id:B})=>({text:b,depth:q,id:B}))},k();return;case"failure":_(),V(),P(G.failureOf(p.failure.reason,p.failure.code),"instant");return;case"unavailable":j(c);return}},F=async c=>{i=!0;try{for(;d!==null&&!l.signal.aborted;){const p=d;d=null;const b=await g(c,p);if(l.signal.aborted)return;H(p,b)}}finally{i=!1}};return t!==null&&t.seed!==null&&D(t.seed),{update:c=>{if(!(l.signal.aborted||c===w)){if(w=c,clearTimeout(m),m=void 0,t===null){j(c);return}d=c,i||F(t.converter)}},dispose:()=>{l.abort(),d=null,clearTimeout(m),m=void 0,_()}}},ze=(e,t)=>Z.createHtmlSanitizer(Se(window),e,t,Z.MAX_HTML_NESTING_DEPTH),Ke=(e,t)=>e.flatMap((r,o)=>{const s=t[o];return s===void 0?[]:[{editor:s.top,preview:r.top},{editor:s.bottom,preview:r.bottom}]}),K=(e,t)=>{const r=e[t];if(r===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${String(t)}`);return r},Ue=e=>{const t=[];for(const o of e){let s=0,l=t.length;for(;s<l;){const a=s+l>>1;K(t,a).pair.preview<=o.preview?s=a+1:l=a}t[s]={pair:o,before:s===0?void 0:K(t,s-1)}}const r=[];for(let o=t.at(-1);o!==void 0;o=o.before)r.push(o.pair);return r.reverse()},We=(e,t)=>{const r=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),s=r-t.editorViewport,l=o-t.previewViewport,a=e.filter(f=>f.editor>0&&f.editor<s&&f.preview>0&&f.preview<l).sort((f,i)=>f.editor-i.editor||f.preview-i.preview);let n={editor:0,preview:0};const w=[n];for(const f of Ue(a))f.editor>n.editor&&f.preview>n.preview&&(w.push(f),n=f);return w.push({editor:r,preview:o}),{toPreview:f=>ce(w,"editor","preview",f),toEditor:f=>ce(w,"preview","editor",f)}},ce=(e,t,r,o)=>{const s=K(e,0),l=K(e,e.length-1);if(Number.isNaN(o)||o<=s[t])return s[r];if(o>=l[t])return l[r];let a=0,n=e.length-1;for(;n-a>1;){const i=a+n>>1;K(e,i)[t]<=o?a=i:n=i}const w=K(e,a),f=K(e,n);return w[r]+(f[r]-w[r])*(o-w[t])/(f[t]-w[t])},Ge=610,ae=89,ue=.5,$e=({editor:e,preview:t,previewBlocks:r,editorSpans:o,requestFrame:s,cancelFrame:l,now:a})=>{let n="editor",w=0,f=null,i=null,d=!1,u=null,v=null;const m={editor:0,preview:0},h={editor:null,preview:null};let S=null,M=()=>{};const T=g=>{f!==null&&g!==f||(n=g,w=a()+Ge)},N=(g,H)=>{g!==n&&f===null&&a()>=w&&!D(g,H)&&(n=g),k()},D=(g,H)=>{const F=h[g];return a()<m[g]||F!==null&&Math.abs(H.position()-F)<ue},_=e.onScroll(()=>N("editor",e)),V=e.onIntent(()=>T("editor")),P=()=>{const g=t();return g!==S&&(M(),S=g,M=g===null?()=>{}:x(g)),g},x=g=>{const H=g.onScroll(()=>N("preview",g)),F=g.onIntent(()=>T("preview"));return()=>{H(),F()}},k=()=>{!d&&i===null&&(i=s(L))},L=()=>{i=null;const g=P();g!==null&&(u??=r(),v??=We(Ke(u,o(u)),{editorMax:e.max(),previewMax:g.max(),editorViewport:e.viewport(),previewViewport:g.viewport()}),n==="editor"?j(g,"preview",v.toPreview(e.position())):j(e,"editor",v.toEditor(g.position())))},j=(g,H,F)=>{if(Math.abs(g.position()-F)<ue){h[H]=g.position();return}m[H]=a()+ae,h[H]=g.scrollTo(F)};return k(),{editorChanged:g=>{v=null,g&&T("editor"),k()},previewChanged:()=>{u=null,v=null,m.preview=a()+ae,k()},showAlone:g=>{f=g,!(g===null||g===n)&&(n=g,w=0,k())},dispose:()=>{d=!0,i!==null&&l(i),i=null,_(),V(),M()}}},de=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 r of de)e.addEventListener(r,t,{capture:!0,passive:!0});return()=>{for(const r of de)e.removeEventListener(r,t,{capture:!0})}}}),$="[data-aqmd-scroll-container]",Xe="[data-aqmd-content]",Ye=`[${Q.SOURCE_LINES_ATTRIBUTE}]`,Je=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),ge=(e,t)=>{const r=y.loadedOf(e.peek(t));return r!==null&&r.document.kind==="markdown"?{htmlContent:r.document.htmlContent,headings:r.document.headings}:null},Qe=(e,t,r,o,s)=>{if(r===void 0)return null;let l;try{l=ze(e,t)}catch(a){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",a),null}return{converter:r,sanitize:l,marksOf:Be,seed:ge(o,s)?.htmlContent??null}},Ze=e=>{const t=[];let r=null;for(const o of e.querySelectorAll(Ye)){const s=Q.parseSourceLines(o.getAttribute(Q.SOURCE_LINES_ATTRIBUTE));if(s===null||o.getClientRects().length===0)continue;r??=e.scrollTop-y.visibleTopOf(e,o);const{top:l,bottom:a}=o.getBoundingClientRect();t.push({first:s.first,last:s.last,top:r+l,bottom:r+a})}return t},et=({path:e,readDraft:t,viewer:r,concealed:o,onEditAt:s,onLayout:l,handleRef:a})=>{const{config:n,data:w,documents:f,draftConverter:i,labels:d}=y.useExplorer(),[u,v]=E.useState(()=>({parsed:ge(f,e),failure:null,busy:!0,tier:i===void 0?"server":"instant"})),m=E.useRef(null),h=E.useRef(null),S=E.useRef(u);E.useLayoutEffect(()=>{S.current=u});const M=E.useEffectEvent(()=>t());E.useEffect(()=>{const x=Qe(n.iframeHosts,n.dataPath,i,f,e),k=Fe({path:e,instant:x,preview:w.preview,initial:S.current,onView:L=>E.startTransition(()=>v(L))});return h.current=k,k.update(M()),()=>{k.dispose(),h.current=null}},[n,w,f,i,e]);const T=E.useEffectEvent(()=>l());E.useLayoutEffect(()=>{u.parsed!==null&&T()},[u.parsed]);const N=u.parsed!==null;E.useLayoutEffect(()=>{const x=N?m.current?.querySelector($):null;if(!(x instanceof HTMLElement))return;x.tabIndex=0;const k=new ResizeObserver(()=>T());k.observe(x);const L=x.querySelector(Xe);return L!==null&&k.observe(L),()=>k.disconnect()},[N]);const D=E.useRef(null);E.useImperativeHandle(a,()=>({draft:x=>{h.current?.update(x)},scrollPort:()=>{const x=m.current?.querySelector($);return x instanceof HTMLElement?(D.current?.scroller!==x&&(D.current={scroller:x,port:ve(x)}),D.current.port):null},blocks:()=>{const x=m.current?.querySelector($);return x instanceof HTMLElement?Ze(x):[]},focus:()=>{const x=m.current?.querySelector($);x instanceof HTMLElement&&x.focus({preventScroll:!0})},anchor:x=>{const k=m.current,L=k?.querySelector($);return k===null||!(L instanceof HTMLElement)?null:y.anchorOfView(k,x(L))},place:({line:x,clientTop:k},L)=>{const j=m.current,g=j===null?null:y.blockAtLine(j,x);g!==null&&(L(g).scrollTop+=y.lineTopIn(g,x)-k)}}),[]);const _=x=>{const k=m.current,{target:L}=x;if(s===void 0||k===null||!(L instanceof Element)||!y.isEditingDoubleClick(L))return;const j=y.anchorOfDoubleClick(L,k,k.ownerDocument.getSelection());j!==null&&s(j)},V=E.useMemo(()=>({...r,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0}),[r]),P=E.useMemo(()=>u.parsed===null?null:O.jsx("div",{className:"aqmx-document-viewer",children:O.jsx(ye.MarkdownViewer,{...V,parseResult:u.parsed,content:null})}),[V,u.parsed]);return O.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":d.previewRegion,"aria-busy":u.busy,inert:o!==null,hidden:o==="removed","data-aqmx-preview-tier":u.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:s===void 0?void 0:_,children:[u.failure===null?null:O.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:d.previewFailed(y.failureTitleOf(d,u.failure.reason))}),P??(u.failure===null?O.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:Je.map(x=>O.jsx("span",{},x))}):null),u.busy?O.jsx("p",{className:"aqmx-sr-only",children:d.previewUpdating}):null]})},we=144,tt=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),rt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:r}=e;return"state"in e&&typeof t=="number"&&typeof r=="number"},nt=e=>{e.stopPropagation()},ot=e=>{const{path:t,name:r,session:o}=e,{edits:s,labels:l,announcer:a}=y.useExplorer(),{phase:n}=o,w=E.useCallback(()=>s.retry(t),[s,t]);switch(E.useEffect(()=>{n.kind==="failed"&&a.announce(l.documentFailed(r,y.failureTitleOf(l,n.failure.reason)))},[n,a,l,r]),n.kind){case"opening":return O.jsxs(O.Fragment,{children:[O.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:tt.map(f=>O.jsx("span",{},f))}),O.jsx("p",{className:"aqmx-sr-only",children:l.editLoading})]});case"grant":return O.jsx("div",{className:"aqmx-edit-message",children:O.jsx(y.EditGrantNotice,{href:n.href,onRetry:w,testId:"markdown-explorer-edit-grant"})});case"failed":return O.jsx("div",{className:"aqmx-edit-message",children:O.jsx(y.FailureView,{failure:n.failure,alert:!1,onRetry:w,testId:"markdown-explorer-edit-failure"})});case"editing":return O.jsx(it,{...e})}},it=({path:e,name:t,session:r,layout:o,viewer:s,region:l,paneScroll:a})=>{const{edits:n,labels:w}=y.useExplorer(),f=E.useRef(null),i=E.useRef(null),d=E.useRef(null),u=E.useRef(null),v=o==="fill",m=y.useSideBySide(),h=y.editViewOf(r,m,v),S=h!=="editor"||r.previewPrepared,M=S&&v,T=E.useRef({layout:o,region:l,paneScroll:a});E.useLayoutEffect(()=>{T.current={layout:o,region:l,paneScroll:a}});const N=E.useRef(r.generation);E.useLayoutEffect(()=>{N.current=r.generation});const D=E.useRef({view:h,previewMounted:S});E.useLayoutEffect(()=>{D.current={view:h,previewMounted:S}});const _=E.useRef(null),V=E.useRef(null),P=E.useRef(!1),x=E.useMemo(()=>({editor:w.editorLabel(t),useOurs:w.conflictUseOurs,useTheirs:w.conflictUseTheirs,keepBoth:w.conflictKeepBoth}),[w,t]),k=E.useCallback(c=>{const{region:p,paneScroll:b}=T.current,q=p();return q===null?c:b.scrollerOf(q,c)},[]);E.useLayoutEffect(()=>{const c=f.current,p=n.draft(e);if(c===null||p===null)return;const b=n.editorState.get(e),q=rt(b)&&b.generation===N.current?b:null;let B=null,R=null;const W=()=>{B!==null&&clearTimeout(B),B=null,R!==null&&n.setDraft(e,R.text())},z=Ce({parent:c,scroll:{scrollerOf:I=>{const{layout:Y,region:be,paneScroll:xe}=T.current,re=be();return Y==="fill"||re===null?I:xe.scrollerOf(re,I)},reveal:I=>T.current.paneScroll.reveal(I)},text:p,saved:q===null?void 0:q.state,labels:x,onGeometry:I=>u.current?.editorChanged(I),onChange:()=>{B??=setTimeout(W,we),D.current.previewMounted&&R!==null&&d.current?.draft(R.text())},onSave:()=>{n.save(e)}});R=z,i.current=z;const ee=()=>{const I=z.topLine();return{line:I.line,clientTop:I.clientTop}},te=()=>d.current?.anchor(k)??null,Ee=n.bindEditor(e,{flush:W,adopt:I=>z.replaceText(I),returnPoint:()=>{const I=D.current.view==="preview"&&T.current.layout==="content"?te():null;return I===null?ee():{line:I.lines.first,clientTop:I.clientTop}},nextConflict:()=>D.current.view!=="preview"?z.nextConflict():z.conflicts().length===0?!1:(P.current=!0,n.setView(e,"editor"),!0),beforeView:I=>{if(T.current.layout==="fill")return;if(I==="preview"){_.current={to:"preview",point:ee()};return}const Y=te();_.current=Y===null?null:{to:"editor",anchor:Y}}});return q!==null&&z.showLine(q.topLine),()=>{W(),n.editorState.set(e,{state:z.save(),generation:N.current,topLine:z.topLine().line}),Ee(),z.destroy(),R=null,i.current=null}},[n,e,x,k]);const{request:L}=r;E.useLayoutEffect(()=>{const c=i.current,p=n.draft(e);c===null||p===null||L===null||(L.anchor!==null&&c.reveal(y.positionInSource(p,L.anchor),L.anchor.clientTop),c.focus(),n.consumeRequest(e))},[n,e,L,x]),E.useLayoutEffect(()=>{h!=="editor"&&!r.previewPrepared&&n.preparePreview(e)},[n,e,h,r.previewPrepared]),E.useLayoutEffect(()=>{const c=_.current,p=V.current,b=P.current;_.current=null,V.current=null,P.current=!1;const q=i.current;if(c?.to==="preview")d.current?.place(c.point,k);else if(c?.to==="editor"&&q!==null){const B=n.draft(e);B!==null&&q.reveal(y.positionInSource(B,c.anchor),c.anchor.clientTop)}b?q?.nextConflict():p==="editor"?q?.focus():p==="preview"&&d.current?.focus()},[n,e,h,k]);const j=E.useCallback(()=>{const c=i.current;if(c===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return c.text()},[]);E.useLayoutEffect(()=>{const c=i.current;if(!M||c===null)return;const p=$e({editor:ve(c.scrollElement),preview:()=>d.current?.scrollPort()??null,previewBlocks:()=>d.current?.blocks()??[],editorSpans:b=>c.lineSpans(b),requestFrame:b=>requestAnimationFrame(b),cancelFrame:b=>cancelAnimationFrame(b),now:()=>performance.now()});return p.showAlone(y.paneShownAlone(D.current.view)),u.current=p,()=>{p.dispose(),u.current=null}},[M,n,e,x]),E.useLayoutEffect(()=>{u.current?.showAlone(y.paneShownAlone(h))},[h]);const g=E.useCallback(()=>u.current?.previewChanged(),[]),H=E.useCallback(c=>n.start(e,c),[n,e]),F=c=>{if(c.key==="Escape"){y.consumeKey(c);return}if(!y.isEditViewShortcut(c.nativeEvent,y.isApplePlatform(navigator.platform)))return;y.consumeKey(c);const p=y.toggledEditView(h);V.current=p,y.chooseEditView(n,e,p,v)};return O.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":h,"data-testid":"markdown-explorer-edit",onKeyDown:F,onDoubleClick:nt,children:[O.jsx("div",{ref:f,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:h==="preview",hidden:h==="preview"&&!v,...y.ALLOW_KEY_REPEAT}),S?O.jsx(et,{path:e,readDraft:j,viewer:s,concealed:h!=="editor"?null:v?"overlay":"removed",onEditAt:h==="preview"?H:void 0,onLayout:g,handleRef:d}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=we;exports.default=ot;