@aiquants/markdown-explorer 0.6.0 → 0.7.1
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 +36 -0
- package/README.md +58 -8
- package/dist/EditSurface-5nbW7NTP.cjs +2 -0
- package/dist/EditSurface-CaS1O6Nt.js +371 -0
- package/dist/{ExplorerSplit-CN5TvRj6.js → ExplorerSplit-C9Y02nvj.js} +391 -417
- package/dist/ExplorerSplit-D60N3_X7.cjs +1 -0
- package/dist/MultiLayout-CqTyFZ_i.cjs +1 -0
- package/dist/MultiLayout-DBpUTcCQ.js +947 -0
- package/dist/{NativeScrollBar-DYEv2GLV.js → NativeScrollBar-CiVlg2ob.js} +1 -1
- package/dist/{NativeScrollBar-CHEQgaVx.cjs → NativeScrollBar-QlOtnddZ.cjs} +1 -1
- package/dist/TreeLayout-bk-Ziybl.js +29 -0
- package/dist/TreeLayout-uwvAgr-t.cjs +1 -0
- package/dist/client/MarkdownExplorer.d.cts +2 -1
- package/dist/client/MarkdownExplorer.d.ts +2 -1
- package/dist/client/storage.d.cts +1 -0
- package/dist/client/storage.d.ts +1 -0
- package/dist/core/contracts.d.cts +58 -0
- package/dist/core/contracts.d.ts +58 -0
- package/dist/core/labels.d.cts +49 -0
- package/dist/core/labels.d.ts +49 -0
- package/dist/core/location.d.cts +7 -0
- package/dist/core/location.d.ts +7 -0
- package/dist/dataRoute-CcZ8PK00.cjs +1 -0
- package/dist/dataRoute-D1vE1wFW.js +270 -0
- package/dist/index-Dlkzr6Zn.cjs +13 -0
- package/dist/index-etFEpIE_.js +3199 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +31 -30
- package/dist/location-DmzVAFvo.cjs +1 -0
- package/dist/{location-CtM94G0O.js → location-Q4sgRrUm.js} +202 -193
- package/dist/merge-BR4jKpIc.cjs +5 -0
- package/dist/merge-DfI0ro2L.js +20 -0
- package/dist/sanitizeWorker.cjs +1 -1
- package/dist/sanitizeWorker.js +173 -172
- package/dist/server/errors.d.cts +1 -1
- package/dist/server/errors.d.ts +1 -1
- package/dist/server/ports.d.cts +33 -1
- package/dist/server/ports.d.ts +33 -1
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +882 -751
- package/dist/{storage-DA4ItHzl.js → storage-BSthKLSG.js} +14 -13
- package/dist/storage-Dgi4JXaB.cjs +1 -0
- package/dist/storage.cjs +1 -1
- package/dist/storage.js +1 -1
- package/dist/styles/markdown-explorer.css +1 -1
- package/docs/behavior/dom-hooks.md +17 -3
- package/docs/behavior/layout.md +6 -1
- package/docs/behavior/security.md +11 -1
- package/docs/behavior/url-contract.md +13 -4
- package/package.json +11 -3
- package/dist/ExplorerSplit-CUIbSLQm.cjs +0 -1
- package/dist/MultiLayout-BDcQSpa6.cjs +0 -1
- package/dist/MultiLayout-hPmV-bae.js +0 -922
- package/dist/TreeLayout-BDaIyoGT.cjs +0 -1
- package/dist/TreeLayout-CqzxLpoM.js +0 -23
- package/dist/dataRoute-CUXlMhUJ.cjs +0 -1
- package/dist/dataRoute-Ce6EIuu4.js +0 -206
- package/dist/index-B3nShkkt.cjs +0 -3
- package/dist/index-gJp1iXTc.js +0 -2238
- package/dist/location-FavgY_gB.cjs +0 -1
- package/dist/storage-Bkb2Axdi.cjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,42 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- **Line endings kept on save**: a file with `\r\n` line endings was saved with `\n` on every line, since the editor (CodeMirror) joins lines with `\n`. The edit store now keeps every text it compares, merges and hands the editor with `\n`, and writes the draft back with the line ending of the file it read (`\r\n` when the file held one, `\n` otherwise); the current document a conflict brings and a revision brought back are read the same way. A save therefore changes only the lines the reader changed. A file that already mixed endings is saved with `\r\n` throughout.
|
|
8
|
+
|
|
9
|
+
## 0.7.0 (2026-10-13)
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Editing a Markdown document** (minor): a host that gives the server the new `edit` ports lets readers edit Markdown documents in place, and the explorer brings everything around the edit — opening where the reader is, saving over the version the draft started from, merging what was saved meanwhile, a preview, the revisions and a guard for unsaved drafts.
|
|
14
|
+
- The document bar offers an **Edit** toggle (`aria-pressed`) between Source and Refresh document for a document whose `edit` is `{ kind: "inline" }` — labelled beside a page view's pane (`editDocumentLabel`, tooltip `editDocument`), icon-only and named after the document in a multi-view panel (`editDocumentNamed`) — or a link to the document's own editor in a new tab for `{ kind: "external", href }` (`editExternallyLabel`, `editExternally`, `editExternallyNamed`).
|
|
15
|
+
Pressing it opens the editor with the block at the top of the reader's view at the same place on screen; pressed again it closes the editor, asking first when the draft is unsaved (`unsavedTitle`, `unsavedBody`, `unsavedDiscard`, `unsavedStay`), and puts the editor's top line back at the same place in the rendered document (again on the fresh copy a save made the pane read, unless the reader moved meanwhile). The toggle is the same element in both states, so the focus stays on it.
|
|
16
|
+
- A double-click on a word of the rendered document opens the editor with the cursor on that word, which stays where it was on screen, in the tree and single views and in a maximized panel; a panel that is not maximized maximizes on a double-click as before. Links, controls, embedded media and drawings keep their own double-click. Places on screen are matched through the converter's source lines (`data-source-lines`, `@aiquants/markdown` 6.3's `includeSourceLines`), text to text.
|
|
17
|
+
- While a document is edited, the bar shows the session's status on one line (`editLoading`, `draftUnsaved`, `draftSaving`, `draftSaved`, `draftSavedMerged`, `draftConflicts`, `draftSaveFailed`) and the editor's actions: Next conflict while conflicts wait, the **Preview** toggle where the pane has room (a page view, a maximized panel), **History** when the host keeps revisions, **Save** (`aria-disabled` until the draft changes; Ctrl/⌘+S in the editor) and the Edit toggle; the source toggle and Refresh document step aside.
|
|
18
|
+
The announcer speaks each save's outcome (`documentSaved`, `documentSavedMerged`, …).
|
|
19
|
+
- The editor is CodeMirror 6 in a chunk loaded on demand (pointing at or focusing Edit starts the download; a chunk that fails to load shows a failure with Try again inside the pane): Markdown with GitHub's extensions, syntax colours from the explorer's tokens at 7:1, line numbers, wrapping, search, undo. Escape inside the editing surface is consumed, so a maximized panel stays maximized; Tab leaves the editor; a held Enter repeats inside it.
|
|
20
|
+
It fills the pane in a page view and a maximized panel and grows with its text in a panel that is not maximized. Every scroll it asks for moves the pane's own scroller only.
|
|
21
|
+
- Saving names the version the draft started from. When the document changed meanwhile, the draft is merged line by line (node-diff3, loaded only then) into the document as it is now: changes on different lines are saved at once (at most three writes per save), lines both sides changed differently become conflicts between git-style markers (`conflictOurs`, `conflictTheirs`) with buttons above each that keep the reader's lines, the saved lines or both (`conflictUseOurs`, `conflictUseTheirs`, `conflictKeepBoth`);
|
|
22
|
+
Next conflict (`conflictNext`) moves the cursor there and the focus to its first button. A draft that still holds markers is not saved.
|
|
23
|
+
- The preview renders the draft as the document would be (the data route's `preview` operation, sanitized like a document) beside the editor, or below it on a narrow pane, once the reader paused typing, and follows the editor's top line. Whether it shows is a setting of the reader kept in browser storage (default off).
|
|
24
|
+
- The revisions dialog lists the revisions the host keeps (`historyTitle`, `historyCurrent`, `historyKept`, `historyEntry`), shows the one picked and puts it into the draft (`historyRestore`, `historyRestored`), saved like any draft.
|
|
25
|
+
- A navigation that would take a document with an unsaved draft off the page asks first (one blocker per router); leaving the page asks through `beforeunload` only while a document is edited. Drafts survive remounts and view switches for the reader's lifetime of the explorer.
|
|
26
|
+
- A save or an edit the server answers with a grant shows a notice (`editGrantTitle`, `editGrantBody`, `editGrantAction`, `editGrantRetry`): with the new `<MarkdownExplorer onEditGrant>` the host opens the grant (a consent popup, for example) and the explorer asks again once it resolves `true`; without it, a link opens the grant in a new tab beside Try again.
|
|
27
|
+
- The server's new `edit` ports (`ExplorerEditPorts`: `source`, `save`, `preview`, `revisions`, `revision`) back the data route's new operations `edit` (GET), `save` and `preview` (POST, the draft as `text/markdown; charset=utf-8` with `X-Markdown-Explorer: edit` and the shared cross-origin check), `revisions` and `revision` (GET), behind the same authentication, deny rules (reported) and admission as a document. The draft is limited to `editMaxBytes` (default 2 MiB), must be UTF-8 without NUL, and is read before the host is called;
|
|
28
|
+
versions and revision ids are tokens of 1 to `EXPLORER_EDIT_TOKEN_MAX_LENGTH` (1024) characters. Without `edit`, the operations answer like unknown ones.
|
|
29
|
+
- New exports: `ExplorerEditPorts`, `ExplorerHostEditSource`, `ExplorerDraft`, `ExplorerHostSaveResult`, `ExplorerHostPreview` (server entry), `ExplorerDocumentEdit`, `ExplorerGrantRequired`, `ExplorerRevision` and `EXPLORER_EDIT_TOKEN_MAX_LENGTH` (root entry). New DOM hooks for the editor, its status, actions, preview, grant notices, the confirmation and the revisions dialog (see [DOM hooks](docs/behavior/dom-hooks.md)); the region's `data-aqmx-document-view` gains `edit`.
|
|
30
|
+
- The server's sanitizer keeps the converter's source lines (`data-source-lines` in the form `<first>-<last>`) on any element.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- **Source in the URL** (minor): whether a Markdown document shows as written is part of the URL (`markup`), so a reload, a shared link and Back and Forward show it the same way. The tree and single views write `markup=true` for their document, the multi view one `markup=<document>` per open document shown as written, in the order of `doc`; the Source toggle replaces the entry (in a page view without the fragment, so the swapped content is not taken back to its target).
|
|
35
|
+
- The choice belongs to the document in the URL, no longer to the reader: another document, a panel navigated to another document and a reopened panel show rendered, while a source switch, the reveal's move of the tree and the switches between the tree and multi views (the view switch, opening a selection that holds the tree view's document) carry it. The document still shown while the next one loads keeps the way it showed.
|
|
36
|
+
- `ExplorerLocation` gains `markup` (a boolean in the tree and single views, a list in the multi view) and `ExplorerHrefTarget` an optional `markup`; `explorerHref` refuses a multi-view document shown as written that is not open or repeats, and a tree view without a document shown as written. The resolver redirects a multi-view `markup` that is not canonical (not open, repeated, out of order) and ignores a tree or single value other than `true`.
|
|
37
|
+
- **Breaking for hosts:** a Markdown document a host's `document` port answers must carry `edit` — `null`, `{ kind: "inline" }` (only with the `edit` ports) or `{ kind: "external", href }` with an absolute `https:` URL. A Markdown document without it is a contract violation (logged, and the reader sees `failed`); `createFileSystemSource` answers `edit: null`.
|
|
38
|
+
|
|
39
|
+
## 0.6.0 (2026-10-13)
|
|
40
|
+
|
|
5
41
|
### Added
|
|
6
42
|
|
|
7
43
|
- **Source of a Markdown document** (minor): the document bar offers a **Source** toggle before Refresh document while its document is a loaded Markdown document — labelled beside a page view's pane (`showMarkupLabel` «Source» / 「ソース」, tooltip `showMarkup`), icon-only and named after the document in a multi-view panel (`showMarkupNamed`) — a toggle button (`aria-pressed`) that shows the document as written instead of rendered, in place, keeping the focus on the toggle.
|
package/README.md
CHANGED
|
@@ -19,8 +19,14 @@ reloaded document is announced, and a failed reload keeps the document under a n
|
|
|
19
19
|
announced too and stays until a newer copy of the document replaces or confirms it, the reader moves to another
|
|
20
20
|
document, or the next refresh starts.
|
|
21
21
|
Beside it, a Markdown document offers **Source**: a toggle that shows the document as written instead of rendered
|
|
22
|
-
(its file read through the data route's `text` operation, shown like a text file)
|
|
23
|
-
|
|
22
|
+
(its file read through the data route's `text` operation, shown like a text file). The choice is part of the URL
|
|
23
|
+
(`markup`), so a reload, a shared link and Back and Forward show the document the same way, and the switches between
|
|
24
|
+
the tree and multi views carry it; another document opens rendered.
|
|
25
|
+
With the server's `edit` ports, a Markdown document also offers **Edit**: the reader edits its Markdown in place
|
|
26
|
+
(CodeMirror, loaded on demand), from where they were reading or from the word they double-clicked, saves over the
|
|
27
|
+
version the draft started from (changes saved elsewhere are merged line by line, and conflicts are resolved in the
|
|
28
|
+
editor), previews the draft beside the editor, brings back an older revision, and is asked before an unsaved draft
|
|
29
|
+
is lost (see [Editing](#editing)).
|
|
24
30
|
A single-view (embedding) page never downloads the tree and multi-panel views, which load on demand.
|
|
25
31
|
- **Embeds and link cards** — with `embeds` in the configuration, a link alone in a paragraph shows its post or video from up to ten providers (YouTube, X, Instagram, Threads, TikTok, Bluesky, LinkedIn, Reddit, note and niconico) in a cross-origin frame, with no provider script in the page, or a link card the explorer's own data route reads (`{dataPath}/link-card`, through `@aiquants/markdown`'s link-card handler: internal addresses never become cards); the link itself always stays, under the frame, as the card or as the paragraph.
|
|
26
32
|
- **Secure by default** — Markdown HTML is sanitized on the server with an allow-list (scripts, event handlers, `srcdoc` and foreign iframes never reach the browser), and the document viewer applies its own on every render (a document keeps only the converter's class tokens, and ids only on headings, footnotes and `user-content-…` targets); document paths are validated, and deny rules hide environment files, keys and version-control metadata through up to three percent-decoding levels; tokens, principals, server paths and raw error messages never leave the server.
|
|
@@ -31,7 +37,7 @@ A single-view (embedding) page never downloads the tree and multi-panel views, w
|
|
|
31
37
|
|
|
32
38
|
- React 19.2.7 or later and React Router 8 in framework mode (route modules with `loader` / `headers`).
|
|
33
39
|
- 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)`.
|
|
34
|
-
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^6.
|
|
40
|
+
- The peer packages, at these versions or later within the caret ranges the package declares: `@aiquants/markdown` ^6.3.0 (document rendering; its math diagnostics, gantt sizing, embeds, link cards and their sizes, the React-free `@aiquants/markdown/embeds` the sanitizer worker loads and `@aiquants/markdown/source-lines` the editor and the sanitizer read, and the Node-only link-card handler of `@aiquants/markdown/server`, which needs Node.js 22.13 or later — below the explorer's own floor),
|
|
35
41
|
`@aiquants/directory-tree` ^4.1.1 (reveals of rows under the scroll bar's buttons), `@aiquants/drag-drop-panels` ^0.10.0, `@aiquants/resize-panels` ^2.1.0 (the source of each layout change, by which the tree pane's width is saved) and `@aiquants/virtualscroll` ^3.11.4.
|
|
36
42
|
The client depends on these floors, while a package manager may only warn about an older peer.
|
|
37
43
|
- A Markdown parser of your choice on the server that produces HTML and its headings (the explorer sanitizes the HTML before it is sent).
|
|
@@ -246,15 +252,16 @@ to; load it when your documents contain math.
|
|
|
246
252
|
| View | URL | What it shows |
|
|
247
253
|
| --- | --- | --- |
|
|
248
254
|
| Tree | `{basePath}/{tree}` or `{basePath}/{tree}/{document}` | The source tree beside the selected document |
|
|
249
|
-
| Multi-panel | `{basePath}/{multi}?doc=…&doc=…&maximized=…` | Several documents as panels in columns |
|
|
255
|
+
| Multi-panel | `{basePath}/{multi}?doc=…&doc=…&maximized=…&markup=…` | Several documents as panels in columns |
|
|
250
256
|
| Single | `{basePath}/{single}/{document}` | One document over the whole frame (for reading and embedding) |
|
|
251
257
|
|
|
252
258
|
- `?source=<id>` selects the tree's source among the server's sources; the first source is the default and is written by omission. Switching the source never closes open documents — a document path names one document whichever trees list it.
|
|
253
259
|
- A document path occupies one URL segment. Build links with `explorerHref(config, target)`, the only function that writes explorer URLs; read them back with `resolveExplorerLocation(config, splat, search)`. Both need the server's source ids for the `source` parameter: pass a configuration joined with them, `withExplorerSources(config, sourceIds)` (`ExplorerLocationConfig`; `isExplorerSourceId` is the id rule, and an empty, invalid or repeated id throws a `RangeError`).
|
|
254
260
|
`explorerHref` also accepts a plain `ExplorerConfig` with a target without `source` (`ExplorerSourcelessHrefTarget`, the default source), such as a host menu's link; a target with a `source` and a configuration without ids throws a `TypeError` naming `withExplorerSources`, as does `resolveExplorerLocation` with such a configuration.
|
|
255
|
-
`explorerHref` throws a `RangeError` for a target the resolver would redirect or partly ignore — repeated or more than `multiView.maxPanels` documents, a maximized document that is not open, an unknown source or document style, an unsupported alignment or embedding value — so every link it writes resolves back to the location given.
|
|
261
|
+
`explorerHref` throws a `RangeError` for a target the resolver would redirect or partly ignore — repeated or more than `multiView.maxPanels` documents, a maximized document or a document shown as written that is not open, an unknown source or document style, an unsupported alignment or embedding value, a tree view without a document shown as written — so every link it writes resolves back to the location given.
|
|
256
262
|
- The single view accepts embedding parameters: `showToc=false`, `showStyle=false`, `showAlign=false`, `padding` (0–256 px, written in decimal digits), `width` and `maxWidth` (a CSS length in px, rem, em, ch, vw or %; the column never grows wider than the pane, whatever the value). The tree and single views accept `style` and `align` as display overrides.
|
|
257
|
-
-
|
|
263
|
+
- `markup` names the Markdown documents shown as written (the Source toggle): `markup=true` for the tree or single view's document, and one `markup=<document>` per open document shown that way in the multi view, in the order of `doc`. In `ExplorerLocation` it is a boolean in the tree and single views and a list in the multi view; a target without it shows every document rendered.
|
|
264
|
+
- History: a click in the tree replaces the URL's document; links inside a document, entries of its table of contents (in the tree and single views, to the heading's hash), source switches and view switches push; every multi-view action and the Source toggle replace (hiding and showing a panel leave the URL unchanged).
|
|
258
265
|
- An entry of a document's table of contents links to its heading's own address: the page's URL with the heading's fragment, or, in a multi-view panel, the panel's document in the tree view with that fragment, so a modified or middle click, a new tab or a copied address opens the heading (see [URL contract](docs/behavior/url-contract.md#table-of-contents)).
|
|
259
266
|
|
|
260
267
|
The full contract, including canonicalization, is in [URL contract](docs/behavior/url-contract.md).
|
|
@@ -343,7 +350,7 @@ Notices are shown in your own words, as given; a malformed notice list is logged
|
|
|
343
350
|
|
|
344
351
|
```ts
|
|
345
352
|
type ExplorerDocument =
|
|
346
|
-
| { kind: "markdown"; name: string; htmlContent: string; headings: { text: string; depth: number; id: string }[] }
|
|
353
|
+
| { kind: "markdown"; name: string; htmlContent: string; headings: { text: string; depth: number; id: string }[]; edit: ExplorerDocumentEdit | null }
|
|
347
354
|
| { kind: "text"; name: string; text: string; truncated: boolean; url: string }
|
|
348
355
|
| { kind: "image"; name: string; url: string }
|
|
349
356
|
| { kind: "media"; name: string; url: string; mediaType: "video" | "audio" | "pdf" }
|
|
@@ -356,6 +363,7 @@ This is the document the browser receives. Your `document` port answers `Explore
|
|
|
356
363
|
`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)).
|
|
357
364
|
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`.
|
|
358
365
|
`failureDocument(reason, code?)` returns an `ExplorerFailureDocument`, which both unions accept.
|
|
366
|
+
A markdown document says how the reader may edit it in `edit` (`ExplorerDocumentEdit`), which every markdown answer must carry: `null` (no editing), `{ kind: "inline" }` (in the explorer, through the server's `edit` ports; without them the answer breaks the contract) or `{ kind: "external", href }` (the document's own editor, an absolute `https:` URL the bar opens in a new tab). Decide it per document and per reader (see [Editing](#editing)); `createFileSystemSource` answers `null`.
|
|
359
367
|
A `text` document shows the beginning of a file under the file header (its name, Open in a new tab and Download, so a truncated preview can still be fetched whole); a `file` document is a file the explorer cannot show, which every view (single, tree, the multi view's panels) shows as a download view: the file header over a note (the label `fileNotShown`) with a download link.
|
|
360
368
|
|
|
361
369
|
A markdown document lists at most `EXPLORER_MAX_HEADINGS` (10,000) headings; one that lists more is answered `too-large`, because every listed heading travels with the document (in the data response, the browser's document cache and the viewer's table of contents, one entry each) and a parser can list headings its HTML never renders (`#` lines inside a math block), so none of the HTML's limits bounds the list. A cache of your parser's results can rely on the same bound.
|
|
@@ -375,6 +383,32 @@ Your parser resolves each link and each image; the rules are in [Document links]
|
|
|
375
383
|
a missing target gets `data-asset-exists="false"`, which the viewer shows as a labelled placeholder; a relative `src` left as written would resolve against the page URL and load an explorer page instead), and the demo's parser (`demo/app/markdown.server.ts` in the source repository) is a complete example.
|
|
376
384
|
The deny rules are checked on the document's path only: a parser that expands include directives (such as `<!-- @import "…" -->`) must apply them to every file it reads, or leave such directives unexpanded (`@aiquants/markdown`'s `parseMarkdown` leaves them unexpanded unless `resolveImports` is set, and applies the `deniedPathSegments` you give it, the explorer's rules, to every import, image and link target). The explorer serves the files of documents and embedded images itself (see [Serving files](#serving-files)).
|
|
377
385
|
|
|
386
|
+
### Editing
|
|
387
|
+
|
|
388
|
+
Give `createMarkdownExplorer` the editor's ports as `edit` (`ExplorerEditPorts`) and answer `edit: { kind: "inline" }` for the markdown documents a reader may edit. Each port receives the context, the document path and the admitting source's `readPath`, after the deny rules (a refusal is logged) and the same admission as a document; refuse with `ExplorerError` as anywhere else, and check in every port that this reader may edit this document, since a request can name any path.
|
|
389
|
+
|
|
390
|
+
```ts
|
|
391
|
+
edit: {
|
|
392
|
+
// The whole source and its version (an opaque token naming this content), or a grant to ask for first
|
|
393
|
+
source: async (context, path, readPath) => ({ kind: "edit", text, version, history: true }), // or { kind: "grant", href: "/auth/consent?grant=edit" }
|
|
394
|
+
// Write only if the document still has draft.baseVersion; otherwise write nothing and answer the current content
|
|
395
|
+
save: async (context, path, readPath, draft) => ({ kind: "saved", version: newVersion }), // or { kind: "conflict", version, text } / a grant
|
|
396
|
+
// Render the draft exactly as the document would be (the explorer sanitizes it like a document)
|
|
397
|
+
preview: async (context, path, readPath, text) => ({ htmlContent, headings }),
|
|
398
|
+
// The revisions you keep, newest first, and one revision's text
|
|
399
|
+
revisions: async (context, path, readPath) => [{ id, modifiedAt, size, author, kept, current }],
|
|
400
|
+
revision: async (context, path, readPath, revisionId) => text,
|
|
401
|
+
},
|
|
402
|
+
editMaxBytes: 2 * 1024 * 1024, // the largest source and draft, the default
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
- **Versions.** A version and a revision id are tokens of 1 to `EXPLORER_EDIT_TOKEN_MAX_LENGTH` (1024) characters: whatever makes a conditional write possible on your storage (an object generation, a revision id, a modification time with the size).
|
|
406
|
+
`save` must write only when the document still has the version the draft started from; when it changed, answer `conflict` with the current version and text and write nothing. The browser then merges the draft into that text line by line and saves again over the new version (up to three writes per save), or leaves the conflicts in the draft for the reader.
|
|
407
|
+
- **Limits.** A draft (`save`, `preview`) is read before any port is called: `text/markdown` with no charset or `utf-8`, at most `editMaxBytes` bytes (`too-large`, 413), valid UTF-8 without NUL (`invalid`, 400). A source, a conflict's text or a revision longer than `editMaxBytes` breaks the contract (logged, `failed`); refuse such a document in `source` with `ExplorerError("too-large")` instead.
|
|
408
|
+
- **Grants.** Answer `{ kind: "grant", href }` from `source` or `save` when the reader must first allow writing (an OAuth consent for a wider scope, for example); `href` is a root-relative address of your own. The explorer shows a notice whose action calls `<MarkdownExplorer onEditGrant>` with it, or, without that prop, links to it in a new tab beside Try again.
|
|
409
|
+
- **Operations.** The data route answers `GET <dataPath>/edit?path=`, `POST <dataPath>/save?path=&base=<version>`, `POST <dataPath>/preview?path=`, `GET <dataPath>/revisions?path=` and `GET <dataPath>/revision?path=&revision=<id>`. `save` and `preview` carry `X-Markdown-Explorer: edit` and must pass the shared cross-origin check, like a refresh. Without `edit`, these operations answer as unknown ones (404), and `editMaxBytes` alone throws.
|
|
410
|
+
- **Source lines.** The editor opens at the place the reader was reading, or at the word they double-clicked, and the preview follows the editor, through the source lines your converter writes on every block: `data-source-lines="<first>-<last>"` (1-based, both inclusive), `@aiquants/markdown`'s `includeSourceLines`. Without them the editor opens at the start of the document; the sanitizer keeps the attribute only in that form.
|
|
411
|
+
|
|
378
412
|
### Revealing the open document
|
|
379
413
|
|
|
380
414
|
The reader's tree setting "Reveal the open document" (`revealDocument`, off in `DEFAULT_TREE_SETTINGS`; turn it on for every reader with `defaultTreeSettings: { revealDocument: true }`) opens the folders down to the open document and brings its row into the tree's window. The open document is the URL's document in the tree view (whatever the selection mode, "Off" included), and in the multi view the maximized panel's document, else the one opened last (a panel's link replaces its document; on load, where no order of opening is known, the last open document in layout order).
|
|
@@ -575,6 +609,7 @@ Spread it into the configuration when your application has no sign-in: it provid
|
|
|
575
609
|
| `renderTreeFailure?` | `(failure) => ReactNode \| undefined` | Renders a tree failure you understand better (by its `code`); `undefined` keeps the explorer's own message. Your node replaces the explorer's callout inside the tree-failure element, which keeps its hooks (`data-testid="markdown-explorer-tree-failure"` and `data-aqmx-failure`); the callout is the failure's only announcement (`role="alert"`), so your node must announce itself (for example with `role="alert"`). |
|
|
576
610
|
| `lockDocumentScroll?` | `boolean` | Stops the page itself from scrolling while the explorer fills the viewport; the explorer must then fit in the viewport (see below). |
|
|
577
611
|
| `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. |
|
|
612
|
+
| `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. |
|
|
578
613
|
|
|
579
614
|
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.
|
|
580
615
|
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.
|
|
@@ -604,6 +639,18 @@ Nothing is listed while the explorer is hidden (a closed sheet, a collapsed expl
|
|
|
604
639
|
While listings are queued or in flight, a progress line floats at the bottom of the tree area without moving the tree ("Loading 12 folders…", or "Opening all folders (40 opened, 12 loading)…" during a press). A press stopped at a limit leaves its stop sentence in a notice above the tree, in the pane's flow (the tree moves down by the notice's height, so the notice covers no row), until the next press, Collapse all, the pane having no rows to show (a failed, empty or cleared tree), or unmount (a source or view switch). Neither is a live region: the stop is announced once.
|
|
605
640
|
A folder met again among its own ancestors (a shortcut inside its own target, or two folders holding shortcuts to each other) is shown as a loop row, "Name (already open above)", that never expands: activating it scrolls to that folder, above it, and moves the focus there.
|
|
606
641
|
|
|
642
|
+
#### The editor
|
|
643
|
+
|
|
644
|
+
A markdown document whose `edit` is `inline` gets an **Edit** toggle (`aria-pressed`) in the document bar, between Source and Refresh document: labelled beside a page view's pane, icon-only and named after the document in a multi-view panel. One whose `edit` is `external` gets a link to its own editor in a new tab instead.
|
|
645
|
+
Pressing Edit opens the editor with the block at the top of the reader's view at the same place on screen; a double-click on a word of the rendered document opens it with the cursor on that word, which stays where it was, in the tree and single views and in a maximized panel (a panel that is not maximized maximizes on its first double-click, as before; links, controls, media and drawings keep their own double-click). Pressed again, Edit closes the editor — asking first when the draft is unsaved — and the rendered document shows the editor's top line at the same place.
|
|
646
|
+
The toggle is one element in both states, so the focus stays on it.
|
|
647
|
+
While a document is edited, the bar shows the draft's status on one line and the editor's actions instead of Source and Refresh document: Next conflict while conflicts wait, Preview where the pane has room (a page view or a maximized panel), History when the host keeps revisions, and Save (Ctrl/⌘+S in the editor), which is `aria-disabled` until the draft changes; the announcer speaks each save's outcome.
|
|
648
|
+
The editor (CodeMirror 6, loaded when the reader first points at or focuses Edit) fills the pane where it can and grows with its text in a panel that is not maximized; Escape inside it is consumed, so a maximized panel stays maximized, and Tab leaves it.
|
|
649
|
+
A save writes the draft back with the line endings of the file it opened (`\r\n` when the file held one, `\n` otherwise), so editing never rewrites the lines the reader left alone; a file that already mixed endings is saved with `\r\n` throughout.
|
|
650
|
+
A save that meets changes saved elsewhere merges them line by line: changes on different lines are saved at once; lines both sides changed differently are written between git-style markers with buttons above each conflict (keep my lines, the saved lines, or both), and Next conflict moves the focus to those buttons. A draft with markers left is not saved.
|
|
651
|
+
The preview renders the draft as the document would be, beside the editor (below it on a narrow pane), once the reader pauses typing, and keeps the block of the editor's top line level with it; whether it shows is the reader's choice, kept in browser storage under `storageNamespace` (default off). History lists the revisions, shows the one picked and puts it into the draft, to be saved like any draft.
|
|
652
|
+
Drafts last while the explorer is mounted, across view switches and remounted panels. A navigation that would take a document with an unsaved draft off the page asks first (the explorer holds the router's one blocker, so render one explorer per router), and leaving the page asks through `beforeunload` while a document is edited.
|
|
653
|
+
|
|
607
654
|
### Localization
|
|
608
655
|
|
|
609
656
|
`locale` selects a built-in catalog (`MARKDOWN_EXPLORER_LABEL_CATALOGS.en` / `.ja`); `labels` overrides single keys.
|
|
@@ -656,6 +703,7 @@ Every scroller of the explorer that the reader browses gets one pointer scroll b
|
|
|
656
703
|
- 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)).
|
|
657
704
|
- A Markdown document's source (the Source toggle) is read only by the explorer's `text` operation, through the same `asset` port after the same deny rules and admission, so it serves nothing the reader could not already download: at most `textMaxBytes` of the file's beginning, decoded as UTF-8 into JSON, which the browser shows as text and never interprets.
|
|
658
705
|
- Data responses are `private, no-store` JSON with `nosniff`, a sandboxing content security policy and `same-origin` resource policy, and the data route refuses React Router's single-fetch requests (`.data`), whose answers would carry none of those headers; the tree refresh, and a document request marked as triggered by a refresh (`X-Markdown-Explorer: refresh`, which makes the host skip its caches), require the custom request header and pass the shared cross-origin check of server routes (`@aiquants/request-isolation`).
|
|
706
|
+
- Editing writes only through the host's `edit` ports, after the deny rules and the same admission as a document. A save and a preview need the custom header `X-Markdown-Explorer: edit` and pass the shared cross-origin check, and their draft is read and checked (media type, `editMaxBytes`, UTF-8 without NUL) before any port is called; a grant's `href` must be root-relative and an external editor's `https:`; the preview is sanitized exactly as a document. The host checks in every port that the reader may edit the document, and writes only over the version the draft started from.
|
|
659
707
|
- Link cards are read by `@aiquants/markdown`'s handler behind a read-only authentication (no token refresh, no `Set-Cookie`; an authentication that carries headers is refused and logged), and its guards keep every internal address from becoming a card; see [Link cards](#link-cards).
|
|
660
708
|
- Each data response carries an opaque, pseudonymous scope (an HMAC of the principal key under `scopeSecret`); when it changes, the browser drops every cache and remembered path. Browser storage is also checked against the page's scope on every page load, before anything reads it.
|
|
661
709
|
|
|
@@ -668,6 +716,7 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
668
716
|
## Known limitations
|
|
669
717
|
|
|
670
718
|
- One explorer per page: the drag-and-drop layout looks up its panels document-wide.
|
|
719
|
+
- 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 no preview; maximize it to see one.
|
|
671
720
|
- 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. 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.
|
|
672
721
|
- 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.
|
|
673
722
|
- Document kinds are the five above; `createFileSystemSource` previews only files with a known text extension or name as text and offers any other file as a `file` document (a download).
|
|
@@ -683,7 +732,8 @@ Tests and host styling may rely on the `data-testid` and `data-aqmx-*` attribute
|
|
|
683
732
|
|
|
684
733
|
The source repository holds a runnable demo next to the package (`packages/markdown-explorer/demo`): three file-system sources with anonymous access (`guide` and `notes`, kept apart by their path prefix, with one folder of the guide, `guide/a`, served lazily through `children`; and `reference`, rooted at the folder `guide/reference` inside `guide`, so a document under it appears in two trees under the same path),
|
|
685
734
|
the page and data routes, the error boundary, document and asset ports that route each path to the first source whose boundary contains it (no asset route of its own), a Markdown parser that produces document links and image targets, GitHub alerts, Zenn's message and details containers, embed placeholders, and footnotes, task lists and formulas in the Go converter's markup,
|
|
686
|
-
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),
|
|
735
|
+
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),
|
|
736
|
+
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), and the end-to-end tests' fixtures.
|
|
687
737
|
Run it with `pnpm run demo:dev` from the package folder.
|
|
688
738
|
|
|
689
739
|
## License
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("react/jsx-runtime"),p=require("react"),g=require("./index-Dlkzr6Zn.cjs"),N=require("@codemirror/commands"),F=require("@codemirror/lang-markdown"),K=require("@codemirror/language"),B=require("@codemirror/search"),A=require("@codemirror/state"),b=require("@codemirror/view"),v=require("@lezer/highlight"),Z=require("@aiquants/markdown"),z={history:N.historyField},ee=K.HighlightStyle.define([{tag:[v.tags.heading1,v.tags.heading2,v.tags.heading3,v.tags.heading4,v.tags.heading5,v.tags.heading6,v.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:v.tags.strong,fontWeight:"700"},{tag:v.tags.emphasis,fontStyle:"italic"},{tag:v.tags.strikethrough,textDecoration:"line-through"},{tag:v.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:v.tags.url,color:"var(--aqmx-syntax-url)"},{tag:v.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:v.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[v.tags.processingInstruction,v.tags.contentSeparator,v.tags.labelName,v.tags.meta],color:"var(--aqmx-syntax-mark)"}]),te=b.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)"}}),G="data-aqmx-conflict-actions",ne=b.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),oe=b.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),re=b.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class se extends b.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(G,String(this.index));for(const[s,d]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const c=document.createElement("button");c.type="button",c.textContent=d,c.setAttribute("data-aqmx-conflict-choice",s),c.addEventListener("mousedown",l=>l.preventDefault()),c.addEventListener("click",()=>{const l=D(t.state.doc)[this.index];l!==void 0&&(U(t,l,s),t.focus())}),n.append(c)}return n}ignoreEvent(){return!0}}const D=e=>g.findConflictsInLines(e.iterLines()),H=(e,t)=>{const n=new A.RangeSetBuilder;return D(e).forEach((s,d)=>{const c=e.line(s.start);n.add(c.from,c.from,b.Decoration.widget({widget:new se(d,t),block:!0,side:-1}));for(let l=s.start;l<=s.end;l+=1){const r=e.line(l).from,h=l===s.start||l===s.separator||l===s.end?ne:l<s.separator?oe:re;n.add(r,r,h)}}),n.finish()},ie=e=>A.StateField.define({create:t=>H(t.doc,e),update:(t,n)=>n.docChanged?H(n.state.doc,e):t,provide:t=>b.EditorView.decorations.from(t)}),U=(e,t,n)=>{const{doc:s}=e.state,d=(m,i)=>{const f=[];for(let u=m;u<=i;u+=1)f.push(s.line(u).text);return f},c=d(t.start+1,t.separator-1),l=d(t.separator+1,t.end-1),r=n==="ours"?c:n==="theirs"?l:[...c,...l];let h=s.line(t.start).from,o=s.line(t.end).to;r.length===0&&(t.end<s.lines?o+=1:t.start>1&&(h-=1));const a=r.join(`
|
|
2
|
+
`);e.dispatch({changes:{from:h,to:o,insert:a},selection:A.EditorSelection.cursor(h),scrollIntoView:!0,userEvent:"input.resolve"})},ae=({parent:e,scroll:t,text:n,saved:s,labels:d,onChange:c,onSave:l})=>{const r=[b.EditorView.scrollHandler.of((a,m,i)=>(le(a,m.head,i,t),!0)),b.lineNumbers(),b.highlightActiveLineGutter(),N.history(),b.drawSelection(),b.highlightActiveLine(),B.highlightSelectionMatches(),b.EditorView.lineWrapping,F.markdown({base:F.markdownLanguage}),K.syntaxHighlighting(ee),ie(d),b.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(l(),!0)},...B.searchKeymap,...N.historyKeymap,...N.defaultKeymap]),b.EditorView.contentAttributes.of({"aria-label":d.editor,"aria-multiline":"true"}),b.EditorView.updateListener.of(a=>{a.docChanged&&c()}),te],h=de(s,r)??A.EditorState.create({doc:n,extensions:r}),o=new b.EditorView({state:h,parent:e});return{text:()=>o.state.doc.toString(),replaceText:a=>{const m=o.state.doc.toString();if(m===a)return;let i=0;const f=Math.min(m.length,a.length);for(;i<f&&m.charCodeAt(i)===a.charCodeAt(i);)i+=1;let u=0;for(;u<f-i&&m.charCodeAt(m.length-1-u)===a.charCodeAt(a.length-1-u);)u+=1;o.dispatch({changes:{from:i,to:m.length-u,insert:a.slice(i,a.length-u)},userEvent:"input.replace"})},reveal:({line:a,column:m},i)=>{const{doc:f}=o.state,u=f.line(Math.min(Math.max(a,1),f.lines)),E=Math.min(u.from+m,u.to);o.dispatch({selection:A.EditorSelection.cursor(E),effects:P(o,E,i,t)})},showLine:a=>{const{doc:m}=o.state,i=m.line(Math.min(Math.max(a,1),m.lines)).from;o.dispatch({effects:P(o,i,null,t)})},topLine:()=>{const a=t.scrollerOf(o.scrollDOM),m=g.visibleTopOf(a,o.contentDOM),i=g.frameTopOf(a)+a.clientHeight,{documentTop:f}=o,{doc:u}=o.state;let E=o.lineBlockAtHeight(Math.max(m-f,0));for(;u.lineAt(E.from).text.trim()===""&&E.to<u.length;){const M=o.lineBlockAt(E.to+1);if(f+M.top>=i)break;E=M}const k=o.coordsAtPos(E.from),L=k===null?f+E.top:k.top;return{line:o.state.doc.lineAt(E.from).number,clientTop:L,offset:L-m}},scrollElement:o.scrollDOM,focus:()=>o.focus(),conflicts:()=>D(o.state.doc),resolveAtCursor:a=>{const m=D(o.state.doc),i=o.state.doc.lineAt(o.state.selection.main.head).number,f=m.find(u=>u.end>=i);return f===void 0?!1:(U(o,f,a),!0)},nextConflict:()=>{const a=D(o.state.doc);if(a[0]===void 0)return!1;const i=o.state.doc.lineAt(o.state.selection.main.head).number,f=a.findIndex(L=>L.start>i),u=f<0?0:f,E=o.state.doc.line(a[u].start).from;o.dispatch({selection:A.EditorSelection.cursor(E),effects:b.EditorView.scrollIntoView(E,{y:"center"})});const k=o.contentDOM.querySelector(`[${G}="${String(u)}"] button`);return k instanceof HTMLElement?k.focus({preventScroll:!0}):o.focus(),!0},save:()=>o.state.toJSON(z),destroy:()=>o.destroy()}},P=(e,t,n,s)=>{const d=s.scrollerOf(e.scrollDOM),c=(n===null?g.visibleTopOf(d,e.contentDOM):n)-g.frameTopOf(d);return b.EditorView.scrollIntoView(t,{y:"start",yMargin:c})},le=(e,t,n,s)=>{const d=ce(e,t),c=s.scrollerOf(e.scrollDOM),l=g.frameTopOf(c),r=g.visibleTopOf(c,e.contentDOM),h=l+c.clientHeight;let o=0;switch(n.y){case"start":o=d.top-(l+n.yMargin);break;case"center":o=(d.top+d.bottom)/2-(r+h)/2;break;case"end":o=d.bottom-(h-n.yMargin);break;default:d.top<r+n.yMargin?o=d.top-(r+n.yMargin):d.bottom>h-n.yMargin&&(o=Math.min(d.bottom-(h-n.yMargin),d.top-(r+n.yMargin)))}if(o!==0&&(c.scrollTop+=o),n.y==="start")return;const a=ue(e,t);a!==null&&s.reveal(a)},ce=(e,t)=>{const{node:n,offset:s}=e.domAtPos(t);if(n.nodeType===Node.TEXT_NODE){const l=n.ownerDocument?.createRange();if(l!==void 0){l.setStart(n,s),l.setEnd(n,s);const[r]=l.getClientRects();if(r!==void 0&&r.height>0)return{top:r.top,bottom:r.bottom}}}const d=e.lineBlockAt(t),c=e.documentTop+d.top;return{top:c,bottom:c+d.height}},ue=(e,t)=>{const{node:n}=e.domAtPos(t);for(let s=n instanceof Element?n:n.parentElement;s!==null;s=s.parentElement)if(s.parentElement===e.contentDOM)return s;return null},de=(e,t)=>{if(e==null)return null;try{return A.EditorState.fromJSON(e,{extensions:t},z)}catch{return null}},fe=610,me="[data-aqmd-scroll-container]",he=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),pe=Object.freeze({parsed:null,failure:null,busy:!0}),W=(e,t)=>{const n=e.querySelector(me),s=g.blockAtLine(e,t.line);n===null||s===null||(n.scrollTop+=g.lineTopIn(s,t.line)-(g.visibleTopOf(n,s)+t.offset))},ge=({path:e,text:t,viewer:n,editorPoint:s,handleRef:d})=>{const{data:c,labels:l}=g.useExplorer(),[r,h]=p.useState(pe),o=p.useRef(null);p.useEffect(()=>{const i=new AbortController;h(u=>u.busy?u:{...u,busy:!0});const f=setTimeout(()=>{c.preview(e,t,i.signal).then(u=>{i.signal.aborted||!("kind"in u)||(u.kind==="failure"?h(E=>({parsed:E.parsed,failure:u.failure,busy:!1})):h({parsed:{htmlContent:u.htmlContent,headings:[...u.headings]},failure:null,busy:!1}))})},fe);return()=>{clearTimeout(f),i.abort()}},[c,e,t]);const a=p.useEffectEvent(()=>{const i=o.current,f=s();i!==null&&f!==null&&W(i,f)});p.useLayoutEffect(()=>{r.parsed!==null&&a()},[r.parsed]),p.useImperativeHandle(d,()=>({follow:i=>{const f=o.current;f!==null&&W(f,i)}}),[]);const m=p.useMemo(()=>({...n,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0}),[n]);return x.jsxs("section",{ref:o,className:"aqmx-edit-preview","aria-label":l.previewRegion,"aria-busy":r.busy,"data-testid":"markdown-explorer-edit-preview",children:[r.failure===null?null:x.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:l.previewFailed(g.failureTitleOf(l,r.failure.reason))}),r.parsed!==null?x.jsx("div",{className:"aqmx-document-viewer",children:x.jsx(Z.MarkdownViewer,{...m,parseResult:r.parsed,content:null})}):r.failure===null?x.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:he.map(i=>x.jsx("span",{},i))}):null,r.busy?x.jsx("p",{className:"aqmx-sr-only",children:l.previewUpdating}):null]})},$=144,xe=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),Ee=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"},be=e=>{e.key==="Escape"&&g.consumeKey(e)},ve=e=>{e.stopPropagation()},ye=e=>{const{path:t,name:n,session:s}=e,{edits:d,labels:c,announcer:l}=g.useExplorer(),{phase:r}=s,h=p.useCallback(()=>d.retry(t),[d,t]);switch(p.useEffect(()=>{r.kind==="failed"&&l.announce(c.documentFailed(n,g.failureTitleOf(c,r.failure.reason)))},[r,l,c,n]),r.kind){case"opening":return x.jsxs(x.Fragment,{children:[x.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:xe.map(o=>x.jsx("span",{},o))}),x.jsx("p",{className:"aqmx-sr-only",children:c.editLoading})]});case"grant":return x.jsx("div",{className:"aqmx-edit-message",children:x.jsx(g.EditGrantNotice,{href:r.href,onRetry:h,testId:"markdown-explorer-edit-grant"})});case"failed":return x.jsx("div",{className:"aqmx-edit-message",children:x.jsx(g.FailureView,{failure:r.failure,alert:!1,onRetry:h,testId:"markdown-explorer-edit-failure"})});case"editing":return x.jsx(we,{...e})}},we=({path:e,name:t,session:n,layout:s,viewer:d,region:c,paneScroll:l})=>{const{edits:r,labels:h}=g.useExplorer(),o=p.useRef(null),a=p.useRef(null),m=p.useRef(null),i=g.usePreviewShown()&&s==="fill",[f,u]=p.useState(null),E=p.useRef({layout:s,region:c,paneScroll:l});p.useLayoutEffect(()=>{E.current={layout:s,region:c,paneScroll:l}});const k=p.useRef(n.generation);p.useLayoutEffect(()=>{k.current=n.generation});const L=p.useRef(i);p.useLayoutEffect(()=>{L.current=i});const M=p.useMemo(()=>({editor:h.editorLabel(t),useOurs:h.conflictUseOurs,useTheirs:h.conflictUseTheirs,keepBoth:h.conflictKeepBoth}),[h,t]);p.useLayoutEffect(()=>{const y=o.current,q=r.draft(e);if(y===null||q===null)return;const S=r.editorState.get(e),C=Ee(S)&&S.generation===k.current?S:null;let O=null,R=null;const _=()=>{if(O!==null&&clearTimeout(O),O=null,R===null)return;const w=R.text();r.setDraft(e,w),L.current&&u(w)},T=ae({parent:y,scroll:{scrollerOf:w=>{const{layout:Y,region:X,paneScroll:Q}=E.current,V=X();return Y==="fill"||V===null?w:Q.scrollerOf(V,w)},reveal:w=>E.current.paneScroll.reveal(w)},text:q,saved:C===null?void 0:C.state,labels:M,onChange:()=>{O??=setTimeout(_,$)},onSave:()=>{r.save(e)}});R=T,a.current=T;const J=r.bindEditor(e,{flush:_,adopt:w=>T.replaceText(w),returnPoint:()=>{const w=T.topLine();return{line:w.line,clientTop:w.clientTop}},nextConflict:()=>T.nextConflict()});return C!==null&&T.showLine(C.topLine),()=>{_(),r.editorState.set(e,{state:T.save(),generation:k.current,topLine:T.topLine().line}),J(),T.destroy(),R=null,a.current=null}},[r,e,M]);const{request:I}=n;p.useLayoutEffect(()=>{const y=a.current,q=r.draft(e);y===null||q===null||I===null||(I.anchor!==null&&y.reveal(g.positionInSource(q,I.anchor),I.anchor.clientTop),y.focus(),r.consumeRequest(e))},[r,e,I,M]),p.useEffect(()=>{i&&(r.flush(e),u(r.draft(e)))},[r,e,i]);const j=p.useCallback(()=>{const y=a.current;if(y===null)return null;const q=y.topLine();return{line:q.line,offset:q.offset}},[]);return p.useEffect(()=>{const y=a.current;if(!i||y===null)return;const q=y.scrollElement;let S=0;const C=()=>{S=0;const R=j();R!==null&&m.current?.follow(R)},O=()=>{S===0&&(S=requestAnimationFrame(C))};return q.addEventListener("scroll",O,{passive:!0}),()=>{q.removeEventListener("scroll",O),cancelAnimationFrame(S)}},[i,j,M]),x.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":s,"data-testid":"markdown-explorer-edit",onKeyDown:be,onDoubleClick:ve,children:[x.jsx("div",{ref:o,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",...g.ALLOW_KEY_REPEAT}),i&&f!==null?x.jsx(ge,{path:e,text:f,viewer:d,editorPoint:j,handleRef:m}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=$;exports.default=ye;
|