@aiquants/markdown-explorer 0.21.0 → 0.23.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.
- package/CHANGELOG.md +80 -0
- package/README.md +27 -16
- package/dist/EditSurface-Bk4tdJ99.cjs +6 -0
- package/dist/EditSurface-Dhvw9IDD.js +975 -0
- package/dist/{ExplorerSplit-CdqEKz-I.cjs → ExplorerSplit-BAFiXU-V.cjs} +1 -1
- package/dist/{ExplorerSplit-3WMRDA7G.js → ExplorerSplit-Q5VqUBDE.js} +3 -3
- package/dist/{MultiLayout-BEg1X8Jx.cjs → MultiLayout-Bq_TS3ez.cjs} +1 -1
- package/dist/{MultiLayout-Gf1xT-Le.js → MultiLayout-DlATT7km.js} +22 -22
- package/dist/{NativeScrollBar-idIQsvCv.cjs → NativeScrollBar-A6-qEpz7.cjs} +1 -1
- package/dist/{NativeScrollBar-0cpp2OIu.js → NativeScrollBar-TsIcS3JZ.js} +1 -1
- package/dist/{TreeLayout-DJY_WqzP.cjs → TreeLayout-l-r2pPao.cjs} +1 -1
- package/dist/{TreeLayout-DzZCgMTt.js → TreeLayout-zrSo4MNZ.js} +3 -3
- package/dist/core/contracts.d.cts +7 -0
- package/dist/core/contracts.d.ts +7 -0
- package/dist/core/labels.d.cts +21 -27
- package/dist/core/labels.d.ts +21 -27
- package/dist/{dataRoute-CObbjNxG.js → dataRoute-Diu_7gle.js} +84 -83
- package/dist/dataRoute-vXGZMVB-.cjs +1 -0
- package/dist/index-BNFl3BsO.cjs +13 -0
- package/dist/{index-CJgHGeZs.js → index-Jz6zeO4O.js} +1500 -1529
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +9 -9
- package/dist/{location-B-m9scLf.js → location-8Ho8ZNv_.js} +1 -1
- package/dist/{location-BVEN_Ihk.cjs → location-DN0AI4ir.cjs} +1 -1
- package/dist/{merge-BOcofJN5.js → merge-BzMpSaxx.js} +1 -1
- package/dist/{merge-BVk6pvO_.cjs → merge-DlPkU2Jc.cjs} +1 -1
- package/dist/{sanitizePolicy-BWQtWhsL.js → sanitizePolicy-BvhYIqVO.js} +1 -1
- package/dist/{sanitizePolicy-gEXeavb-.cjs → sanitizePolicy-Du3lFZd-.cjs} +1 -1
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +1 -1
- package/dist/server/ports.d.cts +2 -1
- package/dist/server/ports.d.ts +2 -1
- package/dist/server.cjs +1 -1
- package/dist/server.js +524 -521
- package/dist/{useSplitPersistence-Ba-v64n-.cjs → useSplitPersistence-CR4Oxtaa.cjs} +1 -1
- package/dist/{useSplitPersistence-Cc4tDxB4.js → useSplitPersistence-HfAb8Kzh.js} +1 -1
- package/docs/behavior/dom-hooks.md +3 -3
- package/docs/behavior/layout.md +11 -5
- package/docs/behavior/localization.md +9 -7
- package/docs/behavior/security.md +1 -1
- package/docs/behavior/url-contract.md +2 -2
- package/package.json +5 -5
- package/dist/EditSurface-Bwl4S1vQ.cjs +0 -7
- package/dist/EditSurface-rKoy_ndP.js +0 -880
- package/dist/dataRoute-BONacTPi.cjs +0 -1
- package/dist/index-bMaSoQTe.cjs +0 -13
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,85 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.23.0 (2026-10-27) — An SVG image shows its SVG a press away, as a document and inside one
|
|
4
|
+
|
|
5
|
+
### Breaking
|
|
6
|
+
|
|
7
|
+
- **An image document names its type: `imageType` is `"raster"` or `"svg"`.** The host's `document` port answers it
|
|
8
|
+
with every image (`{ kind: "image", name, imageType, version }`), from what its storage knows of the file's type —
|
|
9
|
+
`"svg"` for an SVG file, `"raster"` for every other image format —, and the browser's image documents carry it. An
|
|
10
|
+
image answer without one of the two breaks the contract: it is logged and the reader sees `failed`.
|
|
11
|
+
`createFileSystemSource` answers `"svg"` for the `.svg` extension (served as `image/svg+xml`) and `"raster"` for the
|
|
12
|
+
other image extensions. `ExplorerImageType` is exported.
|
|
13
|
+
- **The peer floor is `@aiquants/markdown` ^11.1.0**, whose viewer gives a storage SVG image that stands alone in a
|
|
14
|
+
paragraph its own Source toggle (`imageSource`), shows a notice in place of a block that cannot render instead of
|
|
15
|
+
taking the document down, and renders a fence in a language it does not know as plain text.
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **An SVG image document offers Source**, like a Markdown document: the document bar's toggle (its tooltip
|
|
20
|
+
`showSvgMarkup`) shows the image's SVG as written, read through the data route's `text` operation and shown like a
|
|
21
|
+
text file, and the image again on a second press. The choice is the same `markup` of the URL, so a reload, a shared
|
|
22
|
+
link and Back and Forward keep it, and `data-aqmx-document-view` reports `rendered` or `markup` for the image. A
|
|
23
|
+
raster image offers no toggle, and a `markup` naming one is ignored.
|
|
24
|
+
- **An SVG image inside a rendered document has its own Source toggle.** The explorer hands the viewer a reader of
|
|
25
|
+
image sources that reads the image's path through the same `text` operation, so the toolbar above a storage SVG image
|
|
26
|
+
that stands alone in a paragraph shows its SVG in its place — in the document, a panel and the editor's preview — with
|
|
27
|
+
the same deny rules and admission as the image itself. A double-click inside the shown SVG selects its text and does
|
|
28
|
+
not open the editor.
|
|
29
|
+
- Labels: `showSvgMarkup`, the SVG image block's `viewerSvgImageToolbar`, `viewerSvgImageSource`,
|
|
30
|
+
`viewerSvgImageSourceRegion` (a template with `{name}`), `viewerSvgImageLoading`, `viewerSvgImageFailed`,
|
|
31
|
+
`viewerSvgImageRetry`, `viewerSvgImageTruncated`, `viewerSvgImageCopy`, `viewerSvgImageCopied` and
|
|
32
|
+
`viewerSvgImageCopyFailed`, and `viewerBlockFailed`, the notice in place of a block that cannot render.
|
|
33
|
+
|
|
34
|
+
## 0.22.0 (2026-10-27) — Tables written back exactly as the converter reads their lines, from the line the preview rendered them on
|
|
35
|
+
|
|
36
|
+
### Breaking
|
|
37
|
+
|
|
38
|
+
- **The peer floor is `@aiquants/markdown` ^11.0.1.** markdown 11's editor contract answers what came of each write
|
|
39
|
+
(`written`, `changed`, `closesFence`, `unwritable`) and reads a block's body back (`read`), which the explorer's
|
|
40
|
+
editor implements; its React-free `@aiquants/markdown/code-blocks` holds the converter's reading of a fenced block's
|
|
41
|
+
lines and the table labels with their placeholders. 11.0.1 keeps the viewer's toolbar buttons' focus rings, which
|
|
42
|
+
11.0.0 cleared.
|
|
43
|
+
- **The `viewerSpreadsheet…` labels are derived from `@aiquants/markdown`.** Their keys, built-in texts and placeholders
|
|
44
|
+
are the table block's own (each label of `SPREADSHEET_BLOCK_LABEL_CATALOGS` under `viewerSpreadsheet…`), so the keys
|
|
45
|
+
follow markdown 11: `viewerSpreadsheetResetZoom` takes `{percent}`, `viewerSpreadsheetOptionsError` takes `{word}`,
|
|
46
|
+
`{frozenMax}` and `{heightMax}`, `viewerSpreadsheetCopyFailed` and `viewerSpreadsheetLoadFailed` take none, and
|
|
47
|
+
`viewerSpreadsheetZoomed`, `viewerSpreadsheetTrackSize`, `viewerSpreadsheetDecreaseColumnWidth`,
|
|
48
|
+
`viewerSpreadsheetIncreaseColumnWidth`, `viewerSpreadsheetAutoFitColumnWidth`, `viewerSpreadsheetDecreaseRowHeight`,
|
|
49
|
+
`viewerSpreadsheetIncreaseRowHeight`, `viewerSpreadsheetColumnResized`, `viewerSpreadsheetRowResized`,
|
|
50
|
+
`viewerSpreadsheetReadOnlyCellAnnouncement`, `viewerSpreadsheetUnwritable` and `viewerSpreadsheetTooLarge` are new.
|
|
51
|
+
The viewer is given only the table labels a host replaced, so the others keep the block's text and language.
|
|
52
|
+
- **The peer floor is `@aiquants/spreadsheet` ^0.16.0**, markdown 11's own: its grid takes the block's header rows,
|
|
53
|
+
read-only state and name, and runs the size commands the table's toolbar offers.
|
|
54
|
+
|
|
55
|
+
### Changed
|
|
56
|
+
|
|
57
|
+
- **A table's write-back reads the block's lines as the converter does and rewrites only the lines that change.** The
|
|
58
|
+
editor reads the block through `@aiquants/markdown/code-blocks`: a hand-written block — `>` without its space, a tab
|
|
59
|
+
for a list item's indentation, lines indented less than an indented fence — writes back, each new line taking the
|
|
60
|
+
head of the block's own lines. A write keeps the cursor and the untouched lines where they are, one undo step of its
|
|
61
|
+
own.
|
|
62
|
+
- **A write is refused only for a reason the reader can act on.** A line that would close the block's fence (the same
|
|
63
|
+
character, at least as long, up to three columns after the containers, a tab counted to the next tab stop) is refused
|
|
64
|
+
with its own notice, instead of every line starting with ``` or ~~~ after three spaces; a block whose lines the editor
|
|
65
|
+
cannot read as the converter does (a tab split at a container's edge or right after `>`, a language with an escape or
|
|
66
|
+
a reference) makes the table read-only with a notice that says why, instead of refusing each edit as a conflict.
|
|
67
|
+
- **A table of the document's own rendering in the preview is read-only until the preview renders the draft.** The
|
|
68
|
+
document's own rendering carries no version, so its lines may be those of a text other than the one the session read
|
|
69
|
+
(the file changed after it was drawn) and a write could land on another block that reads the same; its tables say
|
|
70
|
+
(`previewTablePending`, a new label) that they become editable once the preview shows the draft.
|
|
71
|
+
|
|
72
|
+
### Fixed
|
|
73
|
+
|
|
74
|
+
- **An edit of a table below another table's fresh write-back no longer fails.** The editor finds a table's block from
|
|
75
|
+
the line the preview rendered it on, mapped through every change the text took since that draft on either side of
|
|
76
|
+
the block (the editing surface records each change, across a remounted editor), so another table's write-back above
|
|
77
|
+
it (or typing above it) no longer refuses its next edit until the preview is drawn again, and the table reads its
|
|
78
|
+
block back after its own write-back.
|
|
79
|
+
- **The first edit of a table near the end of a long document is never refused for want of time.** The editor parses
|
|
80
|
+
as far as the block without a time limit, and parses ahead while the reader is idle, so a table edit no longer fails
|
|
81
|
+
as a conflict when the parse took more than 500 ms.
|
|
82
|
+
|
|
3
83
|
## 0.21.0 (2026-10-26) — Tables inside list items and quotes write back from the preview, and a table follows every change of the editor's text
|
|
4
84
|
|
|
5
85
|
### Breaking
|
package/README.md
CHANGED
|
@@ -18,11 +18,14 @@ document. The document stays on screen while it reloads and is replaced in place
|
|
|
18
18
|
reloaded document is announced, and a failed reload keeps the document under a notice naming the failure, which is
|
|
19
19
|
announced too and stays until a newer copy of the document replaces or confirms it, the reader moves to another
|
|
20
20
|
document, or the next refresh starts.
|
|
21
|
-
Beside it, a Markdown document
|
|
22
|
-
(its file read through the data route's `text` operation, shown like a text
|
|
23
|
-
as written). The choice is part of the URL
|
|
21
|
+
Beside it, a Markdown document and an SVG image offer **Source**: a toggle that shows the document as written instead
|
|
22
|
+
of rendered (its file — an SVG image's own SVG — read through the data route's `text` operation, shown like a text
|
|
23
|
+
file, whose header copies the text exactly as written); a raster image offers none. The choice is part of the URL
|
|
24
24
|
(`markup`), so a reload, a shared link and Back and Forward show the document the same way, and the switches between
|
|
25
25
|
the tree and multi views carry it; another document opens rendered.
|
|
26
|
+
Inside a rendered document, a storage SVG image that stands alone in a paragraph gets its own Source toggle in a
|
|
27
|
+
toolbar above it, which shows the image's SVG in its place through the same operation, and the image again on a second
|
|
28
|
+
press.
|
|
26
29
|
With the server's `edit` ports, a Markdown document also offers **Edit**: the reader edits its Markdown in place
|
|
27
30
|
(CodeMirror, loaded on demand), from where they were reading or from the word they double-clicked, saves over the
|
|
28
31
|
version the draft started from (changes saved elsewhere are merged line by line, and conflicts are resolved in the
|
|
@@ -39,10 +42,13 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
|
|
|
39
42
|
|
|
40
43
|
- React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
|
|
41
44
|
- Node.js 22.22 or later (the floor React Router 8 declares). The package ships ES modules and CommonJS; the CommonJS entries load the ESM-only `react-router` through `require(esm)`.
|
|
42
|
-
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^
|
|
45
|
+
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^11.1.0 (document rendering; the Source toggle of a storage SVG image that stands alone in a paragraph, read through `imageSource`, a notice in place of a block that cannot render and plain text for a fence in a language it does not know; its components' stylesheet without utilities,
|
|
46
|
+
its controls' 44 px targets under every pointer, ```spreadsheets tables — inside list items and quotes too — and their write-back through an editor that answers what came of each write (written, changed, a line that would close the fence, unwritable), reads a block's body back and tells them of its other changes,
|
|
47
|
+
the React-free `@aiquants/markdown/code-blocks` that names the `data-code-meta` the sanitizer keeps on `code`, holds the converter's reading of a fenced block's lines and the table labels with their placeholders,
|
|
43
48
|
its Mermaid labels and drawings that finish inside the document when a diagram's text changes or it unmounts mid-drawing, its math diagnostics, gantt sizing, embeds, link cards and their sizes, the React-free `@aiquants/markdown/embeds` the sanitizer worker loads and `@aiquants/markdown/source-lines` the editor and the sanitizer read, and the Node-only link-card handler of `@aiquants/markdown/server`, which needs Node.js 22.13 or later — below the explorer's own floor),
|
|
44
49
|
`@aiquants/directory-tree` ^5.0.1 (rows that take paint and text styles only and have no vertical padding, a `removeRootIndent` shift that keeps the root's icon whole, and reveals of rows under the scroll bar's buttons),
|
|
45
|
-
`@aiquants/drag-drop-panels` ^0.12.0 (the panel headers' move menu, named by the explorer's `panelMove`, their 44 px buttons under every pointer and the header arrangement the behavior docs follow), `@aiquants/resize-panels` ^2.2.0 (the source of each layout change, by which the tree pane's width is saved), `@aiquants/spreadsheet` ^0.
|
|
50
|
+
`@aiquants/drag-drop-panels` ^0.12.0 (the panel headers' move menu, named by the explorer's `panelMove`, their 44 px buttons under every pointer and the header arrangement the behavior docs follow), `@aiquants/resize-panels` ^2.2.0 (the source of each layout change, by which the tree pane's width is saved), `@aiquants/spreadsheet` ^0.16.0 (the grid of those tables — one `role="grid"` with header rows,
|
|
51
|
+
read-only where it cannot write and named by its block — which markdown loads only for a document that holds one) and `@aiquants/virtualscroll` ^3.22.1 (44 px scroll-to-edge pills and tap-scroll circles, the pills' text at the body step).
|
|
46
52
|
The client depends on these floors, while a package manager may only warn about an older peer.
|
|
47
53
|
- A Markdown parser of your choice on the server that produces HTML and its headings (the explorer sanitizes the HTML before it is sent).
|
|
48
54
|
- Browsers: the multi view's panel-limit notice and the panel headers' move menu use the Popover API (Chrome and Edge 114, Firefox 125, Safari 17 and later). In browsers without it (for example iOS 16), the notice is drawn in place at the stage's corner instead of in the top layer (while the sheet is open it spans the sheet's header, as in every browser), and the move menu does not open: Alt + Shift + an arrow moves a panel there.
|
|
@@ -387,16 +393,17 @@ Notices are shown in your own words, as given; a malformed notice list is logged
|
|
|
387
393
|
type ExplorerDocument =
|
|
388
394
|
| { kind: "markdown"; name: string; htmlContent: string; headings: { text: string; depth: number; id: string }[]; edit: ExplorerDocumentEdit | null }
|
|
389
395
|
| { kind: "text"; name: string; text: string; truncated: boolean; url: string }
|
|
390
|
-
| { kind: "image"; name: string; url: string }
|
|
396
|
+
| { kind: "image"; name: string; url: string; imageType: "raster" | "svg" }
|
|
391
397
|
| { kind: "media"; name: string; url: string; mediaType: "video" | "audio" | "pdf" }
|
|
392
398
|
| { kind: "file"; name: string; url: string }
|
|
393
399
|
| ExplorerFailureDocument // { kind: "failure"; failure: { reason: ExplorerFailureReason; code?: string } }
|
|
394
400
|
```
|
|
395
401
|
|
|
396
402
|
This is the document the browser receives. Your `document` port answers `ExplorerHostDocument` (exported from the server entry), which is the same except that an image, media, text or file document carries its file's `version` instead of a `url`:
|
|
397
|
-
`{ kind: "image"; name; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; version }` and `{ kind: "file"; name; version }`.
|
|
403
|
+
`{ kind: "image"; name; imageType; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; version }` and `{ kind: "file"; name; version }`.
|
|
398
404
|
`version` is an opaque validator of 1 to 256 visible ASCII characters other than `"`, the same one your `asset` port reports for the file; the explorer writes the document's `url` as its own asset URL with that version (`<dataPath>/asset?path=…&v=<version>`, see [URL contract](docs/behavior/url-contract.md#asset-urls)).
|
|
399
405
|
An answer of those kinds that carries a `url` key, or lacks a valid `version`, breaks the contract: it is logged and the reader sees `failed`.
|
|
406
|
+
An image document names its type in `imageType` (`ExplorerImageType`): `"svg"` for an SVG file, whose SVG the Source toggle shows as written, and `"raster"` for every other image format. Answer it from what your storage knows of the file's type, the type your `asset` port serves it with; the explorer never guesses it from the name, and an image answer without one of the two breaks the contract the same way.
|
|
400
407
|
`failureDocument(reason, code?)` returns an `ExplorerFailureDocument`, which both unions accept.
|
|
401
408
|
A markdown document says how the reader may edit it in `edit` (`ExplorerDocumentEdit`), which every markdown answer must carry: `null` (no editing), `{ kind: "inline" }` (in the explorer, through the server's `edit` ports; without them the answer breaks the contract), `{ kind: "draft" }` (in the explorer without saving, to try changes in the preview: the ports' `source` and `preview` only, and the same contract) or `{ kind: "external", href }` (the document's own editor, an absolute `https:` URL the bar opens in a new tab).
|
|
402
409
|
Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
|
|
@@ -503,7 +510,7 @@ Names the tree cannot carry — not in NFC, with a colon, ending in a dot or a s
|
|
|
503
510
|
|
|
504
511
|
Any other option key (a misspelt limit, an option this source does not have) throws a `TypeError` naming it when the source is created, instead of being ignored.
|
|
505
512
|
|
|
506
|
-
The source's `document(context, path, readPath)` reads the file `readPath` names and shows it as `path` (its parser receives `path`); every other kind (image, media, text, file) reports the file's version, `<size>-<mtimeNs
|
|
513
|
+
The source's `document(context, path, readPath)` reads the file `readPath` names and shows it as `path` (its parser receives `path`); every other kind (image, media, text, file) reports the file's version, `<size>-<mtimeNs>`, and an image its `imageType`: `"svg"` for the `.svg` extension, the one its `asset` serves as `image/svg+xml`, and `"raster"` for the other image extensions. A file of an unknown extension, and a text file whose preview holds a NUL byte, is a `file` document.
|
|
507
514
|
The source's `ancestors(context, path, readPath)` answers the folders down to the file `readPath` names from its path prefixes (`<prefix>a` and `<prefix>a/b` for `<prefix>a/b/c.md`, `[]` for a file at the top level), which are exactly its tree's row paths, and `null` for any path its walk would not list (outside the prefix, missing, not a regular file, denied, or reached through a symbolic link). A wrapper that turns a folder lazy (as the demo's `withLazyFolder` does) keeps it, because the row paths do not change.
|
|
508
515
|
The source's `asset(context, path, readPath)` serves every regular file the same checks admit: images and media with their type, everything else (Markdown, text and the files of unknown extensions) without one (`""`), so the explorer delivers it as an `application/octet-stream` download.
|
|
509
516
|
It opens the file again without following links, requires the device, inode, size and modification time the checks saw (`not-found` when the path now names another file or the file has changed since) and streams the requested range from that handle (the whole file only as long as the checks saw it), which closes when the stream ends, fails or is cancelled, or the request aborts.
|
|
@@ -572,7 +579,7 @@ and `Cache-Control: private, max-age=60, stale-while-revalidate=600, no-transfor
|
|
|
572
579
|
The body of a 200 or 206 with a `Content-Length` carries exactly that many bytes: the explorer drops the bytes past it and cancels the stream `open` returned, and fails the response when that stream ends short, so a file that changes while it is served never gets a body that disagrees with its length and ETag.
|
|
573
580
|
The URL carries the path in its query, so no name needs an extra escape and the request's own path never ends in `.data`; a document's URL carries `v=<version>` as a cache-buster, which the server never reads (the ETag is always the current version).
|
|
574
581
|
|
|
575
|
-
The data route's `text` operation reads a file through the same port for the Source
|
|
582
|
+
The data route's `text` operation reads a file through the same port for the Source toggles (the document bar's, and that of an SVG image inside a rendered document): `<dataPath>/text?path=<document path>` (GET and HEAD) takes the same authentication, deny rules (a refusal logged once with the operation `text`) and admission as `asset`, then answers JSON like a document request — status 200 with a text document (`name`, `text`, `truncated`, and the file's asset `url` with its version) or a failure document, and the reader's scope header.
|
|
576
583
|
It reads at most `textMaxBytes` bytes (the first ones as a range when `size` is larger, the whole file otherwise, an empty file never, a file of unknown `size` one byte past the limit to learn whether more follows), cancels the stream once enough was read, decodes them as UTF-8 (a leading byte order mark dropped, a multi-byte character the limit cuts left out), and answers `unsupported` for bytes holding NUL and `failed` (logged) for a stream that ends before the `size` the port reported. It sends no refresh mark: the port receives `refresh: false`.
|
|
577
584
|
|
|
578
585
|
### Redirecting to the storage
|
|
@@ -727,9 +734,12 @@ A save writes the draft back with the line endings of the file it opened (`\r\n`
|
|
|
727
734
|
A save that meets changes saved elsewhere merges them line by line: changes on different lines are saved at once; lines both sides changed differently are written between git-style markers with buttons above each conflict (keep my lines, the saved lines, or both), and Next conflict moves the focus to those buttons. A draft with markers left is not saved.
|
|
728
735
|
The preview renders the draft as the document would be: on every keystroke with a `draftConverter`, else once the reader pauses typing (SERVER_PREVIEW_DELAY_MS, 610 ms).
|
|
729
736
|
The view switch shows the editor alone, the two side by side (the preview below the editor on a narrow pane), or the preview alone; Ctrl+E (⌘E on a Mac) switches between the editor and the preview from the editor, the preview or the switch and moves the focus there, and a double-click on a word of the preview shown alone opens the editor at that word.
|
|
730
|
-
```spreadsheets tables (see `@aiquants/markdown`'s README, "Spreadsheets") are read-only in the rendered document and editable in the preview: every table with source lines writes each transaction (a committed cell, a paste, a delete, a fill) back into the editor's text as its block's new body, one undo step of its own
|
|
731
|
-
The editor finds the block
|
|
732
|
-
|
|
737
|
+
```spreadsheets tables (see `@aiquants/markdown`'s README, "Spreadsheets") are read-only in the rendered document and editable in the preview: every table with source lines writes each transaction (a committed cell, a paste, a delete, a fill) back into the editor's text as its block's new body, one undo step of its own that rewrites only the lines that change, so the cursor and the rest of the block stay where they are.
|
|
738
|
+
The editor finds the block from the line the preview rendered it on, mapped through every change the editor's text took since that draft on either side of the block (another table's write-back above it and the table's own below its fence included; the surface records each change of the text, across a remounted editor), in its Markdown parse (to the closing fence, or to the end of the list item, the quote or the text); it parses as far as the block without a time limit, and ahead of time while the reader is idle.
|
|
739
|
+
It reads the block's lines as the converter does (`@aiquants/markdown/code-blocks`), so a table inside a list item or a quote, or behind an indented fence, writes back too, and each new line takes the head of the block's own lines (`>` with or without its space, a tab, the item's indentation, the fence's indentation).
|
|
740
|
+
Until the preview has rendered a draft it shows the document's own rendering, whose tables are read-only: the rendering carries no version, so its lines may be those of a text other than the one the session read (the file changed since it was drawn), and a write could land on another block that reads the same. They become editable when the draft's rendering lands (typing in one before says so, `previewTablePending`).
|
|
741
|
+
A write is refused, and the table says why, when the block no longer reads what the table knows (the table then shows the editor's body) or when a line of the new body would close the block's fence; a block the editor cannot read as the converter does stays read-only and says so (see [Known limitations](#known-limitations)).
|
|
742
|
+
Ctrl+Z and Ctrl+Y in a table undo and redo the editor's history, and Save saves the tables' edits with the rest of the draft. A write-back, an undo or a redo from a table leaves the scroll sync's lead with the preview. Any other change of the editor's text — an undo in the editor right after a table's edit included — makes a table whose write-back is not drawn yet read its block again from the editor and show what the editor holds.
|
|
733
743
|
A double-click in an editable table edits a cell instead of opening the editor (a read-only table of the rendered document opens it there, like any other block), and a table shown full screen keeps its keys: Ctrl+E does not switch the panes behind it, and Escape leaves full screen.
|
|
734
744
|
Side by side, a handle on the gutter between the two resizes them, as the explorer's handle resizes the explorer: drag it, or focus it and press the arrow keys (10 px, 50 px with Shift); either side keeps at least 1/φ³ (≈ 23.6 %) of the surface, and the reader's share (an even split by default) is kept in browser storage under `storageNamespace`, for beside and below alike.
|
|
735
745
|
Switching is instant: the hidden pane stays rendered and in step, so the block at the top of the view stays the same; a panel that is not maximized shows one pane at a time and puts the next one at the same place on screen. Where the bar is narrower than two reading columns (a phone), the switch shows its icons alone, keeping its 44 px targets.
|
|
@@ -802,8 +812,9 @@ export const draftConverter: ExplorerDraftConverter = {
|
|
|
802
812
|
### Localization
|
|
803
813
|
|
|
804
814
|
`locale` selects a built-in catalog (`MARKDOWN_EXPLORER_LABEL_CATALOGS.en` / `.ja`); `labels` overrides single keys.
|
|
805
|
-
The catalogs also name every control of the document viewer (the `viewer…` keys: its toolbar, the table of contents, the style and alignment menus, each Mermaid diagram's controls, every name, notice and announcement of a ```spreadsheets table,
|
|
806
|
-
|
|
815
|
+
The catalogs also name every control of the document viewer (the `viewer…` keys: its toolbar, the table of contents, the style and alignment menus, each Mermaid diagram's controls, every name, notice and announcement of a ```spreadsheets table, and the titles of embedded frames).
|
|
816
|
+
A table's labels are `@aiquants/markdown`'s own: each label of its table block under `viewerSpreadsheet…` (`zoomIn` → `viewerSpreadsheetZoomIn`), with the block's catalog of the UI language as the built-in text and its placeholders; only the ones a host replaces reach the viewer, so a table shows its catalog's text marked with its language, and its grid takes `locale` as its own.
|
|
817
|
+
The multi view's labels name everything its drag-and-drop layout shows (the panel headers' buttons and the custom drag mode's badge, the move announcements and a touch or pen drag's lift and cancel announcements, the bar of hidden panels, the columns' names and the drop placeholders), which therefore follow `locale` too.
|
|
807
818
|
The labels the layout or a table fills with a value are templates with `{name}` placeholders (`MARKDOWN_EXPLORER_LABEL_TEMPLATES`). An unknown key, a blank string, a value of the wrong type, a template placeholder its key does not offer or a regional tag such as `"ja-JP"` throws — see [Localization](docs/behavior/localization.md).
|
|
808
819
|
|
|
809
820
|
## Layout
|
|
@@ -853,7 +864,7 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
|
|
|
853
864
|
- Document paths from URLs are limited to 4096 characters without lone surrogates, control characters or backslashes; deny rules are matched through up to three lenient percent-decoding levels, against each level whole and split on `/` or `\` (a storage may read either as part of a name or as a separator), and after full Unicode case folding.
|
|
854
865
|
- Every source is confined to its boundary: its tree and children list only paths inside it, a children request reaches the host only for a path the named source's boundary admits, and a document or a file's bytes reach the host only when the boundary of at least one source admits its path (see [Source boundaries](#source-boundaries)). A source whose boundary admits everything a reader can read in a store confines nothing in that store.
|
|
855
866
|
- File bytes are served only by the explorer's `asset` operation, after the deny rules and the document admission, inline only for raster images, audio, video and PDF, always with `nosniff` and a `same-origin` resource policy, and with a sandboxing policy except for PDF, under which inline audio and video keep the URL's origin (`allow-same-origin`, no `allow-scripts`) (see [Serving files](#serving-files)).
|
|
856
|
-
-
|
|
867
|
+
- The source of a Markdown document or an SVG image (the Source toggles: the document bar's, and that of an SVG image inside a rendered document) is read only by the explorer's `text` operation, through the same `asset` port after the same deny rules and admission, so it serves nothing the reader could not already download: at most `textMaxBytes` of the file's beginning, decoded as UTF-8 into JSON, which the browser shows as text and never interprets.
|
|
857
868
|
- Data responses are `private, no-store` JSON with `nosniff`, a sandboxing content security policy and `same-origin` resource policy, and the data route refuses React Router's single-fetch requests (`.data`), whose answers would carry none of those headers; the tree refresh, and a document request marked as triggered by a refresh (`X-Markdown-Explorer: refresh`, which makes the host skip its caches), require the custom request header and pass the shared cross-origin check of server routes (`@aiquants/request-isolation`).
|
|
858
869
|
- Editing writes only through the host's `edit` ports, after the deny rules and the same admission as a document. A save and a preview need the custom header `X-Markdown-Explorer: edit` and pass the shared cross-origin check, and their draft is read and checked (media type, `editMaxBytes`, UTF-8 without NUL) before any port is called; a grant's `href` must be root-relative and an external editor's `https:`; the preview is sanitized exactly as a document.
|
|
859
870
|
A draft the host's browser converter renders (`draftConverter`) is sanitized in the browser with the same allow-list rules before it is shown, and never leaves the browser; only the existence marks come from the server's answers. The host checks in every port that the reader may edit the document, and writes only over the version the draft started from.
|
|
@@ -874,7 +885,7 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
874
885
|
- A held Enter acts once on every control inside the explorer, those of other packages included (the tree's rows, the panel headers' buttons, the document viewer's toolbar and the controls inside a document), except Zoom in and Zoom out, which keep stepping while a press that began on them is held (see [Held keys](docs/behavior/layout.md#held-keys)): a press that hands the focus to them, such as following a link to an image, does not step them.
|
|
875
886
|
The repeated keydowns end at the explorer's root, so a keydown listener the host attaches outside the explorer for the bubbling phase does not receive them either.
|
|
876
887
|
- A loop row (a folder met again among its own ancestors) shows an expand glyph and `aria-expanded="false"` like any closed folder, because `@aiquants/directory-tree` has no row that cannot expand; it never opens. The 4 listings in flight are counted per explorer, not across browser tabs.
|
|
877
|
-
- A ```spreadsheets table
|
|
888
|
+
- A ```spreadsheets table stays read-only in the preview, and says so, when its block holds a line the converter reads with a tab split at a container's edge or a tab right after `>`, or an info string whose first word holds a backslash or an ampersand: readings the editor does not reproduce, so it never writes such a block in a way the converter would read differently. Inside a list item, a line of spaces and tabs only reads as an empty line (CommonMark), so a row whose cells are all white space is written as an empty line and keeps no cells; the table then shows the row as the editor reads it.
|
|
878
889
|
- Document kinds are the five above; `createFileSystemSource` previews only files with a known text extension or name as text and offers any other file as a `file` document (a download).
|
|
879
890
|
- HTML larger than `sanitizer.maxHtmlBytes` (4 MiB), placed deeper than 512 levels while it is parsed, making the parser create more elements than it has characters, more nodes than the worker's heap holds (81,920 elements, attributes and comments by default) or more than 4,096 comments, holding a tag with more than 1,024 attributes (counted before parsing for every `<` or `</` followed by a letter, so text in a script, a comment or an attribute value that looks like such a tag counts too), giving `html` or `body` more than 1,024 attributes through repeated tags,
|
|
880
891
|
carrying attributes whose characters, counting every copy of a reopened formatting element, exceed `maxHtmlBytes`, sanitizing to HTML longer than four characters per byte of `maxHtmlBytes`, or not sanitized within `sanitizer.deadlineMs` (30 s) shows as `too-large`.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),h=require("react"),T=require("./index-BNFl3BsO.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"),He=require("@aiquants/markdown"),ue=require("@aiquants/markdown/source-lines"),ee=require("./dataRoute-vXGZMVB-.cjs"),de=require("./sanitizePolicy-Du3lFZd-.cjs"),ze=require("isomorphic-dompurify"),se=require("@aiquants/resize-panels"),X=require("./location-DN0AI4ir.cjs"),ve=require("./useSplitPersistence-CR4Oxtaa.cjs"),Ce={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=>T.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,f=l===r.start||l===r.separator||l===r.end?Ge:l<r.separator?We:Xe;n.add(s,s,f)}}),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 f=r.line(t.start).from,d=r.line(t.end).to;s.length===0&&(t.end<r.lines?d+=1:t.start>1&&(f-=1));const p=s.join(`
|
|
2
|
+
`);e.dispatch({changes:{from:f,to:d,insert:p},selection:$.EditorSelection.cursor(f),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 f=t.parent;f!==null;f=f.parent)(f.name==="Blockquote"||f.name==="ListItem")&&r.unshift(f);const i=[],o=[],l=f=>{const d=o.indexOf(f);return d===-1?o.length:d};for(const f of r){const d=e.lineAt(f.from).number;if(f.name==="ListItem"){const p=J.listItemWidthOn(e.line(d).text,i,l(d));if(p===null)return null;i.push({kind:"listItem",width:p})}else i.push({kind:"quote"});o.push(d)}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 f=Ze(n,o,r);if(f===null)return ce;const[,...d]=o.getChildren("CodeMark"),p=d.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,f);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:f,body:E}},tt=({parent:e,scroll:t,text:n,saved:r,labels:i,revisions:o,onChange:l,onGeometry:s,onSave:f})=>{let d=!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:()=>(f(),!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&&!d)}),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=>{d=!0;try{u()}finally{d=!1}};return{text:()=>c.state.doc.toString(),replaceText:u=>{const m=c.state.doc.toString();if(m===u)return;let v=0;const S=Math.min(m.length,u.length);for(;v<S&&m.charCodeAt(v)===u.charCodeAt(v);)v+=1;let g=0;for(;g<S-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,S)=>{const{doc:g}=c.state,L=o.lineOf(S,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=H=>{const j=O.firstLine+H;return j<=g.lines?g.line(j).from:g.length},M=D(I.from),B=`${M===g.length&&g.sliceString(g.length-1)!==`
|
|
4
|
+
`?`
|
|
5
|
+
`:""}${I.lines.map(H=>`${H}
|
|
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 S=be(c.state,v);return S.kind==="found"?S.body:null},undo:()=>E(()=>K.undo(c)),redo:()=>E(()=>K.redo(c)),reveal:({line:u,column:m},v)=>{const{doc:S}=c.state,g=S.line(Math.min(Math.max(u,1),S.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=T.visibleTopOf(u,c.contentDOM),v=T.frameTopOf(u)+u.clientHeight,{documentTop:S}=c,{doc:g}=c.state;let L=c.lineBlockAtHeight(Math.max(m-S,0));for(;g.lineAt(L.from).text.trim()===""&&L.to<g.length;){const D=c.lineBlockAt(L.to+1);if(S+D.top>=v)break;L=D}const O=c.coordsAtPos(L.from),I=O===null?S+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-T.visibleTopOf(m,c.contentDOM),{doc:S}=c.state,g=L=>S.line(Math.min(Math.max(L,1),S.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,S=m.find(g=>g.end>=v);return S===void 0?!1:(_e(c,S,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,S=u.findIndex(I=>I.start>v),g=S<0?0:S,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(Ce),destroy:()=>c.destroy()}},xe=(e,t,n,r)=>{const i=r.scrollerOf(e.scrollDOM),o=(n===null?T.visibleTopOf(i,e.contentDOM):n)-T.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=T.frameTopOf(o),s=T.visibleTopOf(o,e.contentDOM),f=l+o.clientHeight;let d=0;switch(n.y){case"start":d=i.top-(l+n.yMargin);break;case"center":d=(i.top+i.bottom)/2-(s+f)/2;break;case"end":d=i.bottom-(f-n.yMargin);break;default:i.top<s+n.yMargin?d=i.top-(s+n.yMargin):i.bottom>f-n.yMargin&&(d=Math.min(i.bottom-(f-n.yMargin),i.top-(s+n.yMargin)))}if(d!==0&&(o.scrollTop+=d),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},Ce)}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,f=null,d=!1,p=!1,k=null,c=null,E=[],u,m=!1,v,S=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,y)=>{d||(d=!0,console.error(`[markdown-explorer] ${w}`,...y===void 0?[]:[y]))},O=w=>{if(t!==null)for(const{target:y,exists:C}of t.marksOf(w))l[y.kind].set(y.path,C)},I=()=>{clearTimeout(v),v=void 0,S?.abort(),S=null},D=()=>{c=null,E=[],clearTimeout(u),u=void 0},M=(w,y)=>{g({...s,failure:w,busy:!1,tier:y})},F=()=>{clearTimeout(u),u=E.length===0?void 0:setTimeout(H,lt)},B=()=>{if(t===null||c===null)return;const w=c,y=[],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),y.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=y;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()},H=()=>{if(u=void 0,m||c===null||E.length===0)return;m=!0;const w=E;n(e,c.draft.text,o.signal).then(y=>{if(m=!1,!(o.signal.aborted||!("kind"in y))){y.kind==="preview"&&O(y.htmlContent);for(const C of w)l[C.kind].has(C.path)||l[C.kind].set(C.path,null);B()}})},j=w=>{I(),D(),g({...s,busy:!0,tier:"server"});const y=new AbortController;S=y,v=setTimeout(()=>{v=void 0,n(e,w.text,y.signal).then(C=>{if(!(y.signal.aborted||!("kind"in C))){if(S=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,y)=>{let C;try{C=await w.convert({path:e,text:y},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,y)=>{switch(y.kind){case"preview":if(I(),y.headings.length>ee.EXPLORER_MAX_HEADINGS){D(),M(ee.failureOf("too-large"),"instant");return}c={draft:w,html:y.htmlContent,headings:y.headings.map(({text:C,depth:U,id:b})=>({text:C,depth:U,id:b}))},B();return;case"failure":I(),D(),M(ee.failureOf(y.failure.reason,y.failure.code),"instant");return;case"unavailable":j(w);return}},R=async w=>{p=!0;try{for(;k!==null&&!o.signal.aborted;){const y=k;k=null;const C=await a(w,y.text);if(o.signal.aborted)return;A(y,C)}}finally{p=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:w=>{if(!(o.signal.aborted||w.text===f?.text)){if(f=w,clearTimeout(u),u=void 0,t===null){j(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(d=>d.editor>0&&d.editor<i&&d.preview>0&&d.preview<o).sort((d,p)=>d.editor-p.editor||d.preview-p.preview);let s={editor:0,preview:0};const f=[s];for(const d of pt(l))d.editor>s.editor&&d.preview>s.preview&&(f.push(d),s=d);return f.push({editor:n,preview:r}),{toPreview:d=>ye(f,"editor","preview",d),toEditor:d=>ye(f,"preview","editor",d)}},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 f=Y(e,l),d=Y(e,s);return f[n]+(d[n]-f[n])*(r-f[t])/(d[t]-f[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",f=0,d=null,p=null,k=!1,c=null,E=null;const u={editor:0,preview:0},m={editor:null,preview:null};let v=null,S=()=>{};const g=a=>{d!==null&&a!==d||(s=a,f=l()+vt)},L=(a,A)=>{a!==s&&d===null&&l()>=f&&!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&&(S(),v=a,S=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(H))},H=()=>{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"?j(a,"preview",E.toPreview(e.position())):j(e,"editor",E.toEditor(a.position())))},j=(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=>{d=a,!(a===null||a===s)&&(s=a,f=0,B())},dispose:()=>{k=!0,p!==null&&o(p),p=null,I(),D(),S()}}},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=T.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-T.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:f,data:d,documents:p,draftConverter:k,labels:c}=T.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),S=h.useRef(E);h.useLayoutEffect(()=>{S.current=E});const g=h.useEffectEvent(()=>t());h.useEffect(()=>{const a=St(f.iframeHosts,f.dataPath,k,p,e),A=g(),R=ft({path:e,instant:a,preview:d.preview,initial:S.current,onView:w=>h.startTransition(()=>u(w))});return v.current=R,R.update(A),()=>{R.dispose(),v.current=null}},[f,d,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:T.anchorOfView(A,a(R))},place:({line:a,clientTop:A},R)=>{const w=m.current,y=w===null?null:T.blockAtLine(w,a);y!==null&&(R(y).scrollTop+=T.lineTopIn(y,a)-A)}}),[]);const D=a=>{const A=m.current,{target:R}=a;if(o===void 0||A===null||!(R instanceof Element)||!T.isEditingDoubleClick(R))return;const w=T.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]),H=h.useMemo(()=>({...n,labels:F===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0,spreadsheetEditor:F}),[n,B,F]),j=h.useMemo(()=>E.parsed===null?null:q.jsx("div",{className:"aqmx-document-viewer",children:q.jsx(He.MarkdownViewer,{...H,parseResult:E.parsed,content:null})}),[H,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(T.failureTitleOf(c,E.failure.reason))}),j??(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"},qe=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},f=()=>{s.frame>0&&s.measure>0&&i(X.editSplitOrientation(s.frame,s.measure,n))};f();const d=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))}f()});return d.observe(o),d.observe(l),()=>d.disconnect()},[e,t,n]),r},Rt=({editorId:e})=>{const{edits:t,labels:n}=T.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 f=ve.useSplitPersistence(h.useCallback(p=>{const k=qe(p);k!==null&&t.setEditorShare(k)},[t])),d=h.useCallback((p,k)=>{const c=qe(p);c!==null&&ie(r).style.setProperty(ae,`${String(c)}%`),f.layoutChanged(p,k)},[f]);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:d,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:f.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"})]})]})},qt=512,Ct=()=>{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>qt&&(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 f of e.slice(i-t)){const d=f.changes.mapPos(s,1,$.MapMode.TrackAfter);if(d===null)return null;s=d}return n.lineAt(s).number}}},De=144,Mt="[data-aqmd-spreadsheet-fullscreen]",_t=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),Pt=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"},Nt=e=>{e.stopPropagation()},Dt=e=>{const{path:t,name:n,session:r}=e,{edits:i,labels:o,announcer:l}=T.useExplorer(),{phase:s}=r,f=h.useCallback(()=>i.retry(t),[i,t]);switch(h.useEffect(()=>{s.kind==="failed"&&l.announce(o.documentFailed(n,T.failureTitleOf(o,s.failure.reason)))},[s,l,o,n]),s.kind){case"opening":return q.jsxs(q.Fragment,{children:[q.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:_t.map(d=>q.jsx("span",{},d))}),q.jsx("p",{className:"aqmx-sr-only",children:o.editLoading})]});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(T.EditGrantNotice,{href:s.href,onRetry:f,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(T.FailureView,{failure:s.failure,alert:!1,onRetry:f,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Vt,{...e})}},Vt=({path:e,name:t,session:n,layout:r,viewer:i,region:o,paneScroll:l})=>{const{edits:s,labels:f}=T.useExplorer(),d=h.useRef(null),p=h.useId(),k=h.useRef(null),[c]=h.useState(()=>new Set),[E]=h.useState(Ct),u=h.useRef(null),m=h.useRef(null),v=r==="fill",S=T.useSideBySide(),g=T.editViewOf(n,S,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),H=h.useRef(!1),j=h.useMemo(()=>({editor:f.editorLabel(t),useOurs:f.conflictUseOurs,useTheirs:f.conflictUseTheirs,keepBoth:f.conflictKeepBoth}),[f,t]),a=h.useCallback(b=>{const{region:x,paneScroll:_}=I.current,z=x();return z===null?b:_.scrollerOf(z,b)},[]);h.useLayoutEffect(()=>{const b=d.current,x=s.draft(e);if(b===null||x===null)return;const _=s.editorState.get(e),z=Pt(_)&&_.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:je}=I.current,he=Be();return Z==="fill"||he===null?N:je.scrollerOf(he,N)},reveal:N=>I.current.paneScroll.reveal(N)},text:x,saved:z===null?void 0:z.state,labels:j,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:(H.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,j,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(T.positionInSource(x,A.anchor),A.anchor.clientTop),b.focus(),s.consumeRequest(e))},[s,e,A,j]),h.useLayoutEffect(()=>{g!=="editor"&&!n.previewPrepared&&s.preparePreview(e)},[s,e,g,n.previewPrepared]),h.useLayoutEffect(()=>{const b=F.current,x=B.current,_=H.current;F.current=null,B.current=null,H.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(T.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(T.paneShownAlone(M.current.view)),m.current=x,()=>{x.dispose(),m.current=null}},[O,s,e,j]),h.useLayoutEffect(()=>{m.current?.showAlone(T.paneShownAlone(g))},[g]);const y=h.useCallback(()=>m.current?.previewChanged(),[]),C=h.useCallback(b=>s.start(e,b),[s,e]),U=b=>{if(b.target instanceof Element&&b.target.closest(Mt)!==null)return;if(b.key==="Escape"){T.consumeKey(b);return}if(!T.isEditViewShortcut(b.nativeEvent,T.isApplePlatform(navigator.platform)))return;T.consumeKey(b);const x=T.toggledEditView(g);B.current=x,T.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:Nt,children:[q.jsx("div",{ref:d,id:p,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:g==="preview",hidden:g==="preview"&&!v,...T.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:y,handleRef:u}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=De;exports.default=Dt;
|