@aiquants/markdown-explorer 0.34.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +515 -0
- package/README.md +90 -39
- package/dist/EditSurface-CLG70Vnn.cjs +6 -0
- package/dist/EditSurface-D2j1kCEE.js +990 -0
- package/dist/ExplorerSplit-CfP1smbT.js +1589 -0
- package/dist/ExplorerSplit-D_0VohOv.cjs +2 -0
- package/dist/{MultiLayout-kcZyVnvK.js → MultiLayout-BeJ5Lubb.js} +249 -248
- package/dist/MultiLayout-CxV5SI7f.cjs +1 -0
- package/dist/{NativeScrollBar-UNed10Na.js → NativeScrollBar-BM5NULzg.js} +2 -2
- package/dist/{NativeScrollBar-pUbA4Zq3.cjs → NativeScrollBar-RWXpVhbI.cjs} +1 -1
- package/dist/TreeLayout-AxLw-36S.js +103 -0
- package/dist/TreeLayout-Bg2YH-EY.cjs +1 -0
- package/dist/client/MarkdownExplorer.d.cts +14 -1
- package/dist/client/MarkdownExplorer.d.ts +14 -1
- package/dist/client/edit/lineEndings.d.cts +4 -0
- package/dist/client/edit/lineEndings.d.ts +4 -0
- package/dist/client/hostContract.d.cts +67 -0
- package/dist/client/hostContract.d.ts +67 -0
- package/dist/core/config.d.cts +7 -0
- package/dist/core/config.d.ts +7 -0
- package/dist/core/contracts.d.cts +10 -4
- package/dist/core/contracts.d.ts +10 -4
- package/dist/core/draftAnswer.d.cts +23 -0
- package/dist/core/draftAnswer.d.ts +23 -0
- package/dist/core/labels.d.cts +68 -0
- package/dist/core/labels.d.ts +68 -0
- package/dist/core/location.d.cts +1 -2
- package/dist/core/location.d.ts +1 -2
- package/dist/core/ownUrls.d.cts +15 -0
- package/dist/core/ownUrls.d.ts +15 -0
- package/dist/core/treeSettings.d.cts +3 -2
- package/dist/core/treeSettings.d.ts +3 -2
- package/dist/core/viewSettings.d.cts +3 -1
- package/dist/core/viewSettings.d.ts +3 -1
- package/dist/describeValue-CLlVRO8d.js +17 -0
- package/dist/describeValue-Ccvhbt36.cjs +1 -0
- package/dist/explorerCore-DLpDuSev.js +998 -0
- package/dist/explorerCore-DYrxS9ez.cjs +1 -0
- package/dist/index-C1YMH-yI.js +5816 -0
- package/dist/index-LQWQfpAf.cjs +18 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.js +49 -44
- package/dist/licenses/@heroicons/react/LICENSE +21 -0
- package/dist/licenses/entities/LICENSE +11 -0
- package/dist/licenses/parse5/LICENSE +19 -0
- package/dist/location--KvTA0Ri.js +726 -0
- package/dist/location-D8DyDkuA.cjs +1 -0
- package/dist/lru-DC8GBmkX.js +39 -0
- package/dist/lru-SGmUyBQU.cjs +1 -0
- package/dist/{merge-C1MWvhCS.js → merge-Bb_HpPhe.js} +1 -1
- package/dist/{merge-BziXxZkE.cjs → merge-DQUYEGCx.cjs} +1 -1
- package/dist/nestingGuardWorker.js +5511 -0
- package/dist/ownUrls-B259RGgd.cjs +1 -0
- package/dist/ownUrls-Dh5g6ZJi.js +370 -0
- package/dist/sanitizeJob-BYRk17nr.js +21 -0
- package/dist/sanitizeJob-Cs9o3Vpl.cjs +1 -0
- package/dist/sanitizePolicy-CEMdaLUB.js +139 -0
- package/dist/sanitizePolicy-CiQfnxyd.cjs +2 -0
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +134 -139
- package/dist/sanitizerService-BY4CPCoA.cjs +1 -0
- package/dist/sanitizerService-KWXv7bPm.js +240 -0
- package/dist/server/assetResponse.d.cts +60 -0
- package/dist/server/assetResponse.d.ts +60 -0
- package/dist/server/browser/browserPlatform.d.cts +12 -0
- package/dist/server/browser/browserPlatform.d.ts +12 -0
- package/dist/server/createMarkdownExplorer.d.cts +0 -10
- package/dist/server/createMarkdownExplorer.d.ts +0 -10
- package/dist/server/explorerCore.d.cts +12 -0
- package/dist/server/explorerCore.d.ts +12 -0
- package/dist/server/fileSystemSource.d.cts +1 -0
- package/dist/server/fileSystemSource.d.ts +1 -0
- package/dist/server/inProcessFetch.d.cts +5 -0
- package/dist/server/inProcessFetch.d.ts +5 -0
- package/dist/server/platform.d.cts +18 -0
- package/dist/server/platform.d.ts +18 -0
- package/dist/server/ports.d.cts +36 -5
- package/dist/server/ports.d.ts +36 -5
- package/dist/server/sanitizeProtocol.d.cts +3 -0
- package/dist/server/sanitizeProtocol.d.ts +3 -0
- package/dist/server/sanitizer.d.cts +5 -40
- package/dist/server/sanitizer.d.ts +5 -40
- package/dist/server/sanitizerOptions.d.cts +24 -0
- package/dist/server/sanitizerOptions.d.ts +24 -0
- package/dist/server/sanitizerService.d.cts +41 -0
- package/dist/server/sanitizerService.d.ts +41 -0
- package/dist/server/{workerPool.d.cts → workerJobs.d.cts} +0 -16
- package/dist/server/{workerPool.d.ts → workerJobs.d.ts} +0 -16
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +3 -1
- package/dist/server.d.ts +3 -1
- package/dist/server.js +270 -1343
- package/dist/serverBrowser.cjs +1 -0
- package/dist/serverBrowser.d.cts +1 -0
- package/dist/serverBrowser.d.ts +1 -0
- package/dist/serverBrowser.js +120 -0
- package/dist/serverCore.cjs +1 -0
- package/dist/serverCore.d.cts +14 -0
- package/dist/serverCore.d.ts +14 -0
- package/dist/serverCore.js +46 -0
- package/dist/storage-BpYsprog.cjs +1 -0
- package/dist/{storage-CmGHg7OA.js → storage-D1uSw-xj.js} +19 -18
- package/dist/storage.cjs +1 -1
- package/dist/storage.js +1 -1
- package/dist/styles/markdown-explorer.css +1 -1
- package/dist/{tapScrollCircle-D_BpaLwY.js → tapScrollCircle-BEydRn0y.js} +1 -1
- package/dist/{tapScrollCircle-DigcJCsu.cjs → tapScrollCircle-DdX0Wri0.cjs} +1 -1
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +6 -0
- package/dist/testing.d.ts +6 -0
- package/dist/testing.js +4 -0
- package/dist/useSplitPersistence-B2Fj508K.cjs +1 -0
- package/dist/useSplitPersistence-Fkqak8G8.js +44 -0
- package/docs/behavior/dom-hooks.md +2 -0
- package/docs/behavior/hosting.md +123 -0
- package/docs/behavior/layout.md +5 -3
- package/docs/behavior/localization.md +25 -8
- package/docs/behavior/security.md +32 -13
- package/docs/behavior/url-contract.md +4 -3
- package/package.json +48 -10
- package/dist/EditSurface-CF82jZQg.cjs +0 -6
- package/dist/EditSurface-CqHk2R3k.js +0 -982
- package/dist/ExplorerSplit-D325YGEf.cjs +0 -1
- package/dist/ExplorerSplit-DGH9bckm.js +0 -1500
- package/dist/MultiLayout-CzR7yJ0m.cjs +0 -1
- package/dist/TreeLayout-BnIU87HX.js +0 -96
- package/dist/TreeLayout-DtvIpuOe.cjs +0 -1
- package/dist/dataRoute-D6KiSHIc.js +0 -298
- package/dist/dataRoute-DwYtgyt6.cjs +0 -1
- package/dist/index-BDCbvHDs.cjs +0 -15
- package/dist/index-DR31S_-4.js +0 -5012
- package/dist/location-C44b9H1S.js +0 -676
- package/dist/location-hGLhCCg4.cjs +0 -1
- package/dist/sanitizePolicy-CwvyPpp5.js +0 -98
- package/dist/sanitizePolicy-T5T-3vV5.cjs +0 -1
- package/dist/storage-DM0EvkVf.cjs +0 -1
- package/dist/useSplitPersistence-DCeYbJMx.js +0 -38
- package/dist/useSplitPersistence-QGcvyMAa.cjs +0 -1
package/README.md
CHANGED
|
@@ -50,16 +50,19 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
|
|
|
50
50
|
|
|
51
51
|
- React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
|
|
52
52
|
- 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)`.
|
|
53
|
-
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^
|
|
53
|
+
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^13.0.0 (document rendering;
|
|
54
|
+
the column width and colour pair a reader picks in its display popover (`CONTENT_MEASURES` and `CONTENT_COLORS` of `@aiquants/markdown/viewer-settings`) and the labels of the popover's sections and of a diagram's notices, a document's language for its content (`contentLang`) apart from the UI language of the labels the explorer passes (`labelsLang`), and the size of a document table's tap-scroll circle (`spreadsheetTapScrollCircle`'s `size`);
|
|
54
55
|
the gutter its scroll container keeps beside the explorer's bar for the tap-scroll circle (`scrollBarGutter`, given as a custom property that a media query sets), code blocks whose Copy button sits in a header row above the code, and documents whose front matter does not render; the Source toggle of a storage SVG image that stands alone in a paragraph, read through `imageSource`, and a Copy that copies the image as a PNG image or its source, the source readable in every display style, a notice in place of a block that cannot render and plain text for a fence in a language it does not know;
|
|
55
56
|
the full screen of its tables, Mermaid diagrams and SVG images, which every block marks with the same DOM hook (`data-aqmd-fullscreen`), and `DEFAULT_MARKDOWN_STYLE`, the style a document starts in by default; its components' stylesheet without utilities,
|
|
56
57
|
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, with the display options `toolbar=`, `zoom=`, `headings=`, `autofit=`, `frame=` and `tapscroll=` (the circle in the look the explorer passes as `spreadsheetTapScrollCircle`, or `tapScrollCircle` on a table file's block), the tables' bar controls the explorer passes for the reader's pointer (`spreadsheetScrollBarControls`, or `scrollBarControls` on a table file's block),
|
|
57
58
|
every row shown when `height` reaches the table's, and boxes no wider than the table — 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,
|
|
58
59
|
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,
|
|
59
|
-
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,
|
|
60
|
+
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,
|
|
61
|
+
the Node-only link-card handler of `@aiquants/markdown/server`, which opens pages only through the markdown service, answers its own `500` without it and needs Node.js 22.13 or later (below the explorer's own floor), and the core of that handler in `@aiquants/markdown/link-cards`, which the browser runtime builds on the host's `pageFetch`),
|
|
60
62
|
`@aiquants/directory-tree` ^6.1.1 (rows that take paint and text styles only and have no vertical padding, a `removeRootIndent` shift that keeps the root's icon whole, reveals of rows under the scroll bar's buttons, the connector lines and expand glyphs drawn above the rows, its built-in colours from a `light-dark()` palette that follows the explorer's `color-scheme`, a pending expansion that marks the tree busy without dimming it,
|
|
61
63
|
and the expansion applied from the first render of a client mount, by which a tree that mounts again — the explorer reopened, the sheet opened — starts with the row that was at its top),
|
|
62
|
-
`@aiquants/drag-drop-panels` ^0.14.0 (`isMaximizeEscape`, by which Escape restores the tree view's maximized document as it does a maximized panel, the panel headers' move menu, named by the explorer's `panelMove`, their overflow menu, named by `panelMoreActions`, which takes the leading buttons a narrow header's row has no room for, their 44 px buttons under every pointer and the header arrangement the behavior docs follow),
|
|
64
|
+
`@aiquants/drag-drop-panels` ^0.14.0 (`isMaximizeEscape`, by which Escape restores the tree view's maximized document as it does a maximized panel, the panel headers' move menu, named by the explorer's `panelMove`, their overflow menu, named by `panelMoreActions`, which takes the leading buttons a narrow header's row has no room for, their 44 px buttons under every pointer and the header arrangement the behavior docs follow),
|
|
65
|
+
`@aiquants/resize-panels` ^2.3.0 (the source of each layout change, by which the tree pane's width is saved, and `PanelGroup`'s `labels` (`PanelGroupLabelKey`), by which the placeholder it draws over a split that cannot fit its panels reads in the explorer's labels),
|
|
63
66
|
`@aiquants/spreadsheet` ^0.20.0 (the grid of those tables — one `role="grid"` with header rows, the content size a box is fitted to, a keyboard move the document follows, a frame around a range that ends where the range does, under a frozen row and in a right-to-left page too, command chords that type nothing kept from the browser while a cell is being edited, and bars whose arrow buttons, thumb drag and track click a host can leave out (`scrollBarControls`),
|
|
64
67
|
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.24.0 (44 px scroll-to-edge pills and tap-scroll circles, the pills' text at the body step, and under a coarse pointer bars without
|
|
65
68
|
arrows (`showArrowButtons`) whose circles show only while the reader scrolls (`tapScrollCircleOptions.visibility`)).
|
|
@@ -75,7 +78,9 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
|
|
|
75
78
|
pnpm add @aiquants/markdown-explorer @aiquants/markdown @aiquants/directory-tree @aiquants/drag-drop-panels @aiquants/resize-panels @aiquants/virtualscroll
|
|
76
79
|
```
|
|
77
80
|
|
|
78
|
-
The package
|
|
81
|
+
The package's entries are `@aiquants/markdown-explorer` (the browser half: `<MarkdownExplorer>`, the shared configuration and links), `@aiquants/markdown-explorer/server` (the server half on Node), `@aiquants/markdown-explorer/storage` (`clearExplorerStorage` only, with no dependencies), `@aiquants/markdown-explorer/testing` (the answers the deny rules owe, for tests) and the stylesheet `@aiquants/markdown-explorer/styles/markdown-explorer.css`.
|
|
82
|
+
The server half's runtime-independent core is `@aiquants/markdown-explorer/server/core`, and `@aiquants/markdown-explorer/server/browser` is the runtime that runs it inside the page, with its worker `@aiquants/markdown-explorer/server/browser/nesting-guard-worker`.
|
|
83
|
+
[Hosting](docs/behavior/hosting.md) lists what each entry never loads and gives the steps for running the server half inside the page, as a desktop webview does.
|
|
79
84
|
|
|
80
85
|
## Quick start
|
|
81
86
|
|
|
@@ -107,11 +112,13 @@ The source ids are not part of it: they are the ids of the server's `sources` (a
|
|
|
107
112
|
| `multiView?` | `{ maxPanels?, columns? }` | The panel limit (1–64, default 12) and the logical column count (1–6, default 4). |
|
|
108
113
|
| `expandAll?` | `{ maxFolders?, maxDepth? }` | Expand all's budget per press (see [Expand all and Collapse all](#expand-all-and-collapse-all)): the folder listings a press may start (1–10,000, default 500, `EXPAND_ALL_FOLDER_LIMITS`) and the deepest level (the top being 1) at which it opens a folder of unknown contents (1–64, default 16, `EXPAND_ALL_DEPTH_LIMITS`). Each field defaults on its own, also when given as `undefined`; a value that is not an integer within its bounds or an unknown key throws a `RangeError` naming the field, and anything but a plain object a `TypeError`. |
|
|
109
114
|
| `revealDocument?` | `{ maxDepth? }` | The deepest document whose folders the reader's "Reveal the open document" setting opens, counted in folders between the source's top level and the document (1–64, default 16, `REVEAL_DOCUMENT_DEPTH_LIMITS`); a deeper document is not revealed. Each folder of the chain takes at most one listing, so this also bounds a reveal's listings. The field defaults on its own, also when given as `undefined`; an unknown key throws a `RangeError`, anything but a plain object a `TypeError` (see [Revealing the open document](#revealing-the-open-document)). |
|
|
110
|
-
| `documentStyles?` | `readonly { name, className }[]` | Document styles, in the order the viewer's
|
|
115
|
+
| `documentStyles?` | `readonly { name, className }[]` | Document styles, in the order the style section of the viewer's display popover lists them; `@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLES` (None, GitHub, Zenn; also exported without React from `@aiquants/markdown/viewer-settings`) when omitted. |
|
|
111
116
|
| `defaultDocumentStyle?` | `string` | The style a document starts in while neither the URL (`style`) nor the reader's saved preference names one: the name of one of `documentStyles`, matched exactly (`"zenn"` is not `"Zenn"`). `@aiquants/markdown`'s `DEFAULT_MARKDOWN_STYLE` (`"Zenn"`, also exported from `@aiquants/markdown/viewer-settings`) when omitted, also when given as `undefined`; it never falls back to the first style, so a host whose `documentStyles` leave Zenn out names its own, or the configuration throws. A name that is not one of `documentStyles` throws a `RangeError` naming the styles, and anything but a string a `TypeError`. |
|
|
112
117
|
| `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. |
|
|
118
|
+
| `appOrigins?` | `readonly string[]` | The origins the app's own pages are served from, as the browser writes them (`scheme://host[:port]`, such as `http://wails.localhost` or `wails://localhost`): a document's absolute URL of one of them is the app's own, like a relative or path-absolute one, and stays only under the paths its use allows (see [Security](docs/behavior/security.md#html)). None by default. |
|
|
119
|
+
| `mediaDataPath?` | `string` | An absolute `http:` or `https:` URL, of an origin and a mount path, that the asset URLs of videos, audio and PDF documents are built on instead of the data route (a separate media server's data route, for example); a document's `video`, `audio` and `source` may then use it too. None by default (see [Hosting](docs/behavior/hosting.md#the-apps-own-urls-apporigins-and-mediadatapath)). |
|
|
113
120
|
| `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. |
|
|
114
|
-
| `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)). |
|
|
121
|
+
| `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, folder READMEs shown, 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`, `showFolderReadme`, `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)). |
|
|
115
122
|
| `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. |
|
|
116
123
|
| `spreadsheets?` | `{ maxBytes?, maxWorkbookBytes? }` | A table file's preview (see [Table files](#table-files)). `maxBytes`: the most bytes the browser reads of a CSV or TSV 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; 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. `maxWorkbookBytes`: the most bytes the browser reads of a workbook, which it needs whole (a positive integer up to 256 MiB; default 8 MiB; `WORKBOOK_BYTE_LIMITS`); a larger workbook shows a note with the download, or its first sheet as text when the document names one. Each field defaults on its own, also when given as `undefined`. |
|
|
117
124
|
|
|
@@ -138,6 +145,7 @@ const handbook = createFileSystemSource({
|
|
|
138
145
|
label: "Handbook",
|
|
139
146
|
root: resolve(contentRoot),
|
|
140
147
|
pathPrefix: "", // required: "" publishes the whole root
|
|
148
|
+
lang: "en", // required: the language of its Markdown and text documents
|
|
141
149
|
parse: renderMarkdown,
|
|
142
150
|
})
|
|
143
151
|
|
|
@@ -318,9 +326,14 @@ The full contract, including canonicalization, is in [URL contract](docs/behavio
|
|
|
318
326
|
|
|
319
327
|
### Folders and their READMEs
|
|
320
328
|
|
|
321
|
-
In the tree view a folder can be selected as GitHub's file tree does, and the view then shows the folder's README beside the tree.
|
|
329
|
+
In the tree view a folder can be selected as GitHub's file tree does, and the view then shows the folder's README beside the tree. The reader's tree setting "Show folder READMEs" (`showFolderReadme`, on in `DEFAULT_TREE_SETTINGS`) ties the README the view shows to the folders' opening and closing; with it off, a press on a folder only opens or closes it, and a folder URL still shows the folder's README. In the multi-panel view a press on a folder only opens or closes it, and its menu does not offer the setting.
|
|
322
330
|
|
|
323
|
-
- **
|
|
331
|
+
- **Opening a folder**: a press (a click, Enter or Space) that opens a folder other than the shown one shows it at the press: the URL's document is replaced with the folder (no history entry), its row is selected, and the folder opens. A press on the shown folder while it is closed only opens it.
|
|
332
|
+
- **Closing the shown folder**: a press on the shown folder while it is open moves the view up once the folder closes — at the end of the delay that tells a single press from a double click (500 ms), or at the end of a double click. The move replaces the URL's document too (a `close-folder` navigation, which leaves an explorer sheet open: it picks no destination), so repeated presses walk up one level at a time. If the reader shows something else before the folder closes, the view stays on it. A press on an open folder that is not the shown one only closes it.
|
|
333
|
+
- **Where the view moves up to**: the folder above the pressed row (its README, or the line saying it has none), or for a top-level folder the source's README, shown as a document because the source itself has no folder URL, or the empty pane when the source has none.
|
|
334
|
+
- **Double clicks**: a double click still opens or closes a folder with its subfolders (`doubleClickAction`); one that leaves the folder open keeps the README it showed, one that closes the shown folder moves up as a press does.
|
|
335
|
+
- **Always expanded**: a folder whose contents are known stays open, so a press on it shows it or, on the shown folder, moves up at once, and never changes the folder's hidden expansion (the one it shows once the setting is off). A lazy folder whose contents are not known yet opens and closes as usual.
|
|
336
|
+
- **Keys and Collapse all**: the arrow keys move between folders and open or close them, and Collapse all closes every folder; neither changes what the view shows.
|
|
324
337
|
- **Which README**: a README is a file whose name, ignoring case, is `README` or starts with `README.` (`README.md`, `readme.txt`, `README.ja.md`); a folder named so is not one. Among a folder's READMEs the view shows a plain name (`README` with at most one extension) before a longer one, then by extension — `md`, `markdown`, `mdx`, `txt`, none, any other —, then by name and path in the explorer's collation (`folderReadmeOf`).
|
|
325
338
|
- **Where the folder's files come from**: the children its row has in the shown source's tree; a lazy folder whose children are unknown, or a folder the loaded tree does not reach, is listed by the data route's `children` operation, as when the reader opens it. A folder the source does not have answers that operation's `not-found` (a source without `children` answers `not-found` for every folder its tree does not list).
|
|
326
339
|
- **What shows**: the README as the shown document — its refresh bar, Source toggle, editing, the switch to the multi-panel view and the selection's panels all act on it —, the skeleton while it is looked for, a line saying the folder has none (`folderReadmeMissing`, announced once per folder), or the listing's failure, announced once per failed attempt, with Try again for a transient one.
|
|
@@ -351,7 +364,8 @@ In the tree view a folder can be selected as GitHub's file tree does, and the vi
|
|
|
351
364
|
| `logger?` | `{ error(message, detail) }` | Where adapter failures and malformed source output are reported (default `console.error`). A tree or children entry with an empty name, or with a path the browser cannot address (empty, too long, a lone surrogate, a control character or a backslash — for example macOS's `Icon\r`), or outside its source's boundary, is left out together with its subtree and reported with the message `[markdown-explorer] <operation> left out an entry` and the detail `{ operation, sourceId, path, error }`, whose `error` names the reason; any other malformed listing becomes `failed`. A boundary that throws or answers malformed values is reported with the operation `boundary`, and so is the rejection of a promise a `contains` answers (it is not awaited and counts as outside). A failed authentication of a data request is reported with the operation `authenticate` and never quotes a header: `headers` that `Headers` cannot read are reported by a fixed message, and a `Response` that `authenticate` throws (React Router's `throw redirect(...)`) by its status alone; any other exception of your adapters is logged as thrown, so keep secrets out of it. |
|
|
352
365
|
| `onTreeRefreshed?` | `(key: string) => void` | Called once per tree refresh, after its reload settled (whatever its result) unless the request went away, with the refreshed tree's cache key (opaque). A multi-process host relays the key to its other processes, which call `forgetTree(key)` (see [Hosting notes](#hosting-notes)). Its return value is ignored, but a promise it returns (an asynchronous relay) is observed, never awaited: a throw, or the rejection of that promise, is logged with the operation `refresh` and does not change the response. |
|
|
353
366
|
|
|
354
|
-
It returns `{ loader, headers, dataLoader, dataAction, forgetTree }`. `
|
|
367
|
+
It returns `{ loader, headers, dataLoader, dataAction, planData, forgetTree }`. `planData` plans a data request for a host that streams a file's bytes itself (see [Streaming files yourself](docs/behavior/hosting.md#streaming-files-yourself)).
|
|
368
|
+
`forgetTree(key)` drops this process's cached tree for a key another process refreshed and supersedes a load of it that already began (its waiting requests still receive that tree, which is not kept); it starts no load and throws a `TypeError` for a non-string key. Export `headers` from the page route: it carries the loader's `Cache-Control: private, no-store` to both the HTML and the single-fetch responses.
|
|
355
369
|
`dataLoader` and `dataAction` answer a React Router single-fetch request to the data route (`<dataPath>/<operation>.data`) with a `not-found` failure (404) before authenticating or calling a source: React Router would run them for it, read the whole response and keep none of its headers but `Set-Cookie`.
|
|
356
370
|
The loader's result type is exported as `ExplorerPageLoaderResult` (`ReturnType<typeof data<ExplorerPageData>>`, named through React Router's public `data()` rather than a type React Router marks `UNSAFE_`).
|
|
357
371
|
|
|
@@ -412,8 +426,8 @@ Notices are shown in your own words, as given; a malformed notice list is logged
|
|
|
412
426
|
|
|
413
427
|
```ts
|
|
414
428
|
type ExplorerDocument =
|
|
415
|
-
| { kind: "markdown"; name: string; htmlContent: string; headings: { text: string; depth: number; id: string }[]; edit: ExplorerDocumentEdit | null }
|
|
416
|
-
| { kind: "text"; name: string; text: string; truncated: boolean; url: string }
|
|
429
|
+
| { kind: "markdown"; name: string; htmlContent: string; headings: { text: string; depth: number; id: string }[]; lang: string; edit: ExplorerDocumentEdit | null }
|
|
430
|
+
| { kind: "text"; name: string; text: string; truncated: boolean; lang: string; url: string }
|
|
417
431
|
| { kind: "image"; name: string; url: string; imageType: "raster" | "svg" }
|
|
418
432
|
| { kind: "media"; name: string; url: string; mediaType: "video" | "audio" | "pdf" }
|
|
419
433
|
| { kind: "spreadsheet"; name: string; url: string; format: "csv" | "tsv" | "workbook"; firstSheetText: "csv" | "tsv" | null; edit: ExplorerExternalEdit | null }
|
|
@@ -422,9 +436,12 @@ type ExplorerDocument =
|
|
|
422
436
|
```
|
|
423
437
|
|
|
424
438
|
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`:
|
|
425
|
-
`{ kind: "image"; name; imageType; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; version }`, `{ kind: "spreadsheet"; name; format; firstSheetText; edit; version }` and `{ kind: "file"; name; version }`.
|
|
439
|
+
`{ kind: "image"; name; imageType; version }`, `{ kind: "media"; name; mediaType; version }`, `{ kind: "text"; name; text; truncated; lang; version }`, `{ kind: "spreadsheet"; name; format; firstSheetText; edit; version }` and `{ kind: "file"; name; version }`.
|
|
426
440
|
`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)).
|
|
427
441
|
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`.
|
|
442
|
+
A markdown or text document names the language its content is written in, `lang`, which every such answer must carry: a canonical BCP 47 language tag, that is one `Intl.getCanonicalLocales` writes back unchanged (`"ja"`, `"en-US"` or `"zh-Hant-TW"`; not `"EN"`, `"en-us"`, `"en_US"` or the replaced `"iw"`).
|
|
443
|
+
Answer it from your source's settings, not from the explorer's `locale`, which is the language of the explorer's own labels; an answer without such a `lang` breaks the contract the same way.
|
|
444
|
+
The root entry and `./server/core` export that rule as `isExplorerDocumentLang(value)`: check your settings' tags with it when your server reads them, so a wrong tag stops the server there instead of failing every document of its source.
|
|
428
445
|
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.
|
|
429
446
|
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"`, `"tsv"` or `"workbook"`, an Office Open XML workbook or an OpenDocument spreadsheet, which the browser tells apart by its bytes),
|
|
430
447
|
for a workbook your storage converts on read the format of the first sheet's text it delivers when it cannot deliver the workbook (`firstSheetText`, `ExplorerSheetTextFormat`: `"csv"` or `"tsv"`; a Google Sheets spreadsheet is `"csv"`; `null` for a stored workbook and for every CSV or TSV file), and the file's own editor in `edit` (`ExplorerExternalEdit`:
|
|
@@ -548,6 +565,7 @@ Names the tree cannot carry — not in NFC, with a colon, ending in a dot or a s
|
|
|
548
565
|
| `id`, `label` | `string` | The source's id and its display name. |
|
|
549
566
|
| `root` | `string` | The folder to publish: an absolute path that exists (checked when the source is created). |
|
|
550
567
|
| `pathPrefix` | `string` | Required: the prefix of this source's document paths, ending with `/` (for example `"guide/"`), or `""` for a source over the whole root (its boundary then admits every path). The source's `boundary.contains` admits exactly the paths that start with it, and it has no `confirm`. Omitting it, or any value that is not a string, throws a `TypeError`. |
|
|
568
|
+
| `lang` | `string` | Required: the language of the source's Markdown and text documents, a canonical BCP 47 language tag (see [Documents](#documents)), which each of them carries as its `lang`. A value that is not a string throws a `TypeError`, and a string that is not such a tag (`"EN"`, `"en_US"`, `""`) a `RangeError`. |
|
|
551
569
|
| `parse` | `(markdown, docPath) => Promise<{ htmlContent, headings }>` | Turns Markdown into HTML and headings; `docPath` includes the prefix. The explorer sanitizes the HTML afterwards. |
|
|
552
570
|
| `deny?` | `string[] \| false` | Deny rules applied while walking (default `DEFAULT_DENIED_PATH_SEGMENTS`). They are separate from `createMarkdownExplorer`'s `deny`, which filters what every source lists and serves. |
|
|
553
571
|
| `maxEntries?` | `number` | The most entries a tree may list before it is `too-large` (default 20000). |
|
|
@@ -563,7 +581,7 @@ Any other option key (a misspelt limit, an option this source does not have) thr
|
|
|
563
581
|
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).
|
|
564
582
|
`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.
|
|
565
583
|
|
|
566
|
-
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.
|
|
584
|
+
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>`, a Markdown or text document carries the source's `lang`, 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.
|
|
567
585
|
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.
|
|
568
586
|
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.
|
|
569
587
|
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.
|
|
@@ -606,6 +624,7 @@ The host supplies only the bytes, through the `asset` port:
|
|
|
606
624
|
| `size` | `number \| null` | The length in bytes, `null` when the storage cannot tell (then the response has no `Content-Length` and no ranges). |
|
|
607
625
|
| `version` | `string` | An opaque validator (1 to 256 visible ASCII characters other than `"`), sent as the ETag (behind the legacy encoding for `&as=text`); the same `version` the `document` port reports for the file. |
|
|
608
626
|
| `open` | `(range: ExplorerByteRange \| null) => Promise<ReadableStream<Uint8Array>>` | Opens the bytes of `range` (`{ offset, length }`, or `null` for the whole file) of the file `version` and `size` describe (when the storage can tell that the file has changed since the port found it, refuse rather than open other bytes); called at most once per request, never for HEAD, 304, 416 or an empty file — except that `&as=text` also opens the file for a HEAD and before a range, to read the first 64 KiB that name its `charset` (those bytes as a range, or the whole file, cancelled after them, when `size` is `null`). Abort with the `context.signal` the port received; throw `ExplorerError` to refuse. |
|
|
627
|
+
| `bridge?` | `{ uri, storageVersion, readFailure }` | What a host that streams the bytes itself instead of through `open` needs (see [Streaming files yourself](docs/behavior/hosting.md#streaming-files-yourself)): the storage URI, the storage's own version a read must still find (`null` when the storage keeps none) and the host's classification of a failed read. Absent for a host that serves through `open` alone (any other value, `null` included, is a malformed answer); it never reaches the browser. |
|
|
609
628
|
|
|
610
629
|
The port serves any regular file the document admission admits, whatever its kind; a malformed answer is logged and answered `failed`. The explorer decides everything else, in this order:
|
|
611
630
|
|
|
@@ -692,9 +711,11 @@ With `embeds: { linkCards: true }`, the data route has a `link-card` operation:
|
|
|
692
711
|
The log never quotes a header: `headers` that `Headers` cannot read are logged by a fixed message, and a `Response` that `authenticate` throws (React Router's `throw redirect(...)`) by its status alone.
|
|
693
712
|
4. The handler answers: `200` with the card's JSON (`private, max-age=1800`), `204 No Content` with `X-Link-Card-Skip: <reason>` when the link gets no card (`private-network`, `forbidden-url`, `unreachable` or `not-html`), or its own `400`, `401` and `500` JSON with `no-store`. It never sets a cookie.
|
|
694
713
|
|
|
695
|
-
|
|
714
|
+
The handler opens pages only through the markdown service, as `parseMarkdown` does: it reads `MARKDOWN_SOCKET_PATH` and starts the service when needed (see `@aiquants/markdown`'s README, Link-card endpoint). Without the service — `MARKDOWN_SOCKET_PATH` unset or empty, or the service out of reach — it fetches nothing and answers its own `500` (`no-store`), and the link stays its paragraph.
|
|
696
715
|
|
|
697
|
-
|
|
716
|
+
Internal addresses never become cards, in any environment: the service refuses loopback, private, link-local and every other non-global address, internal names, names that resolve to such addresses and redirects to them, before connecting. There is no option to allow them, in the handler, the service or the explorer. A skipped link renders as a compact card that keeps the link, and `@aiquants/markdown` writes one `console.info` line for it; the explorer logs nothing of its own for cards.
|
|
717
|
+
|
|
718
|
+
The cards need nothing extra in your content security policy: they ask the page's own origin, so `connect-src 'self'` covers them (only the cards' images and icons need `https:` in `img-src`, see [Hosting notes](#hosting-notes)). The handler keeps its own cache per explorer (cards 1 hour, skips as long as their `Cache-Control`, 1000 URLs); its transport to the service is the process's, which `parseMarkdown` shares.
|
|
698
719
|
|
|
699
720
|
### `anonymousAccess`
|
|
700
721
|
|
|
@@ -761,11 +782,24 @@ Spread it into the configuration when your application has no sign-in: it provid
|
|
|
761
782
|
| `onMathDiagnostics?` | `(path, diagnostics: readonly MarkdownMathDiagnostic[]) => void` | Receives the KaTeX diagnostics of a markdown document once it rendered (never during render), with the document's path; the reader's console never sees them. `MarkdownMathDiagnostic` (`{ code, message, formula, displayMode }`) comes from `@aiquants/markdown`. The explorer reaches your function through one stable function, so passing a new function on every render neither parses the document again nor delivers its diagnostics twice; text documents report none. |
|
|
762
783
|
| `onEditGrant?` | `(href: string) => Promise<boolean>` | Lets the reader grant what an edit or a save asked for (`{ kind: "grant", href }`, see [Editing](#editing)): open your root-relative `href` as you see fit (a consent popup, for example) and resolve whether the reader came back from it; the editor then asks again. Without it, the editor links to `href` in a new tab beside Try again. |
|
|
763
784
|
| `draftConverter?` | `ExplorerDraftConverter` | Renders drafts in the browser, so the editor's preview follows every keystroke (see [Rendering drafts in the browser](#rendering-drafts-in-the-browser)). Without it the server renders the preview once the reader pauses. The explorer reaches your converter through one stable object, so passing a new one on every render does not restart the preview. |
|
|
785
|
+
| `fetch?` | `typeof fetch` | The fetch of the explorer's data requests and of its link cards (default: the global `fetch`); the explorer always calls the latest one given. A page that runs the server half itself passes the fetch of `createInProcessDataFetch` (see [Hosting](docs/behavior/hosting.md#running-the-server-half-in-the-page)). |
|
|
786
|
+
| `persistSettings?` | `(serialized: string) => void` | Stores the serialized view settings where the server's `readSettings` finds them (default: the `settingsCookie` cookie, which the Node entry reads); the explorer always calls the latest one given. |
|
|
787
|
+
| `subscribeHostChanges?` | `(listener: (change: ExplorerHostChange) => void) => () => void` | Subscribes to the changes the host saw outside the explorer (`{ sourceIds, paths }`: the sources whose trees changed and the documents that changed) and returns the unsubscribe (default: none). A changed source's tree is reloaded while a view shows it, and a changed document a pane shows and the reader does not edit follows `hostChangePolicy`. A new function subscribes again. |
|
|
788
|
+
| `hostChangePolicy?` | `"reload" \| "notify"` | What a changed document the reader is not editing does: `"reload"` (default) reads it again and announces it; `"notify"` shows a notice with Reload above it (`data-aqmx-notice="changed"`), which steps aside while the reader edits the document. |
|
|
789
|
+
| `ref?` | `Ref<MarkdownExplorerHandle>` | Receives the explorer's handle (see [The handle](#the-handle)), which always acts on the current reader's explorer. |
|
|
790
|
+
| `guardUnload?` | `boolean` | Whether leaving the page while a draft is unsaved asks through `beforeunload` (default `true`; a host that asks on close itself passes `false`). |
|
|
791
|
+
| `onReload?` | `() => void` | Reloads after a failure the reader asked to retry (default: the page's reload); a host whose state lives outside the page passes its rebuild. The explorer always calls the latest one given. |
|
|
792
|
+
| `onSessionEnded?` | `() => Promise<boolean>` | Restores a session that ended (the `unauthorized` failure) without leaving the page: open your sign-in and resolve `true` once the reader is signed in again, and the failed view tries again; resolve `false` (never reject) when the sign-in fails or is cancelled, and the failure keeps offering it. Calls made while a sign-in is open share its answer. Without it the failure offers the reload. The explorer always calls the latest one given. |
|
|
793
|
+
| `onDraftChange?` | `(change: ExplorerDraftChange) => void` | Receives the unsaved drafts as the explorer writes them (every 144 ms, those changed since the last call, as `kept`) and the paths whose drafts ended (`ended`: saved, discarded, closed, or back to the text they started from), so a host can keep a copy outside the page that `restoreDrafts` takes back (default: none). Its first call holds every draft unsaved by then; the explorer always calls the latest one given. |
|
|
794
|
+
| `accountState?` | `"signed-in" \| "signed-out"` | Whether the reader is signed in to the host's account, which picks the words of an `unauthorized` failure: `"signed-in"` (default) asks to sign in again, `"signed-out"` to sign in. |
|
|
795
|
+
| `confirmUnversionedSaves?` | `boolean` | Asks before every save that would write a change to a source that keeps no previous versions (an `edit` source answered with `history: false`), so every save can be undone or was confirmed (default `false`). |
|
|
796
|
+
| `paletteKey?` | `string` | An opaque name of the palette the host binds the explorer's colour roles to; when it changes, the explorer reads again the colours it paints itself (the tree's connector lines, drawn on a canvas), which `theme` alone cannot tell (default: none). |
|
|
764
797
|
|
|
765
798
|
The explorer fills its container's block size, so the container needs a definite block size: for example `height: 100dvh`, or a flex column of definite height whose item has `flex: 1` and `min-height: 0`. The quick start's `app.css` is such a container.
|
|
766
799
|
A container whose block size is auto or only a minimum (`html` and `body` at their default auto height included) does not size the explorer: the areas that fill the leftover height collapse to 0 px, or the explorer grows with its content.
|
|
767
800
|
The explorer takes its inline size from its container too, never from its content: the split's frame is a size container in the inline axis (it lays itself out from its own width, from the first paint), so a container that shrinks to fit its content — an absolutely positioned or fixed box without a width, `width: fit-content` or `max-content`, a float, an `auto` grid track with `justify-content: start` — sizes the explorer to 0 px. Give such a container a width; a block container and a stretched flex or grid item already have one.
|
|
768
|
-
With `lockDocumentScroll` the explorer must fill a container of definite block size inside the viewport; while the page is locked it logs one `console.error` per
|
|
801
|
+
With `lockDocumentScroll` the explorer must fill a container of definite block size inside the viewport; while the page is locked it logs one `console.error` per root element (a frame that differs per view recreates the root, which is checked afresh) when, once the layout has settled (no resize of the explorer's root or the window for one second), the explorer ends below the viewport or a rendered part collapses (its root, the document region of the tree or single view, or the explorer's tree area is less than 1 px tall).
|
|
802
|
+
The intermediate viewports a resize can pass through — switching Chrome DevTools' device toolbar between a desktop and a phone size does — are not judged.
|
|
769
803
|
Hidden parts — a closed sheet, a collapsed explorer panel, an explorer the host hides — are not checked.
|
|
770
804
|
|
|
771
805
|
#### Tree settings
|
|
@@ -775,10 +809,10 @@ Storage keeps only the settings the reader changed, each with the value they cho
|
|
|
775
809
|
A stored value of another format version is ignored, so its reader starts from the defaults. A stored `directoriesFirst` (from when "Folders first" was a switch) is read as `folderPlacement`: `true` as `"first"`, `false` as `"mixed"` (a stored `false` exists only where the default was `true`), unless a `folderPlacement` is stored too; the next change the reader makes stores the new key only. Folders: Mixed (the package default) keeps the source's order, or interleaves folders and files by name under a name order;
|
|
776
810
|
First puts the folders before the files and Last after them, under any sort order (a descending name order reverses the names, not the placement).
|
|
777
811
|
README: Mixed (the package default) keeps a folder's READMEs in the sort; First puts them before the folder's other files and Last after them — before or after its folders too while folders mix with the files — under any sort order, and the READMEs keep the sort among themselves (what a README is: [Folders and their READMEs](#folders-and-their-readmes)).
|
|
778
|
-
Reveal the open document: see [Revealing the open document](#revealing-the-open-document). Selection: Single (the package default) selects the shown document or folder; Multiple gathers clicked documents in a tray that opens them as panels; Off shows no row as selected, not even the shown document.
|
|
812
|
+
Reveal the open document: see [Revealing the open document](#revealing-the-open-document). Show folder READMEs: see [Folders and their READMEs](#folders-and-their-readmes). Selection: Single (the package default) selects the shown document or folder; Multiple gathers clicked documents in a tray that opens them as panels; Off shows no row as selected, not even the shown document. The multi-panel view's menu offers neither Selection nor Show folder READMEs: it selects no rows and shows no folder READMEs.
|
|
779
813
|
The tray shrinks and scrolls before the tree does: the tree keeps at least three rows at any text size, the tray keeps its header row and scrolls the rest, and an explorer too short for both scrolls as a whole. Always expanded shows every folder whose contents are known as expanded; a lazy folder stays collapsed until the reader opens it, so the setting never loads folders by itself.
|
|
780
814
|
|
|
781
|
-
Call `clearExplorerStorage(storageNamespace)` when a reader signs out of a shared browser (it throws a `RangeError` for a malformed namespace instead of clearing the wrong keys). Import it from `@aiquants/markdown-explorer/storage`: that entry imports
|
|
815
|
+
Call `clearExplorerStorage(storageNamespace)` when a reader signs out of a shared browser (it throws a `RangeError` for a malformed namespace instead of clearing the wrong keys). Import it from `@aiquants/markdown-explorer/storage`: that entry imports no package (no React, no `@aiquants/markdown`), so a layout or root route that runs on every page can call it without loading the explorer; the root entry exports the same function.
|
|
782
816
|
The explorer also clears the namespace by itself: on every page load, before anything reads it, when the reader recorded there is not the page's reader, and when a data response reports a different reader.
|
|
783
817
|
|
|
784
818
|
#### Expand all and Collapse all
|
|
@@ -826,32 +860,28 @@ Drafts last while the explorer is mounted, across view switches and remounted pa
|
|
|
826
860
|
|
|
827
861
|
#### Rendering drafts in the browser
|
|
828
862
|
|
|
829
|
-
`draftConverter` lets the preview render every draft in the browser, with the conversion your server makes, so the preview follows the reader's typing instead of waiting for a pause and a round trip. With `@aiquants/markdown` the converter is its browser converter, the Go service's converter compiled to WebAssembly (`@aiquants/markdown/converter`)
|
|
863
|
+
`draftConverter` lets the preview render every draft in the browser, with the conversion your server makes, so the preview follows the reader's typing instead of waiting for a pause and a round trip. With `@aiquants/markdown` the converter is its browser converter, the Go service's converter compiled to WebAssembly (`@aiquants/markdown/converter`).
|
|
864
|
+
Make its options with `draftConversionOf` from the deny rules and the conversion limits your server converts documents with, taking as the HTML limit the explorer's sanitizer's (`sanitizer.maxHtmlBytes`, 4 MiB by default) so a draft too large for the server is too large in the browser too, and answer its failures with `draftAnswerOf`:
|
|
830
865
|
|
|
831
866
|
```ts
|
|
832
|
-
import { type BrowserConversion, createMarkdownConverter,
|
|
867
|
+
import { type BrowserConversion, createMarkdownConverter, type MarkdownConverter } from "@aiquants/markdown/converter"
|
|
833
868
|
import converterWasmUrl from "@aiquants/markdown/converter.wasm?url"
|
|
834
869
|
import converterWorkerUrl from "@aiquants/markdown/converter/worker?worker&url"
|
|
835
|
-
import { DEFAULT_DENIED_PATH_SEGMENTS,
|
|
870
|
+
import { DEFAULT_DENIED_PATH_SEGMENTS, draftAnswerOf, draftConversionOf, type ExplorerDraftConverter } from "@aiquants/markdown-explorer"
|
|
836
871
|
|
|
837
872
|
// In a browser-only module (React Router: `draftConverter.client.ts`)
|
|
873
|
+
// The deny rules and the conversion limits your server converts documents with
|
|
874
|
+
const { timeoutMs, options } = draftConversionOf({ deny: DEFAULT_DENIED_PATH_SEGMENTS, conversion: { maxSourceBytes: 8 * 1024 * 1024, maxHtmlBytes: 4 * 1024 * 1024, deadlineMs: 10_000 } })
|
|
838
875
|
let converter: MarkdownConverter | null = null
|
|
839
876
|
let started = false
|
|
840
|
-
const converterOf = (): MarkdownConverter => (converter ??= createMarkdownConverter({ workerUrl: converterWorkerUrl, wasmUrl: converterWasmUrl, timeoutMs
|
|
877
|
+
const converterOf = (): MarkdownConverter => (converter ??= createMarkdownConverter({ workerUrl: converterWorkerUrl, wasmUrl: converterWasmUrl, timeoutMs }))
|
|
841
878
|
const conversionOf = (markdownText: string, filePath: string): BrowserConversion => ({
|
|
842
879
|
markdownText,
|
|
843
880
|
filePath, // a workspace document's path under the root below, or its gcs:// / gdrive:// URI
|
|
844
881
|
workspaceRoot: "/workspace",
|
|
845
|
-
options
|
|
882
|
+
options,
|
|
846
883
|
})
|
|
847
884
|
|
|
848
|
-
const answerOf = (error: unknown): ExplorerDraftAnswer => {
|
|
849
|
-
if (error instanceof MarkdownResourceExhaustedError || error instanceof MarkdownConversionTimeoutError) return failureDocument("too-large")
|
|
850
|
-
if (!(error instanceof MarkdownConversionError)) throw error
|
|
851
|
-
if (error.code === "unavailable") return { kind: "unavailable" }
|
|
852
|
-
return failureDocument(error.code === "invalid_argument" ? "invalid" : "failed")
|
|
853
|
-
}
|
|
854
|
-
|
|
855
885
|
export const draftConverter: ExplorerDraftConverter = {
|
|
856
886
|
convert: async ({ path, text }, signal) => {
|
|
857
887
|
started = true
|
|
@@ -860,7 +890,7 @@ export const draftConverter: ExplorerDraftConverter = {
|
|
|
860
890
|
return { kind: "preview", htmlContent, headings }
|
|
861
891
|
} catch (error) {
|
|
862
892
|
if (signal.aborted) throw signal.reason
|
|
863
|
-
return
|
|
893
|
+
return draftAnswerOf(error)
|
|
864
894
|
}
|
|
865
895
|
},
|
|
866
896
|
// Starts the worker and its WebAssembly ahead of the first draft; a short document warms the first conversion up
|
|
@@ -882,14 +912,34 @@ export const draftConverter: ExplorerDraftConverter = {
|
|
|
882
912
|
So the server is asked about a target once, and a draft that adds no new image or link causes no request at all; a missing image the reader just added shows as a broken image until the answer lands, then as the viewer's missing-image placeholder.
|
|
883
913
|
- **The server tier.** Without a converter, and for a draft the converter answers `unavailable` (its WebAssembly could not load, for example), the server renders the draft once the reader has paused for SERVER_PREVIEW_DELAY_MS (610 ms); the last rendering stays on screen marked `aria-busy` meanwhile, and a newer draft aborts the request. The preview names the tier of what it shows in `data-aqmx-preview-tier` (`instant` or `server`).
|
|
884
914
|
- **Content Security Policy.** A page that sets `script-src` needs `'wasm-unsafe-eval'` in it for the WebAssembly, and `worker-src 'self'` (or a `script-src` covering the worker) for the same-origin worker.
|
|
915
|
+
- **The shared halves.** Two functions of the root entry hold what does not depend on the converter you run, so every host makes it one way: `draftConversionOf({ deny, conversion })` makes the converter's options from the deny rules and the conversion limits (`{ maxSourceBytes, maxHtmlBytes, deadlineMs }`) your server converts documents with — `{ timeoutMs, options: { deniedPathSegments, maxHtmlBytes, includeSourceLines: true } }` —,
|
|
916
|
+
and `draftAnswerOf(error)` maps a conversion's failure to the draft answer as your server answers the same conversion: a size limit or the deadline is `too-large`, `invalid_argument` is `invalid`, `internal` is `failed`, and `unavailable` leaves the draft to the server; it rethrows any other error. `@aiquants/markdown`'s browser and service converters throw the same error classes.
|
|
917
|
+
|
|
918
|
+
#### The handle
|
|
919
|
+
|
|
920
|
+
The handle `ref` receives (`MarkdownExplorerHandle`) lets a host that owns what surrounds the explorer — a desktop shell closing its window, a page routing its announcements — act on the explorer. It always acts on the current reader's explorer.
|
|
921
|
+
|
|
922
|
+
| Method | Purpose |
|
|
923
|
+
| --- | --- |
|
|
924
|
+
| `flushUnsaved()` | Writes every editor's pending keystrokes to its draft, then answers the paths whose drafts are unsaved. |
|
|
925
|
+
| `confirmDiscard(paths)` | Asks with the explorer's own confirmation whether to discard those drafts; discards them and resolves `true` when the reader agrees. |
|
|
926
|
+
| `restoreDrafts(drafts)` | Restores drafts kept outside the page (`ExplorerUnsavedDraft[]`, as `onDraftChange` handed them) as unsaved drafts: a draft whose base version is still the saved one comes back as it was, any other goes through a save's three-way merge. It resolves to `{ restored, failed }`: a path that cannot be read now, or whose document the reader already edits (the reader's draft stays), is in `failed` with its reason, never dropped silently. |
|
|
927
|
+
| `announce(text)` | Announces a sentence politely through the explorer's live region, which stays reachable while the explorer's own modal sheet is open; while a block of a document is shown full screen, the sentence waits until the block leaves it, in arrival order, the same sentence never twice in a row. |
|
|
928
|
+
| `owns(element)` | Whether an element belongs to the explorer (its root or one of its dialogs), so a host can route announcements by the topmost modal's owner. |
|
|
929
|
+
| `reportMediaFailure({ url, final })` | Tells the explorer that the host failed to deliver a media response: every shown `video` and `audio` whose current source without its fragment is `url` is marked and gets the media notice with Reload (`data-aqmx-notice="media-load"`) — at once for a final cut, otherwise once the element stalls or fails, since it reads again on its own —, and the shown PDF frame of `url` gets it at once. |
|
|
930
|
+
|
|
931
|
+
An unsaved draft (`ExplorerUnsavedDraft`) is `{ path, base: { text, version }, draft, lineEnding }`: what the draft started from (the text read or saved last, and its version), the draft, and the line ending of the document's file (`"\n"` or `"\r\n"`). Both texts end their lines with `\n`, as the editor holds them, and a save writes the draft with the file's line ending.
|
|
932
|
+
The handle's methods and the props above check what a host gives: a value of the wrong type is a `TypeError` and a value outside its set a `RangeError`, where it is given rather than read as some default.
|
|
885
933
|
|
|
886
934
|
### Localization
|
|
887
935
|
|
|
888
936
|
`locale` selects a built-in catalog (`MARKDOWN_EXPLORER_LABEL_CATALOGS.en` / `.ja`); `labels` overrides single keys.
|
|
889
|
-
The catalogs also name every control of the document viewer (the `viewer…` keys: its toolbar, the table of contents, the style and alignment menus, each Mermaid diagram's controls
|
|
937
|
+
The catalogs also name every control of the document viewer (the `viewer…` keys: its toolbar, the table of contents, the style and alignment menus, each Mermaid diagram's controls, full-screen dialog, source view with its copy and type name, a storage SVG image's toolbar, source, copies, notices and full-screen dialog, the notice in place of a block that cannot render, every name, notice and announcement of a ```spreadsheets table, and the titles of embedded frames).
|
|
890
938
|
A table's labels are `@aiquants/markdown`'s own: each label of its table block under `viewerSpreadsheet…` (`zoomIn` → `viewerSpreadsheetZoomIn`), with the block's catalog of the UI language as the built-in text and its placeholders; only the ones a host replaces reach the viewer, so a table shows its catalog's text marked with its language, and its grid takes `locale` as its own.
|
|
891
939
|
The multi view's labels name everything its drag-and-drop layout shows (the panel headers' buttons and the custom drag mode's badge, the move announcements and a touch or pen drag's lift and cancel announcements, the bar of hidden panels, the columns' names and the drop placeholders), which therefore follow `locale` too.
|
|
892
|
-
The labels
|
|
940
|
+
The split's labels (`panelGroup…`) name what `@aiquants/resize-panels` shows when the panels of the tree view's split, or of the editor and the preview, cannot fit their frame.
|
|
941
|
+
The labels the layout, the split, a table or an SVG image fills with a value are templates with `{name}` placeholders (`MARKDOWN_EXPLORER_LABEL_TEMPLATES`), in which a brace stands only as a placeholder's. An unknown key, a blank string, a value of the wrong type, a template placeholder its key does not offer, a brace outside a placeholder or a regional tag such as `"ja-JP"` throws — see [Localization](docs/behavior/localization.md).
|
|
942
|
+
The labels the explorer hands the document viewer carry the UI language (the viewer's `labelsLang`), so the controls the viewer draws inside a document keep it, and an inert link's reason (its `title`) reads in the UI language while the link's own text keeps the document's language.
|
|
893
943
|
|
|
894
944
|
## Layout
|
|
895
945
|
|
|
@@ -925,7 +975,7 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
|
|
|
925
975
|
|
|
926
976
|
- Press the circle and pull it up or down: the scroller scrolls while the pointer is held, faster the farther it is pulled, and stops on release and at either end. A plain tap scrolls nothing.
|
|
927
977
|
- A circle is one control wide (44 px) and sits 49 px before its bar, at the middle of the scroller's height. It scrolls the same with a Mermaid diagram or an embedded frame at its height, and a drag that starts on it selects no text.
|
|
928
|
-
- The tables' grids take the same look and
|
|
978
|
+
- The tables' grids take the same look, speeds and size (`TABLE_TAP_SCROLL_CIRCLE`): a table file's preview shows the grid's circle one control wide where the grid places it (toward the bottom-right quarter of its box), once the table scrolls on either axis, and a document's ```` ```spreadsheets ```` table shows one as wide, only where its options say `tapscroll=1` (`@aiquants/markdown`'s `spreadsheetTapScrollCircle`, its `size` included).
|
|
929
979
|
The look loads with the bars' circle module on first use, as the bars do, so a single-view page's static part stays without `@aiquants/virtualscroll`; a circle drawn before it arrives shows it once it has.
|
|
930
980
|
- Under a fine pointer every document scroller with a circle (the viewer's scroller, the image, medium, file and failure views, and each multi-view panel's scroll area) keeps a 54 px gutter at its inline end, outside its own padding: the circle with 5 px on each side.
|
|
931
981
|
So no content (a diagram's or a table's toolbar, a code block's copy button, a focused link) lies under the circle at any scroll position; only an image zoomed wider than its canvas passes beneath it while it pans sideways. The wheel and touch scroll over the gutter as over the rest of the document.
|
|
@@ -944,10 +994,10 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
|
|
|
944
994
|
|
|
945
995
|
## Security model
|
|
946
996
|
|
|
947
|
-
- Markdown HTML is sanitized on the server with DOMPurify and an allow-list, in worker threads with limits on size (4 MiB), nesting (
|
|
997
|
+
- Markdown HTML is sanitized on the server with DOMPurify and an allow-list, in worker threads with limits on size (4 MiB), nesting (256 levels, as the sanitizer's parser builds the tree), parsed nodes (81,920 elements, attributes and comments, at most 4,096 of them comments), attributes (at most 1,024 per element, and no more attribute characters than `maxHtmlBytes`, counting the copies the parser makes of reopened formatting elements), output (at most four characters per byte of `maxHtmlBytes`), heap (512 MiB per worker) and time (30 s) and a fair share of the workers for each reader:
|
|
948
998
|
no `script`, `style`, `form` or embedding elements, no event-handler attributes or `srcdoc`, only `text-align` in `style`, iframes only over HTTPS from hosts listed exactly in `config.iframeHosts` (with `allow` and `referrerpolicy` reduced to safe values, by the frame policy `@aiquants/markdown/embeds` shares with the viewer), `data-*` only for the link, image and footnote contract and the embed placeholder its shared contract accepts, and only `http:`, `https:`, `mailto:`, `tel:` and relative URLs (no `data:` URL in any element).
|
|
949
999
|
- The document viewer (`@aiquants/markdown`) applies its own allow list on every render, so the page holds the intersection: `class` reduced to the converter's tokens (alerts, Zenn containers, footnotes, formulas, `language-*`), `id` only on headings, footnotes and in the `user-content-` namespace, and no author `target`, `rel` or `srcset`. The sanitizer leaves classes and ids to that single definition; render `htmlContent` only through the explorer or `@aiquants/markdown`'s renderers.
|
|
950
|
-
- 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.
|
|
1000
|
+
- 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, and a segment that one more decode would still change after those three is denied whatever the patterns.
|
|
951
1001
|
- 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.
|
|
952
1002
|
- 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)).
|
|
953
1003
|
- 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.
|
|
@@ -968,7 +1018,7 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
968
1018
|
|
|
969
1019
|
- One explorer per page: the drag-and-drop layout looks up its panels document-wide.
|
|
970
1020
|
- Merges are line-based (node-diff3): changes on adjacent lines, or on the same line, conflict even when they would combine. A panel that is not maximized shows the editor or the preview, never both; maximize it to see them side by side.
|
|
971
|
-
- The browser applies the server sanitizer's allow-list rules and nesting limit (
|
|
1021
|
+
- The browser applies the server sanitizer's allow-list rules and nesting limit (256 levels, a margin below the depth at which browsers' own parsers stop nesting elements), but not its other resource limits (parsed nodes, attributes, worker heap, time): the host's converter bounds a draft's HTML with `maxHtmlBytes` instead. The existence marks of a target the reader just added arrive about a second after they pause, so until then a new image that does not exist shows as a broken image, and a new link to a missing document as an ordinary link.
|
|
972
1022
|
- A held Enter acts once on every control inside the explorer, those of other packages included (the tree's rows, the panel headers' buttons, the document viewer's toolbar and the controls inside a document), except Zoom in and Zoom out, which keep stepping while a press that began on them is held (see [Held keys](docs/behavior/layout.md#held-keys)): a press that hands the focus to them, such as following a link to an image, does not step them.
|
|
973
1023
|
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.
|
|
974
1024
|
- 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.
|
|
@@ -980,7 +1030,7 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
980
1030
|
- 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).
|
|
981
1031
|
- 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.
|
|
982
1032
|
- Open in a new tab (`as=text`) names its `charset` from a file's first 64 KiB, which the server reads before it answers: a file whose text outside ASCII starts past them is named UTF-8 there, and text in the legacy encoding past that point shows garbled in the tab, while the explorer's own views decide on the bytes they read (a table on what it reads, a Source view on its first `textMaxBytes`).
|
|
983
|
-
- HTML larger than `sanitizer.maxHtmlBytes` (4 MiB), placed deeper than
|
|
1033
|
+
- HTML larger than `sanitizer.maxHtmlBytes` (4 MiB), placed deeper than 256 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,
|
|
984
1034
|
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`.
|
|
985
1035
|
- 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.
|
|
986
1036
|
- Each sanitizer worker runs with `workerHeapMb` (512 MiB) of old generation and a fixed 32 MiB young generation, about 1.1 GiB for the default two workers. A process-wide `--max-old-space-size` (for example in `NODE_OPTIONS`) overrides the workers' old-generation limit, because V8 gives the flag precedence; the nesting guard's node budget still keeps every document it accepts within about `workerHeapMb`, but the hard stop at the limit no longer applies.
|
|
@@ -996,7 +1046,8 @@ the page and data routes, the error boundary, document and asset ports that rout
|
|
|
996
1046
|
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),
|
|
997
1047
|
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:
|
|
998
1048
|
"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.
|
|
999
|
-
|
|
1049
|
+
Its page `/browser-docs` runs the server half inside the page, as a desktop webview does (`demo/app/browser-host.client.ts`, following [Hosting](docs/behavior/hosting.md)): `createExplorerServer` of `./server/core` on the browser runtime of `./server/browser`, over a source of the Markdown documents the page bundles, rendered by the same browser converter, with the display settings kept in the page's storage. It has no server loader and no data route: the in-process fetch answers every data request in the page.
|
|
1050
|
+
Run it with `pnpm run demo:dev` from the package folder. The end-to-end tests run every spec in Chromium, and the in-page host's spec (`tests/e2e/browser-core.spec.ts`) in WebKit too.
|
|
1000
1051
|
|
|
1001
1052
|
## License
|
|
1002
1053
|
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("react/jsx-runtime"),m=require("react"),S=require("./index-LQWQfpAf.cjs"),Z=require("@aiquants/markdown/code-blocks"),J=require("@codemirror/commands"),we=require("@codemirror/lang-markdown"),ie=require("@codemirror/language"),Ee=require("@codemirror/search"),K=require("@codemirror/state"),_=require("@codemirror/view"),D=require("@lezer/highlight"),Ge=require("@aiquants/markdown"),me=require("@aiquants/markdown/source-lines"),ne=require("./ownUrls-B259RGgd.cjs"),he=require("./sanitizePolicy-CiQfnxyd.cjs"),We=require("isomorphic-dompurify"),X=require("./location-D8DyDkuA.cjs"),Xe=require("./describeValue-Ccvhbt36.cjs"),ce=require("@aiquants/resize-panels"),be=require("./useSplitPersistence-B2Fj508K.cjs"),Pe={history:J.historyField},$e=ie.HighlightStyle.define([{tag:[D.tags.heading1,D.tags.heading2,D.tags.heading3,D.tags.heading4,D.tags.heading5,D.tags.heading6,D.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:D.tags.strong,fontWeight:"700"},{tag:D.tags.emphasis,fontStyle:"italic"},{tag:D.tags.strikethrough,textDecoration:"line-through"},{tag:D.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:D.tags.url,color:"var(--aqmx-syntax-url)"},{tag:D.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:D.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[D.tags.processingInstruction,D.tags.contentSeparator,D.tags.labelName,D.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Ke=_.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)"}}),Ne="data-aqmx-conflict-actions",Ye=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Je=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),Qe=_.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class Ze extends _.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(Ne,String(this.index));for(const[o,s]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const r=document.createElement("button");r.type="button",r.textContent=s,r.setAttribute("data-aqmx-conflict-choice",o),r.addEventListener("mousedown",l=>l.preventDefault()),r.addEventListener("click",()=>{const l=se(t.state.doc)[this.index];l!==void 0&&(De(t,l,o),t.focus())}),n.append(r)}return n}ignoreEvent(){return!0}}const se=e=>S.findConflictsInLines(e.iterLines()),xe=(e,t)=>{const n=new K.RangeSetBuilder;return se(e).forEach((o,s)=>{const r=e.line(o.start);n.add(r.from,r.from,_.Decoration.widget({widget:new Ze(s,t),block:!0,side:-1}));for(let l=o.start;l<=o.end;l+=1){const i=e.line(l).from,f=l===o.start||l===o.separator||l===o.end?Ye:l<o.separator?Je:Qe;n.add(i,i,f)}}),n.finish()},et=e=>K.StateField.define({create:t=>xe(t.doc,e),update:(t,n)=>n.docChanged?xe(n.state.doc,e):t,provide:t=>_.EditorView.decorations.from(t)}),De=(e,t,n)=>{const{doc:o}=e.state,s=(E,c)=>{const w=[];for(let u=E;u<=c;u+=1)w.push(o.line(u).text);return w},r=s(t.start+1,t.separator-1),l=s(t.separator+1,t.end-1),i=n==="ours"?r:n==="theirs"?l:[...r,...l];let f=o.line(t.start).from,d=o.line(t.end).to;i.length===0&&(t.end<o.lines?d+=1:t.start>1&&(f-=1));const b=i.join(`
|
|
2
|
+
`);e.dispatch({changes:{from:f,to:d,insert:b},selection:K.EditorSelection.cursor(f),scrollIntoView:!0,userEvent:"input.resolve"})},Se="input.preview",tt=20,nt=_.ViewPlugin.fromClass(class{constructor(e){this.view=e,this.schedule()}view;cancel=null;update(e){e.docChanged&&this.schedule()}schedule(){if(this.cancel!==null||ie.syntaxTreeAvailable(this.view.state))return;const e=this.view.dom.ownerDocument.defaultView;if(e===null)return;const t=()=>{this.cancel=null,ie.ensureSyntaxTree(this.view.state,this.view.state.doc.length,tt),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}}),rt=/`{3,}|~{3,}/u,re=Object.freeze({kind:"absent"}),de=Object.freeze({kind:"unreadable"}),ot=(e,t,n)=>{const o=[];for(let f=t.parent;f!==null;f=f.parent)(f.name==="Blockquote"||f.name==="ListItem")&&o.unshift(f);const s=[],r=[],l=f=>{const d=r.indexOf(f);return d===-1?r.length:d};for(const f of o){const d=e.lineAt(f.from).number;if(f.name==="ListItem"){const b=Z.listItemWidthOn(e.line(d).text,s,l(d));if(b===null)return null;s.push({kind:"listItem",width:b})}else s.push({kind:"quote"});r.push(d)}const i=Z.openingFenceOn(n.text,s,l(n.number));return i===null?null:{containers:s,...i}},st=(e,t)=>{const{doc:n}=e;let o=n.lineAt(t).to;for(;;){const s=ie.ensureSyntaxTree(e,o,Number.POSITIVE_INFINITY);if(s===null)return null;const r=s.resolveInner(t,1),l=r.parent;if(r.name!=="CodeMark"||l===null||l.name!=="FencedCode"||l.from!==r.from)return null;if(l.to<o||o>=n.length)return l;o=Math.min(n.length,l.to+Math.max(l.to-t,1))}},ye=(e,t)=>{const{doc:n}=e;if(!Number.isInteger(t)||t<1||t>n.lines)return re;const o=n.line(t),s=rt.exec(o.text);if(s===null)return re;const r=st(e,o.from+s.index);if(r===null)return re;const l=r.getChild("CodeInfo");if(l===null)return re;const i=Z.fencedCodeLanguageOf(n.sliceString(l.from,l.to));if(i===null)return de;if(i!==Z.SPREADSHEETS_LANGUAGE)return re;const f=ot(n,r,o);if(f===null)return de;const[,...d]=r.getChildren("CodeMark"),b=d.at(-1),E=b===void 0?n.lineAt(r.to).number:n.lineAt(b.from).number-1,c=[];let w="";for(let u=t+1;u<=E;u+=1){const h=n.line(u).text,g=Z.readFencedLine(h,f);if(g===null)return de;c.push(h),w+=u<n.lines?`${g.content}
|
|
3
|
+
`:g.content}return{kind:"found",firstLine:t+1,lines:c,layout:f,body:w}},it=({parent:e,scroll:t,text:n,saved:o,labels:s,revisions:r,onChange:l,onGeometry:i,onSave:f})=>{let d=!1;const b=[_.EditorView.scrollHandler.of((u,h,g)=>(lt(u,h.head,g,t),!0)),_.lineNumbers(),_.highlightActiveLineGutter(),J.history(),_.drawSelection(),_.highlightActiveLine(),Ee.highlightSelectionMatches(),_.EditorView.lineWrapping,we.markdown({base:we.markdownLanguage}),nt,ie.syntaxHighlighting($e),et(s),_.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(f(),!0)},...Ee.searchKeymap,...J.historyKeymap,...J.defaultKeymap]),_.EditorView.contentAttributes.of({"aria-label":s.editor,"aria-multiline":"true"}),_.EditorView.updateListener.of(u=>{for(const h of u.transactions)h.docChanged&&r.record(h.changes,h.newDoc);u.docChanged&&l(u.transactions.every(h=>!h.docChanged||h.isUserEvent(Se))),(u.docChanged||u.heightChanged||u.geometryChanged)&&i(u.docChanged&&!d)}),Ke],E=ut(o,b)??K.EditorState.create({doc:n,extensions:b}),c=new _.EditorView({state:E,parent:e});r.mount(c.state.doc);const w=u=>{d=!0;try{u()}finally{d=!1}};return{text:()=>c.state.doc.toString(),replaceText:u=>{const h=c.state.doc.toString();if(h===u)return;let g=0;const y=Math.min(h.length,u.length);for(;g<y&&h.charCodeAt(g)===u.charCodeAt(g);)g+=1;let p=0;for(;p<y-g&&h.charCodeAt(h.length-1-p)===u.charCodeAt(u.length-1-p);)p+=1;c.dispatch({changes:{from:g,to:h.length-p,insert:u.slice(g,u.length-p)},userEvent:"input.replace"})},replaceBody:(u,h,g,y)=>{const{doc:p}=c.state,T=r.lineOf(y,u);if(T===null)return"changed";const O=ye(c.state,T);if(O.kind==="absent")return"changed";if(O.kind==="unreadable")return"unwritable";if(O.body!==Z.fencedBodyAsRead(h,O.layout))return"changed";const L=Z.planFencedBodyEdit(O.lines,O.layout,g);if(L.kind!=="edit")return L.kind;if(L.from===L.to&&L.lines.length===0)return"written";const N=z=>{const H=O.firstLine+z;return H<=p.lines?p.line(H).from:p.length},M=N(L.from),B=`${M===p.length&&p.sliceString(p.length-1)!==`
|
|
4
|
+
`?`
|
|
5
|
+
`:""}${L.lines.map(z=>`${z}
|
|
6
|
+
`).join("")}`;return w(()=>c.dispatch({changes:{from:M,to:N(L.to),insert:B},userEvent:Se,annotations:J.isolateHistory.of("full")})),"written"},readBody:(u,h)=>{const g=r.lineOf(h,u);if(g===null)return null;const y=ye(c.state,g);return y.kind==="found"?y.body:null},undo:()=>w(()=>J.undo(c)),redo:()=>w(()=>J.redo(c)),reveal:({line:u,column:h},g)=>{const{doc:y}=c.state,p=y.line(Math.min(Math.max(u,1),y.lines)),T=Math.min(p.from+h,p.to);c.dispatch({selection:K.EditorSelection.cursor(T),effects:Te(c,T,g,t)})},showLine:u=>{const{doc:h}=c.state,g=h.line(Math.min(Math.max(u,1),h.lines)).from;c.dispatch({effects:Te(c,g,null,t)})},topLine:()=>{const u=t.scrollerOf(c.scrollDOM),h=S.visibleTopOf(u,c.contentDOM),g=S.frameTopOf(u)+u.clientHeight,{documentTop:y}=c,{doc:p}=c.state;let T=c.lineBlockAtHeight(Math.max(h-y,0));for(;p.lineAt(T.from).text.trim()===""&&T.to<p.length;){const N=c.lineBlockAt(T.to+1);if(y+N.top>=g)break;T=N}const O=c.coordsAtPos(T.from),L=O===null?y+T.top:O.top;return{line:c.state.doc.lineAt(T.from).number,clientTop:L,offset:L-h}},lineSpans:u=>{const h=c.scrollDOM,g=h.scrollTop+c.documentTop-S.visibleTopOf(h,c.contentDOM),{doc:y}=c.state,p=T=>y.line(Math.min(Math.max(T,1),y.lines)).from;return u.map(({first:T,last:O})=>({top:g+c.lineBlockAt(p(T)).top,bottom:g+c.lineBlockAt(p(O)).bottom}))},scrollElement:c.scrollDOM,focus:()=>c.focus(),conflicts:()=>se(c.state.doc),resolveAtCursor:u=>{const h=se(c.state.doc),g=c.state.doc.lineAt(c.state.selection.main.head).number,y=h.find(p=>p.end>=g);return y===void 0?!1:(De(c,y,u),!0)},nextConflict:()=>{const u=se(c.state.doc);if(u[0]===void 0)return!1;const g=c.state.doc.lineAt(c.state.selection.main.head).number,y=u.findIndex(L=>L.start>g),p=y<0?0:y,T=c.state.doc.line(u[p].start).from;c.dispatch({selection:K.EditorSelection.cursor(T),effects:_.EditorView.scrollIntoView(T,{y:"center"})});const O=c.contentDOM.querySelector(`[${Ne}="${String(p)}"] button`);return O instanceof HTMLElement?O.focus({preventScroll:!0}):c.focus(),!0},save:()=>c.state.toJSON(Pe),destroy:()=>c.destroy()}},Te=(e,t,n,o)=>{const s=o.scrollerOf(e.scrollDOM),r=(n===null?S.visibleTopOf(s,e.contentDOM):n)-S.frameTopOf(s);return _.EditorView.scrollIntoView(t,{y:"start",yMargin:r})},lt=(e,t,n,o)=>{const s=ct(e,t),r=o.scrollerOf(e.scrollDOM),l=S.frameTopOf(r),i=S.visibleTopOf(r,e.contentDOM),f=l+r.clientHeight;let d=0;switch(n.y){case"start":d=s.top-(l+n.yMargin);break;case"center":d=(s.top+s.bottom)/2-(i+f)/2;break;case"end":d=s.bottom-(f-n.yMargin);break;default:s.top<i+n.yMargin?d=s.top-(i+n.yMargin):s.bottom>f-n.yMargin&&(d=Math.min(s.bottom-(f-n.yMargin),s.top-(i+n.yMargin)))}if(d!==0&&(r.scrollTop+=d),n.y==="start")return;const b=at(e,t);b!==null&&o.reveal(b)},ct=(e,t)=>{const{node:n,offset:o}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,o),l.setEnd(n,o);const[i]=l.getClientRects();if(i!==void 0&&i.height>0)return{top:i.top,bottom:i.bottom}}}const s=e.lineBlockAt(t),r=e.documentTop+s.top;return{top:r,bottom:r+s.height}},at=(e,t)=>{const{node:n}=e.domAtPos(t);for(let o=n instanceof Element?n:n.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},ut=(e,t)=>{if(e==null)return null;try{return K.EditorState.fromJSON(e,{extensions:t},Pe)}catch{return null}},dt=610,ft=987,ke=Object.freeze({kind:"unavailable"}),mt="true",ht="false",pt=e=>e===mt?!0:e===ht?!1:null,gt=e=>{const t=new DOMParser().parseFromString(e,"text/html"),n=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const s=o.localName==="img",r=o.getAttribute(s?"data-asset-src":"data-doc-path");r!==null&&n.push({target:{kind:s?"asset":"doc",path:r},exists:pt(o.getAttribute(s?"data-asset-exists":"data-doc-exists"))})}return n},vt=({path:e,instant:t,preview:n,initial:o,onView:s})=>{const r=new AbortController,l={asset:new Map,doc:new Map};let i=o,f=null,d=!1,b=!1,E=null,c=null,w=[],u,h=!1,g,y=null;const p=v=>{v.parsed===i.parsed&&v.source===i.source&&v.failure===i.failure&&v.busy===i.busy&&v.tier===i.tier||(i=v,s(v))},T=(v,x)=>{d||(d=!0,console.error(`[markdown-explorer] ${v}`,...x===void 0?[]:[x]))},O=v=>{if(t!==null)for(const{target:x,exists:q}of t.marksOf(v))l[x.kind].set(x.path,q)},L=()=>{clearTimeout(g),g=void 0,y?.abort(),y=null},N=()=>{c=null,w=[],clearTimeout(u),u=void 0},M=(v,x)=>{p({...i,failure:v,busy:!1,tier:x})},U=()=>{clearTimeout(u),u=w.length===0?void 0:setTimeout(z,ft)},B=()=>{if(t===null||c===null)return;const v=c,x=[],q={asset:new Set,doc:new Set};let G;try{G=t.sanitize(v.html,F=>{const le=l[F.kind].get(F.path);return le===void 0&&!q[F.kind].has(F.path)&&(q[F.kind].add(F.path),x.push(F)),le??void 0})}catch(F){N(),F instanceof he.HtmlNestingLimitError?M(ne.failureOf("too-large"),"instant"):(T("the draft sanitizer failed",F),M(ne.failureOf("failed"),"instant"));return}w=x;const Y=i.parsed!==null&&i.parsed.htmlContent===G&&i.parsed.headings===v.headings?i.parsed:{htmlContent:G,headings:v.headings};p({parsed:Y,source:v.draft,failure:null,busy:!1,tier:"instant"}),U()},z=()=>{if(u=void 0,h||c===null||w.length===0)return;h=!0;const v=w;n(e,c.draft.text,r.signal).then(x=>{if(h=!1,!(r.signal.aborted||!("kind"in x))){x.kind==="preview"&&O(x.htmlContent);for(const q of v)l[q.kind].has(q.path)||l[q.kind].set(q.path,null);B()}})},H=v=>{L(),N(),p({...i,busy:!0,tier:"server"});const x=new AbortController;y=x,g=setTimeout(()=>{g=void 0,n(e,v.text,x.signal).then(q=>{if(!(x.signal.aborted||!("kind"in q))){if(y=null,q.kind==="failure"){M(q.failure,"server");return}O(q.htmlContent),p({parsed:{htmlContent:q.htmlContent,headings:q.headings},source:v,failure:null,busy:!1,tier:"server"})}})},dt)},a=async(v,x)=>{let q;try{q=await v.convert({path:e,text:x},r.signal)}catch(Y){return r.signal.aborted||T("the draft converter rejected a conversion, which its contract allows only once the signal aborted",Y),ke}const G=ne.draftAnswerViolation(q);return G===null?q:(T(`the draft converter answered outside its contract: ${G}`),ke)},I=(v,x)=>{switch(x.kind){case"preview":if(L(),x.headings.length>ne.EXPLORER_MAX_HEADINGS){N(),M(ne.failureOf("too-large"),"instant");return}c={draft:v,html:x.htmlContent,headings:x.headings.map(({text:q,depth:G,id:Y})=>({text:q,depth:G,id:Y}))},B();return;case"failure":L(),N(),M(ne.failureOf(x.failure.reason,x.failure.code),"instant");return;case"unavailable":H(v);return}},A=async v=>{b=!0;try{for(;E!==null&&!r.signal.aborted;){const x=E;E=null;const q=await a(v,x.text);if(r.signal.aborted)return;I(x,q)}}finally{b=!1}};return t!==null&&t.seed!==null&&O(t.seed),{update:v=>{if(!(r.signal.aborted||v.text===f?.text)){if(f=v,clearTimeout(u),u=void 0,t===null){H(v);return}E=v,b||A(t.converter)}},dispose:()=>{r.abort(),E=null,clearTimeout(u),u=void 0,L()}}},wt=e=>he.createHtmlSanitizer(We(window),e.iframeHosts,e.dataPath,he.MAX_HTML_NESTING_DEPTH,X.ownUrlsOf(e)),Et=(e,t)=>e.flatMap((n,o)=>{const s=t[o];return s===void 0?[]:[{editor:s.top,preview:n.top},{editor:s.bottom,preview:n.bottom}]}),Q=(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 ${Xe.describeValue(t)}`);return n},bt=e=>{const t=[];for(const o of e){let s=0,r=t.length;for(;s<r;){const l=s+r>>1;Q(t,l).pair.preview<=o.preview?s=l+1:r=l}t[s]={pair:o,before:s===0?void 0:Q(t,s-1)}}const n=[];for(let o=t.at(-1);o!==void 0;o=o.before)n.push(o.pair);return n.reverse()},xt=(e,t)=>{const n=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),s=n-t.editorViewport,r=o-t.previewViewport,l=e.filter(d=>d.editor>0&&d.editor<s&&d.preview>0&&d.preview<r).sort((d,b)=>d.editor-b.editor||d.preview-b.preview);let i={editor:0,preview:0};const f=[i];for(const d of bt(l))d.editor>i.editor&&d.preview>i.preview&&(f.push(d),i=d);return f.push({editor:n,preview:o}),{toPreview:d=>Le(f,"editor","preview",d),toEditor:d=>Le(f,"preview","editor",d)}},Le=(e,t,n,o)=>{const s=Q(e,0),r=Q(e,e.length-1);if(Number.isNaN(o)||o<=s[t])return s[n];if(o>=r[t])return r[n];let l=0,i=e.length-1;for(;i-l>1;){const b=l+i>>1;Q(e,b)[t]<=o?l=b:i=b}const f=Q(e,l),d=Q(e,i);return f[n]+(d[n]-f[n])*(o-f[t])/(d[t]-f[t])},St=610,Ie=89,Ae=.5,yt=({editor:e,preview:t,previewBlocks:n,editorSpans:o,requestFrame:s,cancelFrame:r,now:l})=>{let i="editor",f=0,d=null,b=null,E=!1,c=null,w=null;const u={editor:0,preview:0},h={editor:null,preview:null};let g=null,y=()=>{};const p=a=>{d!==null&&a!==d||(i=a,f=l()+St)},T=(a,I)=>{a!==i&&d===null&&l()>=f&&!O(a,I)&&(i=a),B()},O=(a,I)=>{const A=h[a];return l()<u[a]||A!==null&&Math.abs(I.position()-A)<Ae},L=e.onScroll(()=>T("editor",e)),N=e.onIntent(()=>p("editor")),M=()=>{const a=t();return a!==g&&(y(),g=a,y=a===null?()=>{}:U(a)),a},U=a=>{const I=a.onScroll(()=>T("preview",a)),A=a.onIntent(()=>p("preview"));return()=>{I(),A()}},B=()=>{!E&&b===null&&(b=s(z))},z=()=>{b=null;const a=M();a!==null&&(c??=n(),w??=xt(Et(c,o(c)),{editorMax:e.max(),previewMax:a.max(),editorViewport:e.viewport(),previewViewport:a.viewport()}),i==="editor"?H(a,"preview",w.toPreview(e.position())):H(e,"editor",w.toEditor(a.position())))},H=(a,I,A)=>{if(Math.abs(a.position()-A)<Ae){h[I]=a.position();return}u[I]=l()+Ie,h[I]=a.scrollTo(A)};return B(),{editorChanged:a=>{w=null,a&&p("editor"),B()},previewChanged:()=>{c=null,w=null,u.preview=l()+Ie,B()},showAlone:a=>{d=a,!(a===null||a===i)&&(i=a,f=0,B())},dispose:()=>{E=!0,b!==null&&r(b),b=null,L(),N(),y()}}},Oe=Object.freeze(["wheel","pointerdown","keydown","focusin"]),Ve=e=>({position:()=>e.scrollTop,max:()=>Math.max(e.scrollHeight-e.clientHeight,0),viewport:()=>e.clientHeight,scrollTo:t=>(e.scrollTo({top:t,behavior:"instant"}),e.scrollTop),onScroll:t=>(e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)),onIntent:t=>{for(const n of Oe)e.addEventListener(n,t,{capture:!0,passive:!0});return()=>{for(const n of Oe)e.removeEventListener(n,t,{capture:!0})}}}),oe="[data-aqmd-scroll-container]",Tt="[data-aqmd-content]",kt=`[${me.SOURCE_LINES_ATTRIBUTE}]`,Lt=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),Be=(e,t)=>{const n=S.loadedOf(e.peek(t));return n!==null&&n.document.kind==="markdown"?{htmlContent:n.document.htmlContent,headings:n.document.headings}:null},It=(e,t,n,o)=>{if(t===void 0)return null;let s;try{s=wt(e)}catch(r){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",r),null}return{converter:t,sanitize:s,marksOf:gt,seed:Be(n,o)?.htmlContent??null}},At=e=>{const t=[];let n=null;for(const o of e.querySelectorAll(kt)){const s=me.parseSourceLines(o.getAttribute(me.SOURCE_LINES_ATTRIBUTE));if(s===null||o.getClientRects().length===0)continue;n??=e.scrollTop-S.visibleTopOf(e,o);const{top:r,bottom:l}=o.getBoundingClientRect();t.push({first:s.first,last:s.last,top:n+r,bottom:n+l})}return t},Ot=({path:e,readDraft:t,viewer:n,tables:o,concealed:s,onEditAt:r,onLayout:l,handleRef:i})=>{const{config:f,data:d,documents:b,draftConverter:E,labels:c}=S.useExplorer(),[w,u]=m.useState(()=>({parsed:Be(b,e),source:null,failure:null,busy:!0,tier:E===void 0?"server":"instant"})),h=m.useRef(null),g=m.useRef(null),y=m.useRef(w);m.useLayoutEffect(()=>{y.current=w});const p=m.useEffectEvent(()=>t());m.useEffect(()=>{const a=It(f,E,b,e),I=p(),A=vt({path:e,instant:a,preview:d.preview,initial:y.current,onView:v=>m.startTransition(()=>u(v))});return g.current=A,A.update(I),()=>{A.dispose(),g.current=null}},[f,d,b,E,e]);const T=m.useEffectEvent(()=>l());m.useLayoutEffect(()=>{w.parsed!==null&&T()},[w.parsed]);const O=w.parsed!==null;m.useLayoutEffect(()=>{const a=O?h.current?.querySelector(oe):null;if(!(a instanceof HTMLElement))return;a.tabIndex=0;const I=new ResizeObserver(()=>T());I.observe(a);const A=a.querySelector(Tt);return A!==null&&I.observe(A),()=>I.disconnect()},[O]);const L=m.useRef(null);m.useImperativeHandle(i,()=>({draft:a=>{g.current?.update(a)},scrollPort:()=>{const a=h.current?.querySelector(oe);return a instanceof HTMLElement?(L.current?.scroller!==a&&(L.current={scroller:a,port:Ve(a)}),L.current.port):null},blocks:()=>{const a=h.current?.querySelector(oe);return a instanceof HTMLElement?At(a):[]},focus:()=>{const a=h.current?.querySelector(oe);a instanceof HTMLElement&&a.focus({preventScroll:!0})},anchor:a=>{const I=h.current,A=I?.querySelector(oe);return I===null||!(A instanceof HTMLElement)?null:S.anchorOfView(I,a(A))},place:({line:a,clientTop:I},A)=>{const v=h.current,x=v===null?null:S.blockAtLine(v,a);x!==null&&(A(x).scrollTop+=S.lineTopIn(x,a)-I)}}),[]);const N=a=>{const I=h.current,{target:A}=a;if(r===void 0||I===null||!(A instanceof Element)||!S.isEditingDoubleClick(A))return;const v=S.anchorOfDoubleClick(A,I,I.ownerDocument.getSelection());v!==null&&r(v)},M=w.source===null?null:w.source.revision,U=m.useMemo(()=>M===null?void 0:{write:a=>o.write(M,a),read:a=>o.read(M,a),undo:o.undo,redo:o.redo,subscribe:o.subscribe},[o,M]),B=m.useMemo(()=>({...n.labels,spreadsheetReadOnly:c.previewTablePending}),[n.labels,c.previewTablePending]),z=m.useMemo(()=>({...n,labels:U===void 0?B:n.labels,showToc:!1,showStyle:!1,showAlign:!1,showMeasure:!1,showContentColors:!1,renderScrollBar:void 0,scrollBarGutter:void 0,scrollBarInlineSize:void 0,spreadsheetEditor:U}),[n,B,U]),H=m.useMemo(()=>w.parsed===null?null:C.jsx("div",{className:"aqmx-document-viewer",children:C.jsx(Ge.MarkdownViewer,{...z,parseResult:w.parsed,content:null})}),[z,w.parsed]);return C.jsxs("section",{ref:h,className:"aqmx-edit-preview","aria-label":c.previewRegion,"aria-busy":w.busy,inert:s!==null,hidden:s==="removed","data-aqmx-preview-tier":w.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:r===void 0?void 0:N,children:[w.failure===null?null:C.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:c.previewFailed(S.failureTitleOf(c,w.failure.reason))}),H??(w.failure===null?C.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:Lt.map(a=>C.jsx("span",{},a))}):null),w.busy?C.jsx("p",{className:"aqmx-sr-only",children:c.previewUpdating}):null]})},Re="data-aqmx-edit-split",fe="--aqmx-edit-share",qe="--aqmx-edit-gutter",Rt="data-aqmx-edit-split-probe",qt="aqmx-edit-split",Ct="aqmx-edit-editor",Mt="aqmx-edit-preview",Ce={value:X.EDIT_SPLIT_MIN_PERCENT,unit:"percentage"},Me={value:X.EDIT_SPLIT_MAX_PERCENT,unit:"percentage"},_e=e=>{if(e.length!==2)return null;const[t=0,n=0]=e,o=t+n;return o>0?t/o*100:null},ae=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},_t=(e,t,n)=>{const[o,s]=m.useState(null);return m.useLayoutEffect(()=>{const r=e.current,l=t.current;if(r===null||l===null)throw new Error("[markdown-explorer] the edit split is not mounted");const i={frame:r.getBoundingClientRect().width,measure:l.getBoundingClientRect().width},f=()=>{i.frame>0&&i.measure>0&&s(X.editSplitOrientation(i.frame,i.measure,n))};f();const d=new ResizeObserver(b=>{for(const E of b){const[c]=E.borderBoxSize;c!==void 0&&(E.target===r&&(i.frame=c.inlineSize),E.target===l&&(i.measure=c.inlineSize))}f()});return d.observe(r),d.observe(l),()=>d.disconnect()},[e,t,n]),o},Pt=({editorId:e})=>{const{edits:t,labels:n}=S.useExplorer(),o=m.useMemo(()=>be.toPanelGroupLabels(n),[n]),s=m.useRef(null),r=m.useRef(null),l=S.useCoarsePointer()?X.COARSE_TARGET_PIXELS:X.FINE_TARGET_PIXELS,i=_t(s,r,l),[f]=m.useState(()=>t.editorShare());m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(qe,`${String(l)}px`),()=>{E.style.removeProperty(qe)}},[l]),m.useLayoutEffect(()=>{const E=ae(s);return E.style.setProperty(fe,`${String(f)}%`),()=>{E.style.removeProperty(fe)}},[f]),m.useLayoutEffect(()=>{if(i===null)return;const E=ae(s);return E.setAttribute(Re,i),()=>E.removeAttribute(Re)},[i]);const d=be.useSplitPersistence(m.useCallback(E=>{const c=_e(E);c!==null&&t.setEditorShare(c)},[t])),b=m.useCallback((E,c)=>{const w=_e(E);w!==null&&ae(s).style.setProperty(fe,`${String(w)}%`),d.layoutChanged(E,c)},[d]);return C.jsxs("div",{ref:s,className:"aqmx-edit-split","data-testid":"markdown-explorer-edit-split",children:[C.jsx("span",{ref:r,className:"aqmx-edit-split-probe","aria-hidden":"true",[Rt]:""}),i===null?null:C.jsxs(ce.PanelGroup,{id:qt,direction:i==="beside"?"horizontal":"vertical",onLayout:b,labels:o,className:"aqmx-edit-split-group",children:[C.jsx(ce.Panel,{id:Ct,defaultSize:{value:f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"}),C.jsx(ce.PanelResizeHandle,{thickness:l,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"}),C.jsx(ce.Panel,{id:Mt,defaultSize:{value:100-f,unit:"percentage"},minSize:Ce,maxSize:Me,contentOverflow:"hidden"})]})]})},Nt=512,Dt=()=>{const e=[];let t=0,n=null;const o=s=>{if(n===null||!Number.isInteger(s)||s<t)return null;if(s===t+e.length)return n;const r=e[s-t];return r===void 0?null:r.before};return{revision:()=>t+e.length,mount:s=>{if(n!==null&&(n===s||n.eq(s))){n=s;return}const r=t+e.length;e.length=0,t=n===null?r:r+1,n=s},record:(s,r)=>{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:s}),n=r,e.length>Nt&&(e.shift(),t+=1)},lineOf:(s,r)=>{const l=o(s);if(l===null||n===null||!Number.isInteger(r)||r<1||r>l.lines)return null;let i=l.line(r).from;for(const f of e.slice(s-t)){const d=f.changes.mapPos(i,1,K.MapMode.TrackAfter);if(d===null)return null;i=d}return n.lineAt(i).number}}},He=144,Vt=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"},Bt=e=>{e.stopPropagation()},Ht=e=>{const{path:t,name:n,session:o}=e,{edits:s,labels:r,announcer:l}=S.useExplorer(),{phase:i}=o,f=m.useCallback(()=>s.retry(t),[s,t]);switch(m.useEffect(()=>{i.kind==="failed"&&l.announce(r.documentFailed(n,S.failureTitleOf(r,i.failure.reason)))},[i,l,r,n]),i.kind){case"opening":return C.jsx(S.ContentSkeleton,{label:r.editLoading,testId:"markdown-explorer-edit-skeleton"});case"grant":return C.jsx("div",{className:"aqmx-edit-message",children:C.jsx(S.EditGrantNotice,{href:i.href,onRetry:f,testId:"markdown-explorer-edit-grant"})});case"failed":return C.jsx("div",{className:"aqmx-edit-message",children:C.jsx(S.FailureView,{failure:i.failure,alert:!1,onRetry:f,testId:"markdown-explorer-edit-failure"})});case"editing":return C.jsx(jt,{...e})}},jt=({path:e,name:t,session:n,layout:o,viewer:s,region:r,paneScroll:l})=>{const{edits:i,labels:f}=S.useExplorer(),d=m.useRef(null),b=m.useId(),E=m.useRef(null),[c]=m.useState(()=>new Set),[w]=m.useState(Dt),u=m.useRef(null),h=m.useRef(null),g=o==="fill",y=S.useSideBySide(),p=S.editViewOf(n,y,g),T=p!=="editor"||n.previewPrepared,O=T&&g,L=m.useRef({layout:o,region:r,paneScroll:l});m.useLayoutEffect(()=>{L.current={layout:o,region:r,paneScroll:l}});const N=m.useRef(n.generation);m.useLayoutEffect(()=>{N.current=n.generation});const M=m.useRef({view:p,previewMounted:T});m.useLayoutEffect(()=>{M.current={view:p,previewMounted:T}});const{requestSave:U,confirmation:B}=S.useSaveRequest(e),z=m.useRef(U);m.useLayoutEffect(()=>{z.current=U});const H=m.useRef(null),a=m.useRef(null),I=m.useRef(!1),A=m.useMemo(()=>({editor:f.editorLabel(t),useOurs:f.conflictUseOurs,useTheirs:f.conflictUseTheirs,keepBoth:f.conflictKeepBoth}),[f,t]),v=m.useCallback(k=>{const{region:R,paneScroll:V}=L.current,j=R();return j===null?k:V.scrollerOf(j,k)},[]);m.useLayoutEffect(()=>{const k=d.current,R=i.draft(e);if(k===null||R===null)return;const V=i.editorState.get(e),j=Vt(V)&&V.generation===N.current?V:null;let $=null,ee=null;const ue=()=>{$!==null&&clearTimeout($),$=null,ee!==null&&i.setDraft(e,ee.text())},W=it({parent:k,scroll:{scrollerOf:P=>{const{layout:te,region:Fe,paneScroll:Ue}=L.current,ve=Fe();return te==="fill"||ve===null?P:Ue.scrollerOf(ve,P)},reveal:P=>L.current.paneScroll.reveal(P)},text:R,saved:j===null?void 0:j.state,labels:A,revisions:w,onGeometry:P=>h.current?.editorChanged(P),onChange:P=>{if($??=setTimeout(ue,He),!P)for(const te of[...c])te();M.current.previewMounted&&ee!==null&&u.current?.draft({text:ee.text(),revision:w.revision()})},onSave:()=>z.current()});ee=W,E.current=W;const pe=()=>{const P=W.topLine();return{line:P.line,clientTop:P.clientTop}},ge=()=>u.current?.anchor(v)??null,ze=i.bindEditor(e,{flush:ue,adopt:P=>W.replaceText(P),returnPoint:()=>{const P=M.current.view==="preview"&&L.current.layout==="content"?ge():null;return P===null?pe():{line:P.lines.first,clientTop:P.clientTop}},nextConflict:()=>M.current.view!=="preview"?W.nextConflict():W.conflicts().length===0?!1:(I.current=!0,i.setView(e,"editor"),!0),beforeView:P=>{if(L.current.layout==="fill")return;if(P==="preview"){H.current={to:"preview",point:pe()};return}const te=ge();H.current=te===null?null:{to:"editor",anchor:te}}});return j!==null&&W.showLine(j.topLine),()=>{ue(),i.editorState.set(e,{state:W.save(),generation:N.current,topLine:W.topLine().line}),ze(),W.destroy(),ee=null,E.current=null}},[i,e,A,v,c,w]);const{request:x}=n;m.useLayoutEffect(()=>{const k=E.current,R=i.draft(e);k===null||R===null||x===null||(x.anchor!==null&&k.reveal(S.positionInSource(R,x.anchor),x.anchor.clientTop),k.focus(),i.consumeRequest(e))},[i,e,x,A]),m.useLayoutEffect(()=>{p!=="editor"&&!n.previewPrepared&&i.preparePreview(e)},[i,e,p,n.previewPrepared]),m.useLayoutEffect(()=>{const k=H.current,R=a.current,V=I.current;H.current=null,a.current=null,I.current=!1;const j=E.current;if(k?.to==="preview")u.current?.place(k.point,v);else if(k?.to==="editor"&&j!==null){const $=i.draft(e);$!==null&&j.reveal(S.positionInSource($,k.anchor),k.anchor.clientTop)}V?j?.nextConflict():R==="editor"?j?.focus():R==="preview"&&u.current?.focus()},[i,e,p,v]);const q=m.useMemo(()=>{const k=()=>{const R=E.current;if(R===null)throw new Error("[markdown-explorer] a table of the preview wrote back while no editor was mounted");return R};return{write:(R,{fenceLine:V,expected:j,text:$})=>k().replaceBody(V,j,$,R),read:(R,V)=>k().readBody(V,R),undo:()=>k().undo(),redo:()=>k().redo(),subscribe:R=>(c.add(R),()=>{c.delete(R)})}},[c]),G=m.useCallback(()=>{const k=E.current;if(k===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return{text:k.text(),revision:w.revision()}},[w]);m.useLayoutEffect(()=>{const k=E.current;if(!O||k===null)return;const R=yt({editor:Ve(k.scrollElement),preview:()=>u.current?.scrollPort()??null,previewBlocks:()=>u.current?.blocks()??[],editorSpans:V=>k.lineSpans(V),requestFrame:V=>requestAnimationFrame(V),cancelFrame:V=>cancelAnimationFrame(V),now:()=>performance.now()});return R.showAlone(S.paneShownAlone(M.current.view)),h.current=R,()=>{R.dispose(),h.current=null}},[O,i,e,A]),m.useLayoutEffect(()=>{h.current?.showAlone(S.paneShownAlone(p))},[p]);const Y=m.useCallback(()=>h.current?.previewChanged(),[]),F=m.useCallback(k=>i.start(e,k),[i,e]),le=k=>{if(S.isInFullscreenBlock(k.target))return;if(k.key==="Escape"){S.consumeKey(k);return}if(!S.isEditViewShortcut(k.nativeEvent,S.isApplePlatform(navigator.platform)))return;S.consumeKey(k);const R=S.toggledEditView(p);a.current=R,S.chooseEditView(i,e,R,g)},je=C.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":p,"data-testid":"markdown-explorer-edit",onKeyDown:le,onDoubleClick:Bt,children:[C.jsx("div",{ref:d,id:b,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:p==="preview",hidden:p==="preview"&&!g,...S.ALLOW_KEY_REPEAT}),p==="split"?C.jsx(Pt,{editorId:b}):null,T?C.jsx(Ot,{path:e,readDraft:G,viewer:s,tables:q,concealed:p!=="editor"?null:g?"overlay":"removed",onEditAt:p==="preview"?F:void 0,onLayout:Y,handleRef:u}):null]});return C.jsxs(C.Fragment,{children:[je,B]})};exports.DRAFT_WRITE_INTERVAL_MS=He;exports.default=Ht;
|