@aiquants/markdown-explorer 0.33.0 → 0.35.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 (146) hide show
  1. package/CHANGELOG.md +795 -0
  2. package/README.md +119 -55
  3. package/dist/EditSurface-CLG70Vnn.cjs +6 -0
  4. package/dist/EditSurface-D2j1kCEE.js +990 -0
  5. package/dist/ExplorerSplit-CfP1smbT.js +1589 -0
  6. package/dist/ExplorerSplit-D_0VohOv.cjs +2 -0
  7. package/dist/{MultiLayout-DYNGlNy0.js → MultiLayout-BeJ5Lubb.js} +291 -290
  8. package/dist/MultiLayout-CxV5SI7f.cjs +1 -0
  9. package/dist/NativeScrollBar-BM5NULzg.js +62 -0
  10. package/dist/NativeScrollBar-RWXpVhbI.cjs +1 -0
  11. package/dist/TreeLayout-AxLw-36S.js +103 -0
  12. package/dist/TreeLayout-Bg2YH-EY.cjs +1 -0
  13. package/dist/client/MarkdownExplorer.d.cts +14 -1
  14. package/dist/client/MarkdownExplorer.d.ts +14 -1
  15. package/dist/client/edit/lineEndings.d.cts +4 -0
  16. package/dist/client/edit/lineEndings.d.ts +4 -0
  17. package/dist/client/hostContract.d.cts +67 -0
  18. package/dist/client/hostContract.d.ts +67 -0
  19. package/dist/core/config.d.cts +7 -0
  20. package/dist/core/config.d.ts +7 -0
  21. package/dist/core/contracts.d.cts +10 -4
  22. package/dist/core/contracts.d.ts +10 -4
  23. package/dist/core/draftAnswer.d.cts +23 -0
  24. package/dist/core/draftAnswer.d.ts +23 -0
  25. package/dist/core/geometry.d.cts +1 -0
  26. package/dist/core/geometry.d.ts +1 -0
  27. package/dist/core/labels.d.cts +78 -0
  28. package/dist/core/labels.d.ts +78 -0
  29. package/dist/core/location.d.cts +3 -2
  30. package/dist/core/location.d.ts +3 -2
  31. package/dist/core/ownUrls.d.cts +15 -0
  32. package/dist/core/ownUrls.d.ts +15 -0
  33. package/dist/core/treeSettings.d.cts +3 -2
  34. package/dist/core/treeSettings.d.ts +3 -2
  35. package/dist/core/viewSettings.d.cts +5 -1
  36. package/dist/core/viewSettings.d.ts +5 -1
  37. package/dist/describeValue-CLlVRO8d.js +17 -0
  38. package/dist/describeValue-Ccvhbt36.cjs +1 -0
  39. package/dist/explorerCore-DLpDuSev.js +998 -0
  40. package/dist/explorerCore-DYrxS9ez.cjs +1 -0
  41. package/dist/index-C1YMH-yI.js +5816 -0
  42. package/dist/index-LQWQfpAf.cjs +18 -0
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +7 -4
  45. package/dist/index.d.ts +7 -4
  46. package/dist/index.js +47 -42
  47. package/dist/licenses/@heroicons/react/LICENSE +21 -0
  48. package/dist/licenses/entities/LICENSE +11 -0
  49. package/dist/licenses/parse5/LICENSE +19 -0
  50. package/dist/location--KvTA0Ri.js +726 -0
  51. package/dist/location-D8DyDkuA.cjs +1 -0
  52. package/dist/lru-DC8GBmkX.js +39 -0
  53. package/dist/lru-SGmUyBQU.cjs +1 -0
  54. package/dist/{merge-D7L_pINl.js → merge-Bb_HpPhe.js} +1 -1
  55. package/dist/{merge-DZI4pkWI.cjs → merge-DQUYEGCx.cjs} +1 -1
  56. package/dist/nestingGuardWorker.js +5511 -0
  57. package/dist/ownUrls-B259RGgd.cjs +1 -0
  58. package/dist/ownUrls-Dh5g6ZJi.js +370 -0
  59. package/dist/sanitizeJob-BYRk17nr.js +21 -0
  60. package/dist/sanitizeJob-Cs9o3Vpl.cjs +1 -0
  61. package/dist/sanitizePolicy-CEMdaLUB.js +139 -0
  62. package/dist/sanitizePolicy-CiQfnxyd.cjs +2 -0
  63. package/dist/sanitizeWorker.cjs +1 -1
  64. package/dist/sanitizeWorker.js +134 -139
  65. package/dist/sanitizerService-BY4CPCoA.cjs +1 -0
  66. package/dist/sanitizerService-KWXv7bPm.js +240 -0
  67. package/dist/server/assetResponse.d.cts +60 -0
  68. package/dist/server/assetResponse.d.ts +60 -0
  69. package/dist/server/browser/browserPlatform.d.cts +12 -0
  70. package/dist/server/browser/browserPlatform.d.ts +12 -0
  71. package/dist/server/createMarkdownExplorer.d.cts +0 -10
  72. package/dist/server/createMarkdownExplorer.d.ts +0 -10
  73. package/dist/server/explorerCore.d.cts +12 -0
  74. package/dist/server/explorerCore.d.ts +12 -0
  75. package/dist/server/fileSystemSource.d.cts +1 -0
  76. package/dist/server/fileSystemSource.d.ts +1 -0
  77. package/dist/server/inProcessFetch.d.cts +5 -0
  78. package/dist/server/inProcessFetch.d.ts +5 -0
  79. package/dist/server/platform.d.cts +18 -0
  80. package/dist/server/platform.d.ts +18 -0
  81. package/dist/server/ports.d.cts +36 -5
  82. package/dist/server/ports.d.ts +36 -5
  83. package/dist/server/sanitizeProtocol.d.cts +3 -0
  84. package/dist/server/sanitizeProtocol.d.ts +3 -0
  85. package/dist/server/sanitizer.d.cts +5 -40
  86. package/dist/server/sanitizer.d.ts +5 -40
  87. package/dist/server/sanitizerOptions.d.cts +24 -0
  88. package/dist/server/sanitizerOptions.d.ts +24 -0
  89. package/dist/server/sanitizerService.d.cts +41 -0
  90. package/dist/server/sanitizerService.d.ts +41 -0
  91. package/dist/server/{workerPool.d.cts → workerJobs.d.cts} +0 -16
  92. package/dist/server/{workerPool.d.ts → workerJobs.d.ts} +0 -16
  93. package/dist/server.cjs +1 -1
  94. package/dist/server.d.cts +3 -1
  95. package/dist/server.d.ts +3 -1
  96. package/dist/server.js +270 -1343
  97. package/dist/serverBrowser.cjs +1 -0
  98. package/dist/serverBrowser.d.cts +1 -0
  99. package/dist/serverBrowser.d.ts +1 -0
  100. package/dist/serverBrowser.js +120 -0
  101. package/dist/serverCore.cjs +1 -0
  102. package/dist/serverCore.d.cts +14 -0
  103. package/dist/serverCore.d.ts +14 -0
  104. package/dist/serverCore.js +46 -0
  105. package/dist/storage-BpYsprog.cjs +1 -0
  106. package/dist/{storage-CmGHg7OA.js → storage-D1uSw-xj.js} +19 -18
  107. package/dist/storage.cjs +1 -1
  108. package/dist/storage.js +1 -1
  109. package/dist/styles/markdown-explorer.css +1 -1
  110. package/dist/tapScrollCircle-BEydRn0y.js +14 -0
  111. package/dist/tapScrollCircle-DdX0Wri0.cjs +1 -0
  112. package/dist/testing.cjs +1 -0
  113. package/dist/testing.d.cts +6 -0
  114. package/dist/testing.d.ts +6 -0
  115. package/dist/testing.js +4 -0
  116. package/dist/useSplitPersistence-B2Fj508K.cjs +1 -0
  117. package/dist/useSplitPersistence-Fkqak8G8.js +44 -0
  118. package/docs/behavior/dom-hooks.md +14 -3
  119. package/docs/behavior/hosting.md +123 -0
  120. package/docs/behavior/layout.md +69 -19
  121. package/docs/behavior/localization.md +28 -10
  122. package/docs/behavior/security.md +34 -14
  123. package/docs/behavior/url-contract.md +13 -6
  124. package/package.json +54 -16
  125. package/dist/EditSurface-BPqqykro.cjs +0 -6
  126. package/dist/EditSurface-CWq35IWQ.js +0 -972
  127. package/dist/ExplorerSplit-BRY4uy6x.js +0 -1493
  128. package/dist/ExplorerSplit-CQxr6b0v.cjs +0 -1
  129. package/dist/MultiLayout-TXbet9k3.cjs +0 -1
  130. package/dist/NativeScrollBar-BsWdvkHa.js +0 -64
  131. package/dist/NativeScrollBar-UpjxjLlB.cjs +0 -1
  132. package/dist/TreeLayout-BQEgZhz9.js +0 -72
  133. package/dist/TreeLayout-C0O1OGi4.cjs +0 -1
  134. package/dist/dataRoute-DLhQfdoW.js +0 -298
  135. package/dist/dataRoute-DwYtgyt6.cjs +0 -1
  136. package/dist/index-CO-RgTml.js +0 -4912
  137. package/dist/index-DSkK8iLE.cjs +0 -15
  138. package/dist/location-BxiJRTyw.cjs +0 -1
  139. package/dist/location-perTmwct.js +0 -663
  140. package/dist/sanitizePolicy-By0tKOpZ.js +0 -98
  141. package/dist/sanitizePolicy-T5T-3vV5.cjs +0 -1
  142. package/dist/storage-DM0EvkVf.cjs +0 -1
  143. package/dist/tapScrollCircle-CRKZremf.js +0 -12
  144. package/dist/tapScrollCircle-Cbf17x8g.cjs +0 -1
  145. package/dist/useSplitPersistence-Du01PHNg.js +0 -42
  146. package/dist/useSplitPersistence-pPmE4GTT.cjs +0 -1
@@ -10,6 +10,7 @@ The explorer renders documents that the reader did not write, from storage the r
10
10
  - Deny rules (`deny`, default `DEFAULT_DENIED_PATH_SEGMENTS`) hide matching entries from every listing — by entry name and by path, so a denied folder is pruned with everything under it — and refuse every document or children request for a matching path with a `forbidden` failure before any source is called.
11
11
  - A rule is matched against each path segment (or entry name) at every percent-decoding level up to three decodes, against each level whole and against its parts split again on `/` or `\` (a storage may read either character as part of one name, as a Linux file name, a Drive name or a GCS object name does, or as a separator), and after NFKC normalization and full case folding (upper-casing then lower-casing, which folds `ſ` to `s` and `ı` to `i`). Decoding is lenient: a malformed escape stays as written while the valid ones around it are decoded.
12
12
  `%2Eenv`, `%252Eenv`, `.%65nv`, `docs%5C.env`, `SECRETS` and `ſecrets` are all denied like `.env` and `secrets`, whatever the storage backend decodes or folds before opening the path.
13
+ A segment that one more lenient decode would still change after those three is denied whatever the patterns; rules without a pattern (`deny: []`) deny nothing.
13
14
  - Pattern syntax: a pattern matches one whole segment; `*` matches any run of characters inside it. `deny: false` turns the rules off; a custom array replaces the defaults (spread `DEFAULT_DENIED_PATH_SEGMENTS` to extend them).
14
15
  - The defaults cover environment files (`.env*` — every name starting with `.env`, for example `.env~`, `.env-old`, `.envs/`, and also `.envelope.md` — and `*.env` with the names its backups and copies take:
15
16
  `*.env.*`, `*.env~*`, `*.env-*`, `*.env_*` and `*.env#*`, for example `prod.env.bak`, `prod.env.production`, `prod.env.1`, `prod.env~`, `prod.env-old`, `prod.env_backup` and `#prod.env#`; rules have no exceptions, so a document named like `deploy.env.md` is denied too, while names in which `.env` is followed by a letter or digit, such as `prod.environment.md`, or has no dot before it, such as `environment.md` and `my-env.md`, are not),
@@ -17,7 +18,8 @@ The explorer renders documents that the reader did not write, from storage the r
17
18
  keys and keystores (`id_rsa*`, `id_dsa*`, `id_ecdsa*`, `id_ed25519*`, `*.pem`, `*.key`, `*.p8`, `*.p12`, `*.pfx`, `*.ppk`, `*.jks`, `*.keystore`, `*.kdbx`), credential files (`*credentials*.json`, `service-account*.json`), Terraform state and variables (`*.tfstate`, `*.tfstate.*`, `*.tfvars`, `*.tfvars.json`) and shell histories (`.*_history`, `fish_history`).
