@aiquants/markdown-explorer 0.23.0 → 0.24.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 +112 -0
- package/README.md +61 -21
- package/dist/{EditSurface-Bk4tdJ99.cjs → EditSurface-CRc4g0Qa.cjs} +5 -5
- package/dist/{EditSurface-Dhvw9IDD.js → EditSurface-CcWEczj3.js} +333 -336
- package/dist/{ExplorerSplit-Q5VqUBDE.js → ExplorerSplit-97SeIAOS.js} +81 -81
- package/dist/{ExplorerSplit-BAFiXU-V.cjs → ExplorerSplit-ByxxXlgs.cjs} +1 -1
- package/dist/{MultiLayout-Bq_TS3ez.cjs → MultiLayout-B_yMVDt_.cjs} +1 -1
- package/dist/{MultiLayout-DlATT7km.js → MultiLayout-CnbuAlxd.js} +22 -22
- package/dist/{NativeScrollBar-TsIcS3JZ.js → NativeScrollBar-BXdaM3EA.js} +1 -1
- package/dist/{NativeScrollBar-A6-qEpz7.cjs → NativeScrollBar-D4a7fBOS.cjs} +1 -1
- package/dist/{TreeLayout-zrSo4MNZ.js → TreeLayout-BIQBKAkV.js} +3 -3
- package/dist/{TreeLayout-l-r2pPao.cjs → TreeLayout-C6QDpEBS.cjs} +1 -1
- package/dist/core/config.d.cts +13 -0
- package/dist/core/config.d.ts +13 -0
- package/dist/core/contracts.d.cts +22 -4
- package/dist/core/contracts.d.ts +22 -4
- package/dist/core/labels.d.cts +9 -0
- package/dist/core/labels.d.ts +9 -0
- package/dist/core/textEncoding.d.cts +4 -0
- package/dist/core/textEncoding.d.ts +4 -0
- package/dist/{dataRoute-Diu_7gle.js → dataRoute-BEvesOvN.js} +105 -97
- package/dist/dataRoute-Cv7fgCW7.cjs +1 -0
- package/dist/index-BwTVYkTR.cjs +13 -0
- package/dist/index-CeZDCyEl.js +4088 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +24 -23
- package/dist/location-CasigkBk.cjs +1 -0
- package/dist/location-gXXmC7CQ.js +643 -0
- package/dist/{merge-BzMpSaxx.js → merge-DqjUgcV_.js} +1 -1
- package/dist/{merge-DlPkU2Jc.cjs → merge-QLktbpZY.cjs} +1 -1
- package/dist/{sanitizePolicy-Du3lFZd-.cjs → sanitizePolicy-CZwOaJ92.cjs} +1 -1
- package/dist/{sanitizePolicy-BvhYIqVO.js → sanitizePolicy-gVKBhabq.js} +1 -1
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +1 -1
- package/dist/server/fileSystemSource.d.cts +1 -0
- package/dist/server/fileSystemSource.d.ts +1 -0
- package/dist/server/ports.d.cts +8 -1
- package/dist/server/ports.d.ts +8 -1
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +1 -0
- package/dist/server.d.ts +1 -0
- package/dist/server.js +783 -768
- package/dist/styles/markdown-explorer.css +1 -1
- package/dist/{useSplitPersistence-HfAb8Kzh.js → useSplitPersistence-BPNjvuJi.js} +1 -1
- package/dist/{useSplitPersistence-CR4Oxtaa.cjs → useSplitPersistence-Bmpb2prR.cjs} +1 -1
- package/docs/behavior/dom-hooks.md +13 -6
- package/docs/behavior/layout.md +19 -10
- package/docs/behavior/localization.md +6 -3
- package/docs/behavior/security.md +6 -4
- package/docs/behavior/url-contract.md +2 -2
- package/package.json +5 -5
- package/dist/dataRoute-vXGZMVB-.cjs +0 -1
- package/dist/index-BNFl3BsO.cjs +0 -13
- package/dist/index-Jz6zeO4O.js +0 -3703
- package/dist/location-8Ho8ZNv_.js +0 -499
- package/dist/location-DN0AI4ir.cjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,117 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.24.0 (2026-10-27) — Table files shown as tables: CSV, TSV and a workbook's first sheet
|
|
4
|
+
|
|
5
|
+
### Breaking
|
|
6
|
+
|
|
7
|
+
- **A new document kind, `spreadsheet`: a table file shown as a table.** The browser's documents gain
|
|
8
|
+
`{ kind: "spreadsheet", name, url, format, firstSheetOnly, edit }` and the host's `document` port may answer
|
|
9
|
+
`{ kind: "spreadsheet", name, format, firstSheetOnly, edit, version }`: `format` is `"csv"` or `"tsv"` (the bytes
|
|
10
|
+
the `asset` port delivers), `firstSheetOnly` says the file is only the first sheet of a workbook the storage exports,
|
|
11
|
+
and `edit` is `null` or an external editor (`{ kind: "external", href }`, the explorer editing no table file itself).
|
|
12
|
+
A spreadsheet answer without a known `format`, a boolean `firstSheetOnly` and such an `edit` breaks the contract (it
|
|
13
|
+
is logged and the reader sees `failed`). `ExplorerSpreadsheetDocument`, `ExplorerSpreadsheetFormat` and
|
|
14
|
+
`ExplorerExternalEdit` are exported. `createFileSystemSource` answers `.csv` files as `csv` and `.tsv` and `.tab`
|
|
15
|
+
files as `tsv` spreadsheet documents: a `.csv` or `.tsv` file was a text document, and a `.tab` file a `file`
|
|
16
|
+
document offered for download. Excel and OpenDocument workbooks stay `file` documents.
|
|
17
|
+
- **The resolved configuration carries `legacyTextEncoding` (`string | null`) and `spreadsheets` (`{ maxBytes }`), and
|
|
18
|
+
`revalidateExplorerConfig` checks every key.** `defineExplorerConfig` fills both. Revalidation now asks a
|
|
19
|
+
configuration to equal, key by key, what `defineExplorerConfig` resolves from it, so one built or edited by hand
|
|
20
|
+
with a key left out, a group left partial (`spreadsheets: {}`, `multiView` without `columns`) or a value it would
|
|
21
|
+
resolve otherwise fails with a `RangeError` naming the place that differs and both values there
|
|
22
|
+
(`config.spreadsheets.maxBytes`, `config.iframeHosts.length`), or the key the resolved configuration does not have
|
|
23
|
+
(`config.embeds.linkCardSize` given as `undefined`) — unless a check of `defineExplorerConfig` refuses the value
|
|
24
|
+
first with its own error (a missing `legacyTextEncoding` or `embeds`, or a `multiView` that is not a plain object,
|
|
25
|
+
throws a `TypeError`) —, where a missing group used to be completed with its defaults while the browser read the
|
|
26
|
+
host's object as it was.
|
|
27
|
+
- **`defineExplorerConfig` refuses an option it does not know**: a key outside `ExplorerConfigInput` (a misspelled
|
|
28
|
+
`legacyEncoding`, a singular `spreadsheet`, a `sourceIds` left in) fails with a `RangeError` naming it, where it was
|
|
29
|
+
ignored and the option it meant silently took its default.
|
|
30
|
+
- **Text is read by the explorer's one rule**: the encoding a byte order mark names (the mark dropped), else UTF-8,
|
|
31
|
+
else the configuration's legacy encoding, each strictly, and bytes none of them reads in the first encoding tried,
|
|
32
|
+
with U+FFFD for each sequence it cannot read; a beginning of a file that ends within a byte order mark reads nothing
|
|
33
|
+
yet. The `text` operation reads that way, and so does `createFileSystemSource` for its text and Markdown files, NUL
|
|
34
|
+
being looked for in the decoded text: a UTF-16 file with a byte order mark now answers its text (the `text` operation
|
|
35
|
+
answered `unsupported`, and the file-system source a `file` document).
|
|
36
|
+
|
|
37
|
+
### Added
|
|
38
|
+
|
|
39
|
+
- **Table files show as tables.** A spreadsheet document shows its file under the file header (Open in a new tab as
|
|
40
|
+
plain text, Download) as a read-only `@aiquants/markdown` table block named after the file, in the UI language and
|
|
41
|
+
the explorer's colour scheme, filling a page pane (never fewer than three rows) and taking its rows' height in a
|
|
42
|
+
multi-view panel. The file's notes and table share one scroller under the header, the document's scroller, so at a
|
|
43
|
+
400 % zoom both are reached by scrolling it. The browser reads the file itself through the asset's plain-text
|
|
44
|
+
delivery (never redirected to the storage), as a stream, and stops reading once the table holds the 100,000 cells a
|
|
45
|
+
grid operates on at once or the bytes reach `spreadsheets.maxBytes` (default 2 MiB); columns past the 1,000th are
|
|
46
|
+
left out, and a cell keeps at most the 32,767 characters a cell of Excel holds. A file read partway yields only the
|
|
47
|
+
rows the rest of it cannot change — every row a line break ends, up to a quoted cell the bytes read do not close —,
|
|
48
|
+
so the rows shown are always the file's first rows; its encoding is decided on the bytes read. CSV is read by
|
|
49
|
+
RFC 4180 (quoted cells with commas, line breaks and doubled quotes; the text after a closing quote joining the cell,
|
|
50
|
+
as Excel reads it), TSV by `@aiquants/spreadsheet`'s grammar. Notes say when the file is only a workbook's first
|
|
51
|
+
sheet, when the table is only part of the file and when the file has no data (its cells, taken whole within that
|
|
52
|
+
budget, are all empty, or it has none); bytes in no encoding of the explorer's rule show a note naming the encodings tried (by their written names:
|
|
53
|
+
`UTF-8`, `Shift_JIS`, or the one a byte order mark names), text holding NUL a note that the file is not text, and a
|
|
54
|
+
file in whose bytes read no row ends a note that it cannot be shown as a table, each with the download. The skeleton
|
|
55
|
+
shows until the first reading, and a page view announces the document once its table shows; a failure before
|
|
56
|
+
anything was read shows the failure view with its retry and is announced alone (in a multi-view panel through the
|
|
57
|
+
panel's announcer), and a retry that succeeds moves the focus into the table's body and, in a page view, announces
|
|
58
|
+
the document. A refresh reads the file again with the previous table on screen and the region busy, and is reported
|
|
59
|
+
once the file is read (see Changed); a background answer whose reading fails keeps the table without a word, as a
|
|
60
|
+
background failure keeps a loaded document.
|
|
61
|
+
- **A table file offers Source**: the document bar's toggle (its tooltip `showSpreadsheetMarkup` naming the CSV or the
|
|
62
|
+
TSV) shows the file as written through the `text` operation, read by the same rule as the table, and keeps the choice
|
|
63
|
+
in the URL's `markup`. A spreadsheet's external editor (a Google Sheets spreadsheet's, for example) is linked from the
|
|
64
|
+
bar like a Markdown document's.
|
|
65
|
+
- **Configuration**: `legacyTextEncoding`, the legacy encoding of the files the explorer reads as text (a WHATWG label
|
|
66
|
+
`TextDecoder` knows, such as `Shift_JIS`, `sjis` or `windows-1252`, resolved to the encoding's written name), in
|
|
67
|
+
which it reads bytes that carry no byte order mark and are not UTF-8 — a table file's and a document shown as written
|
|
68
|
+
alike; UTF-8, UTF-16, ISO-2022-JP (seven-bit, so UTF-8 always reads it first) and x-user-defined (no text encoding)
|
|
69
|
+
are refused with a `RangeError` naming why. `spreadsheets.maxBytes`: a positive integer up to 256 MiB, default 2 MiB
|
|
70
|
+
(`SPREADSHEET_BYTE_LIMITS`), the most a Source view reads by default, since the browser parses what it reads on its
|
|
71
|
+
main thread at a cost that grows with the bytes.
|
|
72
|
+
- **`createFileSystemSource` takes `legacyTextEncoding`** for its text and Markdown files — a label, or `null` for none,
|
|
73
|
+
so the resolved configuration's value passes as it is —, and `@aiquants/markdown-explorer/server` exports the rule
|
|
74
|
+
for a host's own sources: `legacyTextEncodingOf`, and `decodeText` and `decodeTextLeniently`, which resolve a legacy
|
|
75
|
+
label as `legacyTextEncodingOf` does and refuse the same names.
|
|
76
|
+
- Labels: `showSpreadsheetMarkup`, `spreadsheetLoading`, `spreadsheetFirstSheetOnly`, `spreadsheetTruncated`,
|
|
77
|
+
`spreadsheetUnreadableEncoding` (given the encodings tried), `spreadsheetNotText`, `spreadsheetLongRow`,
|
|
78
|
+
`spreadsheetEmpty` and `spreadsheetFullscreen`. DOM hooks: `markdown-explorer-spreadsheet-view` (with
|
|
79
|
+
`data-aqmx-spreadsheet`: `loading`, `table`, `empty`, `unreadable` or `failure`), its body, the document's scroller
|
|
80
|
+
(`data-aqmx-document-scroller`), `-spreadsheet-first-sheet`, `-spreadsheet-truncated`, `-spreadsheet-empty`,
|
|
81
|
+
`-spreadsheet-skeleton`, `-spreadsheet-failure` and `-spreadsheet-unreadable` (with `data-aqmx-unreadable`:
|
|
82
|
+
`encoding`, `binary` or `long-row`) and its download, and the document kind `spreadsheet`.
|
|
83
|
+
- The demo's `notes/tables` holds a UTF-8 CSV with quoted cells, a Shift_JIS CSV (the demo gives
|
|
84
|
+
`legacyTextEncoding: "Shift_JIS"` to its configuration and to its file-system sources), a TSV and a CSV wider than
|
|
85
|
+
the preview's 1,000 columns.
|
|
86
|
+
|
|
87
|
+
### Changed
|
|
88
|
+
|
|
89
|
+
- **A document's refresh is reported once what it brought is on screen.** Where the document's content reads a part
|
|
90
|
+
of it itself — a table file's table, a document shown as written —, the document bar stays busy until that part is
|
|
91
|
+
read from the new answer and only then announces `documentRefreshed`; a failure of that reading is the refresh's
|
|
92
|
+
failure, shown in the bar's one notice with what was read before kept and announced once, so a refresh is never
|
|
93
|
+
announced as both reloaded and failed, and no second notice repeats it. A refresh that replaces the content's own
|
|
94
|
+
failure view is reported as the pane shows it, as for a shown failure: in a page view the pane alone announces the
|
|
95
|
+
document (or the new failure), in a multi-view panel the bar announces it as reloaded and leaves a failure to the
|
|
96
|
+
pane. The bar's notice of a failed reload also comes down when the reader switches between the document rendered and
|
|
97
|
+
as written, whose content then reads the document again. A page view announces a document whose content reads such a
|
|
98
|
+
part as shown once the part shows, or when the reader switches to a view that reads none before it does, and says
|
|
99
|
+
nothing for a document it shows as stale while another one the reader asked for loads.
|
|
100
|
+
- **A document shown as written keeps its text when reading it again fails**, as the table does (both read their own
|
|
101
|
+
part the same way): the region is busy while it reads again, a refresh reports the failure in the bar, a background
|
|
102
|
+
answer's reading that fails keeps the text without a word, and a retry that replaces its failure view moves the
|
|
103
|
+
focus into the text and, in a page view, announces the document, as a document that replaces a failure is.
|
|
104
|
+
- **The focus ring of a document's scroller is drawn inside its edge.** The pane carries the focus to the scroller of
|
|
105
|
+
the shown document (a viewer's, a file view's, a table file's body) when nothing inside takes it, and the region
|
|
106
|
+
clips what lies outside that scroller, so its outer ring was hidden all around; one rule now insets the ring of every
|
|
107
|
+
such scroller, the edit preview's included.
|
|
108
|
+
- Peers: `@aiquants/markdown` ^11.2.0 (the table that fills its pane keeps three rows; an SVG image's toolbar sits at
|
|
109
|
+
the row's end with Copy before the Source toggle, and Copy copies the image's source from the image too) and
|
|
110
|
+
`@aiquants/spreadsheet` ^0.16.1 (`iterateTsvPrefixRows`, the rows of a TSV file read partway).
|
|
111
|
+
- While the editing chunk loads, its skeleton carries the screen-reader text `editLoading`, as the editor's skeleton
|
|
112
|
+
does while it reads the source; the two are one skeleton, shared with the document pane's other loading and failure
|
|
113
|
+
states.
|
|
114
|
+
|
|
3
115
|
## 0.23.0 (2026-10-27) — An SVG image shows its SVG a press away, as a document and inside one
|
|
4
116
|
|
|
5
117
|
### Breaking
|
package/README.md
CHANGED
|
@@ -18,14 +18,19 @@ 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
|
-
of rendered (its file — an SVG image's own SVG
|
|
23
|
-
file, whose header copies the text exactly as written); a raster image
|
|
21
|
+
Beside it, a Markdown document, an SVG image and a table file offer **Source**: a toggle that shows the document as
|
|
22
|
+
written instead of rendered (its file — an SVG image's own SVG, a table file's CSV or TSV — read through the data
|
|
23
|
+
route's `text` operation, shown like a text file, whose header copies the text exactly as written); a raster image
|
|
24
|
+
offers none. The choice is part of the URL
|
|
24
25
|
(`markup`), so a reload, a shared link and Back and Forward show the document the same way, and the switches between
|
|
25
26
|
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
|
|
27
|
-
toolbar above it,
|
|
28
|
-
press.
|
|
27
|
+
Inside a rendered document, a storage SVG image that stands alone in a paragraph gets its own Copy and Source toggle in
|
|
28
|
+
a toolbar above it, at the row's end: the toggle shows the image's SVG in its place through the same operation, and the
|
|
29
|
+
image again on a second press, and Copy copies that SVG whole, from the image as well.
|
|
30
|
+
A table file — a CSV or TSV file, or a workbook the host exports as one, such as a Google Sheets spreadsheet's first
|
|
31
|
+
sheet — shows as a read-only grid under its file header, named after the file: the browser reads the file itself in its
|
|
32
|
+
encoding (a byte order mark's, UTF-8 or the configured legacy encoding) and stops once the table holds as much as a
|
|
33
|
+
grid shows, saying so (see [Table files](#table-files)).
|
|
29
34
|
With the server's `edit` ports, a Markdown document also offers **Edit**: the reader edits its Markdown in place
|
|
30
35
|
(CodeMirror, loaded on demand), from where they were reading or from the word they double-clicked, saves over the
|
|
31
36
|
version the draft started from (changes saved elsewhere are merged line by line, and conflicts are resolved in the
|
|
@@ -42,13 +47,13 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
|
|
|
42
47
|
|
|
43
48
|
- React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
|
|
44
49
|
- 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)`.
|
|
45
|
-
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^11.
|
|
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,
|
|
50
|
+
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^11.2.0 (document rendering; the Source toggle of a storage SVG image that stands alone in a paragraph, read through `imageSource`, and a Copy that copies that image's source from the image too, 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,
|
|
51
|
+
its controls' 44 px targets under every pointer, ```spreadsheets tables — inside list items and quotes too, and in a pane of their own (`layout="fill"`) never fewer than three rows — 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
52
|
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,
|
|
48
53
|
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),
|
|
49
54
|
`@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),
|
|
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.
|
|
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).
|
|
55
|
+
`@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.1 (the grid of those tables — one `role="grid"` with header rows,
|
|
56
|
+
read-only where it cannot write and named by its block — which markdown loads only for a document that holds one, and the grid of a table file's preview, whose TSV grammar (`@aiquants/spreadsheet/tsv`) reads a TSV file — `iterateTsvPrefixRows` the rows of a file read partway — and whose operation budget (`SPREADSHEET_MAX_OPERATION_CELLS` of `@aiquants/spreadsheet/view`) bounds its table) and `@aiquants/virtualscroll` ^3.22.1 (44 px scroll-to-edge pills and tap-scroll circles, the pills' text at the body step).
|
|
52
57
|
The client depends on these floors, while a package manager may only warn about an older peer.
|
|
53
58
|
- A Markdown parser of your choice on the server that produces HTML and its headings (the explorer sanitizes the HTML before it is sent).
|
|
54
59
|
- 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.
|
|
@@ -79,7 +84,7 @@ export const explorerConfig = defineExplorerConfig({
|
|
|
79
84
|
})
|
|
80
85
|
```
|
|
81
86
|
|
|
82
|
-
`defineExplorerConfig` validates everything once and returns a frozen value: mount paths, view slugs (`tree`, `multi`, `single` by default), the multi-view limits (`maxPanels` 12, `columns` 4), Expand all's budget per press (`maxFolders` 500, `maxDepth` 16), the deepest document the reader's reveal opens folders for (`maxDepth` 16), the document styles, the iframe host allow-list, the embeds and link cards
|
|
87
|
+
`defineExplorerConfig` validates everything once and returns a frozen value: mount paths, view slugs (`tree`, `multi`, `single` by default), the multi-view limits (`maxPanels` 12, `columns` 4), Expand all's budget per press (`maxFolders` 500, `maxDepth` 16), the deepest document the reader's reveal opens folders for (`maxDepth` 16), the document styles, the iframe host allow-list, the embeds and link cards, the reader's default tree settings, the legacy text encoding and a table file's byte budget. A mistake throws at startup instead of producing links that point nowhere, a key that is not an option (a misspelled `legacyEncoding`, a singular `spreadsheet`) included: it throws a `RangeError` naming it instead of leaving the option it meant at its default.
|
|
83
88
|
The source ids are not part of it: they are the ids of the server's `sources` (a runtime setting of the server), and the browser learns them from the page data. `withExplorerSources(config, sourceIds)` joins them to the configuration where the URL codec needs them (see [Views and URLs](#views-and-urls)).
|
|
84
89
|
|
|
85
90
|
| Option | Type | Purpose |
|
|
@@ -95,6 +100,8 @@ The source ids are not part of it: they are the ids of the server's `sources` (a
|
|
|
95
100
|
| `iframeHosts?` | `readonly string[]` | Host names whose `https:` iframes written in documents may load (exact match); none when omitted. They gate only iframes written in documents; provider frames come from `embeds`, and no iframe of the page's own origin ever renders, whatever is listed. |
|
|
96
101
|
| `embeds?` | `{ providers?, linkCards?, linkCardSize? }` | What `@aiquants/markdown` makes of a link alone in a paragraph. `providers` lists the ids (`EMBED_PROVIDER_IDS` of `@aiquants/markdown/embeds`: `youtube`, `x`, `instagram`, `threads`, `tiktok`, `bluesky`, `linkedin`, `reddit`, `note`, `niconico`) whose posts and videos documents embed as cross-origin frames, whatever the link's text. `linkCards: true` turns a link written as its own URL into a card, which the data route's own `link-card` operation serves (see [Link cards](#link-cards)): no route of yours is needed. `linkCardSize` picks the size of every card, `compact`, `banner` or `full` (`LINK_CARD_SIZES` of `@aiquants/markdown/embeds`; `@aiquants/markdown`'s `banner` when omitted), and needs `linkCards: true`. Each field defaults to none (`[]`, `false`, omitted), also when given as `undefined`, so without the option such a link stays its paragraph. Repeated ids are removed. An unknown id, a `linkCards` that is not a boolean, an unknown size, a size without `linkCards: true` or an unknown key (`linkCardEndpoint` included) throws a `RangeError` (`[markdown-explorer] embeds…`), and anything but a plain object a `TypeError`. The resolved `config.embeds` is the `MarkdownEmbeds` the viewer takes: `linkCardEndpoint` is `<dataPath>/link-card` when link cards are on and `null` otherwise, and `linkCardSize` is present only when given. See `@aiquants/markdown`'s README (Embeds) for the URLs each provider recognizes, the frames' sizes and the cards' sizes. |
|
|
97
102
|
| `defaultTreeSettings?` | `Partial<TreeSettings>` | The reader's tree settings before they change any, merged over the package's `DEFAULT_TREE_SETTINGS` (the source's own order, folders and READMEs mixed among the files, Single selection, a recursive double click, 8 px expand icons, nothing kept expanded, the open document not revealed, the root indent kept, lines, expand icons and folder and file icons on). Each value is one the settings menu offers: `sortMode` `"native"`, `"asc"`, `"desc"`, `"oldest"` or `"newest"` (by the entries' `modifiedAt`); `folderPlacement` `"mixed"`, `"first"` or `"last"`; `readmePlacement` `"mixed"`, `"first"` or `"last"`; `selectionMode` `"single"`, `"multiple"` or `"none"`; `doubleClickAction` `"recursive"` or `"toggle"`; `expandIconSize` `8`, `13` or `5`; the other settings (`alwaysExpanded`, `revealDocument`, `removeRootIndent`, `lines`, `expandIcons`, `directoryIcons`, `fileIcons`) `true` or `false`. An unknown key or any other value throws a `RangeError`, and anything but a plain object (a `Map`, a class instance, an object inheriting its settings) throws a `TypeError`; a setting given as `undefined` keeps the package default. The server render and the hydration draw these defaults (see [Tree settings](#tree-settings)). |
|
|
103
|
+
| `legacyTextEncoding?` | `string` | The legacy encoding of the files the explorer reads as text: a WHATWG label `TextDecoder` knows (for example `Shift_JIS`, `sjis` or `windows-1252`), resolved to the encoding's written name (`Shift_JIS`; `legacyTextEncodingOf`). UTF-8 and UTF-16 (read before it, and only by a byte order mark), ISO-2022-JP (seven-bit, so UTF-8 always reads it first) and x-user-defined (no text encoding) are refused with a `RangeError` naming why. The explorer reads a file's bytes in it when they carry no byte order mark and are not UTF-8 — a table file it shows as a table and a document it shows as written alike (see [Table files](#table-files)); give `createFileSystemSource` the same encoding for its text and Markdown files. None when omitted: a table file of such bytes is then not shown as a table, and a document shown as written shows them as UTF-8, with U+FFFD for each sequence UTF-8 cannot read. |
|
|
104
|
+
| `spreadsheets?` | `{ maxBytes? }` | A table file's preview: the most bytes the browser reads of the file (a positive integer up to 256 MiB; default 2 MiB, the most a Source view reads by default; `SPREADSHEET_BYTE_LIMITS`), which stops sooner once the table holds as many cells as a preview shows (see [Table files](#table-files)). The browser parses what it reads on its main thread, at a cost that grows with the bytes rather than with the cells it shows, so a larger value costs a pathological file (one long row, one long cell) more time. The field defaults on its own, also when given as `undefined`. |
|
|
98
105
|
|
|
99
106
|
For example, `defaultTreeSettings: { sortMode: "desc" }` lists every folder's entries by name, Z to A, until the reader picks another order.
|
|
100
107
|
|
|
@@ -289,7 +296,7 @@ to; load it when your documents contain math.
|
|
|
289
296
|
`explorerHref` throws a `RangeError` for a target the resolver would redirect, read as another location or partly ignore — repeated or more than `multiView.maxPanels` documents, a maximized document or a document shown as written that is not open, an unknown source or document style, an unsupported alignment or embedding value, a tree view with both a document and a folder, a document path that ends in a slash, a tree view with neither a document nor a folder shown as written — so every link it writes resolves back to the location given.
|
|
290
297
|
- A folder of the tree view takes the same segment with a slash after its path: `explorerHref(config, { view: "tree", folder: "guide/concepts" })` writes `/docs/tree/guide%2Fconcepts%2F`, and `ExplorerLocation`'s tree view carries `doc` and `folder`, at most one of them not `null` (see [Folders and their READMEs](#folders-and-their-readmes)). The single view shows documents only and redirects a folder to the tree view.
|
|
291
298
|
- The single view accepts embedding parameters: `showToc=false`, `showStyle=false`, `showAlign=false`, `padding` (0–256 px, written in decimal digits), `width` and `maxWidth` (a CSS length in px, rem, em, ch, vw or %; the column never grows wider than the pane, whatever the value). The tree and single views accept `style` and `align` as display overrides.
|
|
292
|
-
- `markup` names the Markdown documents shown as written (the Source toggle): `markup=true` for the tree or single view's document, and one `markup=<document>` per open document shown that way in the multi view, in the order of `doc`. In `ExplorerLocation` it is a boolean in the tree and single views and a list in the multi view; a target without it shows every document rendered.
|
|
299
|
+
- `markup` names the Markdown documents, SVG images and table files shown as written (the Source toggle): `markup=true` for the tree or single view's document, and one `markup=<document>` per open document shown that way in the multi view, in the order of `doc`. In `ExplorerLocation` it is a boolean in the tree and single views and a list in the multi view; a target without it shows every document rendered.
|
|
293
300
|
- History: a click in the tree replaces the URL's document or folder; links inside a document, entries of its table of contents (in the tree and single views, to the heading's hash), source switches and view switches push; every multi-view action and the Source toggle replace (hiding and showing a panel leave the URL unchanged).
|
|
294
301
|
- An entry of a document's table of contents links to its heading's own address: the page's URL with the heading's fragment, or, in a multi-view panel, the panel's document in the tree view with that fragment, so a modified or middle click, a new tab or a copied address opens the heading (see [URL contract](docs/behavior/url-contract.md#table-of-contents)).
|
|
295
302
|
|
|
@@ -395,15 +402,18 @@ type ExplorerDocument =
|
|
|
395
402
|
| { kind: "text"; name: string; text: string; truncated: boolean; url: string }
|
|
396
403
|
| { kind: "image"; name: string; url: string; imageType: "raster" | "svg" }
|
|
397
404
|
| { kind: "media"; name: string; url: string; mediaType: "video" | "audio" | "pdf" }
|
|
405
|
+
| { kind: "spreadsheet"; name: string; url: string; format: "csv" | "tsv"; firstSheetOnly: boolean; edit: ExplorerExternalEdit | null }
|
|
398
406
|
| { kind: "file"; name: string; url: string }
|
|
399
407
|
| ExplorerFailureDocument // { kind: "failure"; failure: { reason: ExplorerFailureReason; code?: string } }
|
|
400
408
|
```
|
|
401
409
|
|
|
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`:
|
|
403
|
-
`{ kind: "image"; name; imageType; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; version }` and `{ kind: "file"; name; version }`.
|
|
410
|
+
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, spreadsheet or file document carries its file's `version` instead of a `url`:
|
|
411
|
+
`{ kind: "image"; name; imageType; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; version }`, `{ kind: "spreadsheet"; name; format; firstSheetOnly; edit; version }` and `{ kind: "file"; name; version }`.
|
|
404
412
|
`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)).
|
|
405
413
|
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
414
|
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.
|
|
415
|
+
A spreadsheet document is a table file the explorer shows as a table (see [Table files](#table-files)); it names the format of the bytes your `asset` port delivers for it in `format` (`ExplorerSpreadsheetFormat`: `"csv"` or `"tsv"`), whether those bytes are only the first sheet of a workbook your storage exports (`firstSheetOnly`, which adds a note above the table; a Google Sheets spreadsheet exported as CSV is), and the file's own editor in `edit` (`ExplorerExternalEdit`:
|
|
416
|
+
`null`, or `{ kind: "external", href }` with an absolute `https:` URL the bar opens in a new tab, as for a markdown document; the explorer edits no table file itself). Answer them from what your storage knows of the file, as for an image; a spreadsheet answer without a known `format`, a boolean `firstSheetOnly` and such an `edit` breaks the contract the same way.
|
|
407
417
|
`failureDocument(reason, code?)` returns an `ExplorerFailureDocument`, which both unions accept.
|
|
408
418
|
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).
|
|
409
419
|
Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
|
|
@@ -429,6 +439,23 @@ Your parser resolves each link and each image; the rules are in [Document links]
|
|
|
429
439
|
a missing target gets `data-asset-exists="false"`, which the viewer shows as a labelled placeholder; a relative `src` left as written would resolve against the page URL and load an explorer page instead), and the demo's parser (`demo/app/markdown.server.ts` in the source repository) is a complete example.
|
|
430
440
|
The deny rules are checked on the document's path only: a parser that expands include directives (such as `<!-- @import "…" -->`) must apply them to every file it reads, or leave such directives unexpanded (`@aiquants/markdown`'s `parseMarkdown` leaves them unexpanded unless `resolveImports` is set, and applies the `deniedPathSegments` you give it, the explorer's rules, to every import, image and link target). The explorer serves the files of documents and embedded images itself (see [Serving files](#serving-files)).
|
|
431
441
|
|
|
442
|
+
### Table files
|
|
443
|
+
|
|
444
|
+
A spreadsheet document shows its file under the file header (its name; Open in a new tab, which shows the file as plain text; Download) as a read-only table: `@aiquants/markdown`'s table block — the grid of `@aiquants/spreadsheet`, with its zoom, copy, save as TSV and full screen —, named after the file, in the UI language and the explorer's colour scheme, filling a page pane (the block's `fill` layout, never fewer than three rows at the grid's zoom) and taking the height of its rows in a multi-view panel.
|
|
445
|
+
The file's notes and its table share one scroller under the file header, the document's scroller: in a page pane the table fills what the notes leave, and the body scrolls only when the pane is shorter than the file header, the notes, the stage's padding and the table block at its fewest — its toolbar and notice line and those three rows (at a 400 % zoom, for example).
|
|
446
|
+
|
|
447
|
+
- **Reading**: the browser reads the file itself, through the asset's plain-text delivery (`&as=text`: one request on the page's origin, never redirected to the storage), as a stream. At looks that each wait for twice the bytes the one before saw (the first after 64 KiB) it makes the table of what it has, so the looks together parse less than twice the bytes read, and it stops reading — cancelling the rest of the request — once the cell budget refuses a row (the 100,000 cells a grid operates on at once, `SPREADSHEET_MAX_OPERATION_CELLS`) or the bytes reach `spreadsheets.maxBytes` (default 2 MiB);
|
|
448
|
+
columns past the 1,000th are left out, so the widest table still shows 100 rows, and a cell keeps at most the 32,767 characters a cell of Excel holds, so one long cell cannot stall the grid's layout. A file read partway yields only the rows the rest of it cannot change — every row a line break ends, up to a quoted cell the bytes read do not close —, so the rows shown are always the file's first rows, wherever the reading stopped. A table that is not the whole file says so above it (the label `spreadsheetTruncated`), and a file in whose first `spreadsheets.maxBytes` no row ends — its first row runs past them, or, in a TSV, a quote that opens in it closes nowhere within them — shows a note that it cannot be shown as a table (`spreadsheetLongRow`), with the download.
|
|
449
|
+
- **Text**: the bytes are read by the explorer's one rule: the encoding a byte order mark names (UTF-8, UTF-16LE or UTF-16BE), else UTF-8, else the configuration's `legacyTextEncoding` (for example `Shift_JIS`, in which a Japanese spreadsheet application writes CSV), each strictly and never guessed, and decided on the bytes read when the reading stops: a file that is UTF-8 up to there shows as UTF-8 even if a later byte is not. Bytes none of them reads show a note naming the encodings tried by their written names (`spreadsheetUnreadableEncoding`:
|
|
450
|
+
the one a byte order mark names, or UTF-8 and the legacy encoding), text holding NUL a note that the file is not text (`spreadsheetNotText`), each with the download, and a file without data — read whole, its cells, taken whole within the budget, all empty, or none at all — a note that it has no data (`spreadsheetEmpty`; a file whose empty cells run past the budget shows them as a table that is only part of the file).
|
|
451
|
+
- **Rows**: CSV by RFC 4180 — rows end at CRLF, LF or CR; a cell that starts with `"` is quoted and holds commas and line breaks, `""` standing for one `"`; the text after its closing quote joins the cell up to the next comma or line break, as Excel reads it; a quote that never closes holds the rest of the file — and TSV by `@aiquants/spreadsheet`'s grammar, the one a ```spreadsheets block reads. Rows of different widths are padded with empty cells.
|
|
452
|
+
- **States**: the skeleton until the first reading, after which a page view announces the document; a failure before anything was read (the asset answering one, or the connection breaking) shows the failure view with its retry and is announced as a document's failure, alone (in a multi-view panel through the panel's announcer), and a retry that succeeds moves the focus into the table's body and, in a page view, announces the document, as the pane does for a document that replaces a failure;
|
|
453
|
+
every new answer for the document reads the file again with the previous table on screen and the region busy (its progress line and `aria-busy`). Refresh document waits for that reading and reports it once: as reloaded, or, when the reading fails, in the bar's notice (`documentRefreshFailed`) with the table kept; a background answer whose reading fails keeps the table without a word, as a background failure keeps a loaded document. Leaving the view aborts the reading. A document shown as written (its Source) behaves the same way.
|
|
454
|
+
- **As written**: the document bar's Source toggle shows the file's CSV or TSV as written (its tooltip names which), read through the `text` operation by the same rule.
|
|
455
|
+
- **Workbooks**: a `firstSheetOnly` document shows the note `spreadsheetFirstSheetOnly` above the table, and an `external` edit puts the link to the workbook's own editor in the bar.
|
|
456
|
+
|
|
457
|
+
`createFileSystemSource` answers `.csv` files as `csv` and `.tsv` and `.tab` files as `tsv`, never `firstSheetOnly` and without an editor. Excel and OpenDocument workbooks stay `file` documents (downloads): the explorer reads no workbook format.
|
|
458
|
+
|
|
432
459
|
### Editing
|
|
433
460
|
|
|
434
461
|
Give `createMarkdownExplorer` the editor's ports as `edit` (`ExplorerEditPorts`) and answer `edit: { kind: "inline" }` for the markdown documents a reader may edit, or `edit: { kind: "draft" }` for those they may edit but not save: `source` answers those with `{ kind: "draft", text }`, the text alone, and such a session never calls `save`, `revisions` or `revision` (refuse them there all the same).
|
|
@@ -504,13 +531,16 @@ Names the tree cannot carry — not in NFC, with a colon, ending in a dot or a s
|
|
|
504
531
|
| `maxEntries?` | `number` | The most entries a tree may list before it is `too-large` (default 20000). |
|
|
505
532
|
| `maxDocumentBytes?` | `number` | The largest Markdown file read (default 2 MiB); a larger one is `too-large`. |
|
|
506
533
|
| `textPreviewBytes?` | `number` | How many leading bytes of a text file are shown (default 8 KiB). |
|
|
534
|
+
| `legacyTextEncoding?` | `string \| null` | The legacy encoding of the source's text and Markdown files, read by the explorer's rule like every file the explorer reads as text: a byte order mark's encoding, else UTF-8, else this; bytes none of them reads show in the first encoding tried, with U+FFFD for each sequence it cannot read, and a text file whose decoded text holds NUL is a `file` document. A label `legacyTextEncodingOf` accepts, or `null` for none, so the resolved configuration's `legacyTextEncoding` passes as it is. None when omitted. |
|
|
507
535
|
| `walkConcurrency?` | `number` | The most directories the walk reads at once (default 8). |
|
|
508
536
|
| `cacheScope?` | `"principal" \| "shared"` | Who shares the cached tree: `"principal"` (default), or `"shared"` when the tree does not depend on the reader. Keep `"principal"` when you wrap the source to filter its tree per reader. |
|
|
509
537
|
| `reportSkipped?` | `(skipped: FileSystemSkippedEntry) => void` | Receives each name the walk leaves out (`sourceId`, `path` and a `FileSystemSkipReason`), once per path (default: a `console.warn`). |
|
|
510
538
|
|
|
511
539
|
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.
|
|
512
540
|
|
|
513
|
-
|
|
541
|
+
A host's own sources read text by the same rule through the exports of `@aiquants/markdown-explorer/server`: `legacyTextEncodingOf(label)` (a label's written name, or a `RangeError` for a label that cannot name the legacy encoding), `decodeText(bytes, complete, legacyEncoding)` (strict: the text, or `null` when no encoding of the rule reads the bytes) and `decodeTextLeniently(bytes, complete, legacyEncoding)` (the first encoding tried, with U+FFFD, when none reads them). `legacyEncoding` is a label `legacyTextEncodingOf` accepts, or `null` for none — the resolved configuration's `legacyTextEncoding` as it is —, and the decoders refuse the labels it refuses with the same `RangeError`. `complete` says the bytes are the whole file; otherwise a character their end cut is left out, and bytes that end within a byte order mark read nothing yet.
|
|
542
|
+
|
|
543
|
+
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 decoded preview holds NUL, is a `file` document.
|
|
514
544
|
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.
|
|
515
545
|
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.
|
|
516
546
|
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.
|
|
@@ -542,7 +572,7 @@ export const explorer = createMarkdownExplorer({
|
|
|
542
572
|
### Serving files
|
|
543
573
|
|
|
544
574
|
The explorer serves every file it shows or offers for download itself, through the `asset` operation of its data route: `<dataPath>/asset?path=<document path>[&v=<version>][&as=text]` (GET and HEAD; see [URL contract](docs/behavior/url-contract.md#asset-urls)).
|
|
545
|
-
Images, audio, video and PDF are shown in place; every other file (Markdown, text,
|
|
575
|
+
Images, audio, video and PDF are shown in place; every other file (Markdown, text, table files, workbooks, anything else) is delivered as a download, except that `&as=text` asks for any file as UTF-8 plain text shown in place (`text/plain; charset=utf-8`, under the same `nosniff` and sandboxing policy), which is where a text viewer's Open in a new tab goes, since a browser downloads Markdown or cannot show it, and what a table file's preview reads (one request on the page's origin, since the operation reads the bytes itself and never redirects).
|
|
546
576
|
The host supplies only the bytes, through the `asset` port:
|
|
547
577
|
|
|
548
578
|
| `ExplorerAssetFile` field | Type | Meaning |
|
|
@@ -579,8 +609,11 @@ and `Cache-Control: private, max-age=60, stale-while-revalidate=600, no-transfor
|
|
|
579
609
|
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.
|
|
580
610
|
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).
|
|
581
611
|
|
|
582
|
-
The data route's `text` operation reads a file through the same port for the Source toggles (the document bar's
|
|
583
|
-
|
|
612
|
+
The data route's `text` operation reads a file through the same port for the Source toggles (the document bar's — a Markdown document, an SVG image, a table file — and that of an SVG image inside a rendered document) and that image's Copy:
|
|
613
|
+
`<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.
|
|
614
|
+
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),
|
|
615
|
+
cancels the stream once enough was read, decodes them by the explorer's one rule — the encoding a byte order mark names (the mark dropped), else UTF-8, else the configuration's `legacyTextEncoding`, each strictly, and bytes none of them reads in the first encoding tried with U+FFFD for each sequence it cannot read (a character the limit cuts left out; `decodeTextLeniently`) —, and answers `unsupported` for text holding NUL and `failed` (logged) for a stream that ends before the `size` the port reported.
|
|
616
|
+
It sends no refresh mark: the port receives `refresh: false`.
|
|
584
617
|
|
|
585
618
|
### Redirecting to the storage
|
|
586
619
|
|
|
@@ -864,7 +897,8 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
|
|
|
864
897
|
- 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.
|
|
865
898
|
- 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.
|
|
866
899
|
- 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)).
|
|
867
|
-
- The source of a Markdown document
|
|
900
|
+
- The source of a Markdown document, an SVG image or a table file (the Source toggles: the document bar's, and that of an SVG image inside a rendered document, and that image's Copy) 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 by the explorer's rule into JSON, which the browser shows as text and never interprets.
|
|
901
|
+
- A table file's preview reads the file's bytes through the asset's plain-text delivery, the download the reader already has, and puts its cells into the grid as text (a cell is never markup or a link). What the grid copies and saves is each cell's text as read, so a cell a spreadsheet application reads as a formula stays one there, exactly as in the downloaded file.
|
|
868
902
|
- 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`).
|
|
869
903
|
- 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.
|
|
870
904
|
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.
|
|
@@ -886,7 +920,12 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
886
920
|
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.
|
|
887
921
|
- 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.
|
|
888
922
|
- 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.
|
|
889
|
-
- Document kinds are the
|
|
923
|
+
- Document kinds are the six above; `createFileSystemSource` previews only files with a known text extension or name as text, shows `.csv`, `.tsv` and `.tab` files as tables, and offers any other file as a `file` document (a download). The explorer reads no workbook format (Excel, OpenDocument): a workbook shows as a table only when the host exports it as CSV or TSV, and then as one sheet.
|
|
924
|
+
- A table file's preview shows at most the 100,000 cells a grid operates on at once, 1,000 columns and 32,767 characters of a cell, and reads at most `spreadsheets.maxBytes` of the file, which it parses on the browser's main thread (a row of more cells than a preview shows is still read whole: a single 2 MiB row of commas or tabs takes a few tenths of a second, where 2 MiB of ordinary rows stops at the cell budget in about a hundredth). It reads no encoding the file does not mark or the configuration does not name:
|
|
925
|
+
a UTF-8 file with a few stray bytes shows the encoding note instead of a table (or, with a legacy encoding configured, is read in that encoding). The encoding is decided on the bytes each view reads, so the table and the Source view of a file whose encoding changes past where one of them stopped reading may read it differently.
|
|
926
|
+
- A TSV file read partway shows only the rows before the first cell that opens a quote the bytes read do not close (a lone `"` used as a ditto mark, for example), since the rest of the file could still close it: a TSV larger than `spreadsheets.maxBytes` with such a cell near its start shows only the rows above it — or, with no row above it, the note that no row ends within the part read (`spreadsheetLongRow`) —, where read whole it shows every row (an unclosed quote is literal in a whole TSV). A CSV is not affected (an unclosed quote holds the rest of a whole CSV too).
|
|
927
|
+
- Text is decoded by the runtime's `TextDecoder`, and runtimes answer a few bytes differently from the Encoding Standard: Node refuses the byte 0x80 in Shift_JIS (the standard reads it as U+0080) and reads it as U+0080 in Big5 and EUC-KR (the standard refuses it). A file holding such a byte can therefore show as a table in the browser while its Source, read on the server, falls back to the first encoding tried with U+FFFD, or the other way round.
|
|
928
|
+
- Open in a new tab shows a text or table file as UTF-8 plain text (`as=text`) whatever `legacyTextEncoding` names: the server would have to read the whole file to name its encoding, which a HEAD or ranged request never does, so a file in the legacy encoding shows garbled there, while the explorer's own views read it in that encoding (a table, a Source view, and the text preview of a file-system source given the same encoding).
|
|
890
929
|
- 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,
|
|
891
930
|
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`.
|
|
892
931
|
- All anonymous readers share one scope, so they share the admission budget as well as the running share: with `anonymousAccess`, the `jobsPerScope` documents running or waiting are counted for all visitors together, and panels beyond that budget come back `failed` until a reload or "Try again". For a public deployment, set `jobsPerScope` to the number of visitors expected to open a multi view at the same moment times `multiView.maxPanels`; `maxQueuedJobs` then defaults to four times that.
|
|
@@ -901,7 +940,8 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
901
940
|
The source repository holds a runnable demo next to the package (`packages/markdown-explorer/demo`): three file-system sources with anonymous access (`guide` and `notes`, kept apart by their path prefix, with one folder of the guide, `guide/a`, served lazily through `children`; and `reference`, rooted at the folder `guide/reference` inside `guide`, so a document under it appears in two trees under the same path),
|
|
902
941
|
the page and data routes, the error boundary, document and asset ports that route each path to the first source whose boundary contains it (no asset route of its own), a Markdown parser that produces document links and image targets, GitHub alerts, Zenn's message and details containers, embed placeholders, and footnotes, task lists and formulas in the Go converter's markup,
|
|
903
942
|
every embed provider and link cards served by the data route (`embeds: { providers, linkCards: true }`; `guide/reference/embeds.md` and `guide/reference/link-cards.md` show them; the end-to-end tests answer the browser's card requests from their own fixtures, so they stay offline),
|
|
904
|
-
editing (the parser writes source lines; the Markdown of `notes` is edited in place and saved to memory, never to the files, per draft space named by a cookie so tests never share saves; `guide/reference/embeds.md` links to an external editor),
|
|
943
|
+
editing (the parser writes source lines; the Markdown of `notes` is edited in place and saved to memory, never to the files, per draft space named by a cookie so tests never share saves; `guide/reference/embeds.md` links to an external editor), table files (`notes/tables`: a UTF-8 CSV with quoted cells, a Shift_JIS CSV read through `legacyTextEncoding:
|
|
944
|
+
"Shift_JIS"`, which the demo gives its file-system sources too, a TSV, and a CSV wider than the preview's 1,000 columns), the instant preview with `@aiquants/markdown`'s browser converter as `draftConverter` (`demo/app/draft-converter.client.ts`), and the end-to-end tests' fixtures.
|
|
905
945
|
Run it with `pnpm run demo:dev` from the package folder.
|
|
906
946
|
|
|
907
947
|
## License
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),h=require("react"),
|
|
2
|
-
`);e.dispatch({changes:{from:
|
|
3
|
-
`:v.content}return{kind:"found",firstLine:t+1,lines:c,layout:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("react/jsx-runtime"),h=require("react"),y=require("./index-BwTVYkTR.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-Cv7fgCW7.cjs"),de=require("./sanitizePolicy-CZwOaJ92.cjs"),ze=require("isomorphic-dompurify"),se=require("@aiquants/resize-panels"),X=require("./location-CasigkBk.cjs"),ve=require("./useSplitPersistence-Bmpb2prR.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=>y.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 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=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
4
|
`?`
|
|
5
|
-
`:""}${I.lines.map(
|
|
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;
|
|
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 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=y.visibleTopOf(u,c.contentDOM),v=y.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-y.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(qe),destroy:()=>c.destroy()}},xe=(e,t,n,r)=>{const i=r.scrollerOf(e.scrollDOM),o=(n===null?y.visibleTopOf(i,e.contentDOM):n)-y.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=y.frameTopOf(o),s=y.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,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,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,S?.abort(),S=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;S=T,v=setTimeout(()=>{v=void 0,n(e,w.text,T.signal).then(C=>{if(!(T.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,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,S=()=>{};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&&(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(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(),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=y.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-y.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}=y.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(d.iframeHosts,d.dataPath,k,p,e),A=g(),R=ft({path:e,instant:a,preview:f.preview,initial:S.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:y.anchorOfView(A,a(R))},place:({line:a,clientTop:A},R)=>{const w=m.current,T=w===null?null:y.blockAtLine(w,a);T!==null&&(R(T).scrollTop+=y.lineTopIn(T,a)-A)}}),[]);const D=a=>{const A=m.current,{target:R}=a;if(o===void 0||A===null||!(R instanceof Element)||!y.isEditingDoubleClick(R))return;const w=y.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,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(y.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}=y.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="[data-aqmd-spreadsheet-fullscreen]",_t=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"},Pt=e=>{e.stopPropagation()},Nt=e=>{const{path:t,name:n,session:r}=e,{edits:i,labels:o,announcer:l}=y.useExplorer(),{phase:s}=r,d=h.useCallback(()=>i.retry(t),[i,t]);switch(h.useEffect(()=>{s.kind==="failed"&&l.announce(o.documentFailed(n,y.failureTitleOf(o,s.failure.reason)))},[s,l,o,n]),s.kind){case"opening":return q.jsx(y.ContentSkeleton,{label:o.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(y.EditGrantNotice,{href:s.href,onRetry:d,testId:"markdown-explorer-edit-grant"})});case"failed":return q.jsx("div",{className:"aqmx-edit-message",children:q.jsx(y.FailureView,{failure:s.failure,alert:!1,onRetry:d,testId:"markdown-explorer-edit-failure"})});case"editing":return q.jsx(Dt,{...e})}},Dt=({path:e,name:t,session:n,layout:r,viewer:i,region:o,paneScroll:l})=>{const{edits:s,labels:d}=y.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",S=y.useSideBySide(),g=y.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),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=_t(_)&&_.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(y.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(y.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(y.paneShownAlone(M.current.view)),m.current=x,()=>{x.dispose(),m.current=null}},[O,s,e,H]),h.useLayoutEffect(()=>{m.current?.showAlone(y.paneShownAlone(g))},[g]);const T=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"){y.consumeKey(b);return}if(!y.isEditViewShortcut(b.nativeEvent,y.isApplePlatform(navigator.platform)))return;y.consumeKey(b);const x=y.toggledEditView(g);B.current=x,y.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:Pt,children:[q.jsx("div",{ref:f,id:p,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:g==="preview",hidden:g==="preview"&&!v,...y.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=Nt;
|