@aiquants/markdown-explorer 0.14.0 → 0.16.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 (60) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/README.md +60 -12
  3. package/dist/EditSurface-CwKsTS11.cjs +2 -0
  4. package/dist/EditSurface-DGMLY7Gh.js +786 -0
  5. package/dist/ExplorerSplit-BLOaU5fE.cjs +1 -0
  6. package/dist/{ExplorerSplit-BPLECNpv.js → ExplorerSplit-tUCp0XdJ.js} +613 -592
  7. package/dist/MultiLayout-BBP2ajz8.cjs +1 -0
  8. package/dist/MultiLayout-DYy66vcO.js +963 -0
  9. package/dist/{NativeScrollBar-BUWXPvTV.cjs → NativeScrollBar-BkFg1EcW.cjs} +1 -1
  10. package/dist/{NativeScrollBar-BFF12oEd.js → NativeScrollBar-Dazd542j.js} +1 -1
  11. package/dist/TreeLayout-C8s5lBH_.cjs +1 -0
  12. package/dist/TreeLayout-CXX-rFO6.js +72 -0
  13. package/dist/client/storage.d.cts +1 -0
  14. package/dist/client/storage.d.ts +1 -0
  15. package/dist/core/geometry.d.cts +20 -1
  16. package/dist/core/geometry.d.ts +20 -1
  17. package/dist/core/labels.d.cts +7 -0
  18. package/dist/core/labels.d.ts +7 -0
  19. package/dist/core/location.d.cts +3 -0
  20. package/dist/core/location.d.ts +3 -0
  21. package/dist/core/treeSettings.d.cts +3 -1
  22. package/dist/core/treeSettings.d.ts +3 -1
  23. package/dist/index-DTKGgaok.js +3613 -0
  24. package/dist/index-DffJZ8-y.cjs +13 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +25 -25
  27. package/dist/location-D85EXiPt.cjs +1 -0
  28. package/dist/location-G7psbmv_.js +499 -0
  29. package/dist/{merge-Bi2VedIr.js → merge-BkFru0eg.js} +5 -5
  30. package/dist/{merge-BFk7nT59.cjs → merge-SRws1-Zj.cjs} +1 -1
  31. package/dist/server/ports.d.cts +8 -1
  32. package/dist/server/ports.d.ts +8 -1
  33. package/dist/server.cjs +1 -1
  34. package/dist/server.d.cts +1 -1
  35. package/dist/server.d.ts +1 -1
  36. package/dist/server.js +512 -499
  37. package/dist/{storage-BSthKLSG.js → storage-CmGHg7OA.js} +11 -10
  38. package/dist/storage-DM0EvkVf.cjs +1 -0
  39. package/dist/storage.cjs +1 -1
  40. package/dist/storage.js +1 -1
  41. package/dist/styles/markdown-explorer.css +1 -1
  42. package/dist/useSplitPersistence-B1b5Lg5E.js +42 -0
  43. package/dist/useSplitPersistence-DRjsPZdH.cjs +1 -0
  44. package/docs/behavior/dom-hooks.md +15 -10
  45. package/docs/behavior/layout.md +53 -14
  46. package/docs/behavior/localization.md +2 -1
  47. package/docs/behavior/url-contract.md +18 -6
  48. package/package.json +12 -10
  49. package/dist/EditSurface-BLlu5zEt.cjs +0 -2
  50. package/dist/EditSurface-CF2io496.js +0 -705
  51. package/dist/ExplorerSplit-Cjvy0JHP.cjs +0 -1
  52. package/dist/MultiLayout-BjA0k-5n.cjs +0 -1
  53. package/dist/MultiLayout-D8F0BfxA.js +0 -947
  54. package/dist/TreeLayout-CQUpgsxz.cjs +0 -1
  55. package/dist/TreeLayout-rhyVTfrI.js +0 -29
  56. package/dist/index-Dn7cYy-4.cjs +0 -13
  57. package/dist/index-v997iKxe.js +0 -3464
  58. package/dist/location-D6RE3wAN.cjs +0 -1
  59. package/dist/location-IRD9h42r.js +0 -444
  60. package/dist/storage-Dgi4JXaB.cjs +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,116 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.0 (2026-10-22) — folders that show their README, a resizable editor split, and fixes from a phone audit