18
19
  - `createFileSystemSource` additionally checks lexical containment before any filesystem call and again after resolving the real path, refuses symbolic links, and never follows a path outside its root. It opens a file without following a link (where the platform has `O_NOFOLLOW`) and reads it only when the opened file is the one the checks saw (the same device and inode; a document read refuses another file as `forbidden`).
19
20
  Its `asset` port also requires the size and modification time the checks saw, answers `not-found` when the file is another one or has changed since, and streams a whole file no further than the size the checks saw.
20
- The walk leaves out every name it cannot carry — not in NFC, with a colon, ending in a dot or a space, holding a control character or a backslash, too long, a symbolic link or a special file — and every subdirectory it cannot read (a permission error, or one that vanished or became a file during the walk), and reports each once per path through `reportSkipped` (a `console.warn` by default); only an unreadable root fails the tree. Only files with a known text extension or name are previewed as text; any other file is `unsupported`.
21
+ The walk leaves out every name it cannot carry — not in NFC, with a colon, ending in a dot or a space, holding a control character or a backslash, too long, a symbolic link or a special file — and every subdirectory it cannot read (a permission error, or one that vanished or became a file during the walk), and reports each once per path through `reportSkipped` (a `console.warn` by default); only an unreadable root fails the tree.
22
+ Only files with a known text extension or name are previewed as text; any other file that is not a Markdown document, an image, a medium or a table file is a `file` document, offered for download.
21
23
 
22
24
  ## Source boundaries
23
25
 
@@ -40,11 +42,17 @@ The explorer renders documents that the reader did not write, from storage the r
40
42
 
41
43
  ## HTML
42
44
 
43
- Markdown HTML returned by a source is sanitized on the server with DOMPurify, in worker threads, before it reaches the page loader's stream or the data route, so the browser never receives markup the allow-list rejects:
45
+ Markdown HTML returned by a source is sanitized by the explorer's core with DOMPurify before it reaches the page loader's stream or the data route — on the Node entry in worker threads, on the browser runtime (`./server/browser`) on the page's main thread after a guard in a Web Worker (see below) — so the views never receive markup the allow-list rejects:
44
46
 
45
47
  - removed elements: `script`, `style`, `noscript`, `template`, `form`, `button`, `textarea`, `select`, `option`, `object`, `embed`, `base`, `meta`, `link`, `frame`, `frameset`; `input` survives only as a disabled checkbox (task lists);
46
48
  - removed attributes: every event handler (`on*`), `srcdoc`, `formaction`; `style` keeps only `text-align`;
47
49
  - URLs keep only the `http:`, `https:`, `mailto:` and `tel:` schemes and relative references, and `data:` URLs are removed from every element;
50
+ - a URL of the app itself stays only where its use allows. The app's own are relative and path-absolute URLs, and absolute ones whose origin `config.appOrigins` lists or `config.mediaDataPath` names, or whose scheme is that of a listed origin with a scheme that is not special (such as `wails:`); any other absolute URL follows the scheme rule above alone.
51
+ A resource the page fetches (a `src`, `poster` or `background`, a `srcset` candidate, the `href` of SVG's `image`) stays only under `dataPath`; a link's `href` only under `basePath` or `dataPath`; the `src` of a `video`, `audio` or `source` also under `config.mediaDataPath`, as an absolute URL; and any other `href` inside SVG, which may name an element of the same document, under `dataPath` or as a fragment.
52
+ A path stays when, normalized as the URL parser normalizes it, it equals an allowed path or continues one after a `/` (the query and the fragment are not looked at). Of the relative URLs, a link stays without a `.` or `..` segment, a link the converter marked as one to a document always stays, and no resource stays.
53
+ A URL holding a backslash is removed, a scheme-relative one (`//host…`) is read under every scheme the page may have and stays only when every reading does, and a `srcset` loses the whole attribute when any of its candidates does not stay. Only the attribute is removed, never the element;
54
+ - the presentation attributes CSS may read a URL from (`clip-path`, `color-profile`, `cursor`, `fill`, `filter`, `marker-start`, `marker-mid`, `marker-end`, `mask`, `stroke`) keep only a value that refers to the same document alone: a `url()` of a fragment, no image function (`image-set()`, `image()`, `src()`, `element()`, `cross-fade()`, prefixed forms included) and no backslash;
55
+ - the `preload` of a `video` or an `audio` is `none` when it is written `none` (in any ASCII case) and `metadata` otherwise (missing, empty, `auto` or an unknown value);
48
56
  - `iframe` survives only with an `https:` source without a user name, a password or an explicit port whose host is listed exactly in `config.iframeHosts` (a longer host such as `www.youtube.com.example.net`, or a protocol-relative source, is removed), judged on the `src` trimmed as DOMPurify trims it; this gate is `allowedFrameUrlOf` of `@aiquants/markdown/embeds`, the same function the viewer applies, and the viewer also never renders an iframe of the page's own origin;
49
57
  - `allow`, `allowfullscreen`, `frameborder` and `referrerpolicy` survive only on iframes: `referrerpolicy` only as `no-referrer`, `origin`, `same-origin`, `strict-origin` or `strict-origin-when-cross-origin` (`EMBED_FRAME_REFERRER_POLICIES`), and `allow` reduced to `autoplay`, `clipboard-write`, `encrypted-media`, `fullscreen`, `picture-in-picture` and `web-share`, each without its allowlist (`reduceFrameFeatures`);
50
58
  - `target` survives only on `a` and `area`, and a link with any `target` other than `_self` gets `rel="noopener noreferrer"`;
@@ -71,9 +79,10 @@ Every document the explorer shows is rendered by the viewer, on the server and i
71
79
  The sanitized `htmlContent` of the page data and of the data route's answers still carries the classes and ids DOMPurify kept; a host that renders it outside the explorer reduces them itself (see [What the host must do](#what-the-host-must-do)).
72
80
 
73
81
  A markdown document that lists more than 10,000 headings (`EXPLORER_MAX_HEADINGS`) is refused as `too-large` before it is sanitized: every listed heading travels with the document — copied by the server, sent in the data response, kept in the browser's document cache and rendered as an entry of the viewer's table of contents — 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 host's own cache of parse results can rely on the same bound.
74
- Sanitizing never runs on the request thread. HTML larger than `sanitizer.maxHtmlBytes` (4 MiB by default) is refused as `too-large` at once; the rest goes to a pool of worker threads (`sanitizer.workers`, 2 by default), shared by every explorer of the process with the same pool settings, with a per-document deadline (`sanitizer.deadlineMs`, 30 s by default): a document that misses it is `too-large`, and its worker is replaced.
82
+ On the Node entry (`./server`), sanitizing never runs on the request thread. HTML larger than `sanitizer.maxHtmlBytes` (4 MiB by default) is refused as `too-large` at once; the rest goes to a pool of worker threads (`sanitizer.workers`, 2 by default), shared by every explorer of the process with the same pool settings, with a per-document deadline (`sanitizer.deadlineMs`, 30 s by default): a document that misses it is `too-large`, and its worker is replaced.
75
83
  In the worker the nesting limit is enforced while the HTML is parsed, by the parser and in the mode DOMPurify's jsdom uses (parse5, the input as a whole document, scripting disabled), before DOMPurify runs and within the document's deadline.
76
- The parse stops, and the document is `too-large` without being sanitized, as soon as an element is placed deeper than 512 levels (the depth at which Chromium's HTML parser stops nesting elements; the children of `body` are at depth 1 and a `template`'s contents one level below it), or as soon as the parser has created more elements than the HTML has characters plus `html`, `head` and `body` (only formatting elements the parser reopens over and over can do that; an ordinary document stays far below).
84
+ The parse stops, and the document is `too-large` without being sanitized, as soon as an element is placed deeper than 256 levels (the children of `body` are at depth 1 and a `template`'s contents one level below it), or as soon as the parser has created more elements than the HTML has characters plus `html`, `head` and `body` (only formatting elements the parser reopens over and over can do that; an ordinary document stays far below).
85
+ The depth limit keeps a margin below the depth at which browsers' HTML parsers stop nesting elements (about 510 levels, by engine and by whether a document or a fragment is parsed), so no engine moves an element the sanitizer accepted to another parent for its depth, also inside a page that embeds the HTML.
77
86
  Before DOMPurify runs, the guard also counts every element, attribute and comment the parser creates and refuses the document (`too-large`) once the count passes (`sanitizer.workerHeapMb` − 64 MiB − `sanitizer.maxHtmlBytes` × 32 bytes) ÷ 4 KiB, which is 81,920 nodes by default, or once it has seen more than 4,096 comments wherever they sit. jsdom inserts each comment the parser attaches to the document itself (before `<html>` or after `</html>`) in time that grows with those already there (4,000 took 0.37 s and 8,000 took 1.4 s in the worker, while 8,000 comments inside the body took 0.14 s),
78
87
  so the cap keeps that worst case near 0.4 s. The constants are measured: the worker needs about 48 MiB of its own, a parsed node costs at most about 3.4 KB at the sanitizer's peak and a byte of HTML at most about 31 bytes, so a document the guard accepts fits in the worker's heap. The budget does not depend on the worker's heap limit and holds even where a process-wide `--max-old-space-size` overrides it.
79
88
  Before parsing, a linear scan follows every `<` or `</` followed by a letter through the tokenizer's tag states, quotes included, and refuses the document once a tag could hold more than 1,024 attributes, duplicates included; it also reads text the tokenizer would treat as text, so it may refuse more, never less.
@@ -81,7 +90,7 @@ While parsing, `html` and `body` may receive at most 1,024 attributes through re
81
90
  The guard also adds up the name and value characters of every attribute the parser creates, including the copies it gives a formatting element it reopens or the adoption agency recreates, and refuses the document once they exceed `sanitizer.maxHtmlBytes` (a document whose elements each appear once never does): Without the budget, 1 MiB of copied `title` makes the worker write 210 million characters; the budget refuses it in about 0.1 s.
82
91
  Sanitized HTML longer than 4 × `sanitizer.maxHtmlBytes` UTF-16 code units (16,777,216 by default; ordinary HTML measured at most 2.05 characters per byte) is a cached `too-large`: the worker never posts it and the service refuses it should it arrive, so neither the cache (where the longest outcome weighs 32 MiB of the default 64 MiB) nor a caller ever holds more.
83
92
  Every sanitizer worker starts with Node's `resourceLimits`: `workerHeapMb` MiB of old generation (512 by default) and 32 MiB of young generation. A worker whose heap runs out is ended with `ERR_WORKER_OUT_OF_MEMORY`, and its document is answered `too-large` and cached. The young generation is kept small on purpose: with Node's default for a worker (192 MiB), a worker at its limit could abort the whole process instead of ending alone, because one scavenge can promote more than the 16 MiB of leeway Node gives it.
84
- An element counts at the depth where the parser first places it, so when the parser later moves misnested markup to a shallower place (the adoption agency for misnested formatting tags, a `frameset` replacing `body`), a document whose finished tree is at most 512 levels deep can still be refused; a deeper one is never accepted. DOMPurify's own walk also stops at the first element deeper than 512 levels.
93
+ An element counts at the depth where the parser first places it, so when the parser later moves misnested markup to a shallower place (the adoption agency for misnested formatting tags, a `frameset` replacing `body`), a document whose finished tree is at most 256 levels deep can still be refused; a deeper one is never accepted. DOMPurify's own walk also stops at the first element deeper than 256 levels.
85
94
  Each request names its reader's scope. The pool admits at most `sanitizer.jobsPerScope` documents per reader running or waiting and `sanitizer.maxQueuedJobs` waiting in all; a document beyond either is `failed`, logged without the principal and not remembered, so a later request tries again.
86
95
  A page sends the document of every panel to the sanitizer at once for one reader, so the admission defaults follow the multi view: `jobsPerScope` defaults to `multiView.maxPanels` + max(1, `workers` − 1) + 3 — the panels, the previous page's documents still running after a reload (a running job is not stopped when its requests leave, and one reader runs at most max(1, `workers` − 1) at once), the two intent prefetches and one spare; 16 with the default 12 panels and two workers. `maxQueuedJobs` defaults to four times `jobsPerScope`, also when it is set.
87
96
  Neither may be set below `multiView.maxPanels` (a `RangeError` naming both at startup). All anonymous readers share one scope and therefore one admission budget.
@@ -91,6 +100,11 @@ Every outcome that describes the HTML (a refusal for nesting, the node budget, t
91
100
  A worker that fails before then (it cannot be started, is not ready within the deadline, or fails or exits while starting) never received the document: the document is answered `failed`, the cause is logged, and the outcome is not cached. A failure while a worker holds a document it was sent, such as an uncaught error or an unexpected exit, is that document's crash and stays a cached `failed`, whatever order Node delivers the worker's error and its messages in. Running out of heap and missing the deadline stay a cached `too-large`.
92
101
  Creating the explorer fails when the worker file is missing next to the server module; where DOMPurify cannot run, it refuses instead of returning its input unchanged, and the document fails.
93
102
 
103
+ The browser runtime (`createBrowserExplorerPlatform` of `./server/browser`) keeps the same rules with one worker. The nesting guard above (the same parser, depth, node, comment and attribute budgets) runs in a module Web Worker started from the host's `nestingGuardWorkerUrl`, so its cost never blocks the page and HTML it stops never reaches the DOM; DOMPurify then sanitizes on the page's main thread, over the window the host gives, one document at a time and after yielding the main thread once.
104
+ Its limits are those above but for the worker fields: `sanitizer.workers` and `sanitizer.workerHeapMb` are refused (a `TypeError` when the explorer is created), the node budget is the one of Node's default worker heap (512 MiB, so 81,920 nodes with the default 4 MiB of HTML), and `sanitizer.maxHtmlBytes` may be at most 14,155,776, the most that leaves the budget 4,096 nodes (a `RangeError` above it).
105
+ The admission defaults are those of one worker (`jobsPerScope` defaults to `multiView.maxPanels` + 4, 16 with the default 12 panels). The deadline spans both steps: a guard that overruns it is ended and replaced, and DOMPurify, which keeps the main thread until it finishes, has its output discarded when it finishes after the deadline, so the document is `too-large` either way.
106
+ A guard worker that fails before it is ready leaves the document `failed` and not remembered, and one that fails while it holds a document makes that document a remembered `failed`; nothing here ends for a heap, since the guard's budgets bound what reaches DOMPurify.
107
+
94
108
  Fixed or absolutely positioned markup in a document cannot cover the host or the explorer: the document region is its containing block and clips its painting (in a multi-view panel, the panel's frame clips it). Such markup can still cover the rest of its own document.
95
109
 
96
110
  The rest of a source's output is validated before it is sent: image and media URLs must be `http:`, `https:` or relative, media types `video`, `audio` or `pdf`, notice links `http:`, `https:`, `mailto:` or relative, heading depths 1–6, and failure codes 1–64 lowercase letters, digits or hyphens. A violation is logged and the reader sees a generic failure (an empty notice list for notices).
@@ -111,7 +125,7 @@ In a tree or children listing, an entry with an empty name, or with a path the b
111
125
  Once the reload settled and unless the request went away, `onTreeRefreshed` receives the tree's cache key, which a multi-process host relays to its other processes' `forgetTree`; the response does not wait for a promise it returns, and a throw or that promise's rejection is logged (operation `refresh`).
112
126
  - A document GET carrying `X-Markdown-Explorer: refresh` marks a request a refresh triggered: the host's `document` (and the admitting source's `confirm`) receive `refresh: true` and skip their caches. Such a request must carry the header's exact value and pass the same cross-origin check as the refresh itself (as a `GET`, a request without Fetch Metadata passes whatever its `Origin`, since another origin's page cannot add the header without a CORS preflight), or it is answered 403 before any host call, so a cross-site page cannot make the host re-parse documents.
113
127
  - The `text` operation (`GET {dataPath}/text?path=`) answers JSON like a document request: GET and HEAD only; a missing, repeated or unacceptable `path` is 400; signed out 401 and forbidden 403.
114
- Everything else is status 200: a text document (`name`, `text`, `truncated`, and the file's asset `url` with its version), or a failure document — `forbidden` for a denied or unadmitted path, `unsupported` for a file whose decoded text holds NUL (U+0000;
128
+ Everything else is status 200: the file read as text (`kind: "text"` with `name`, `text`, `truncated` and the file's asset `url` with its version, but no `lang`, since the operation reads any file a view shows as written), or a failure document — `forbidden` for a denied or unadmitted path, `unsupported` for a file whose decoded text holds NUL (U+0000;
115
129
  the zero bytes of a UTF-16 file with a byte order mark are read as part of its characters, so only a U+0000 of its own is NUL, while a UTF-16 file without the mark is read as UTF-8 and its zero bytes are), the reason of an `ExplorerError` the host's `asset` port throws, and otherwise `failed`, logged with the operation `text` (a stream that ends before the size the port reported included).
116
130
  It carries no refresh mark: the host's `asset` port receives `refresh: false`. The file is opened as the asset operation opens it — the first `textMaxBytes` bytes as a range when the port reports a longer size, the whole file otherwise, an empty file never — and the stream is cancelled once enough was read.
117
131
  - The `asset` operation answers bytes instead of JSON (its failures stay JSON failures with the statuses above). GET and HEAD only; a request whose own URL path ends in `.data` is 404 before authentication; signed out 401 and forbidden 403 with no redirect; a missing, repeated or unacceptable `path` 400; a denied or unadmitted path 403.
@@ -137,7 +151,7 @@ In a tree or children listing, an entry with an empty name, or with a path the b
137
151
  - `save` and `preview` are `POST` only, and need `X-Markdown-Explorer: edit` and the shared cross-origin check of a refresh (`crossOriginRefusal`), checked before the body is read (403). The body must be `text/markdown` with no charset or `utf-8` (else 400); a declared or actual length over `editMaxBytes` is refused (413) and the reading stops at the first byte past the limit; invalid UTF-8 and NUL are refused (400). All of this happens before any port is called.
138
152
  - `base` (a save's version) and `revision` are tokens of 1 to 1024 characters (400 otherwise). A version, a revision id and a grant are copied from the ports' answers only in their contract's shape: a grant's `href` must be root-relative, an external editor's `href` an absolute `https:` URL; sources, conflict texts and revisions longer than `editMaxBytes`, and malformed revisions, are logged and answered `failed`.
139
153
  - The preview's HTML goes through the same sanitizer, limits and reader share as a document's. The sanitizer keeps a converter's source lines only as `data-source-lines="<first>-<last>"` (positive line numbers, the first not after the last).
140
- - With a draft converter (`draftConverter`), a draft is rendered in the browser and sanitized there before it is shown, by the same allow-list rules (`core/sanitizePolicy`, on a DOMPurify instance of the preview's own from `isomorphic-dompurify`'s browser build, so no hook another script adds to the page's shared DOMPurify takes part) and the same nesting limit (`too-large` deeper than 512 levels). The server's other resource limits do not apply there: the host's converter bounds the HTML (`maxHtmlBytes`), and the rendering never leaves the browser.
154
+ - With a draft converter (`draftConverter`), a draft is rendered in the browser and sanitized there before it is shown, by the same allow-list rules (`core/sanitizePolicy`, on a DOMPurify instance of the preview's own from `isomorphic-dompurify`'s browser build, so no hook another script adds to the page's shared DOMPurify takes part) and the same nesting limit (`too-large` deeper than 256 levels). The server's other resource limits do not apply there: the host's converter bounds the HTML (`maxHtmlBytes`), and the rendering never leaves the browser.
141
155
  The only thing the browser takes from the server for it is the existence marks of images and linked documents, read from the HTML the server's `preview` operation answered (sanitized on the server) and written by the browser's sanitizer onto the elements naming the same document paths, exactly as the converter writes them; a draft the converter answers `unavailable` for is rendered by the server as before.
142
156
  - What the host must do: decide per document and per reader whether a document is editable, and check it again in every port (a request names any admitted path); write with the reader's own credentials, never a service account's; write only when the document still has the draft's base version, and otherwise answer the current content without writing; keep revisions only where readers may see them.
143
157
 
@@ -148,9 +162,10 @@ In a tree or children listing, an entry with an empty name, or with a path the b
148
162
  - **Fail closed.** A read-only authentication that carries any header (whatever its status; an empty `headers` holds none) is a broken contract: none of its headers is forwarded, the failure is logged once through `logger` with the operation `authenticate`, and the request is answered `failed` (500, `private, no-store`, no `Set-Cookie`).
149
163
  A malformed authentication, or an `authenticate` that throws, is answered the same way; an `ExplorerError` answers its reason without a log, as on every operation, and an aborted request is not logged.
150
164
  Nothing logged quotes a header value: `headers` that `Headers` cannot read are refused with a fixed message (on every request, the page loader included), and a `Response` that `authenticate` throws — React Router's `throw redirect(...)`, whose headers carry cookies — is logged by its status alone. `signed-out` and `forbidden` both mean no card: the handler answers its 401 with `no-store` before fetching anything.
151
- - **SSRF guards live in `@aiquants/markdown`.** The explorer creates `createLinkCardHandler` once, with `authorize` as its only option, and adds no option of its own: internal addresses never become cards in any environment.
152
- The handler refuses loopback, private, link-local, CGNAT and every other non-global IPv4 or IPv6 address in every form the URL parser normalizes, internal names (`localhost`, single-label names, `.local`, `.internal`, `.home.arpa`), names that resolve to such addresses (checked again at connect time against DNS rebinding) and every redirect hop to them, and it bounds time, redirects, headers and body.
153
- Its answer for such a link — `204 No Content` with `X-Link-Card-Skip: private-network` — is passed through unchanged, and `@aiquants/markdown`'s link card shows the link as a compact card and writes one `console.info` line; the explorer logs nothing of its own for cards.
165
+ - **SSRF guards live in `@aiquants/markdown`'s service.** The explorer creates `createLinkCardHandler` once, with `authorize` as its only option, and adds no option of its own: internal addresses never become cards in any environment.
166
+ The handler opens pages only through the markdown service (`MARKDOWN_SOCKET_PATH`, as `parseMarkdown`), and the service alone decides which hosts a card may reach: it refuses loopback, private, link-local, CGNAT and every other non-global IPv4 or IPv6 address in every form the URL parser normalizes, internal names (`localhost`, `*.localhost`, single-label names, `.local`, `.internal`, `.home.arpa`), names that resolve to such addresses (at every connection, against DNS rebinding) and every redirect hop to them, and it bounds time, redirects, headers and body.
167
+ Without the service the handler fetches nothing and answers its own `500` (`no-store`), which is passed through unchanged like its other answers.
168
+ Its answer for an internal link — `204 No Content` with `X-Link-Card-Skip: private-network` — is passed through unchanged, and `@aiquants/markdown`'s link card shows the link as a compact card and writes one `console.info` line; the explorer logs nothing of its own for cards.
154
169
  - **Same origin.** The browser asks the page's own origin with its credentials and `redirect: "error"`, so no `connect-src` beyond `'self'` is needed and no cross-origin page can read an answer (the data route grants no CORS).
155
170
 
156
171
  ## Caches and identity
@@ -158,7 +173,8 @@ In a tree or children listing, an entry with an empty name, or with a path the b
158
173
  - The server's tree cache is keyed by the reader's scope (derived from the principal's stable key) and the source. `cacheScope: "shared"` lets readers share one entry when the tree does not depend on who reads it; `createFileSystemSource` uses `"principal"` unless told otherwise, which a source wrapped to filter its tree per reader must keep. Entries expire after `treeCache.ttlMs`, and the cache holds at most `treeCache.maxEntries` trees and `treeCache.maxBytes` of their JSON.
159
174
  It never keeps an empty or failed tree and never answers a tree past its time to live, counted from the moment its walk began: a page load or tree request after it waits for one new walk, which every concurrent request shares. At most one walk of a tree runs at a time per key; a walk a refresh or `forgetTree` superseded keeps running for the requests already waiting on it (they receive its tree, which is not kept) and is aborted once none waits, and the next walk starts once it settles (at once for a source that honours its signal).
160
175
  Each process keeps its own cache: `forgetTree(key)` drops a key another process refreshed, without starting a walk.
161
- - Each data response carries an opaque, pseudonymous scope (`X-Markdown-Explorer-Scope`): an HMAC of the principal's key under `scopeSecret`, which nobody without the secret can link to a principal. When the browser sees a different scope — another reader signed in on the same browser — it drops every cached tree and document, clears the explorer's storage and reloads the page data (once per run of the loader, without cancelling a loader that is running). A 401 erases nothing and reloads the page data, whose loader answers a signed-out reader with `signedOutPage`.
176
+ - Each data response carries an opaque, pseudonymous scope (`X-Markdown-Explorer-Scope`): on the Node entry an HMAC of the principal's key under `scopeSecret`, which nobody without the secret can link to a principal, and on the browser runtime the one scope the host gives with the page's one principal key.
177
+ When the browser sees a different scope — another reader signed in on the same browser — it drops every cached tree and document, clears the explorer's storage and reloads the page data (once per run of the loader, without cancelling a loader that is running). A 401 erases nothing and reloads the page data, whose loader answers a signed-out reader with `signedOutPage`.
162
178
  - The page data carries the same scope, and the explorer records it in its storage namespace. On every page load, and whenever the page data names another reader, the recorded scope is compared during render — before any part of the explorer reads browser storage — and the namespace is erased unless it belongs to the page's reader (keys without a recorded scope are erased too).
163
179
  A new scope also clears and reseeds both browser stores in a layout effect, before the browser paints, and rebuilds the explorer's components, so no document of the previous reader is drawn and no expansion state, selection or panel arrangement survives in memory either. Each reader also has a live-region announcer of their own: the rebuilt explorer's regions (the root's and the sheet's) start empty, and neither what the previous reader was last told (a folder or document name) nor a message their work posted just before the switch reaches it.
164
180
  - The server keeps no failed tree and asks the source again for every document request (the sanitizer's cache only remembers what it made of a given HTML input). In the browser a failure is kept only until a pane has shown it: opening it again, or "Try again", asks the server again.
@@ -166,8 +182,10 @@ In a tree or children listing, an entry with an empty name, or with a path the b
166
182
  ## What the host must do
167
183
 
168
184
  - Authenticate in `authenticate` and keep `principalKey` stable for one reader. Honour its `mode`: with `{ readOnly: true }` (the `link-card` operation) only read the session — never refresh a token, write no cookie and return no `headers`; the explorer refuses an authentication that does.
169
- - Set `scopeSecret` from configuration, kept out of the source code and the browser: at least 32 characters, the same on every server instance.
170
- - Keep the package external in your server bundle, so the sanitizer's worker file stays next to the server entry.
185
+ - On the Node entry, set `scopeSecret` from configuration, kept out of the source code and the browser: at least 32 characters, the same on every server instance.
186
+ - On the Node entry, keep the package external in your server bundle, so the sanitizer's worker file stays next to the server entry.
187
+ - On the browser runtime (`./server/browser`; [Hosting](hosting.md) gives the steps), create the runtime in a secure context (a window without `crypto.subtle` is refused), serve one principal per page (a request naming another principal key is a `TypeError`), and give `nestingGuardWorkerUrl` the URL your bundler emits for `@aiquants/markdown-explorer/server/browser/nesting-guard-worker`.
188
+ Answer the page's data requests with `createInProcessDataFetch` passed as `<MarkdownExplorer fetch>` (the page's router has no `basename`). The browser loads a document's images and media from their URLs, never through that fetch, so serve `{dataPath}/asset` (and `mediaDataPath`) over the page's own scheme, or show content without them.
171
189
  - Implement the ports: `document` and `asset` (and `children` for lazy folders) read what the explorer admitted, with the `readPath` it hands them, and report the same `version` for the same file.
172
190
  The explorer serves every file's bytes itself (see [What the explorer serves](#what-the-explorer-serves)), so the host writes no asset route (nor a route for a document's source, which the `text` operation reads through the same port); the `asset` port only finds the file and opens its bytes, through a handle it checked (for example by comparing the opened file's device, inode, size and modification time with those of the checked path, refusing a file that has changed since it was found) and aborting with the request's signal.
173
191
  - Refuse React Router single-fetch requests in any code your data route module runs before it hands the request to `dataLoader` or `dataAction` (which refuse them themselves), and in every resource route of your own: answer 404 for a request whose own URL path (`new URL(request.url).pathname`) ends in `.data`, before authenticating or touching storage.
@@ -182,6 +200,7 @@ In a tree or children listing, an entry with an empty name, or with a path the b
182
200
  - List only the iframe hosts you trust in `iframeHosts`, and list the host's own origin only when documents must frame it: every page of a listed host can be framed by a document, and a frame of your own origin is same-site, so it carries the reader's cookies (`SameSite=Lax` included) and the page's side effects happen in an invisible frame.
183
201
  - Serve a content security policy for every page of the app — from the root route, the document handler or the edge — rather than on the explorer's route responses alone: a client-side navigation keeps the document it started in, and with it that document's policy, so a policy sent with the explorer's pages is missing when the reader arrives by a client-side navigation and stays on every page visited after them.
184
202
  The explorer needs `frame-src`, `img-src` and `media-src` to allow `'self'`, the origin of its own asset URLs (PDF documents open in a frame from that URL), plus `frame-src https://<host>` for each `iframeHosts` entry, and works under `object-src 'none'` and `base-uri 'none'`.
203
+ With `mediaDataPath`, `media-src` and `frame-src` also allow its origin, which videos, audio and PDF documents then load from; on the browser runtime, `worker-src` (or the directive it falls back to) allows the nesting-guard worker's URL.
185
204
  - Call `clearExplorerStorage(storageNamespace)` when a reader signs out of a shared browser. It throws a `RangeError` for a malformed namespace (empty, containing `:` or spaces, longer than 64 characters), so a typo cannot clear another namespace's keys or nothing at all.
186
205
 
187
206
  ## What the explorer serves
@@ -190,4 +209,5 @@ In a tree or children listing, an entry with an empty name, or with a path the b
190
209
  - Inline only for raster images, audio, video and PDF; everything else, SVG and an empty or unknown type included, as an attachment — unless the request asks for the plain-text display (`as=text`, the text viewers' Open in a new tab and a table file's preview), which shows any admitted file in place as `text/plain; charset=<encoding>` (the encoding the explorer's one text rule reads the file's first 64 KiB in) whatever its declared type,
191
210
  under the same `nosniff` and sandboxing policy, so an HTML or SVG file opened that way shows its source and runs nothing. A workbook's preview delivery (`as=workbook`) is always an attachment of `application/octet-stream`, whatever the declared type. Both dispositions name the file (`filename*=UTF-8''<name>`, the RFC 8187 encoding of the name with `'`, `(`, `)` and `*` percent-encoded too), so a saved file keeps its name although every asset URL's path ends in `asset`.
192
211
  - The type is the one the host declares, parsed as a browser parses it, never guessed from the name; `nosniff` stops the browser from guessing either, and the sandboxing policy keeps an SVG or HTML file opened on its own from running script.
193
- - For `createFileSystemSource`, files of unknown extensions are downloadable, and so are the whole bytes of every Markdown and text file the source admits: raw Markdown keeps what the rendered view drops (front matter, HTML comments), and a text file is served beyond its preview. Its deny rules — `DEFAULT_DENIED_PATH_SEGMENTS` (environment files, keys and certificates, credential files, Terraform state, shell histories) plus the host's `deny` patterns — are the only filter, so add a pattern for anything else the folder must withhold.
212
+ - For `createFileSystemSource`, files of unknown extensions are downloadable, and so are the whole bytes of every Markdown and text file the source admits: raw Markdown keeps what the rendered view drops (front matter, which `@aiquants/markdown`'s converter renders as nothing in every document, and HTML comments), and a text file is served beyond its preview.
213
+ Its deny rules — `DEFAULT_DENIED_PATH_SEGMENTS` (environment files, keys and certificates, credential files, Terraform state, shell histories) plus the host's `deny` patterns — are the only filter, so add a pattern for anything else the folder must withhold.
@@ -6,7 +6,7 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
6
6
 
7
7
  | View | Path | Query |
8
8
  | --- | --- | --- |
9
- | Tree | `{basePath}/{views.tree}`, `{basePath}/{views.tree}/{document}` or `{basePath}/{views.tree}/{folder}/` | `source`, `style`, `align`, `markup` |
9
+ | Tree | `{basePath}/{views.tree}`, `{basePath}/{views.tree}/{document}` or `{basePath}/{views.tree}/{folder}/` | `source`, `style`, `align`, `maximized`, `markup` |
10
10
  | Multi-panel | `{basePath}/{views.multi}` | `source`, `doc` (repeated, in panel order), `maximized`, `markup` (repeated, in the order of `doc`) |
11
11
  | Single | `{basePath}/{views.single}/{document}` | `source`, `style`, `align`, `markup`, `showToc`, `showStyle`, `showAlign`, `padding`, `width`, `maxWidth` |
12
12
 
@@ -15,10 +15,11 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
15
15
  - The tree view shows a document, a folder (its README, see [Folder segment](#folder-segment)) or neither: `ExplorerLocation`'s tree view has `doc` and `folder`, at most one of them not `null`.
16
16
  - `markup` names the Markdown documents, SVG images and table files shown as written (their source — an SVG image's own SVG, a table file's CSV or TSV —, the document bar's Source toggle) instead of rendered (a table file as its table): in the tree and single views `markup=true` for the URL's document — in the tree view a folder's README too —, and in the multi-panel view one `markup` per open document shown that way, in the order of `doc` (a maximized document included).
17
17
  `ExplorerLocation`'s `markup` is a boolean in the tree and single views (always `false` in the tree view without a document or a folder) and a list in the multi-panel view; a target without it (`ExplorerHrefTarget`) shows every document rendered. A document that is neither Markdown, an SVG image nor a table file (a raster image, media, text, a file or a failure) ignores it and shows as it always does. The Source toggle of an SVG image inside a rendered document is the image block's own and never enters the URL.
18
+ - `maximized` says what fills the page: in the tree view `maximized=true` for the URL's document — a folder's README too — (the document bar's Maximize, see [Layout](layout.md#the-maximized-document)), and in the multi-panel view the open document whose panel is maximized. `ExplorerLocation`'s `maximized` is a boolean in the tree view (always `false` without a document or a folder) and a document or `null` in the multi-panel view; the single view has none, and a target without it fills nothing.
18
19
  - The source never limits which documents can be open: a path names one document; it may appear in several sources' trees, and it opens when the boundary of at least one source admits it, whichever source the URL names. Switching the source therefore keeps every open document, and a document no source's boundary admits is answered `forbidden` in every view.
19
20
  - `explorerHref(config, target)` is the only function that writes explorer URLs, and `resolveExplorerLocation(config, splat, search)` is the only one that reads them. The server's loader and the browser call the same two functions, each with a configuration joined with the server's source ids by `withExplorerSources(config, sourceIds)` (an `ExplorerLocationConfig`; no ids, an invalid id or a repeated one throws a `RangeError`).
20
21
  `explorerHref` has two forms: any target with such a configuration, and a target without `source` (`ExplorerSourcelessHrefTarget`, the default source) with a plain `ExplorerConfig`, for links built where the server's sources are not known (a host menu). A target with a `source` and a configuration without ids throws a `TypeError` naming `withExplorerSources`, and so does `resolveExplorerLocation` given such a configuration.
21
- - `explorerHref` writes only canonical URLs. It throws a `RangeError` for a target the resolver would redirect, read as another location or partly ignore: an unknown source, an unacceptable document or folder path, a tree or single view's document path that ends in a slash (its segment would name a folder), a tree view with both a document and a folder, multi-panel documents that repeat or exceed `multiView.maxPanels`, a maximized document or a document shown as written that is not open, a document shown as written twice, a tree view with neither a document nor a folder shown as written,
22
+ - `explorerHref` writes only canonical URLs. It throws a `RangeError` for a target the resolver would redirect, read as another location or partly ignore: an unknown source, an unacceptable document or folder path, a tree or single view's document path that ends in a slash (its segment would name a folder), a tree view with both a document and a folder, multi-panel documents that repeat or exceed `multiView.maxPanels`, a maximized document or a document shown as written that is not open, a document shown as written twice, a tree view with neither a document nor a folder maximized or shown as written,
22
23
  a `style` naming no configured document style, an `align` other than `left`, `center` or `right`, and an embedding value outside the rules below (a non-boolean switch, a padding outside 0–256 or not writable in decimal digits, a width that is not one of the accepted CSS lengths).
23
24
  Resolving a link it wrote therefore always yields the very location it was given.
24
25
 
@@ -53,13 +54,14 @@ Every URL resolves either to a location or to a redirect to its canonical form.
53
54
  | A single URL whose segment names a folder | Redirect to the tree view's folder, keeping `source`, `style`, `align` and `markup` (the embedding parameters are dropped) |
54
55
  | `source` unknown, repeated, or equal to the default | Redirect to the same location with `source` dropped |
55
56
  | Multi-panel `doc` values that are not acceptable paths, repeated, or beyond `multiView.maxPanels` | Redirect with only the first occurrence of each acceptable path, in order, up to the limit |
56
- | `maximized` repeated, or not one of the open documents | Redirect without `maximized` |
57
+ | Multi-panel `maximized` repeated, or not one of the open documents | Redirect without `maximized` |
57
58
  | Multi-panel `markup` values that are not open documents, repeated, or out of the order of `doc` | Redirect with each open document shown as written once, in the order of `doc` |
58
59
  | A path segment after the multi-panel slug | Redirect to the multi-panel view without it |
59
60
  | `style` naming no configured document style, `align` other than `left`, `center` or `right` | Ignored (the reader's own setting applies) |
60
61
  | `padding` outside 0–256 or not written in decimal digits (signs, exponents, hexadecimal, surrounding spaces and `Infinity` are not numbers here), `width` / `maxWidth` not a CSS length in `px`, `rem`, `em`, `ch`, `vw` or `%` | Ignored (the default applies) |
61
62
  | `showToc`, `showStyle`, `showAlign` other than `false` | Ignored (the control is shown) |
62
63
  | `markup` in the tree or single view other than `true`, or in the tree view without a document or a folder | Ignored (the document shows rendered) |
64
+ | `maximized` in the tree view other than `true`, or without a document or a folder | Ignored (the document does not fill the page) |
63
65
 
64
66
  An acceptable document path is non-empty, at most 4096 UTF-16 code units long, well-formed (no lone surrogate, which no URL can carry), and contains neither a control character (U+0000–U+001F, U+007F) nor a backslash. Whether the path exists, and whether it is denied, is decided by the server for the document request; the URL itself stays as written.
65
67
 
@@ -137,22 +139,27 @@ In the tree and single views that address is the page's URL (the same view, with
137
139
  | Switching between the views (the view switch, "open selection in the multi-panel view") | Pushes |
138
140
  | Any multi-panel action (open, close, maximize, restore, navigate inside a panel, rearrange (drag or move)) | Replaces; hiding and showing a panel do not change the URL (browser storage remembers them) |
139
141
  | The Source toggle (a Markdown document shown as written or rendered) | Replaces; in the tree and single views the fragment is dropped, since the swapped content starts at its top |
142
+ | The tree view's Maximize (the document filling the page or restored) | Replaces, keeping the scroll; the fragment is dropped, since it would take the reader back to its target on every press |
140
143
 
141
144
  A multi-panel action that follows a source switch before the router reports it keeps the new source.
142
145
 
143
146
  Whether a document shows as written stays with that document only: selecting another document in the tree, following a document link and navigating inside a panel show the next document rendered (the document still shown while it loads keeps the way it showed), and closing a panel forgets it.
144
147
  Switching the tree's source, the reveal's move of the tree and the switches between the views keep it — the view switch carries it for the document it opens (the tree view's document as a panel, the multi-panel view's maximized or first document in the tree view), and opening a selection carries it for the tree view's document when the selection holds it.
145
148
 
149
+ Whether the tree view's document fills the page stays with it through a source switch, the reveal's move and the document links and table-of-contents entries it follows, which read it at the moment of the click: their hrefs never carry it, so a modified click or a copied link opens the target at its size. Selecting a document or a folder in the tree shows it at its size, and the switches between the views, whose controls lie inert under the cover, never carry it.
150
+
146
151
  The page loader only seeds the first paint; after that the browser reads through the data route. Export `shouldRevalidateExplorer` as the page route's `shouldRevalidate`: it runs the loader again only for a revalidation of the very same URL (`useRevalidator().revalidate()`, or a navigation to the current URL) and never after a form or fetcher submission elsewhere on the page, so moving between views, documents and sources never reloads the tree. Entering the explorer from another route always runs the loader.
147
152
  A revalidation keeps the shown tree and documents on screen and replaces each only when its new value differs (a different tree also drops its loaded lazy folders); a failure, or a value the loader gave up on, leaves the shown one alone.
148
153
 
149
154
  ## Display settings
150
155
 
151
- The reader's display settings — the explorer width per view, the document style and the alignment — live in a cookie named by `settingsCookie`, so the server renders the first paint with them:
156
+ The reader's display settings — the explorer width per view, whether the reader closed the explorer in each view, the document style, the alignment, the column width and the colour pair — live in a cookie named by `settingsCookie`, so the server renders the first paint with them:
152
157
 
153
- - the value is percent-encoded JSON with the keys `treeExplorer`, `multiExplorer`, `style` and `align`, written in that order and only when set;
158
+ - the value is percent-encoded JSON with the keys `treeExplorer`, `treeExplorerHidden`, `multiExplorer`, `multiExplorerHidden`, `style`, `align`, `measure` and `documentColors`, written in that order and only when set;
159
+ - `style` is one of the configuration's document styles, and `align`, `measure` and `documentColors` are one of `@aiquants/markdown`'s own alignments (`CONTENT_ALIGNS`), column widths (`CONTENT_MEASURES`) and colour pairs (`CONTENT_COLORS`);
154
160
  - widths are percentages of the split, greater than 0 and at most 1/φ² (38.197 %), rounded to 0.01 %;
161
+ - a closed explorer is written as `true` and an open one not at all, and the explorer reads the flag as `=== true`, so `false` and a missing key mean the same (see [Layout](layout.md#closing-the-explorer));
155
162
  - the cookie is written with `Path=/`, `Max-Age=31536000`, `SameSite=Lax`, and `Secure` on HTTPS;
156
163
  - a malformed cookie, or a value outside these rules, is treated as absent (key by key).
157
164
 
158
- The `style` and `align` query parameters override the cookie for one URL without changing it. Without either, a document takes the configuration's `defaultDocumentStyle` (`@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE`, Zenn, unless the host names another of its styles) and `@aiquants/markdown`'s own default alignment, so the explorer and the viewer always agree.
165
+ The `style` and `align` query parameters override the cookie for one URL without changing it. Without either, a document takes the configuration's `defaultDocumentStyle` (`@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE`, Zenn, unless the host names another of its styles) and `@aiquants/markdown`'s own default alignment, so the explorer and the viewer always agree. The column width and the colour pair have no query parameter: without a stored one, a document takes `@aiquants/markdown`'s own defaults (`DEFAULT_CONTENT_MEASURE`, `fill`, and `DEFAULT_CONTENT_COLORS`, `default`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/markdown-explorer",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "Markdown document explorer for React Router 8 (framework mode): a source tree with a single-document view and a multi-panel reading view, storage-agnostic server ports, golden-ratio layout and an en / ja UI.",
5
5
  "sideEffects": [
6
6
  "**/*.css"
@@ -32,6 +32,29 @@
32
32
  },
33
33
  "default": "./dist/server.js"
34
34
  },
35
+ "./server/core": {
36
+ "import": {
37
+ "types": "./dist/serverCore.d.ts",
38
+ "default": "./dist/serverCore.js"
39
+ },
40
+ "require": {
41
+ "types": "./dist/serverCore.d.cts",
42
+ "default": "./dist/serverCore.cjs"
43
+ },
44
+ "default": "./dist/serverCore.js"
45
+ },
46
+ "./server/browser": {
47
+ "import": {
48
+ "types": "./dist/serverBrowser.d.ts",
49
+ "default": "./dist/serverBrowser.js"
50
+ },
51
+ "require": {
52
+ "types": "./dist/serverBrowser.d.cts",
53
+ "default": "./dist/serverBrowser.cjs"
54
+ },
55
+ "default": "./dist/serverBrowser.js"
56
+ },
57
+ "./server/browser/nesting-guard-worker": "./dist/nestingGuardWorker.js",
35
58
  "./storage": {
36
59
  "import": {
37
60
  "types": "./dist/storage.d.ts",
@@ -43,6 +66,17 @@
43
66
  },
44
67
  "default": "./dist/storage.js"
45
68
  },
69
+ "./testing": {
70
+ "import": {
71
+ "types": "./dist/testing.d.ts",
72
+ "default": "./dist/testing.js"
73
+ },
74
+ "require": {
75
+ "types": "./dist/testing.d.cts",
76
+ "default": "./dist/testing.cjs"
77
+ },
78
+ "default": "./dist/testing.js"
79
+ },
46
80
  "./styles/markdown-explorer.css": "./dist/styles/markdown-explorer.css",
47
81
  "./package.json": "./package.json"
48
82
  },
@@ -68,23 +102,23 @@
68
102
  "parse5": "^8.0.0"
69
103
  },
70
104
  "peerDependencies": {
71
- "@aiquants/directory-tree": "^6.0.0",
72
- "@aiquants/drag-drop-panels": "^0.13.0",
73
- "@aiquants/markdown": "^12.1.0",
74
- "@aiquants/resize-panels": "^2.2.0",
75
- "@aiquants/spreadsheet": "^0.19.0",
76
- "@aiquants/virtualscroll": "^3.22.1",
105
+ "@aiquants/directory-tree": "^6.1.1",
106
+ "@aiquants/drag-drop-panels": "^0.14.0",
107
+ "@aiquants/markdown": "^13.0.0",
108
+ "@aiquants/resize-panels": "^2.3.0",
109
+ "@aiquants/spreadsheet": "^0.20.0",
110
+ "@aiquants/virtualscroll": "^3.24.0",
77
111
  "react": "^19.2.7",
78
112
  "react-dom": "^19.2.7",
79
113
  "react-router": "^8.0.0"
80
114
  },
81
115
  "devDependencies": {
82
- "@aiquants/directory-tree": "6.0.0",
83
- "@aiquants/drag-drop-panels": "0.13.0",
84
- "@aiquants/markdown": "12.1.0",
85
- "@aiquants/resize-panels": "2.2.0",
86
- "@aiquants/spreadsheet": "0.19.0",
87
- "@aiquants/virtualscroll": "3.23.1",
116
+ "@aiquants/directory-tree": "6.1.3",
117
+ "@aiquants/drag-drop-panels": "0.14.1",
118
+ "@aiquants/markdown": "13.0.0",
119
+ "@aiquants/resize-panels": "2.3.0",
120
+ "@aiquants/spreadsheet": "0.20.0",
121
+ "@aiquants/virtualscroll": "3.24.0",
88
122
  "@heroicons/react": "^2.2.0",
89
123
  "@playwright/test": "^1.64.1",
90
124
  "@tailwindcss/cli": "^4.1.18",
@@ -95,8 +129,11 @@
95
129
  "@types/react": "^19.2.7",
96
130
  "@types/react-dom": "^19.2.3",
97
131
  "@vitejs/plugin-react": "^5.1.2",
132
+ "@vitest/browser": "4.1.10",
133
+ "@vitest/browser-playwright": "4.1.10",
98
134
  "@vitest/coverage-v8": "^4.1.10",
99
135
  "jsdom": "^27.4.0",
136
+ "playwright": "^1.64.1",
100
137
  "react": "^19.2.7",
101
138
  "react-dom": "^19.2.7",
102
139
  "react-router": "^8.3.0",
@@ -131,7 +168,7 @@
131
168
  "scripts": {
132
169
  "build": "pnpm -w run workspace:build \"$PNPM_SCRIPT_SRC_DIR\"",
133
170
  "prebuild:self": "pnpm -w run workspace:sync \"$PNPM_SCRIPT_SRC_DIR\"",
134
- "build:self": "vite build && pnpm run build:css && node ../../.config/scripts/strip-dts-comments.mjs dist && node scripts/verify-dist.mjs",
171
+ "build:self": "vite build && vite build --mode nesting-guard-worker && pnpm run build:css && node ../../.config/scripts/strip-dts-comments.mjs dist && node scripts/verify-dist.mjs",
135
172
  "build:css": "tailwindcss -i src/styles/markdown-explorer.css -o dist/styles/markdown-explorer.css --minify",
136
173
  "dev": "vite build --watch",
137
174
  "watch": "vite build --watch",
@@ -139,10 +176,11 @@
139
176
  "demo:build": "cd demo && pnpm run build",
140
177
  "demo:start": "cd demo && pnpm run start",
141
178
  "typecheck": "tsc --noEmit && pnpm --dir demo run typecheck",
142
- "test": "vitest run",
179
+ "test": "vitest run --project browser --project wiring --project server --project server-plan --project server-browser-chromium",
143
180
  "test:run": "vitest run",
144
181
  "test:watch": "vitest --watch",
145
- "test:coverage": "vitest run --coverage",
182
+ "test:coverage": "vitest run --project browser --project wiring --project server --project server-plan --project server-browser-chromium --coverage",
183
+ "test:browser:webkit": "vitest run --project server-browser-webkit",
146
184
  "test:e2e": "playwright test",
147
185
  "test:e2e:ui": "playwright test --ui",
148
186
  "lint": "biome check src tests",
@@ -1,6 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),h=require("react"),S=require("./index-DSkK8iLE.cjs"),J=require("@aiquants/markdown/code-blocks"),K=require("@codemirror/commands"),pe=require("@codemirror/lang-markdown"),oe=require("@codemirror/language"),ge=require("@codemirror/search"),$=require("@codemirror/state"),P=require("@codemirror/view"),V=require("@lezer/highlight"),je=require("@aiquants/markdown"),ue=require("@aiquants/markdown/source-lines"),ee=require("./dataRoute-DwYtgyt6.cjs"),de=require("./sanitizePolicy-T5T-3vV5.cjs"),ze=require("isomorphic-dompurify"),se=require("@aiquants/resize-panels"),X=require("./location-BxiJRTyw.cjs"),ve=require("./useSplitPersistence-pPmE4GTT.cjs"),qe={history:K.historyField},Fe=oe.HighlightStyle.define([{tag:[V.tags.heading1,V.tags.heading2,V.tags.heading3,V.tags.heading4,V.tags.heading5,V.tags.heading6,V.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:V.tags.strong,fontWeight:"700"},{tag:V.tags.emphasis,fontStyle:"italic"},{tag:V.tags.strikethrough,textDecoration:"line-through"},{tag:V.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:V.tags.url,color:"var(--aqmx-syntax-url)"},{tag:V.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:V.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[V.tags.processingInstruction,V.tags.contentSeparator,V.tags.labelName,V.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ue=P.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",Ge=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),We=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),Xe=P.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class $e extends P.WidgetType{constructor(t,n){super(),this.index=t,this.labels=n}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const n=document.createElement("div");n.setAttribute(Me,String(this.index));for(const[r,i]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const o=document.createElement("button");o.type="button",o.textContent=i,o.setAttribute("data-aqmx-conflict-choice",r),o.addEventListener("mousedown",l=>l.preventDefault()),o.addEventListener("click",()=>{const l=re(t.state.doc)[this.index];l!==void 0&&(_e(t,l,r),t.focus())}),n.append(o)}return n}ignoreEvent(){return!0}}const re=e=>S.findConflictsInLines(e.iterLines()),we=(e,t)=>{const n=new $.RangeSetBuilder;return re(e).forEach((r,i)=>{const o=e.line(r.start);n.add(o.from,o.from,P.Decoration.widget({widget:new $e(i,t),block:!0,side:-1}));for(let l=r.start;l<=r.end;l+=1){const s=e.line(l).from,d=l===r.start||l===r.separator||l===r.end?Ge:l<r.separator?We:Xe;n.add(s,s,d)}}),n.finish()},Ke=e=>$.StateField.define({create:t=>we(t.doc,e),update:(t,n)=>n.docChanged?we(n.state.doc,e):t,provide:t=>P.EditorView.decorations.from(t)}),_e=(e,t,n)=>{const{doc:r}=e.state,i=(k,c)=>{const E=[];for(let u=k;u<=c;u+=1)E.push(r.line(u).text);return E},o=i(t.start+1,t.separator-1),l=i(t.separator+1,t.end-1),s=n==="ours"?o:n==="theirs"?l:[...o,...l];let d=r.line(t.start).from,f=r.line(t.end).to;s.length===0&&(t.end<r.lines?f+=1:t.start>1&&(d-=1));const p=s.join(`
2
- `);e.dispatch({changes:{from:d,to:f,insert:p},selection:$.EditorSelection.cursor(d),scrollIntoView:!0,userEvent:"input.resolve"})},Ee="input.preview",Ye=20,Je=P.ViewPlugin.fromClass(class{constructor(e){this.view=e,this.schedule()}view;cancel=null;update(e){e.docChanged&&this.schedule()}schedule(){if(this.cancel!==null||oe.syntaxTreeAvailable(this.view.state))return;const e=this.view.dom.ownerDocument.defaultView;if(e===null)return;const t=()=>{this.cancel=null,oe.ensureSyntaxTree(this.view.state,this.view.state.doc.length,Ye),this.schedule()};if(typeof e.requestIdleCallback=="function"){const n=e.requestIdleCallback(t);this.cancel=()=>e.cancelIdleCallback(n)}else{const n=e.setTimeout(t,0);this.cancel=()=>e.clearTimeout(n)}}destroy(){this.cancel?.(),this.cancel=null}}),Qe=/`{3,}|~{3,}/u,te=Object.freeze({kind:"absent"}),ce=Object.freeze({kind:"unreadable"}),Ze=(e,t,n)=>{const r=[];for(let d=t.parent;d!==null;d=d.parent)(d.name==="Blockquote"||d.name==="ListItem")&&r.unshift(d);const i=[],o=[],l=d=>{const f=o.indexOf(d);return f===-1?o.length:f};for(const d of r){const f=e.lineAt(d.from).number;if(d.name==="ListItem"){const p=J.listItemWidthOn(e.line(f).text,i,l(f));if(p===null)return null;i.push({kind:"listItem",width:p})}else i.push({kind:"quote"});o.push(f)}const s=J.openingFenceOn(n.text,i,l(n.number));return s===null?null:{containers:i,...s}},et=(e,t)=>{const{doc:n}=e;let r=n.lineAt(t).to;for(;;){const i=oe.ensureSyntaxTree(e,r,Number.POSITIVE_INFINITY);if(i===null)return null;const o=i.resolveInner(t,1),l=o.parent;if(o.name!=="CodeMark"||l===null||l.name!=="FencedCode"||l.from!==o.from)return null;if(l.to<r||r>=n.length)return l;r=Math.min(n.length,l.to+Math.max(l.to-t,1))}},be=(e,t)=>{const{doc:n}=e;if(!Number.isInteger(t)||t<1||t>n.lines)return te;const r=n.line(t),i=Qe.exec(r.text);if(i===null)return te;const o=et(e,r.from+i.index);if(o===null)return te;const l=o.getChild("CodeInfo");if(l===null)return te;const s=J.fencedCodeLanguageOf(n.sliceString(l.from,l.to));if(s===null)return ce;if(s!==J.SPREADSHEETS_LANGUAGE)return te;const d=Ze(n,o,r);if(d===null)return ce;const[,...f]=o.getChildren("CodeMark"),p=f.at(-1),k=p===void 0?n.lineAt(o.to).number:n.lineAt(p.from).number-1,c=[];let E="";for(let u=t+1;u<=k;u+=1){const m=n.line(u).text,v=J.readFencedLine(m,d);if(v===null)return ce;c.push(m),E+=u<n.lines?`${v.content}
3
- `:v.content}return{kind:"found",firstLine:t+1,lines:c,layout:d,body:E}},tt=({parent:e,scroll:t,text:n,saved:r,labels:i,revisions:o,onChange:l,onGeometry:s,onSave:d})=>{let f=!1;const p=[P.EditorView.scrollHandler.of((u,m,v)=>(nt(u,m.head,v,t),!0)),P.lineNumbers(),P.highlightActiveLineGutter(),K.history(),P.drawSelection(),P.highlightActiveLine(),ge.highlightSelectionMatches(),P.EditorView.lineWrapping,pe.markdown({base:pe.markdownLanguage}),Je,oe.syntaxHighlighting(Fe),Ke(i),P.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(d(),!0)},...ge.searchKeymap,...K.historyKeymap,...K.defaultKeymap]),P.EditorView.contentAttributes.of({"aria-label":i.editor,"aria-multiline":"true"}),P.EditorView.updateListener.of(u=>{for(const m of u.transactions)m.docChanged&&o.record(m.changes,m.newDoc);u.docChanged&&l(u.transactions.every(m=>!m.docChanged||m.isUserEvent(Ee))),(u.docChanged||u.heightChanged||u.geometryChanged)&&s(u.docChanged&&!f)}),Ue],k=st(r,p)??$.EditorState.create({doc:n,extensions:p}),c=new P.EditorView({state:k,parent:e});o.mount(c.state.doc);const E=u=>{f=!0;try{u()}finally{f=!1}};return{text:()=>c.state.doc.toString(),replaceText:u=>{const m=c.state.doc.toString();if(m===u)return;let v=0;const y=Math.min(m.length,u.length);for(;v<y&&m.charCodeAt(v)===u.charCodeAt(v);)v+=1;let g=0;for(;g<y-v&&m.charCodeAt(m.length-1-g)===u.charCodeAt(u.length-1-g);)g+=1;c.dispatch({changes:{from:v,to:m.length-g,insert:u.slice(v,u.length-g)},userEvent:"input.replace"})},replaceBody:(u,m,v,y)=>{const{doc:g}=c.state,L=o.lineOf(y,u);if(L===null)return"changed";const O=be(c.state,L);if(O.kind==="absent")return"changed";if(O.kind==="unreadable")return"unwritable";if(O.body!==J.fencedBodyAsRead(m,O.layout))return"changed";const I=J.planFencedBodyEdit(O.lines,O.layout,v);if(I.kind!=="edit")return I.kind;if(I.from===I.to&&I.lines.length===0)return"written";const D=j=>{const H=O.firstLine+j;return H<=g.lines?g.line(H).from:g.length},M=D(I.from),B=`${M===g.length&&g.sliceString(g.length-1)!==`
4
- `?`
5
- `:""}${I.lines.map(j=>`${j}
6
- `).join("")}`;return E(()=>c.dispatch({changes:{from:M,to:D(I.to),insert:B},userEvent:Ee,annotations:K.isolateHistory.of("full")})),"written"},readBody:(u,m)=>{const v=o.lineOf(m,u);if(v===null)return null;const y=be(c.state,v);return y.kind==="found"?y.body:null},undo:()=>E(()=>K.undo(c)),redo:()=>E(()=>K.redo(c)),reveal:({line:u,column:m},v)=>{const{doc:y}=c.state,g=y.line(Math.min(Math.max(u,1),y.lines)),L=Math.min(g.from+m,g.to);c.dispatch({selection:$.EditorSelection.cursor(L),effects:xe(c,L,v,t)})},showLine:u=>{const{doc:m}=c.state,v=m.line(Math.min(Math.max(u,1),m.lines)).from;c.dispatch({effects:xe(c,v,null,t)})},topLine:()=>{const u=t.scrollerOf(c.scrollDOM),m=S.visibleTopOf(u,c.contentDOM),v=S.frameTopOf(u)+u.clientHeight,{documentTop:y}=c,{doc:g}=c.state;let L=c.lineBlockAtHeight(Math.max(m-y,0));for(;g.lineAt(L.from).text.trim()===""&&L.to<g.length;){const D=c.lineBlockAt(L.to+1);if(y+D.top>=v)break;L=D}const O=c.coordsAtPos(L.from),I=O===null?y+L.top:O.top;return{line:c.state.doc.lineAt(L.from).number,clientTop:I,offset:I-m}},lineSpans:u=>{const m=c.scrollDOM,v=m.scrollTop+c.documentTop-S.visibleTopOf(m,c.contentDOM),{doc:y}=c.state,g=L=>y.line(Math.min(Math.max(L,1),y.lines)).from;return u.map(({first:L,last:O})=>({top:v+c.lineBlockAt(g(L)).top,bottom:v+c.lineBlockAt(g(O)).bottom}))},scrollElement:c.scrollDOM,focus:()=>c.focus(),conflicts:()=>re(c.state.doc),resolveAtCursor:u=>{const m=re(c.state.doc),v=c.state.doc.lineAt(c.state.selection.main.head).number,y=m.find(g=>g.end>=v);return y===void 0?!1:(_e(c,y,u),!0)},nextConflict:()=>{const u=re(c.state.doc);if(u[0]===void 0)return!1;const v=c.state.doc.lineAt(c.state.selection.main.head).number,y=u.findIndex(I=>I.start>v),g=y<0?0:y,L=c.state.doc.line(u[g].start).from;c.dispatch({selection:$.EditorSelection.cursor(L),effects:P.EditorView.scrollIntoView(L,{y:"center"})});const O=c.contentDOM.querySelector(`[${Me}="${String(g)}"] button`);return O instanceof HTMLElement?O.focus({preventScroll:!0}):c.focus(),!0},save:()=>c.state.toJSON(qe),destroy:()=>c.destroy()}},xe=(e,t,n,r)=>{const i=r.scrollerOf(e.scrollDOM),o=(n===null?S.visibleTopOf(i,e.contentDOM):n)-S.frameTopOf(i);return P.EditorView.scrollIntoView(t,{y:"start",yMargin:o})},nt=(e,t,n,r)=>{const i=rt(e,t),o=r.scrollerOf(e.scrollDOM),l=S.frameTopOf(o),s=S.visibleTopOf(o,e.contentDOM),d=l+o.clientHeight;let f=0;switch(n.y){case"start":f=i.top-(l+n.yMargin);break;case"center":f=(i.top+i.bottom)/2-(s+d)/2;break;case"end":f=i.bottom-(d-n.yMargin);break;default:i.top<s+n.yMargin?f=i.top-(s+n.yMargin):i.bottom>d-n.yMargin&&(f=Math.min(i.bottom-(d-n.yMargin),i.top-(s+n.yMargin)))}if(f!==0&&(o.scrollTop+=f),n.y==="start")return;const p=ot(e,t);p!==null&&r.reveal(p)},rt=(e,t)=>{const{node:n,offset:r}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,r),l.setEnd(n,r);const[s]=l.getClientRects();if(s!==void 0&&s.height>0)return{top:s.top,bottom:s.bottom}}}const i=e.lineBlockAt(t),o=e.documentTop+i.top;return{top:o,bottom:o+i.height}},ot=(e,t)=>{const{node:n}=e.domAtPos(t);for(let r=n instanceof Element?n:n.parentElement;r!==null;r=r.parentElement)if(r.parentElement===e.contentDOM)return r;return null},st=(e,t)=>{if(e==null)return null;try{return $.EditorState.fromJSON(e,{extensions:t},qe)}catch{return null}},it=610,lt=987,Se=Object.freeze({kind:"unavailable"}),ct="true",at="false",ut=e=>e===ct?!0:e===at?!1:null,dt=e=>{const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const r of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const i=r.localName==="img",o=r.getAttribute(i?"data-asset-src":"data-doc-path");o!==null&&n.push({target:{kind:i?"asset":"doc",path:o},exists:ut(r.getAttribute(i?"data-asset-exists":"data-doc-exists"))})}return n},ft=({path:e,instant:t,preview:n,initial:r,onView:i})=>{const o=new AbortController,l={asset:new Map,doc:new Map};let s=r,d=null,f=!1,p=!1,k=null,c=null,E=[],u,m=!1,v,y=null;const g=w=>{w.parsed===s.parsed&&w.source===s.source&&w.failure===s.failure&&w.busy===s.busy&&w.tier===s.tier||(s=w,i(w))},L=(w,T)=>{f||(f=!0,console.error(`[markdown-explorer] ${w}`,...T===void 0?[]:[T]))},O=w=>{if(t!==null)for(const{target:T,exists:C}of t.marksOf(w))l[T.kind].set(T.path,C)},I=()=>{clearTimeout(v),v=void 0,y?.abort(),y=null},D=()=>{c=null,E=[],clearTimeout(u),u=void 0},M=(w,T)=>{g({...s,failure:w,busy:!1,tier:T})},F=()=>{clearTimeout(u),u=E.length===0?void 0:setTimeout(j,lt)},B=()=>{if(t===null||c===null)return;const w=c,T=[],C={asset:new Set,doc:new Set};let U;try{U=t.sanitize(w.html,x=>{const _=l[x.kind].get(x.path);return _===void 0&&!C[x.kind].has(x.path)&&(C[x.kind].add(x.path),T.push(x)),_??void 0})}catch(x){D(),x instanceof de.HtmlNestingLimitError?M(ee.failureOf("too-large"),"instant"):(L("the draft sanitizer failed",x),M(ee.failureOf("failed"),"instant"));return}E=T;const b=s.parsed!==null&&s.parsed.htmlContent===U&&s.parsed.headings===w.headings?s.parsed:{htmlContent:U,headings:w.headings};g({parsed:b,source:w.draft,failure:null,busy:!1,tier:"instant"}),F()},j=()=>{if(u=void 0,m||c===null||E.length===0)return;m=!0;const w=E;n(e,c.draft.text,o.signal).then(T=>{if(m=!1,!(o.signal.aborted||!("kind"in T))){T.kind==="preview"&&O(T.htmlContent);for(const C of w)l[C.kind].has(C.path)||l[C.kind].set(C.path,null);B()}})},H=w=>{I(),D(),g({...s,busy:!0,tier:"server"});const T=new AbortController;y=T,v=setTimeout(()=>{v=void 0,n(e,w.text,T.signal).then(C=>{if(!(T.signal.aborted||!("kind"in C))){if(y=null,C.kind==="failure"){M(C.failure,"server");return}O(C.htmlContent),g({parsed:{htmlContent:C.htmlContent,headings:C.headings},source:w,failure:null,busy:!1,tier:"server"})}})},it)},a=async(w,T)=>{let C;try{C=await w.convert({path:e,text:T},o.signal)}catch(b){return o.signal.aborted||L("the draft converter rejected a conversion, which its contract allows only once the signal aborted",b),Se}const U=ee.draftAnswerViolation(C);return U===null?C:(L(`the draft converter answered outside its contract: ${U}`),Se)},A=(w,T)=>{switch(T.kind){case"preview":if(I(),T.headings.length>ee.EXPLORER_MAX_HEADINGS){D(),M(ee.failureOf("too-large"),"instant");return}c={draft:w,html:T.htmlContent,headings:T.headings.map(({text:C,depth:U,id:b})=>({text:C,depth:U,id:b}))},B();return;case"failure":I(),D(),M(ee.failureOf(T.failure.reason,T.failure.code),"instant");return;case"unavailable":H(w);return}},R=async w=>{p=!0;try{for(;k!==null&&!o.signal.aborted;){const T=k;k=null;const C=await a(w,T.text);if(o.signal.aborted)return;A(T,C)}}finally{p=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:w=>{if(!(o.signal.aborted||w.text===d?.text)){if(d=w,clearTimeout(u),u=void 0,t===null){H(w);return}k=w,p||R(t.converter)}},dispose:()=>{o.abort(),k=null,clearTimeout(u),u=void 0,I()}}},mt=(e,t)=>de.createHtmlSanitizer(ze(window),e,t,de.MAX_HTML_NESTING_DEPTH),ht=(e,t)=>e.flatMap((n,r)=>{const i=t[r];return i===void 0?[]:[{editor:i.top,preview:n.top},{editor:i.bottom,preview:n.bottom}]}),Y=(e,t)=>{const n=e[t];if(n===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${String(t)}`);return n},pt=e=>{const t=[];for(const r of e){let i=0,o=t.length;for(;i<o;){const l=i+o>>1;Y(t,l).pair.preview<=r.preview?i=l+1:o=l}t[i]={pair:r,before:i===0?void 0:Y(t,i-1)}}const n=[];for(let r=t.at(-1);r!==void 0;r=r.before)n.push(r.pair);return n.reverse()},gt=(e,t)=>{const n=Math.max(t.editorMax,0),r=Math.max(t.previewMax,0),i=n-t.editorViewport,o=r-t.previewViewport,l=e.filter(f=>f.editor>0&&f.editor<i&&f.preview>0&&f.preview<o).sort((f,p)=>f.editor-p.editor||f.preview-p.preview);let s={editor:0,preview:0};const d=[s];for(const f of pt(l))f.editor>s.editor&&f.preview>s.preview&&(d.push(f),s=f);return d.push({editor:n,preview:r}),{toPreview:f=>ye(d,"editor","preview",f),toEditor:f=>ye(d,"preview","editor",f)}},ye=(e,t,n,r)=>{const i=Y(e,0),o=Y(e,e.length-1);if(Number.isNaN(r)||r<=i[t])return i[n];if(r>=o[t])return o[n];let l=0,s=e.length-1;for(;s-l>1;){const p=l+s>>1;Y(e,p)[t]<=r?l=p:s=p}const d=Y(e,l),f=Y(e,s);return d[n]+(f[n]-d[n])*(r-d[t])/(f[t]-d[t])},vt=610,Te=89,ke=.5,wt=({editor:e,preview:t,previewBlocks:n,editorSpans:r,requestFrame:i,cancelFrame:o,now:l})=>{let s="editor",d=0,f=null,p=null,k=!1,c=null,E=null;const u={editor:0,preview:0},m={editor:null,preview:null};let v=null,y=()=>{};const g=a=>{f!==null&&a!==f||(s=a,d=l()+vt)},L=(a,A)=>{a!==s&&f===null&&l()>=d&&!O(a,A)&&(s=a),B()},O=(a,A)=>{const R=m[a];return l()<u[a]||R!==null&&Math.abs(A.position()-R)<ke},I=e.onScroll(()=>L("editor",e)),D=e.onIntent(()=>g("editor")),M=()=>{const a=t();return a!==v&&(y(),v=a,y=a===null?()=>{}:F(a)),a},F=a=>{const A=a.onScroll(()=>L("preview",a)),R=a.onIntent(()=>g("preview"));return()=>{A(),R()}},B=()=>{!k&&p===null&&(p=i(j))},j=()=>{p=null;const a=M();a!==null&&(c??=n(),E??=gt(ht(c,r(c)),{editorMax:e.max(),previewMax:a.max(),editorViewport:e.viewport(),previewViewport:a.viewport()}),s==="editor"?H(a,"preview",E.toPreview(e.position())):H(e,"editor",E.toEditor(a.position())))},H=(a,A,R)=>{if(Math.abs(a.position()-R)<ke){m[A]=a.position();return}u[A]=l()+Te,m[A]=a.scrollTo(R)};return B(),{editorChanged:a=>{E=null,a&&g("editor"),B()},previewChanged:()=>{c=null,E=null,u.preview=l()+Te,B()},showAlone:a=>{f=a,!(a===null||a===s)&&(s=a,d=0,B())},dispose:()=>{k=!0,p!==null&&o(p),p=null,I(),D(),y()}}},Le=Object.freeze(["wheel","pointerdown","keydown","focusin"]),Pe=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const n of Le)e.addEventListener(n,t,{capture:!0,passive:!0});return()=>{for(const n of Le)e.removeEventListener(n,t,{capture:!0})}}}),ne="[data-aqmd-scroll-container]",Et="[data-aqmd-content]",bt=`[${ue.SOURCE_LINES_ATTRIBUTE}]`,xt=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Ne=(e,t)=>{const n=S.loadedOf(e.peek(t));return n!==null&&n.document.kind==="markdown"?{htmlContent:n.document.htmlContent,headings:n.document.headings}:null},St=(e,t,n,r,i)=>{if(n===void 0)return null;let o;try{o=mt(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:n,sanitize:o,marksOf:dt,seed:Ne(r,i)?.htmlContent??null}},yt=e=>{const t=[];let n=null;for(const r of e.querySelectorAll(bt)){const i=ue.parseSourceLines(r.getAttribute(ue.SOURCE_LINES_ATTRIBUTE));if(i===null||r.getClientRects().length===0)continue;n??=e.scrollTop-S.visibleTopOf(e,r);const{top:o,bottom:l}=r.getBoundingClientRect();t.push({first:i.first,last:i.last,top:n+o,bottom:n+l})}return t},Tt=({path:e,readDraft:t,viewer:n,tables:r,concealed:i,onEditAt:o,onLayout:l,handleRef:s})=>{const{config:d,data:f,documents:p,draftConverter:k,labels:c}=S.useExplorer(),[E,u]=h.useState(()=>({parsed:Ne(p,e),source:null,failure:null,busy:!0,tier:k===void 0?"server":"instant"})),m=h.useRef(null),v=h.useRef(null),y=h.useRef(E);h.useLayoutEffect(()=>{y.current=E});const g=h.useEffectEvent(()=>t());h.useEffect(()=>{const a=St(d.iframeHosts,d.dataPath,k,p,e),A=g(),R=ft({path:e,instant:a,preview:f.preview,initial:y.current,onView:w=>h.startTransition(()=>u(w))});return v.current=R,R.update(A),()=>{R.dispose(),v.current=null}},[d,f,p,k,e]);const L=h.useEffectEvent(()=>l());h.useLayoutEffect(()=>{E.parsed!==null&&L()},[E.parsed]);const O=E.parsed!==null;h.useLayoutEffect(()=>{const a=O?m.current?.querySelector(ne):null;if(!(a instanceof HTMLElement))return;a.tabIndex=0;const A=new ResizeObserver(()=>L());A.observe(a);const R=a.querySelector(Et);return R!==null&&A.observe(R),()=>A.disconnect()},[O]);const I=h.useRef(null);h.useImperativeHandle(s,()=>({draft:a=>{v.current?.update(a)},scrollPort:()=>{const a=m.current?.querySelector(ne);return a instanceof HTMLElement?(I.current?.scroller!==a&&(I.current={scroller:a,port:Pe(a)}),I.current.port):null},blocks:()=>{const a=m.current?.querySelector(ne);return a instanceof HTMLElement?yt(a):[]},focus:()=>{const a=m.current?.querySelector(ne);a instanceof HTMLElement&&a.focus({preventScroll:!0})},anchor:a=>{const A=m.current,R=A?.querySelector(ne);return A===null||!(R instanceof HTMLElement)?null:S.anchorOfView(A,a(R))},place:({line:a,clientTop:A},R)=>{const w=m.current,T=w===null?null:S.blockAtLine(w,a);T!==null&&(R(T).scrollTop+=S.lineTopIn(T,a)-A)}}),[]);const D=a=>{const A=m.current,{target:R}=a;if(o===void 0||A===null||!(R instanceof Element)||!S.isEditingDoubleClick(R))return;const w=S.anchorOfDoubleClick(R,A,A.ownerDocument.getSelection());w!==null&&o(w)},M=E.source===null?null:E.source.revision,F=h.useMemo(()=>M===null?void 0:{write:a=>r.write(M,a),read:a=>r.read(M,a),undo:r.undo,redo:r.redo,subscribe:r.subscribe},[r,M]),B=h.useMemo(()=>({...n.labels,spreadsheetReadOnly:c.previewTablePending}),[n.labels,c.previewTablePending]),j=h.useMemo(()=>({...n,labels:F===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0,scrollBarGutter:void 0,spreadsheetEditor:F}),[n,B,F]),H=h.useMemo(()=>E.parsed===null?null:q.jsx("div",{className:"aqmx-document-viewer",children:q.jsx(je.MarkdownViewer,{...j,parseResult:E.parsed,content:null})}),[j,E.parsed]);return q.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":c.previewRegion,"aria-busy":E.busy,inert:i!==null,hidden:i==="removed","data-aqmx-preview-tier":E.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:o===void 0?void 0:D,children:[E.failure===null?null:q.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:c.previewFailed(S.failureTitleOf(c,E.failure.reason))}),H??(E.failure===null?q.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:xt.map(a=>q.jsx("span",{},a))}):null),E.busy?q.jsx("p",{className:"aqmx-sr-only",children:c.previewUpdating}):null]})},Ae="data-aqmx-edit-split",ae="--aqmx-edit-share",Ie="--aqmx-edit-gutter",kt="data-aqmx-edit-split-probe",Lt="aqmx-edit-split",At="aqmx-edit-editor",It="aqmx-edit-preview",Oe={value:X.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},Re={value:X.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},Ce=e=>{if(e.length!==2)return null;const[t=0,n=0]=e,r=t+n;return r>0?t/r*100:null},ie=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},Ot=(e,t,n)=>{const[r,i]=h.useState(null);return h.useLayoutEffect(()=>{const o=e.current,l=t.current;if(o===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const s={frame:o.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},d=()=>{s.frame>0&&s.measure>0&&i(X.editSplitOrientation(s.frame,s.measure,n))};d();const f=new ResizeObserver(p=>{for(const k of p){const[c]=k.borderBoxSize;c!==void 0&&(k.target===o&&(s.frame=c.inlineSize),k.target===l&&(s.measure=c.inlineSize))}d()});return f.observe(o),f.observe(l),()=>f.disconnect()},[e,t,n]),r},Rt=({editorId:e})=>{const{edits:t,labels:n}=S.useExplorer(),r=h.useRef(null),i=h.useRef(null),o=ve.useCoarsePointer()?X.COARSE_TARGET_PIXELS:X.FINE_TARGET_PIXELS,l=Ot(r,i,o),[s]=h.useState(()=>t.editorShare());h.useLayoutEffect(()=>{const p=ie(r);return p.style.setProperty(Ie,`${String(o)}px`),()=>{p.style.removeProperty(Ie)}},[o]),h.useLayoutEffect(()=>{const p=ie(r);return p.style.setProperty(ae,`${String(s)}%`),()=>{p.style.removeProperty(ae)}},[s]),h.useLayoutEffect(()=>{if(l===null)return;const p=ie(r);return p.setAttribute(Ae,l),()=>p.removeAttribute(Ae)},[l]);const d=ve.useSplitPersistence(h.useCallback(p=>{const k=Ce(p);k!==null&&t.setEditorShare(k)},[t])),f=h.useCallback((p,k)=>{const c=Ce(p);c!==null&&ie(r).style.setProperty(ae,`${String(c)}%`),d.layoutChanged(p,k)},[d]);return q.jsxs("div",{ref:r,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[q.jsx("span",{ref:i,className:"aqmx-edit-split-probe","aria-hidden":"true",[kt]:""}),l===null?null:q.jsxs(se.PanelGroup,{id:Lt,direction:l==="beside"?"horizontal":"vertical",onLayout:f,className:"aqmx-edit-split-group",children:[q.jsx(se.Panel,{id:At,defaultSize:{value:s,unit:"percentage"},minSize:Oe,maxSize:Re,contentOverflow:"hidden"}),q.jsx(se.PanelResizeHandle,{thickness:o,indicator:{visible:!0,thickness:X.SPLIT_HANDLE_PIXELS.gripThickness,length:X.SPLIT_HANDLE_PIXELS.gripLength,barThickness:X.SPLIT_HANDLE_PIXELS.barThickness,barLength:X.SPLIT_HANDLE_PIXELS.barLength},title:n.editViewSplitResize,"aria-label":n.editViewSplitResize,"aria-controls":e,onDragging:d.draggingChanged,className:"aqmx-split-handle aqmx-edit-split-handle"}),q.jsx(se.Panel,{id:It,defaultSize:{value:100-s,unit:"percentage"},minSize:Oe,maxSize:Re,contentOverflow:"hidden"})]})]})},Ct=512,qt=()=>{const e=[];let t=0,n=null;const r=i=>{if(n===null||!Number.isInteger(i)||i<t)return null;if(i===t+e.length)return n;const o=e[i-t];return o===void 0?null:o.before};return{revision:()=>t+e.length,mount:i=>{if(n!==null&&(n===i||n.eq(i))){n=i;return}const o=t+e.length;e.length=0,t=n===null?o:o+1,n=i},record:(i,o)=>{if(n===null)throw new Error("[markdown-explorer] a change of the editor's text was recorded before an editor mounted");e.push({before:n,changes:i}),n=o,e.length>Ct&&(e.shift(),t+=1)},lineOf:(i,o)=>{const l=r(i);if(l===null||n===null||!Number.isInteger(o)||o<1||o>l.lines)return null;let s=l.line(o).from;for(const d of e.slice(i-t)){const f=d.changes.mapPos(s,1,$.MapMode.TrackAfter);if(f===null)return null;s=f}return n.lineAt(s).number}}},De=144,Mt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:n}=e;return"state"in e&&typeof t=="number"&&typeof n=="number"},_t=e=>{e.stopPropagation()},Pt=e=>{const{path:t,name:n,session:r}=e,{edits:i,labels:o,announcer:l}=S.useExplorer(),{phase:s}=r,d=h.useCallback(()=>i.retry(t),[i,t]);switch(h.useEffect(()=>{s.kind==="failed"&&l.announce(o.documentFailed(n,S.failureTitleOf(o,s.failure.reason)))},[s,l,o,n]),s.kind){case"opening":return q.jsx(S.ContentSkeleton,{label:o.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(S.EditGrantNotice,{href:s.href,onRetry:d,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(S.FailureView,{failure:s.failure,alert:!1,onRetry:d,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Nt,{...e})}},Nt=({path:e,name:t,session:n,layout:r,viewer:i,region:o,paneScroll:l})=>{const{edits:s,labels:d}=S.useExplorer(),f=h.useRef(null),p=h.useId(),k=h.useRef(null),[c]=h.useState(()=>new Set),[E]=h.useState(qt),u=h.useRef(null),m=h.useRef(null),v=r==="fill",y=S.useSideBySide(),g=S.editViewOf(n,y,v),L=g!=="editor"||n.previewPrepared,O=L&&v,I=h.useRef({layout:r,region:o,paneScroll:l});h.useLayoutEffect(()=>{I.current={layout:r,region:o,paneScroll:l}});const D=h.useRef(n.generation);h.useLayoutEffect(()=>{D.current=n.generation});const M=h.useRef({view:g,previewMounted:L});h.useLayoutEffect(()=>{M.current={view:g,previewMounted:L}});const F=h.useRef(null),B=h.useRef(null),j=h.useRef(!1),H=h.useMemo(()=>({editor:d.editorLabel(t),useOurs:d.conflictUseOurs,useTheirs:d.conflictUseTheirs,keepBoth:d.conflictKeepBoth}),[d,t]),a=h.useCallback(b=>{const{region:x,paneScroll:_}=I.current,z=x();return z===null?b:_.scrollerOf(z,b)},[]);h.useLayoutEffect(()=>{const b=f.current,x=s.draft(e);if(b===null||x===null)return;const _=s.editorState.get(e),z=Mt(_)&&_.generation===D.current?_:null;let W=null,Q=null;const le=()=>{W!==null&&clearTimeout(W),W=null,Q!==null&&s.setDraft(e,Q.text())},G=tt({parent:b,scroll:{scrollerOf:N=>{const{layout:Z,region:Be,paneScroll:He}=I.current,he=Be();return Z==="fill"||he===null?N:He.scrollerOf(he,N)},reveal:N=>I.current.paneScroll.reveal(N)},text:x,saved:z===null?void 0:z.state,labels:H,revisions:E,onGeometry:N=>m.current?.editorChanged(N),onChange:N=>{if(W??=setTimeout(le,De),!N)for(const Z of[...c])Z();M.current.previewMounted&&Q!==null&&u.current?.draft({text:Q.text(),revision:E.revision()})},onSave:()=>{s.save(e)}});Q=G,k.current=G;const fe=()=>{const N=G.topLine();return{line:N.line,clientTop:N.clientTop}},me=()=>u.current?.anchor(a)??null,Ve=s.bindEditor(e,{flush:le,adopt:N=>G.replaceText(N),returnPoint:()=>{const N=M.current.view==="preview"&&I.current.layout==="content"?me():null;return N===null?fe():{line:N.lines.first,clientTop:N.clientTop}},nextConflict:()=>M.current.view!=="preview"?G.nextConflict():G.conflicts().length===0?!1:(j.current=!0,s.setView(e,"editor"),!0),beforeView:N=>{if(I.current.layout==="fill")return;if(N==="preview"){F.current={to:"preview",point:fe()};return}const Z=me();F.current=Z===null?null:{to:"editor",anchor:Z}}});return z!==null&&G.showLine(z.topLine),()=>{le(),s.editorState.set(e,{state:G.save(),generation:D.current,topLine:G.topLine().line}),Ve(),G.destroy(),Q=null,k.current=null}},[s,e,H,a,c,E]);const{request:A}=n;h.useLayoutEffect(()=>{const b=k.current,x=s.draft(e);b===null||x===null||A===null||(A.anchor!==null&&b.reveal(S.positionInSource(x,A.anchor),A.anchor.clientTop),b.focus(),s.consumeRequest(e))},[s,e,A,H]),h.useLayoutEffect(()=>{g!=="editor"&&!n.previewPrepared&&s.preparePreview(e)},[s,e,g,n.previewPrepared]),h.useLayoutEffect(()=>{const b=F.current,x=B.current,_=j.current;F.current=null,B.current=null,j.current=!1;const z=k.current;if(b?.to==="preview")u.current?.place(b.point,a);else if(b?.to==="editor"&&z!==null){const W=s.draft(e);W!==null&&z.reveal(S.positionInSource(W,b.anchor),b.anchor.clientTop)}_?z?.nextConflict():x==="editor"?z?.focus():x==="preview"&&u.current?.focus()},[s,e,g,a]);const R=h.useMemo(()=>{const b=()=>{const x=k.current;if(x===null)throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");return x};return{write:(x,{fenceLine:_,expected:z,text:W})=>b().replaceBody(_,z,W,x),read:(x,_)=>b().readBody(_,x),undo:()=>b().undo(),redo:()=>b().redo(),subscribe:x=>(c.add(x),()=>{c.delete(x)})}},[c]),w=h.useCallback(()=>{const b=k.current;if(b===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return{text:b.text(),revision:E.revision()}},[E]);h.useLayoutEffect(()=>{const b=k.current;if(!O||b===null)return;const x=wt({editor:Pe(b.scrollElement),preview:()=>u.current?.scrollPort()??null,previewBlocks:()=>u.current?.blocks()??[],editorSpans:_=>b.lineSpans(_),requestFrame:_=>requestAnimationFrame(_),cancelFrame:_=>cancelAnimationFrame(_),now:()=>performance.now()});return x.showAlone(S.paneShownAlone(M.current.view)),m.current=x,()=>{x.dispose(),m.current=null}},[O,s,e,H]),h.useLayoutEffect(()=>{m.current?.showAlone(S.paneShownAlone(g))},[g]);const T=h.useCallback(()=>m.current?.previewChanged(),[]),C=h.useCallback(b=>s.start(e,b),[s,e]),U=b=>{if(S.isInFullscreenBlock(b.target))return;if(b.key==="Escape"){S.consumeKey(b);return}if(!S.isEditViewShortcut(b.nativeEvent,S.isApplePlatform(navigator.platform)))return;S.consumeKey(b);const x=S.toggledEditView(g);B.current=x,S.chooseEditView(s,e,x,v)};return q.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":r,"data-aqmx-edit-view":g,"data-testid":"markdown-explorer-edit",onKeyDown:U,onDoubleClick:_t,children:[q.jsx("div",{ref:f,id:p,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:g==="preview",hidden:g==="preview"&&!v,...S.ALLOW_KEY_REPEAT}),g==="split"?q.jsx(Rt,{editorId:p}):null,L?q.jsx(Tt,{path:e,readDraft:w,viewer:i,tables:R,concealed:g!=="editor"?null:v?"overlay":"removed",onEditAt:g==="preview"?C:void 0,onLayout:T,handleRef:u}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=De;exports.default=Pt;