4
+
5
+ ### Added
6
+
7
+ - **The editor and the preview shown side by side can be resized.** A handle on the gutter between them — the explorer
8
+ split's band, grip, keys and target sizes, a `separator` named by the new label `editViewSplitResize` that controls the
9
+ editor — moves the boundary by dragging or with the arrow keys (10 px, 50 px with Shift), in both orientations; either
10
+ side keeps at least 1/φ³ (≈ 23.6 %) of the surface. The reader's share (an even split by default) is kept in browser
11
+ storage under `storageNamespace` (`<namespace>:edit-split`, cleared by `clearExplorerStorage` like the other keys),
12
+ written only after the reader moved the handle. The editor and the preview stay where they were, so switching views is
13
+ as instant as before. See [The editor's split](docs/behavior/layout.md#the-editors-split).
14
+ - **A folder can be selected in the tree view, which then shows the folder's README, as GitHub's file tree does.** A
15
+ click (or Enter or Space) on a folder other than the shown one selects it — its row is selected, a closed folder
16
+ opens and an open one stays open — and replaces the URL's document with the folder: `explorerHref` takes a tree
17
+ target's new `folder` and writes its path with a slash after it (`/docs/tree/guide%2Fconcepts%2F`), and
18
+ `ExplorerLocation`'s tree view carries `folder` beside `doc`. The view shows the folder's README — a file named
19
+ `README` or `README.*`, ignoring case, the plain names first, then by extension: `md`, `markdown`, `mdx`, `txt`,
20
+ none, any other — as the shown document, the skeleton while it is looked for, a line saying the folder has none (the
21
+ new label `folderReadmeMissing`), or the failure of the folder's listing. A lazy folder, or one the loaded tree does
22
+ not reach, is listed through the `children` operation. See
23
+ [Folders and their READMEs](README.md#folders-and-their-readmes) and the
24
+ [Folder segment](docs/behavior/url-contract.md#folder-segment).
25
+ - **README placement:** a tree setting (`readmePlacement`: `"mixed"` by default, `"first"` or `"last"`; labels
26
+ `settingReadmePlacement`, `readmePlacementMixed`, `readmePlacementFirst`, `readmePlacementLast`) puts a folder's
27
+ READMEs before or after its other files once they are sorted, under any sort order; hosts set it for every reader with
28
+ `defaultTreeSettings`.
29
+ - **DOM hooks:** `data-aqmx-content-pane` marks the content pane (the tree view's document column, the single view's
30
+ frame, the multi view's stage, a maximized panel's frame, a view's loading placeholder);
31
+ `markdown-explorer-edit-split` is the split laid over the editing surface, which carries `data-aqmx-edit-split`
32
+ (`beside` / `stacked`) while side by side; `markdown-explorer-folder-empty` and `markdown-explorer-folder-failure`
33
+ are a folder without a README and the failure of a folder's listing.
34
+
35
+ ### Changed
36
+
37
+ - **A click on a folder in the tree view selects it** (above) instead of only opening or closing it; a click on the
38
+ shown folder still opens or closes it, and the multi-panel view's folders only open and close.
39
+ - **A tree or single view's document path that ends in a slash has no URL any more:** such a segment names a folder.
40
+ `explorerHref` throws a `RangeError` for it, and the single view redirects a folder's segment to the tree view.
41
+ - **Side by side, the editor and the preview sit in two columns from 2 × the reading measure + the handle's band**
42
+ (24 px, 44 px under a coarse pointer), each keeping the measure at an even share; below it the preview sits under the
43
+ editor. The two are parted by a gutter as wide as the band with a hairline at its middle (it was a 1 px hairline), and
44
+ the view switch drops its words below the same width.
45
+ - **Text colours reach WCAG 2.2's enhanced 7:1 contrast** (they reached 4.5:1) against every surface and tint they are
46
+ drawn on, in both colour schemes: in the light scheme `--aqmx-text-muted`, `--aqmx-accent` and the editor's
47
+ `--aqmx-syntax-heading`, `--aqmx-syntax-link`, `--aqmx-syntax-code` and `--aqmx-syntax-mark` are darker; in the dark
48
+ scheme `--aqmx-text-muted`, `--aqmx-accent` and `--aqmx-syntax-heading`, `--aqmx-syntax-link` and `--aqmx-syntax-url`
49
+ are lighter. The multi view's restore buttons, drop placeholders and header icons follow, as they are drawn in
50
+ `--aqmx-accent` and `--aqmx-text-muted`.
51
+ - **Text is larger under a coarse pointer, and the tree's rows are in the body size.** Under a coarse pointer (a phone, a
52
+ tablet) the body text — the explorer's header and tree, the document bar, the sheet's toggle, menus and notes — is
53
+ 16 px (1rem, the reader's root size) instead of 13 px, as the controls grow to 44 px there, and Safari on iOS no longer
54
+ zooms the page into the source switch when it takes focus; titles keep 16 px and stand out by their weight. The tree's
55
+ rows take the body size (13 px under a fine pointer) instead of `@aiquants/directory-tree`'s 12 px.
56
+ - **The sheet's close button sits beside the source switch.** On a frame too narrow for the split, the sheet no longer
57
+ gives its close button a row of its own: the sheet's header overlays the explorer's first line, which leaves the button
58
+ its room at the end, beside the source switch (beside the header's actions when there is one source), and takes its
59
+ 44 px height, so the tree starts a row higher. The button is still the first stop in the sheet and takes the focus
60
+ when the sheet opens. The panel-limit notice spans that band, so on one line it now covers the source switch (a
61
+ focus moving onto the switch ends it).
62
+
63
+ ### Fixed
64
+
65
+ - **The explorer's dialogs no longer sit in the viewport's top-left corner under a host's base styles.** The
66
+ confirmation before unsaved changes are lost and the revisions relied on the user agent's `margin: auto`, which a
67
+ host's reset (Tailwind's preflight) removes; they now place themselves, centered over the visible part of the content
68
+ pane and clear of the viewport's edges, and follow the window, the pane and their own size while open. See
69
+ [Dialogs](docs/behavior/layout.md#dialogs).
70
+ - **A dialog the browser closes on its own opens again.** A platform's close request that a page may not cancel (a back
71
+ gesture) closed the confirmation or the revisions while the explorer still held them open, so they could not open
72
+ again until the explorer remounted; such a close now counts as dismissing the dialog.
73
+ - **Pinching an image zooms the image, not the page.** Two fingers on an image's canvas take the zoom one level up or
74
+ down each time the distance between them grows or shrinks by φ, as Zoom in and Zoom out would, and keep the point
75
+ between them under them; one finger still pans the canvas. See [Layout](docs/behavior/layout.md).
76
+ - **A PDF no longer leaves the pane blank in a browser that shows no PDF inside a page** (a phone's Chrome, where
77
+ `navigator.pdfViewerEnabled` is `false`): a note (the new label `pdfNotShown`) takes the frame's place, with links to
78
+ open the PDF in a new tab and to download it (DOM hooks `markdown-explorer-pdf-not-shown`,
79
+ `markdown-explorer-pdf-not-shown-open` and `markdown-explorer-pdf-not-shown-download`). Only the browser can say which
80
+ it is, so the server's HTML holds neither the frame nor the note, and such a browser no longer starts loading the PDF.
81
+ - **The explorer's resize handle no longer covers the tree's scroll bar or the start of the content.** The handle's band
82
+ lies over the boundary, so the explorer and the content now keep half of it clear on their sides (12 px under a fine
83
+ pointer, 22 px under a coarse one); on a landscape phone the 44 px band covered both.
84
+ - **A multi-view panel keeps the reader's line when the column count changes.** The element at the top of the panel was
85
+ put back as far above the top as it had been, so when its text rewrapped shorter in a wider column the panel showed
86
+ the next paragraph instead; an element that crossed the top now keeps the same share of its height above it (one that
87
+ started below the top keeps its distance). The panel also put the place back before the rebuilt panel had its new
88
+ width, leaving the browser's re-anchoring (which keeps a distance) to finish; it now puts the reader's place back at
89
+ every change of the panel's width (the explorer's handle resizing the columns included).
90
+ - **The README names the peer floors the package declares** (`@aiquants/markdown` ^7.0.0, `@aiquants/resize-panels`
91
+ ^2.2.0, `@aiquants/virtualscroll` ^3.20.0); it named older ones. A unit test now holds the README to the floors the
92
+ package publishes.
93
+
94
+ ## 0.15.0 (2026-10-21) — an `asset` port that may answer a short-lived URL, and `@aiquants/markdown` 7
95
+
96
+ ### Added
97
+
98
+ - **The `asset` port may answer a short-lived URL instead of bytes.** The port receives a fourth argument,
99
+ `{ redirect }` (the new `ExplorerAssetOptions`), which is `true` only when the `asset` operation delivers the stored
100
+ file. The port may then answer `{ kind: "redirect", url }` (the new `ExplorerAssetRedirect`) with an absolute `https:`
101
+ URL without credentials, and the data route answers `302` to it with `Cache-Control: private, no-store` and
102
+ `Referrer-Policy: no-referrer`, after the same deny rules and admission, for GET and HEAD, with or without `Range`.
103
+ Hosts that never answer a redirect keep streaming, unchanged; see [Redirecting to the storage](README.md#redirecting-to-the-storage)
104
+ for what a redirecting host must allow (CSP origins, COEP and CORP, seeking against the URL's lifetime, no shared caching).
105
+
106
+ ### Changed
107
+
108
+ - **The peer `@aiquants/markdown` is `^7.0.0`.** Its service and `parseMarkdown` require `MARKDOWN_SOCKET_PATH`, its
109
+ socket is owner-only by default and it refuses non-canonical schemes; a host upgrades both together.
110
+ - **An `asset` answer that carries a `kind` key must be a valid redirect.** A redirect where `redirect` is `false`
111
+ (`&as=text` and the `text` operation read the bytes themselves), a URL that is not absolute `https:` without
112
+ credentials, or another `kind` is a contract violation, logged and answered `failed`, as any malformed answer.
113
+
3
114
  ## 0.14.0 (2026-10-16)
4
115
 
5
116
  ### Breaking
package/README.md CHANGED
@@ -33,14 +33,14 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
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.
35
35
  - **Multi-panel reading** — open documents as panels, rearrange them by dragging (on a touch screen or with a pen, after a long-press on a panel's header), with the move buttons in each panel's header, or with Alt + Shift + arrow keys, hide, maximize (Escape restores), and navigate inside a panel; the arrangement survives reloads, and a document reopened later returns to its column.
36
- - **Accessible and localized** — named landmarks and controls, a keyboard-operable tree with one Tab stop on the shown document, keyboard-operable menus, panel headers and resize handle, polite announcements (spoken from the sheet while it is open), WCAG 2.2 contrast in light and dark; English (default) and Japanese built in — the tree's and the panel headers' strings included —, every string overridable.
36
+ - **Accessible and localized** — named landmarks and controls, a keyboard-operable tree with one Tab stop on the shown document, keyboard-operable menus, panel headers and resize handle, polite announcements (spoken from the sheet while it is open), WCAG 2.2 enhanced contrast (7:1 for text) in light and dark; English (default) and Japanese built in — the tree's and the panel headers' strings included —, every string overridable.
37
37
 
38
38
  ## Requirements
39
39
 
40
40
  - React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
41
41
  - 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)`.
42
- - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^6.3.0 (document rendering; its math diagnostics, gantt sizing, embeds, link cards and their sizes, the React-free `@aiquants/markdown/embeds` the sanitizer worker loads and `@aiquants/markdown/source-lines` the editor and the sanitizer read, and the Node-only link-card handler of `@aiquants/markdown/server`, which needs Node.js 22.13 or later — below the explorer's own floor),
43
- `@aiquants/directory-tree` ^4.1.1 (reveals of rows under the scroll bar's buttons), `@aiquants/drag-drop-panels` ^0.10.0, `@aiquants/resize-panels` ^2.1.0 (the source of each layout change, by which the tree pane's width is saved) and `@aiquants/virtualscroll` ^3.11.4.
42
+ - The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^7.0.0 (document rendering; its math diagnostics, gantt sizing, embeds, link cards and their sizes, the React-free `@aiquants/markdown/embeds` the sanitizer worker loads and `@aiquants/markdown/source-lines` the editor and the sanitizer read, and the Node-only link-card handler of `@aiquants/markdown/server`, which needs Node.js 22.13 or later — below the explorer's own floor),
43
+ `@aiquants/directory-tree` ^4.1.1 (reveals of rows under the scroll bar's buttons), `@aiquants/drag-drop-panels` ^0.10.0, `@aiquants/resize-panels` ^2.2.0 (the source of each layout change, by which the tree pane's width is saved) and `@aiquants/virtualscroll` ^3.20.0.
44
44
  The client depends on these floors, while a package manager may only warn about an older peer.
45
45
  - A Markdown parser of your choice on the server that produces HTML and its headings (the explorer sanitizes the HTML before it is sent).
46
46
  - Browsers: the multi view's panel-limit notice uses the Popover API (Chrome and Edge 114, Firefox 125, Safari 17 and later). In browsers without it (for example iOS 16), the notice is drawn in place at the stage's corner instead of in the top layer (while the sheet is open it spans the sheet's header, as in every browser).
@@ -86,7 +86,7 @@ The source ids are not part of it: they are the ids of the server's `sources` (a
86
86
  | `documentStyles?` | `readonly { name, className }[]` | Document styles, the first being the default; `@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLES` (None, GitHub, Zenn; also exported without React from `@aiquants/markdown/viewer-settings`) when omitted. |
87
87
  | `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. |
88
88
  | `embeds?` | `{ providers?, linkCards?, linkCardSize? }` | What `@aiquants/markdown` makes of a link alone in a paragraph. `providers` lists the ids (`EMBED_PROVIDER_IDS` of `@aiquants/markdown/embeds`: `youtube`, `x`, `instagram`, `threads`, `tiktok`, `bluesky`, `linkedin`, `reddit`, `note`, `niconico`) whose posts and videos documents embed as cross-origin frames, whatever the link's text. `linkCards: true` turns a link written as its own URL into a card, which the data route's own `link-card` operation serves (see [Link cards](#link-cards)): no route of yours is needed. `linkCardSize` picks the size of every card, `compact`, `banner` or `full` (`LINK_CARD_SIZES` of `@aiquants/markdown/embeds`; `@aiquants/markdown`'s `banner` when omitted), and needs `linkCards: true`. Each field defaults to none (`[]`, `false`, omitted), also when given as `undefined`, so without the option such a link stays its paragraph. Repeated ids are removed. An unknown id, a `linkCards` that is not a boolean, an unknown size, a size without `linkCards: true` or an unknown key (`linkCardEndpoint` included) throws a `RangeError` (`[markdown-explorer] embeds…`), and anything but a plain object a `TypeError`. The resolved `config.embeds` is the `MarkdownEmbeds` the viewer takes: `linkCardEndpoint` is `<dataPath>/link-card` when link cards are on and `null` otherwise, and `linkCardSize` is present only when given. See `@aiquants/markdown`'s README (Embeds) for the URLs each provider recognizes, the frames' sizes and the cards' sizes. |
89
- | `defaultTreeSettings?` | `Partial<TreeSettings>` | The reader's tree settings before they change any, merged over the package's `DEFAULT_TREE_SETTINGS` (the source's own order, folders mixed among the files, Single selection, a recursive double click, 8 px expand icons, nothing kept expanded, the open document not revealed, the root indent kept, lines, expand icons and folder and file icons on). Each value is one the settings menu offers: `sortMode` `"native"`, `"asc"`, `"desc"`, `"oldest"` or `"newest"` (by the entries' `modifiedAt`); `folderPlacement` `"mixed"`, `"first"` or `"last"`; `selectionMode` `"single"`, `"multiple"` or `"none"`; `doubleClickAction` `"recursive"` or `"toggle"`; `expandIconSize` `8`, `13` or `5`; the other settings (`alwaysExpanded`, `revealDocument`, `removeRootIndent`, `lines`, `expandIcons`, `directoryIcons`, `fileIcons`) `true` or `false`. An unknown key or any other value throws a `RangeError`, and anything but a plain object (a `Map`, a class instance, an object inheriting its settings) throws a `TypeError`; a setting given as `undefined` keeps the package default. The server render and the hydration draw these defaults (see [Tree settings](#tree-settings)). |
89
+ | `defaultTreeSettings?` | `Partial<TreeSettings>` | The reader's tree settings before they change any, merged over the package's `DEFAULT_TREE_SETTINGS` (the source's own order, folders and READMEs mixed among the files, Single selection, a recursive double click, 8 px expand icons, nothing kept expanded, the open document not revealed, the root indent kept, lines, expand icons and folder and file icons on). Each value is one the settings menu offers: `sortMode` `"native"`, `"asc"`, `"desc"`, `"oldest"` or `"newest"` (by the entries' `modifiedAt`); `folderPlacement` `"mixed"`, `"first"` or `"last"`; `readmePlacement` `"mixed"`, `"first"` or `"last"`; `selectionMode` `"single"`, `"multiple"` or `"none"`; `doubleClickAction` `"recursive"` or `"toggle"`; `expandIconSize` `8`, `13` or `5`; the other settings (`alwaysExpanded`, `revealDocument`, `removeRootIndent`, `lines`, `expandIcons`, `directoryIcons`, `fileIcons`) `true` or `false`. An unknown key or any other value throws a `RangeError`, and anything but a plain object (a `Map`, a class instance, an object inheriting its settings) throws a `TypeError`; a setting given as `undefined` keeps the package default. The server render and the hydration draw these defaults (see [Tree settings](#tree-settings)). |
90
90
 
91
91
  For example, `defaultTreeSettings: { sortMode: "desc" }` lists every folder's entries by name, Z to A, until the reader picks another order.
92
92
 
@@ -255,21 +255,33 @@ to; load it when your documents contain math.
255
255
 
256
256
  | View | URL | What it shows |
257
257
  | --- | --- | --- |
258
- | Tree | `{basePath}/{tree}` or `{basePath}/{tree}/{document}` | The source tree beside the selected document |
258
+ | Tree | `{basePath}/{tree}`, `{basePath}/{tree}/{document}` or `{basePath}/{tree}/{folder}/` | The source tree beside the selected document, or the selected folder's README |
259
259
  | Multi-panel | `{basePath}/{multi}?doc=…&doc=…&maximized=…&markup=…` | Several documents as panels in columns |
260
260
  | Single | `{basePath}/{single}/{document}` | One document over the whole frame (for reading and embedding) |
261
261
 
262
262
  - `?source=<id>` selects the tree's source among the server's sources; the first source is the default and is written by omission. Switching the source never closes open documents — a document path names one document whichever trees list it.
263
263
  - A document path occupies one URL segment. Build links with `explorerHref(config, target)`, the only function that writes explorer URLs; read them back with `resolveExplorerLocation(config, splat, search)`. Both need the server's source ids for the `source` parameter: pass a configuration joined with them, `withExplorerSources(config, sourceIds)` (`ExplorerLocationConfig`; `isExplorerSourceId` is the id rule, and an empty, invalid or repeated id throws a `RangeError`).
264
264
  `explorerHref` also accepts a plain `ExplorerConfig` with a target without `source` (`ExplorerSourcelessHrefTarget`, the default source), such as a host menu's link; a target with a `source` and a configuration without ids throws a `TypeError` naming `withExplorerSources`, as does `resolveExplorerLocation` with such a configuration.
265
- `explorerHref` throws a `RangeError` for a target the resolver would redirect or partly ignore — repeated or more than `multiView.maxPanels` documents, a maximized document or a document shown as written that is not open, an unknown source or document style, an unsupported alignment or embedding value, a tree view without a document shown as written — so every link it writes resolves back to the location given.
265
+ `explorerHref` throws a `RangeError` for a target the resolver would redirect, read as another location or partly ignore — repeated or more than `multiView.maxPanels` documents, a maximized document or a document shown as written that is not open, an unknown source or document style, an unsupported alignment or embedding value, a tree view with both a document and a folder, a document path that ends in a slash, a tree view with neither a document nor a folder shown as written — so every link it writes resolves back to the location given.
266
+ - A folder of the tree view takes the same segment with a slash after its path: `explorerHref(config, { view: "tree", folder: "guide/concepts" })` writes `/docs/tree/guide%2Fconcepts%2F`, and `ExplorerLocation`'s tree view carries `doc` and `folder`, at most one of them not `null` (see [Folders and their READMEs](#folders-and-their-readmes)). The single view shows documents only and redirects a folder to the tree view.
266
267
  - The single view accepts embedding parameters: `showToc=false`, `showStyle=false`, `showAlign=false`, `padding` (0–256 px, written in decimal digits), `width` and `maxWidth` (a CSS length in px, rem, em, ch, vw or %; the column never grows wider than the pane, whatever the value). The tree and single views accept `style` and `align` as display overrides.
267
268
  - `markup` names the Markdown documents shown as written (the Source toggle): `markup=true` for the tree or single view's document, and one `markup=<document>` per open document shown that way in the multi view, in the order of `doc`. In `ExplorerLocation` it is a boolean in the tree and single views and a list in the multi view; a target without it shows every document rendered.
268
- - History: a click in the tree replaces the URL's document; links inside a document, entries of its table of contents (in the tree and single views, to the heading's hash), source switches and view switches push; every multi-view action and the Source toggle replace (hiding and showing a panel leave the URL unchanged).
269
+ - History: a click in the tree replaces the URL's document or folder; links inside a document, entries of its table of contents (in the tree and single views, to the heading's hash), source switches and view switches push; every multi-view action and the Source toggle replace (hiding and showing a panel leave the URL unchanged).
269
270
  - An entry of a document's table of contents links to its heading's own address: the page's URL with the heading's fragment, or, in a multi-view panel, the panel's document in the tree view with that fragment, so a modified or middle click, a new tab or a copied address opens the heading (see [URL contract](docs/behavior/url-contract.md#table-of-contents)).
270
271
 
271
272
  The full contract, including canonicalization, is in [URL contract](docs/behavior/url-contract.md).
272
273
 
274
+ ### Folders and their READMEs
275
+
276
+ In the tree view a folder can be selected as GitHub's file tree does, and the view then shows the folder's README beside the tree.
277
+
278
+ - **Selecting**: a click (or Enter or Space) on a folder other than the shown one selects it: the URL's document is replaced with the folder (no history entry), its row is selected, and a closed folder opens; an open one stays open. A click on the shown folder opens or closes it, as before, and a double click still opens or closes it with its subfolders. The arrow keys move and open folders without selecting them. In the multi-panel view a click on a folder only opens or closes it.
279
+ - **Which README**: a README is a file whose name, ignoring case, is `README` or starts with `README.` (`README.md`, `readme.txt`, `README.ja.md`); a folder named so is not one. Among a folder's READMEs the view shows a plain name (`README` with at most one extension) before a longer one, then by extension — `md`, `markdown`, `mdx`, `txt`, none, any other —, then by name and path in the explorer's collation (`folderReadmeOf`).
280
+ - **Where the folder's files come from**: the children its row has in the shown source's tree; a lazy folder whose children are unknown, or a folder the loaded tree does not reach, is listed by the data route's `children` operation, as when the reader opens it. A folder the source does not have answers that operation's `not-found` (a source without `children` answers `not-found` for every folder its tree does not list).
281
+ - **What shows**: the README as the shown document — its refresh bar, Source toggle, editing, the switch to the multi-panel view and the selection's panels all act on it —, the skeleton while it is looked for, a line saying the folder has none (`folderReadmeMissing`, announced once per folder), or the listing's failure, announced once per failed attempt, with Try again for a transient one.
282
+ - **First paint**: the page loader seeds no document for a folder, because which README it shows depends on the folder's listing: the server renders the skeleton, and the browser finds the README in the tree (the source's tree seeds the first paint) and loads it.
283
+ - **Revealing**: with the reader's `revealDocument` the tree brings a folder's row into view where it lists it, but never opens the folders down to it: the reveal's ports (`ancestors`, `reveal`) answer for documents.
284
+
273
285
  ## Server API
274
286
 
275
287
  ### `createMarkdownExplorer(config)`
@@ -282,7 +294,7 @@ The full contract, including canonicalization, is in [URL contract](docs/behavio
282
294
  | `scopeSecret` | `string` | The deployment's secret for the readers' scopes: at least 32 characters (a shorter one throws a `RangeError`) and the same on every server instance. |
283
295
  | `sources` | `ExplorerSource<P>[]` | The sources in switcher order (at least one; the first is the default): `id` (lowercase letters, digits and `-`, starting with a letter or digit, unique; the URL's `source` value), `label` (a string, or a function of the principal), `boundary` (where the source's documents may lie, see [Source boundaries](#source-boundaries)), `tree(context)` (lists the source's roots), `children?(context, path, readPath)` for lazy folders (asked only while the tree shows the folder open — the reader opened it, Expand all opened it (a press keeps opening folders as their listings land, within `expandAll`), or a remembered expansion opened it — and only for a path inside the source's boundary; a listing no tree wants any more is aborted through `context.signal`, which the source should honour), `ancestors?(context, path, readPath, options)` (the folders down to a document, for the reader's reveal; see [Revealing the open document](#revealing-the-open-document)), `cacheScope?` (`"principal"`, the default, or `"shared"`). The `context` is described under [Entries and notices](#entries-and-notices). |
284
296
  | `document` | `(context, path, readPath) => Promise<ExplorerHostDocument>` | Resolves a document path. Called only for a path inside at least one source's boundary; `readPath` is what the admitting source's `confirm` answered (`path` when that source has no `confirm`), so read `readPath` and show the document as `path`. An image, media, text or file document reports its file's `version`; the explorer writes its URL (see [Documents](#documents)). |
285
- | `asset` | `(context, path, readPath) => Promise<ExplorerAssetFile>` | Finds the file behind the data route's `asset` operation (and its `text` operation, which reads a Markdown document's source through it): any regular file the document admission admits, whatever its kind. Called only after the path passed the deny rules and the same union admission as a document, with the same `readPath`; see [Serving files](#serving-files). |
297
+ | `asset` | `(context, path, readPath, options) => Promise<ExplorerAssetFile \| ExplorerAssetRedirect>` | Finds the file behind the data route's `asset` operation (and its `text` operation, which reads a Markdown document's source through it): any regular file the document admission admits, whatever its kind. Called only after the path passed the deny rules and the same union admission as a document, with the same `readPath`; see [Serving files](#serving-files). With `options.redirect` true it may answer a short-lived URL instead, see [Redirecting to the storage](#redirecting-to-the-storage). |
286
298
  | `signedOutPage` | `(request, headers) => Response` | The page response for a signed-out reader, usually a redirect to sign-in. Data requests answer 401 instead. |
287
299
  | `forbiddenPage?` | `(request, headers) => Response` | The page response for a reader without access (default: a 403 for the route's error boundary). |
288
300
  | `notices?` | `(context) => Promise<ExplorerNotice[]>` | Callouts above the tree (a missing permission with a link that grants it, for example). |
@@ -371,6 +383,8 @@ An answer of those kinds that carries a `url` key, or lacks a valid `version`, b
371
383
  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
384
  Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
373
385
  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.
386
+ A `media` document of type `pdf` opens in a frame, in the browser's own PDF viewer; a browser that says it shows no PDF inside a page (`navigator.pdfViewerEnabled` is `false`, as a phone's Chrome does) gets a note instead (the label `pdfNotShown`) with links to open the PDF in a new tab and to download it, since the frame would stay blank.
387
+ Only the browser can say which, so the server's HTML holds neither, and a browser that cannot show the PDF never starts loading it.
374
388
 
375
389
  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.
376
390
 
@@ -541,6 +555,33 @@ The URL carries the path in its query, so no name needs an extra escape and the
541
555
  The data route's `text` operation reads a file through the same port for the Source toggle: `<dataPath>/text?path=<document path>` (GET and HEAD) takes the same authentication, deny rules (a refusal logged once with the operation `text`) and admission as `asset`, then answers JSON like a document request — status 200 with a text document (`name`, `text`, `truncated`, and the file's asset `url` with its version) or a failure document, and the reader's scope header.
542
556
  It reads at most `textMaxBytes` bytes (the first ones as a range when `size` is larger, the whole file otherwise, an empty file never, a file of unknown `size` one byte past the limit to learn whether more follows), cancels the stream once enough was read, decodes them as UTF-8 (a leading byte order mark dropped, a multi-byte character the limit cuts left out), and answers `unsupported` for bytes holding NUL and `failed` (logged) for a stream that ends before the `size` the port reported. It sends no refresh mark: the port receives `refresh: false`.
543
557
 
558
+ ### Redirecting to the storage
559
+
560
+ A host whose storage issues short-lived URLs (a storage-api `gcs://` signed URL, for example) can let the browser read a file's bytes from the storage instead of through the explorer.
561
+ The `asset` port receives a fourth argument, `{ redirect }`: it is `true` only when the `asset` operation delivers the stored file, and `false` for `&as=text` and the `text` operation, which read the bytes themselves.
562
+ When it is `true` the port may answer an `ExplorerAssetRedirect`, `{ kind: "redirect", url }`, instead of an `ExplorerAssetFile`:
563
+
564
+ ```ts
565
+ asset: async (context, path, readPath, { redirect }) =>
566
+ redirect ? { kind: "redirect", url: await signedUrlOf(readPath, context.signal) } : fileOf(readPath, context.signal),
567
+ ```
568
+
569
+ The explorer then answers `302` with `Location: <url>`, `Cache-Control: private, no-store` and `Referrer-Policy: no-referrer` (plus the headers authentication returned), for GET and HEAD alike and with or without `Range`: the storage answers ranges itself.
570
+ The deny rules and the source admission run before the port exactly as for a file, so a denied or unadmitted path never reaches the port and is never redirected; `If-None-Match` is not read for a redirect.
571
+ The page's HTML keeps pointing at the explorer's own `asset` operation.
572
+ The URL must be absolute `https:` without credentials (it is written as the URL parser serializes it); any other URL, a redirect when `redirect` is `false`, or an answer whose `kind` is not `"redirect"` is a contract violation, logged and answered `failed` (500).
573
+ A host that never answers a redirect keeps streaming through `open`, unchanged.
574
+
575
+ What a host that redirects must allow and decide:
576
+
577
+ | Concern | What to do |
578
+ | --- | --- |
579
+ | CSP | The redirect target is checked against the page's policy. Add the storage's origin (`https://storage.googleapis.com` for storage-api's Cloud Storage URLs) to `img-src` and `media-src`, to `frame-src` / `object-src` when PDFs are shown in frames, and to `connect-src` for `fetch`. |
580
+ | COEP and CORP | Under `Cross-Origin-Embedder-Policy: require-corp` a cross-origin response needs `Cross-Origin-Resource-Policy: cross-origin` or CORS, and Cloud Storage sends neither by default: configure the bucket's CORS for the page's origin and load with `crossorigin="anonymous"`, or use `COEP: credentialless`. CORS is also needed whenever the bytes are read into a canvas. |
581
+ | Range, seeking and lifetime | A media element may reuse the URL it was redirected to for later range requests (seeking), and those fail with 403 once the URL expires. Choose a lifetime that covers a viewing session, or make sure each request comes back through the explorer's route. |
582
+ | Caching | The redirect is never cached (`private, no-store`). Never let a shared cache (a CDN or reverse proxy) store it: the URL lets whoever holds it read the file until it expires. |
583
+ | What the storage serves | The storage answers with the object's stored content type and its own headers, not the explorer's (download disposition, `nosniff`, sandboxing). Redirect only the kinds whose in-place display you accept (images, audio, video); the port receives `path` to decide. |
584
+
544
585
  ### Link cards
545
586
 
546
587
  With `embeds: { linkCards: true }`, the data route has a `link-card` operation: `GET` or `HEAD` `<dataPath>/link-card?url=<href>`, which `@aiquants/markdown`'s link card asks (same-origin, in the background, once the card nears the viewport). It is the only route of the cards: the explorer creates `@aiquants/markdown`'s `createLinkCardHandler` once, in `createMarkdownExplorer`, behind the read-only authentication, and passes every answer of it through unchanged — status, headers and cache headers. In order:
@@ -610,7 +651,7 @@ Spread it into the configuration when your application has no sign-in: it provid
610
651
  | --- | --- | --- |
611
652
  | `data` | `ExplorerPageData` | `useLoaderData()` of the page route. |
612
653
  | `config` | `ExplorerConfig` | The shared configuration. |
613
- | `storageNamespace` | `string` | Prefix of the browser storage keys (tree settings, expansion state, the multi-view layout): 1–64 letters, digits, `.`, `_` or `-`, starting with a letter or digit (anything else throws a `RangeError`). |
654
+ | `storageNamespace` | `string` | Prefix of the browser storage keys (tree settings, expansion state, the multi-view layout, the editor's side-by-side setting and share): 1–64 letters, digits, `.`, `_` or `-`, starting with a letter or digit (anything else throws a `RangeError`). |
614
655
  | `locale?` | `"en" \| "ja"` | The UI language (default `"en"`). |
615
656
  | `labels?` | `Partial<MarkdownExplorerLabels>` | Per-key overrides; strings that embed a value are functions, except the multi view's templates for `@aiquants/drag-drop-panels` (`MARKDOWN_EXPLORER_LABEL_TEMPLATES`). |
616
657
  | `theme?` | `"light" \| "dark"` | The colour scheme (default `"light"`). |
@@ -630,7 +671,9 @@ With `lockDocumentScroll` the explorer must fill a container of definite block s
630
671
  The reader's tree settings are kept in memory for the explorer's lifetime and saved to browser storage under `storageNamespace` when the browser allows it; where it cannot write (blocked site data, a full quota) they last until the explorer unmounts (a navigation away from its route, a reload). The server render and the hydration use the defaults — the package's, with the configuration's `defaultTreeSettings` over them — and the stored settings apply right after the hydration.
631
672
  Storage keeps only the settings the reader changed, each with the value they chose: a later change of `defaultTreeSettings` reaches every setting the reader has left alone, the ones they changed stay as they set them (also when a later default happens to equal their choice), and a setting the reader moves back to the default in force at that moment is dropped from storage, so later defaults reach it again.
632
673
  A stored value of another format version is ignored, so its reader starts from the defaults. A stored `directoriesFirst` (from when "Folders first" was a switch) is read as `folderPlacement`: `true` as `"first"`, `false` as `"mixed"` (a stored `false` exists only where the default was `true`), unless a `folderPlacement` is stored too; the next change the reader makes stores the new key only. Folders: Mixed (the package default) keeps the source's order, or interleaves folders and files by name under a name order;
633
- First puts the folders before the files and Last after them, under any sort order (a descending name order reverses the names, not the placement). Reveal the open document: see [Revealing the open document](#revealing-the-open-document). Selection: Single (the package default) selects the shown document; Multiple gathers clicked documents in a tray that opens them as panels; Off shows no row as selected, not even the shown document.
674
+ First puts the folders before the files and Last after them, under any sort order (a descending name order reverses the names, not the placement).
675
+ README: Mixed (the package default) keeps a folder's READMEs in the sort; First puts them before the folder's other files and Last after them — before or after its folders too while folders mix with the files — under any sort order, and the READMEs keep the sort among themselves (what a README is: [Folders and their READMEs](#folders-and-their-readmes)).
676
+ Reveal the open document: see [Revealing the open document](#revealing-the-open-document). Selection: Single (the package default) selects the shown document or folder; Multiple gathers clicked documents in a tray that opens them as panels; Off shows no row as selected, not even the shown document.
634
677
  The tray shrinks and scrolls before the tree does: the tree keeps at least three rows at any text size, the tray keeps its header row and scrolls the rest, and an explorer too short for both scrolls as a whole. Always expanded shows every folder whose contents are known as expanded; a lazy folder stays collapsed until the reader opens it, so the setting never loads folders by itself.
635
678
 
636
679
  Call `clearExplorerStorage(storageNamespace)` when a reader signs out of a shared browser (it throws a `RangeError` for a malformed namespace instead of clearing the wrong keys). Import it from `@aiquants/markdown-explorer/storage`: that entry imports nothing (no React, no `@aiquants/markdown`), so a layout or root route that runs on every page can call it without loading the explorer; the root entry exports the same function. The explorer also clears the namespace by itself: on every page load, before anything reads it, when the reader recorded there is not the page's reader, and when a data response reports a different reader.
@@ -660,10 +703,12 @@ A save writes the draft back with the line endings of the file it opened (`\r\n`
660
703
  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.
661
704
  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
705
  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.
706
+ Side by side, a handle on the gutter between the two resizes them, as the explorer's handle resizes the explorer: drag it, or focus it and press the arrow keys (10 px, 50 px with Shift); either side keeps at least 1/φ³ (≈ 23.6 %) of the surface, and the reader's share (an even split by default) is kept in browser storage under `storageNamespace`, for beside and below alike.
663
707
  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
708
  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
709
  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
710
  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.
711
+ The confirmation before an unsaved draft is lost and the revisions are modal dialogs centered over the content pane — the document beside the tree, the single view's document, the multi view's panels or the panel maximized over them — and keep clear of the viewport's edges; they place themselves, so a host's base styles that reset a dialog's margins (Tailwind's preflight) do not move them.
667
712
  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.
668
713
  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.
669
714
 
@@ -738,12 +783,15 @@ The labels the layout fills with a value are templates with `{name}` placeholder
738
783
  | Explorer maximum | the golden section 1/φ² ≈ 38.197 % |
739
784
  | Explorer minimum | 13rem (208 px at a 16 px root font size; 16 px is assumed until the browser measures it) |
740
785
  | Narrow frames | below 13rem × φ² the explorer leaves the split and opens as a sheet over the content, from a labelled 44 px toggle |
741
- | Resize handle | a band 24 px wide under a fine pointer and 44 px under a coarse one, around a 5 × 34 px grip |
786
+ | Resize handle | a band 24 px wide under a fine pointer and 44 px under a coarse one, around a 5 × 34 px grip (the explorer's and the editor's); the sides keep the band clear, so it covers neither the tree's scroll bar nor the content's edge |
787
+ | Editor beside the preview | an even split by default; either side keeps at least 1/φ³ ≈ 23.607 % of the surface; two columns from 2 × the reading measure + the handle's band, else the preview below the editor |
788
+ | Dialogs | centered over the visible part of the content pane, at least 21 px (`--aqmx-space-7`) from every edge of the viewport |
742
789
  | Multi-view column minimum | 40ch at 1rem (the multi-column reading measure) |
743
790
  | Multi-view panel height | between the stage height / φ³ and the stage height / φ, except that the panel's scroll area always keeps three lines of 1rem × φ text below the panel's header (where the header wraps that far, the panel is the header plus that floor) |
744
791
  | Spacing, controls, durations | Fibonacci numbers (px written in rem; ms), except the pointer targets: 44 px (2.75rem) for every control under a coarse pointer and for the sheet's toggle and close button, and the resize handle's 24 px under a fine pointer |
792
+ | Text sizes | 13, 16 and 21 px (0.8125, 1 and 1.3125rem) for body text, titles and display text; under a coarse pointer the body text is 16 px (1rem) as well; tree rows are in the body size |
745
793
 
746
- The reader's own explorer width is remembered per view as a percentage, and only after the reader moves the handle: a drag that moved it (once, when it ends) or an arrow key that moved it, never a press that moved nothing or a change of the window. The document's column fills its pane; the viewer's alignment control appears only for a column a single-view embed narrows (`?width=` / `?maxWidth=`). See [Layout](docs/behavior/layout.md).
794
+ The reader's own explorer width is remembered per view as a percentage, and only after the reader moves the handle: a drag that moved it (once, when it ends) or an arrow key that moved it, never a press that moved nothing or a change of the window. The editor's share beside the preview is remembered the same way. The document's column fills its pane; the viewer's alignment control appears only for a column a single-view embed narrows (`?width=` / `?maxWidth=`). See [Layout](docs/behavior/layout.md).
747
795
 
748
796
  ### Scroll bars and the tap-scroll circle
749
797
 
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("react/jsx-runtime"),p=require("react"),x=require("./index-DffJZ8-y.cjs"),ee=require("@codemirror/commands"),ae=require("@codemirror/lang-markdown"),ye=require("@codemirror/language"),ce=require("@codemirror/search"),K=require("@codemirror/state"),I=require("@codemirror/view"),_=require("@lezer/highlight"),Ce=require("@aiquants/markdown"),ne=require("@aiquants/markdown/source-lines"),W=require("./dataRoute-BONacTPi.cjs"),oe=require("./sanitizePolicy-DrIMuYCb.cjs"),_e=require("isomorphic-dompurify"),Q=require("@aiquants/resize-panels"),G=require("./location-D85EXiPt.cjs"),ue=require("./useSplitPersistence-DRjsPZdH.cjs"),Te={history:ee.historyField},Pe=ye.HighlightStyle.define([{tag:[_.tags.heading1,_.tags.heading2,_.tags.heading3,_.tags.heading4,_.tags.heading5,_.tags.heading6,_.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:_.tags.strong,fontWeight:"700"},{tag:_.tags.emphasis,fontStyle:"italic"},{tag:_.tags.strikethrough,textDecoration:"line-through"},{tag:_.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:_.tags.url,color:"var(--aqmx-syntax-url)"},{tag:_.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:_.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[_.tags.processingInstruction,_.tags.contentSeparator,_.tags.labelName,_.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ne=I.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)"}}),Le="data-aqmx-conflict-actions",De=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Ve=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),je=I.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class He extends I.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(Le,String(this.index));for(const[o,a]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const s=document.createElement("button");s.type="button",s.textContent=a,s.setAttribute("data-aqmx-conflict-choice",o),s.addEventListener("mousedown",l=>l.preventDefault()),s.addEventListener("click",()=>{const l=Y(t.state.doc)[this.index];l!==void 0&&(ke(t,l,o),t.focus())}),r.append(s)}return r}ignoreEvent(){return!0}}const Y=e=>x.findConflictsInLines(e.iterLines()),de=(e,t)=>{const r=new K.RangeSetBuilder;return Y(e).forEach((o,a)=>{const s=e.line(o.start);r.add(s.from,s.from,I.Decoration.widget({widget:new He(a,t),block:!0,side:-1}));for(let l=o.start;l<=o.end;l+=1){const n=e.line(l).from,h=l===o.start||l===o.separator||l===o.end?De:l<o.separator?Ve:je;r.add(n,n,h)}}),r.finish()},Be=e=>K.StateField.define({create:t=>de(t.doc,e),update:(t,r)=>r.docChanged?de(r.state.doc,e):t,provide:t=>I.EditorView.decorations.from(t)}),ke=(e,t,r)=>{const{doc:o}=e.state,a=(u,c)=>{const g=[];for(let m=u;m<=c;m+=1)g.push(o.line(m).text);return g},s=a(t.start+1,t.separator-1),l=a(t.separator+1,t.end-1),n=r==="ours"?s:r==="theirs"?l:[...s,...l];let h=o.line(t.start).from,f=o.line(t.end).to;n.length===0&&(t.end<o.lines?f+=1:t.start>1&&(h-=1));const i=n.join(`
2
+ `);e.dispatch({changes:{from:h,to:f,insert:i},selection:K.EditorSelection.cursor(h),scrollIntoView:!0,userEvent:"input.resolve"})},ze=({parent:e,scroll:t,text:r,saved:o,labels:a,onChange:s,onGeometry:l,onSave:n})=>{const h=[I.EditorView.scrollHandler.of((u,c,g)=>(Fe(u,c.head,g,t),!0)),I.lineNumbers(),I.highlightActiveLineGutter(),ee.history(),I.drawSelection(),I.highlightActiveLine(),ce.highlightSelectionMatches(),I.EditorView.lineWrapping,ae.markdown({base:ae.markdownLanguage}),ye.syntaxHighlighting(Pe),Be(a),I.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(n(),!0)},...ce.searchKeymap,...ee.historyKeymap,...ee.defaultKeymap]),I.EditorView.contentAttributes.of({"aria-label":a.editor,"aria-multiline":"true"}),I.EditorView.updateListener.of(u=>{u.docChanged&&s(),(u.docChanged||u.heightChanged||u.geometryChanged)&&l(u.docChanged)}),Ne],f=Xe(o,h)??K.EditorState.create({doc:r,extensions:h}),i=new I.EditorView({state:f,parent:e});return{text:()=>i.state.doc.toString(),replaceText:u=>{const c=i.state.doc.toString();if(c===u)return;let g=0;const m=Math.min(c.length,u.length);for(;g<m&&c.charCodeAt(g)===u.charCodeAt(g);)g+=1;let S=0;for(;S<m-g&&c.charCodeAt(c.length-1-S)===u.charCodeAt(u.length-1-S);)S+=1;i.dispatch({changes:{from:g,to:c.length-S,insert:u.slice(g,u.length-S)},userEvent:"input.replace"})},reveal:({line:u,column:c},g)=>{const{doc:m}=i.state,S=m.line(Math.min(Math.max(u,1),m.lines)),v=Math.min(S.from+c,S.to);i.dispatch({selection:K.EditorSelection.cursor(v),effects:fe(i,v,g,t)})},showLine:u=>{const{doc:c}=i.state,g=c.line(Math.min(Math.max(u,1),c.lines)).from;i.dispatch({effects:fe(i,g,null,t)})},topLine:()=>{const u=t.scrollerOf(i.scrollDOM),c=x.visibleTopOf(u,i.contentDOM),g=x.frameTopOf(u)+u.clientHeight,{documentTop:m}=i,{doc:S}=i.state;let v=i.lineBlockAtHeight(Math.max(c-m,0));for(;S.lineAt(v.from).text.trim()===""&&v.to<S.length;){const A=i.lineBlockAt(v.to+1);if(m+A.top>=g)break;v=A}const k=i.coordsAtPos(v.from),O=k===null?m+v.top:k.top;return{line:i.state.doc.lineAt(v.from).number,clientTop:O,offset:O-c}},lineSpans:u=>{const c=i.scrollDOM,g=c.scrollTop+i.documentTop-x.visibleTopOf(c,i.contentDOM),{doc:m}=i.state,S=v=>m.line(Math.min(Math.max(v,1),m.lines)).from;return u.map(({first:v,last:k})=>({top:g+i.lineBlockAt(S(v)).top,bottom:g+i.lineBlockAt(S(k)).bottom}))},scrollElement:i.scrollDOM,focus:()=>i.focus(),conflicts:()=>Y(i.state.doc),resolveAtCursor:u=>{const c=Y(i.state.doc),g=i.state.doc.lineAt(i.state.selection.main.head).number,m=c.find(S=>S.end>=g);return m===void 0?!1:(ke(i,m,u),!0)},nextConflict:()=>{const u=Y(i.state.doc);if(u[0]===void 0)return!1;const g=i.state.doc.lineAt(i.state.selection.main.head).number,m=u.findIndex(O=>O.start>g),S=m<0?0:m,v=i.state.doc.line(u[S].start).from;i.dispatch({selection:K.EditorSelection.cursor(v),effects:I.EditorView.scrollIntoView(v,{y:"center"})});const k=i.contentDOM.querySelector(`[${Le}="${String(S)}"] button`);return k instanceof HTMLElement?k.focus({preventScroll:!0}):i.focus(),!0},save:()=>i.state.toJSON(Te),destroy:()=>i.destroy()}},fe=(e,t,r,o)=>{const a=o.scrollerOf(e.scrollDOM),s=(r===null?x.visibleTopOf(a,e.contentDOM):r)-x.frameTopOf(a);return I.EditorView.scrollIntoView(t,{y:"start",yMargin:s})},Fe=(e,t,r,o)=>{const a=Ue(e,t),s=o.scrollerOf(e.scrollDOM),l=x.frameTopOf(s),n=x.visibleTopOf(s,e.contentDOM),h=l+s.clientHeight;let f=0;switch(r.y){case"start":f=a.top-(l+r.yMargin);break;case"center":f=(a.top+a.bottom)/2-(n+h)/2;break;case"end":f=a.bottom-(h-r.yMargin);break;default:a.top<n+r.yMargin?f=a.top-(n+r.yMargin):a.bottom>h-r.yMargin&&(f=Math.min(a.bottom-(h-r.yMargin),a.top-(n+r.yMargin)))}if(f!==0&&(s.scrollTop+=f),r.y==="start")return;const i=Ge(e,t);i!==null&&o.reveal(i)},Ue=(e,t)=>{const{node:r,offset:o}=e.domAtPos(t);if(r.nodeType===Node.TEXT_NODE){const l=r.ownerDocument?.createRange();if(l!==void 0){l.setStart(r,o),l.setEnd(r,o);const[n]=l.getClientRects();if(n!==void 0&&n.height>0)return{top:n.top,bottom:n.bottom}}}const a=e.lineBlockAt(t),s=e.documentTop+a.top;return{top:s,bottom:s+a.height}},Ge=(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},Xe=(e,t)=>{if(e==null)return null;try{return K.EditorState.fromJSON(e,{extensions:t},Te)}catch{return null}},Ke=610,We=987,pe=Object.freeze({kind:"unavailable"}),$e="true",Ye="false",Je=e=>e===$e?!0:e===Ye?!1:null,Qe=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 a=o.localName==="img",s=o.getAttribute(a?"data-asset-src":"data-doc-path");s!==null&&r.push({target:{kind:a?"asset":"doc",path:s},exists:Je(o.getAttribute(a?"data-asset-exists":"data-doc-exists"))})}return r},Ze=({path:e,instant:t,preview:r,initial:o,onView:a})=>{const s=new AbortController,l={asset:new Map,doc:new Map};let n=o,h=null,f=!1,i=!1,u=null,c=null,g=[],m,S=!1,v,k=null;const O=y=>{y.parsed===n.parsed&&y.failure===n.failure&&y.busy===n.busy&&y.tier===n.tier||(n=y,a(y))},A=(y,d)=>{f||(f=!0,console.error(`[markdown-explorer] ${y}`,...d===void 0?[]:[d]))},j=y=>{if(t!==null)for(const{target:d,exists:E}of t.marksOf(y))l[d.kind].set(d.path,E)},D=()=>{clearTimeout(v),v=void 0,k?.abort(),k=null},V=()=>{c=null,g=[],clearTimeout(m),m=void 0},H=(y,d)=>{O({parsed:n.parsed,failure:y,busy:!1,tier:d})},b=()=>{clearTimeout(m),m=g.length===0?void 0:setTimeout(q,We)},T=()=>{if(t===null||c===null)return;const y=c,d=[],E={asset:new Set,doc:new Set};let R;try{R=t.sanitize(y.html,C=>{const U=l[C.kind].get(C.path);return U===void 0&&!E[C.kind].has(C.path)&&(E[C.kind].add(C.path),d.push(C)),U??void 0})}catch(C){V(),C instanceof oe.HtmlNestingLimitError?H(W.failureOf("too-large"),"instant"):(A("the draft sanitizer failed",C),H(W.failureOf("failed"),"instant"));return}g=d;const M=n.parsed!==null&&n.parsed.htmlContent===R&&n.parsed.headings===y.headings?n.parsed:{htmlContent:R,headings:y.headings};O({parsed:M,failure:null,busy:!1,tier:"instant"}),b()},q=()=>{if(m=void 0,S||c===null||g.length===0)return;S=!0;const y=g;r(e,c.text,s.signal).then(d=>{if(S=!1,!(s.signal.aborted||!("kind"in d))){d.kind==="preview"&&j(d.htmlContent);for(const E of y)l[E.kind].has(E.path)||l[E.kind].set(E.path,null);T()}})},P=y=>{D(),V(),O({...n,busy:!0,tier:"server"});const d=new AbortController;k=d,v=setTimeout(()=>{v=void 0,r(e,y,d.signal).then(E=>{if(!(d.signal.aborted||!("kind"in E))){if(k=null,E.kind==="failure"){H(E.failure,"server");return}j(E.htmlContent),O({parsed:{htmlContent:E.htmlContent,headings:E.headings},failure:null,busy:!1,tier:"server"})}})},Ke)},w=async(y,d)=>{let E;try{E=await y.convert({path:e,text:d},s.signal)}catch(M){return s.signal.aborted||A("the draft converter rejected a conversion, which its contract allows only once the signal aborted",M),pe}const R=W.draftAnswerViolation(E);return R===null?E:(A(`the draft converter answered outside its contract: ${R}`),pe)},B=(y,d)=>{switch(d.kind){case"preview":if(D(),d.headings.length>W.EXPLORER_MAX_HEADINGS){V(),H(W.failureOf("too-large"),"instant");return}c={text:y,html:d.htmlContent,headings:d.headings.map(({text:E,depth:R,id:M})=>({text:E,depth:R,id:M}))},T();return;case"failure":D(),V(),H(W.failureOf(d.failure.reason,d.failure.code),"instant");return;case"unavailable":P(y);return}},z=async y=>{i=!0;try{for(;u!==null&&!s.signal.aborted;){const d=u;u=null;const E=await w(y,d);if(s.signal.aborted)return;B(d,E)}}finally{i=!1}};return t!==null&&t.seed!==null&&j(t.seed),{update:y=>{if(!(s.signal.aborted||y===h)){if(h=y,clearTimeout(m),m=void 0,t===null){P(y);return}u=y,i||z(t.converter)}},dispose:()=>{s.abort(),u=null,clearTimeout(m),m=void 0,D()}}},et=(e,t)=>oe.createHtmlSanitizer(_e(window),e,t,oe.MAX_HTML_NESTING_DEPTH),tt=(e,t)=>e.flatMap((r,o)=>{const a=t[o];return a===void 0?[]:[{editor:a.top,preview:r.top},{editor:a.bottom,preview:r.bottom}]}),X=(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},rt=e=>{const t=[];for(const o of e){let a=0,s=t.length;for(;a<s;){const l=a+s>>1;X(t,l).pair.preview<=o.preview?a=l+1:s=l}t[a]={pair:o,before:a===0?void 0:X(t,a-1)}}const r=[];for(let o=t.at(-1);o!==void 0;o=o.before)r.push(o.pair);return r.reverse()},nt=(e,t)=>{const r=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),a=r-t.editorViewport,s=o-t.previewViewport,l=e.filter(f=>f.editor>0&&f.editor<a&&f.preview>0&&f.preview<s).sort((f,i)=>f.editor-i.editor||f.preview-i.preview);let n={editor:0,preview:0};const h=[n];for(const f of rt(l))f.editor>n.editor&&f.preview>n.preview&&(h.push(f),n=f);return h.push({editor:r,preview:o}),{toPreview:f=>me(h,"editor","preview",f),toEditor:f=>me(h,"preview","editor",f)}},me=(e,t,r,o)=>{const a=X(e,0),s=X(e,e.length-1);if(Number.isNaN(o)||o<=a[t])return a[r];if(o>=s[t])return s[r];let l=0,n=e.length-1;for(;n-l>1;){const i=l+n>>1;X(e,i)[t]<=o?l=i:n=i}const h=X(e,l),f=X(e,n);return h[r]+(f[r]-h[r])*(o-h[t])/(f[t]-h[t])},ot=610,he=89,ge=.5,it=({editor:e,preview:t,previewBlocks:r,editorSpans:o,requestFrame:a,cancelFrame:s,now:l})=>{let n="editor",h=0,f=null,i=null,u=!1,c=null,g=null;const m={editor:0,preview:0},S={editor:null,preview:null};let v=null,k=()=>{};const O=w=>{f!==null&&w!==f||(n=w,h=l()+ot)},A=(w,B)=>{w!==n&&f===null&&l()>=h&&!j(w,B)&&(n=w),T()},j=(w,B)=>{const z=S[w];return l()<m[w]||z!==null&&Math.abs(B.position()-z)<ge},D=e.onScroll(()=>A("editor",e)),V=e.onIntent(()=>O("editor")),H=()=>{const w=t();return w!==v&&(k(),v=w,k=w===null?()=>{}:b(w)),w},b=w=>{const B=w.onScroll(()=>A("preview",w)),z=w.onIntent(()=>O("preview"));return()=>{B(),z()}},T=()=>{!u&&i===null&&(i=a(q))},q=()=>{i=null;const w=H();w!==null&&(c??=r(),g??=nt(tt(c,o(c)),{editorMax:e.max(),previewMax:w.max(),editorViewport:e.viewport(),previewViewport:w.viewport()}),n==="editor"?P(w,"preview",g.toPreview(e.position())):P(e,"editor",g.toEditor(w.position())))},P=(w,B,z)=>{if(Math.abs(w.position()-z)<ge){S[B]=w.position();return}m[B]=l()+he,S[B]=w.scrollTo(z)};return T(),{editorChanged:w=>{g=null,w&&O("editor"),T()},previewChanged:()=>{c=null,g=null,m.preview=l()+he,T()},showAlone:w=>{f=w,!(w===null||w===n)&&(n=w,h=0,T())},dispose:()=>{u=!0,i!==null&&s(i),i=null,D(),V(),k()}}},ve=Object.freeze(["wheel","pointerdown","keydown","focusin"]),qe=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 ve)e.addEventListener(r,t,{capture:!0,passive:!0});return()=>{for(const r of ve)e.removeEventListener(r,t,{capture:!0})}}}),$="[data-aqmd-scroll-container]",st="[data-aqmd-content]",lt=`[${ne.SOURCE_LINES_ATTRIBUTE}]`,at=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Re=(e,t)=>{const r=x.loadedOf(e.peek(t));return r!==null&&r.document.kind==="markdown"?{htmlContent:r.document.htmlContent,headings:r.document.headings}:null},ct=(e,t,r,o,a)=>{if(r===void 0)return null;let s;try{s=et(e,t)}catch(l){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",l),null}return{converter:r,sanitize:s,marksOf:Qe,seed:Re(o,a)?.htmlContent??null}},ut=e=>{const t=[];let r=null;for(const o of e.querySelectorAll(lt)){const a=ne.parseSourceLines(o.getAttribute(ne.SOURCE_LINES_ATTRIBUTE));if(a===null||o.getClientRects().length===0)continue;r??=e.scrollTop-x.visibleTopOf(e,o);const{top:s,bottom:l}=o.getBoundingClientRect();t.push({first:a.first,last:a.last,top:r+s,bottom:r+l})}return t},dt=({path:e,readDraft:t,viewer:r,concealed:o,onEditAt:a,onLayout:s,handleRef:l})=>{const{config:n,data:h,documents:f,draftConverter:i,labels:u}=x.useExplorer(),[c,g]=p.useState(()=>({parsed:Re(f,e),failure:null,busy:!0,tier:i===void 0?"server":"instant"})),m=p.useRef(null),S=p.useRef(null),v=p.useRef(c);p.useLayoutEffect(()=>{v.current=c});const k=p.useEffectEvent(()=>t());p.useEffect(()=>{const b=ct(n.iframeHosts,n.dataPath,i,f,e),T=Ze({path:e,instant:b,preview:h.preview,initial:v.current,onView:q=>p.startTransition(()=>g(q))});return S.current=T,T.update(k()),()=>{T.dispose(),S.current=null}},[n,h,f,i,e]);const O=p.useEffectEvent(()=>s());p.useLayoutEffect(()=>{c.parsed!==null&&O()},[c.parsed]);const A=c.parsed!==null;p.useLayoutEffect(()=>{const b=A?m.current?.querySelector($):null;if(!(b instanceof HTMLElement))return;b.tabIndex=0;const T=new ResizeObserver(()=>O());T.observe(b);const q=b.querySelector(st);return q!==null&&T.observe(q),()=>T.disconnect()},[A]);const j=p.useRef(null);p.useImperativeHandle(l,()=>({draft:b=>{S.current?.update(b)},scrollPort:()=>{const b=m.current?.querySelector($);return b instanceof HTMLElement?(j.current?.scroller!==b&&(j.current={scroller:b,port:qe(b)}),j.current.port):null},blocks:()=>{const b=m.current?.querySelector($);return b instanceof HTMLElement?ut(b):[]},focus:()=>{const b=m.current?.querySelector($);b instanceof HTMLElement&&b.focus({preventScroll:!0})},anchor:b=>{const T=m.current,q=T?.querySelector($);return T===null||!(q instanceof HTMLElement)?null:x.anchorOfView(T,b(q))},place:({line:b,clientTop:T},q)=>{const P=m.current,w=P===null?null:x.blockAtLine(P,b);w!==null&&(q(w).scrollTop+=x.lineTopIn(w,b)-T)}}),[]);const D=b=>{const T=m.current,{target:q}=b;if(a===void 0||T===null||!(q instanceof Element)||!x.isEditingDoubleClick(q))return;const P=x.anchorOfDoubleClick(q,T,T.ownerDocument.getSelection());P!==null&&a(P)},V=p.useMemo(()=>({...r,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0}),[r]),H=p.useMemo(()=>c.parsed===null?null:L.jsx("div",{className:"aqmx-document-viewer",children:L.jsx(Ce.MarkdownViewer,{...V,parseResult:c.parsed,content:null})}),[V,c.parsed]);return L.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":u.previewRegion,"aria-busy":c.busy,inert:o!==null,hidden:o==="removed","data-aqmx-preview-tier":c.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:a===void 0?void 0:D,children:[c.failure===null?null:L.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:u.previewFailed(x.failureTitleOf(u,c.failure.reason))}),H??(c.failure===null?L.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:at.map(b=>L.jsx("span",{},b))}):null),c.busy?L.jsx("p",{className:"aqmx-sr-only",children:u.previewUpdating}):null]})},we="data-aqmx-edit-split",re="--aqmx-edit-share",Ee="--aqmx-edit-gutter",ft="data-aqmx-edit-split-probe",pt="aqmx-edit-split",mt="aqmx-edit-editor",ht="aqmx-edit-preview",be={value:G.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},xe={value:G.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},Se=e=>{if(e.length!==2)return null;const[t=0,r=0]=e,o=t+r;return o>0?t/o*100:null},Z=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},gt=(e,t,r)=>{const[o,a]=p.useState(null);return p.useLayoutEffect(()=>{const s=e.current,l=t.current;if(s===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const n={frame:s.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},h=()=>{n.frame>0&&n.measure>0&&a(G.editSplitOrientation(n.frame,n.measure,r))};h();const f=new ResizeObserver(i=>{for(const u of i){const[c]=u.borderBoxSize;c!==void 0&&(u.target===s&&(n.frame=c.inlineSize),u.target===l&&(n.measure=c.inlineSize))}h()});return f.observe(s),f.observe(l),()=>f.disconnect()},[e,t,r]),o},vt=({editorId:e})=>{const{edits:t,labels:r}=x.useExplorer(),o=p.useRef(null),a=p.useRef(null),s=ue.useCoarsePointer()?G.COARSE_TARGET_PIXELS:G.FINE_TARGET_PIXELS,l=gt(o,a,s),[n]=p.useState(()=>t.editorShare());p.useLayoutEffect(()=>{const i=Z(o);return i.style.setProperty(Ee,`${String(s)}px`),()=>{i.style.removeProperty(Ee)}},[s]),p.useLayoutEffect(()=>{const i=Z(o);return i.style.setProperty(re,`${String(n)}%`),()=>{i.style.removeProperty(re)}},[n]),p.useLayoutEffect(()=>{if(l===null)return;const i=Z(o);return i.setAttribute(we,l),()=>i.removeAttribute(we)},[l]);const h=ue.useSplitPersistence(p.useCallback(i=>{const u=Se(i);u!==null&&t.setEditorShare(u)},[t])),f=p.useCallback((i,u)=>{const c=Se(i);c!==null&&Z(o).style.setProperty(re,`${String(c)}%`),h.layoutChanged(i,u)},[h]);return L.jsxs("div",{ref:o,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[L.jsx("span",{ref:a,className:"aqmx-edit-split-probe","aria-hidden":"true",[ft]:""}),l===null?null:L.jsxs(Q.PanelGroup,{id:pt,direction:l==="beside"?"horizontal":"vertical",onLayout:f,className:"aqmx-edit-split-group",children:[L.jsx(Q.Panel,{id:mt,defaultSize:{value:n,unit:"percentage"},minSize:be,maxSize:xe,contentOverflow:"hidden"}),L.jsx(Q.PanelResizeHandle,{thickness:s,indicator:{visible:!0,thickness:G.SPLIT_HANDLE_PIXELS.gripThickness,length:G.SPLIT_HANDLE_PIXELS.gripLength,barThickness:G.SPLIT_HANDLE_PIXELS.barThickness,barLength:G.SPLIT_HANDLE_PIXELS.barLength},title:r.editViewSplitResize,"aria-label":r.editViewSplitResize,"aria-controls":e,onDragging:h.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),L.jsx(Q.Panel,{id:ht,defaultSize:{value:100-n,unit:"percentage"},minSize:be,maxSize:xe,contentOverflow:"hidden"})]})]})},Oe=144,wt=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),Et=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"},bt=e=>{e.stopPropagation()},xt=e=>{const{path:t,name:r,session:o}=e,{edits:a,labels:s,announcer:l}=x.useExplorer(),{phase:n}=o,h=p.useCallback(()=>a.retry(t),[a,t]);switch(p.useEffect(()=>{n.kind==="failed"&&l.announce(s.documentFailed(r,x.failureTitleOf(s,n.failure.reason)))},[n,l,s,r]),n.kind){case"opening":return L.jsxs(L.Fragment,{children:[L.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:wt.map(f=>L.jsx("span",{},f))}),L.jsx("p",{className:"aqmx-sr-only",children:s.editLoading})]});case"grant":return L.jsx("div",{className:"aqmx-edit-message",children:L.jsx(x.EditGrantNotice,{href:n.href,onRetry:h,testId:"markdown-explorer-edit-grant"})});case"failed":return L.jsx("div",{className:"aqmx-edit-message",children:L.jsx(x.FailureView,{failure:n.failure,alert:!1,onRetry:h,testId:"markdown-explorer-edit-failure"})});case"editing":return L.jsx(St,{...e})}},St=({path:e,name:t,session:r,layout:o,viewer:a,region:s,paneScroll:l})=>{const{edits:n,labels:h}=x.useExplorer(),f=p.useRef(null),i=p.useId(),u=p.useRef(null),c=p.useRef(null),g=p.useRef(null),m=o==="fill",S=x.useSideBySide(),v=x.editViewOf(r,S,m),k=v!=="editor"||r.previewPrepared,O=k&&m,A=p.useRef({layout:o,region:s,paneScroll:l});p.useLayoutEffect(()=>{A.current={layout:o,region:s,paneScroll:l}});const j=p.useRef(r.generation);p.useLayoutEffect(()=>{j.current=r.generation});const D=p.useRef({view:v,previewMounted:k});p.useLayoutEffect(()=>{D.current={view:v,previewMounted:k}});const V=p.useRef(null),H=p.useRef(null),b=p.useRef(!1),T=p.useMemo(()=>({editor:h.editorLabel(t),useOurs:h.conflictUseOurs,useTheirs:h.conflictUseTheirs,keepBoth:h.conflictKeepBoth}),[h,t]),q=p.useCallback(d=>{const{region:E,paneScroll:R}=A.current,M=E();return M===null?d:R.scrollerOf(M,d)},[]);p.useLayoutEffect(()=>{const d=f.current,E=n.draft(e);if(d===null||E===null)return;const R=n.editorState.get(e),M=Et(R)&&R.generation===j.current?R:null;let C=null,U=null;const te=()=>{C!==null&&clearTimeout(C),C=null,U!==null&&n.setDraft(e,U.text())},F=ze({parent:d,scroll:{scrollerOf:N=>{const{layout:J,region:Ie,paneScroll:Me}=A.current,le=Ie();return J==="fill"||le===null?N:Me.scrollerOf(le,N)},reveal:N=>A.current.paneScroll.reveal(N)},text:E,saved:M===null?void 0:M.state,labels:T,onGeometry:N=>g.current?.editorChanged(N),onChange:()=>{C??=setTimeout(te,Oe),D.current.previewMounted&&U!==null&&c.current?.draft(U.text())},onSave:()=>{n.save(e)}});U=F,u.current=F;const ie=()=>{const N=F.topLine();return{line:N.line,clientTop:N.clientTop}},se=()=>c.current?.anchor(q)??null,Ae=n.bindEditor(e,{flush:te,adopt:N=>F.replaceText(N),returnPoint:()=>{const N=D.current.view==="preview"&&A.current.layout==="content"?se():null;return N===null?ie():{line:N.lines.first,clientTop:N.clientTop}},nextConflict:()=>D.current.view!=="preview"?F.nextConflict():F.conflicts().length===0?!1:(b.current=!0,n.setView(e,"editor"),!0),beforeView:N=>{if(A.current.layout==="fill")return;if(N==="preview"){V.current={to:"preview",point:ie()};return}const J=se();V.current=J===null?null:{to:"editor",anchor:J}}});return M!==null&&F.showLine(M.topLine),()=>{te(),n.editorState.set(e,{state:F.save(),generation:j.current,topLine:F.topLine().line}),Ae(),F.destroy(),U=null,u.current=null}},[n,e,T,q]);const{request:P}=r;p.useLayoutEffect(()=>{const d=u.current,E=n.draft(e);d===null||E===null||P===null||(P.anchor!==null&&d.reveal(x.positionInSource(E,P.anchor),P.anchor.clientTop),d.focus(),n.consumeRequest(e))},[n,e,P,T]),p.useLayoutEffect(()=>{v!=="editor"&&!r.previewPrepared&&n.preparePreview(e)},[n,e,v,r.previewPrepared]),p.useLayoutEffect(()=>{const d=V.current,E=H.current,R=b.current;V.current=null,H.current=null,b.current=!1;const M=u.current;if(d?.to==="preview")c.current?.place(d.point,q);else if(d?.to==="editor"&&M!==null){const C=n.draft(e);C!==null&&M.reveal(x.positionInSource(C,d.anchor),d.anchor.clientTop)}R?M?.nextConflict():E==="editor"?M?.focus():E==="preview"&&c.current?.focus()},[n,e,v,q]);const w=p.useCallback(()=>{const d=u.current;if(d===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return d.text()},[]);p.useLayoutEffect(()=>{const d=u.current;if(!O||d===null)return;const E=it({editor:qe(d.scrollElement),preview:()=>c.current?.scrollPort()??null,previewBlocks:()=>c.current?.blocks()??[],editorSpans:R=>d.lineSpans(R),requestFrame:R=>requestAnimationFrame(R),cancelFrame:R=>cancelAnimationFrame(R),now:()=>performance.now()});return E.showAlone(x.paneShownAlone(D.current.view)),g.current=E,()=>{E.dispose(),g.current=null}},[O,n,e,T]),p.useLayoutEffect(()=>{g.current?.showAlone(x.paneShownAlone(v))},[v]);const B=p.useCallback(()=>g.current?.previewChanged(),[]),z=p.useCallback(d=>n.start(e,d),[n,e]),y=d=>{if(d.key==="Escape"){x.consumeKey(d);return}if(!x.isEditViewShortcut(d.nativeEvent,x.isApplePlatform(navigator.platform)))return;x.consumeKey(d);const E=x.toggledEditView(v);H.current=E,x.chooseEditView(n,e,E,m)};return L.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":v,"data-testid":"markdown-explorer-edit",onKeyDown:y,onDoubleClick:bt,children:[L.jsx("div",{ref:f,id:i,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:v==="preview",hidden:v==="preview"&&!m,...x.ALLOW_KEY_REPEAT}),v==="split"?L.jsx(vt,{editorId:i}):null,k?L.jsx(dt,{path:e,readDraft:w,viewer:a,concealed:v!=="editor"?null:m?"overlay":"removed",onEditAt:v==="preview"?z:void 0,onLayout:B,handleRef:c}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=Oe;exports.default=xt;