@aiquants/markdown-explorer 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +173 -15
  2. package/README.md +73 -27
  3. package/dist/EditSurface-0owpPyLE.js +786 -0
  4. package/dist/EditSurface-D-nhilRk.cjs +2 -0
  5. package/dist/{ExplorerSplit-BPLECNpv.js → ExplorerSplit-8c93p1hy.js} +613 -592
  6. package/dist/ExplorerSplit-bpEvHrCo.cjs +1 -0
  7. package/dist/MultiLayout-BXfzR6XC.cjs +1 -0
  8. package/dist/MultiLayout-Dy3DD_09.js +963 -0
  9. package/dist/NativeScrollBar-CI9fTvkt.js +65 -0
  10. package/dist/NativeScrollBar-Ddn0iHjv.cjs +1 -0
  11. package/dist/TreeLayout-CKZ-XQgn.cjs +1 -0
  12. package/dist/TreeLayout-eFQmzpNj.js +72 -0
  13. package/dist/client/storage.d.cts +1 -0
  14. package/dist/client/storage.d.ts +1 -0
  15. package/dist/core/geometry.d.cts +20 -1
  16. package/dist/core/geometry.d.ts +20 -1
  17. package/dist/core/labels.d.cts +17 -0
  18. package/dist/core/labels.d.ts +17 -0
  19. package/dist/core/location.d.cts +3 -0
  20. package/dist/core/location.d.ts +3 -0
  21. package/dist/core/treeSettings.d.cts +3 -1
  22. package/dist/core/treeSettings.d.ts +3 -1
  23. package/dist/index-5gwNJ8CB.cjs +13 -0
  24. package/dist/index-h9e3p5Pd.js +3645 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +25 -25
  27. package/dist/location-D85EXiPt.cjs +1 -0
  28. package/dist/location-G7psbmv_.js +499 -0
  29. package/dist/{merge-Bi2VedIr.js → merge-CS3p9BVw.js} +5 -5
  30. package/dist/{merge-BFk7nT59.cjs → merge-C_g05UGC.cjs} +1 -1
  31. package/dist/server.cjs +1 -1
  32. package/dist/server.js +1 -1
  33. package/dist/{storage-BSthKLSG.js → storage-CmGHg7OA.js} +11 -10
  34. package/dist/storage-DM0EvkVf.cjs +1 -0
  35. package/dist/storage.cjs +1 -1
  36. package/dist/storage.js +1 -1
  37. package/dist/styles/markdown-explorer.css +1 -1
  38. package/dist/useSplitPersistence-B1b5Lg5E.js +42 -0
  39. package/dist/useSplitPersistence-DRjsPZdH.cjs +1 -0
  40. package/docs/behavior/dom-hooks.md +19 -11
  41. package/docs/behavior/layout.md +121 -42
  42. package/docs/behavior/localization.md +12 -6
  43. package/docs/behavior/url-contract.md +18 -6
  44. package/package.json +5 -5
  45. package/dist/EditSurface-BLlu5zEt.cjs +0 -2
  46. package/dist/EditSurface-CF2io496.js +0 -705
  47. package/dist/ExplorerSplit-Cjvy0JHP.cjs +0 -1
  48. package/dist/MultiLayout-BjA0k-5n.cjs +0 -1
  49. package/dist/MultiLayout-D8F0BfxA.js +0 -947
  50. package/dist/NativeScrollBar-BFF12oEd.js +0 -59
  51. package/dist/NativeScrollBar-BUWXPvTV.cjs +0 -1
  52. package/dist/TreeLayout-CQUpgsxz.cjs +0 -1
  53. package/dist/TreeLayout-rhyVTfrI.js +0 -29
  54. package/dist/index-Dn7cYy-4.cjs +0 -13
  55. package/dist/index-v997iKxe.js +0 -3464
  56. package/dist/location-D6RE3wAN.cjs +0 -1
  57. package/dist/location-IRD9h42r.js +0 -444
  58. package/dist/storage-Dgi4JXaB.cjs +0 -1
@@ -6,18 +6,19 @@ This page is part of the host-facing contract of `@aiquants/markdown-explorer`;
6
6
 
7
7
  | View | Path | Query |
8
8
  | --- | --- | --- |
9
- | Tree | `{basePath}/{views.tree}` or `{basePath}/{views.tree}/{document}` | `source`, `style`, `align`, `markup` |
9
+ | Tree | `{basePath}/{views.tree}`, `{basePath}/{views.tree}/{document}` or `{basePath}/{views.tree}/{folder}/` | `source`, `style`, `align`, `markup` |
10
10
  | Multi-panel | `{basePath}/{views.multi}` | `source`, `doc` (repeated, in panel order), `maximized`, `markup` (repeated, in the order of `doc`) |
11
11
  | Single | `{basePath}/{views.single}/{document}` | `source`, `style`, `align`, `markup`, `showToc`, `showStyle`, `showAlign`, `padding`, `width`, `maxWidth` |
12
12
 
13
13
  - `basePath` and the view slugs come from `defineExplorerConfig` (`tree`, `multi` and `single` by default). The data route lives at `dataPath` and is not a page.
14
14
  - `source` names the source shown in the tree: one of the server's sources, whose ids come from `createMarkdownExplorer`'s `sources` in their order (the browser reads them from the page data's `sources`). The first is the default and is written by **omission**; it is never written explicitly. A source id is lowercase letters, digits and `-`, starting with a letter or digit (`isExplorerSourceId`).
15
- - `markup` names the Markdown documents shown as written (their source, the document bar's Source toggle) instead of rendered: in the tree and single views `markup=true` for the URL's document, and in the multi-panel view one `markup` per open document shown that way, in the order of `doc` (a maximized document included).
16
- `ExplorerLocation`'s `markup` is a boolean in the tree and single views (always `false` in the tree view without a document) and a list in the multi-panel view; a target without it (`ExplorerHrefTarget`) shows every document rendered. A document that is not Markdown ignores it.
15
+ - The tree view shows a document, a folder (its README, see [Folder segment](#folder-segment)) or neither: `ExplorerLocation`'s tree view has `doc` and `folder`, at most one of them not `null`.
16
+ - `markup` names the Markdown documents shown as written (their source, the document bar's Source toggle) instead of rendered: in the tree and single views `markup=true` for the URL's document — in the tree view a folder's README too —, and in the multi-panel view one `markup` per open document shown that way, in the order of `doc` (a maximized document included).
17
+ `ExplorerLocation`'s `markup` is a boolean in the tree and single views (always `false` in the tree view without a document or a folder) and a list in the multi-panel view; a target without it (`ExplorerHrefTarget`) shows every document rendered. A document that is not Markdown ignores it.
17
18
  - The source never limits which documents can be open: a path names one document; it may appear in several sources' trees, and it opens when the boundary of at least one source admits it, whichever source the URL names. Switching the source therefore keeps every open document, and a document no source's boundary admits is answered `forbidden` in every view.
18
19
  - `explorerHref(config, target)` is the only function that writes explorer URLs, and `resolveExplorerLocation(config, splat, search)` is the only one that reads them. The server's loader and the browser call the same two functions, each with a configuration joined with the server's source ids by `withExplorerSources(config, sourceIds)` (an `ExplorerLocationConfig`; no ids, an invalid id or a repeated one throws a `RangeError`).
19
20
  `explorerHref` has two forms: any target with such a configuration, and a target without `source` (`ExplorerSourcelessHrefTarget`, the default source) with a plain `ExplorerConfig`, for links built where the server's sources are not known (a host menu). A target with a `source` and a configuration without ids throws a `TypeError` naming `withExplorerSources`, and so does `resolveExplorerLocation` given such a configuration.
20
- - `explorerHref` writes only canonical URLs. It throws a `RangeError` for a target the resolver would redirect or partly ignore: an unknown source, an unacceptable document path, multi-panel documents that repeat or exceed `multiView.maxPanels`, a maximized document or a document shown as written that is not open, a document shown as written twice, a tree view without a document shown as written,
21
+ - `explorerHref` writes only canonical URLs. It throws a `RangeError` for a target the resolver would redirect, read as another location or partly ignore: an unknown source, an unacceptable document or folder path, a tree or single view's document path that ends in a slash (its segment would name a folder), a tree view with both a document and a folder, multi-panel documents that repeat or exceed `multiView.maxPanels`, a maximized document or a document shown as written that is not open, a document shown as written twice, a tree view with neither a document nor a folder shown as written,
21
22
  a `style` naming no configured document style, an `align` other than `left`, `center` or `right`, and an embedding value outside the rules below (a non-boolean switch, a padding outside 0–256 or not writable in decimal digits, a width that is not one of the accepted CSS lengths).
22
23
  Resolving a link it wrote therefore always yields the very location it was given.
23
24
 
@@ -30,6 +31,15 @@ A document path occupies one URL segment of the tree and single views.
30
31
  - The remainder of the splat after the view slug is the document path, so `/docs/tree/guide%2Fintro.md` and `/docs/tree/guide/intro.md` name the same document (`guide/intro.md`). Only the first is what `explorerHref` writes; both are accepted and neither is redirected.
31
32
  - In the multi-panel view documents are query values (`doc`, `maximized`) and need no segment encoding.
32
33
 
34
+ ## Folder segment
35
+
36
+ A folder of the tree view takes the segment of a document, with a slash after its path: the slash is added before the encoding, so the folder `guide/concepts` is `/docs/tree/guide%2Fconcepts%2F` (and `/docs/tree/guide/concepts/` names it too).
37
+
38
+ - The resolver reads a segment that ends in a slash as a folder, once that one slash is removed, so a folder whose own path ends in a slash (a cloud prefix such as `gs://bucket/notes/`) round-trips, and a document path that ends in a slash has no tree or single URL.
39
+ - A folder path is acceptable by the same rule as a document path. Whether it is a folder of the shown source is decided by the browser, from the source's tree and the `children` operation (see the README's [Folders and their READMEs](../../README.md#folders-and-their-readmes)); the URL stays as written.
40
+ - The single view shows documents only: its segment that ends in a slash redirects to the tree view's folder.
41
+ - The page loader seeds no document for a folder: which README the folder shows depends on its listing, which the browser reads.
42
+
33
43
  ## Canonical form
34
44
 
35
45
  Every URL resolves either to a location or to a redirect to its canonical form. Decisions are made on the parsed result — never by comparing URL text — and unknown query parameters are ignored, so resolving a canonical URL always yields a location and canonicalization is idempotent.
@@ -38,7 +48,9 @@ Every URL resolves either to a location or to a redirect to its canonical form.
38
48
  | --- | --- |
39
49
  | The base path, an unknown view slug, an empty splat | Redirect to the tree view without a document, keeping a valid `source` |
40
50
  | A tree or single URL whose document segment is empty (a trailing slash) or not an acceptable path | Redirect to the tree view without a document |
51
+ | A tree or single URL whose folder segment names an empty or unacceptable path | Redirect to the tree view without a document |
41
52
  | A single URL without a document | Redirect to the tree view without a document |
53
+ | A single URL whose segment names a folder | Redirect to the tree view's folder, keeping `source`, `style`, `align` and `markup` (the embedding parameters are dropped) |
42
54
  | `source` unknown, repeated, or equal to the default | Redirect to the same location with `source` dropped |
43
55
  | Multi-panel `doc` values that are not acceptable paths, repeated, or beyond `multiView.maxPanels` | Redirect with only the first occurrence of each acceptable path, in order, up to the limit |
44
56
  | `maximized` repeated, or not one of the open documents | Redirect without `maximized` |
@@ -47,7 +59,7 @@ Every URL resolves either to a location or to a redirect to its canonical form.
47
59
  | `style` naming no configured document style, `align` other than `left`, `center` or `right` | Ignored (the reader's own setting applies) |
48
60
  | `padding` outside 0–256 or not written in decimal digits (signs, exponents, hexadecimal, surrounding spaces and `Infinity` are not numbers here), `width` / `maxWidth` not a CSS length in `px`, `rem`, `em`, `ch`, `vw` or `%` | Ignored (the default applies) |
49
61
  | `showToc`, `showStyle`, `showAlign` other than `false` | Ignored (the control is shown) |
50
- | `markup` in the tree or single view other than `true`, or in the tree view without a document | Ignored (the document shows rendered) |
62
+ | `markup` in the tree or single view other than `true`, or in the tree view without a document or a folder | Ignored (the document shows rendered) |
51
63
 
52
64
  An acceptable document path is non-empty, at most 4096 UTF-16 code units long, well-formed (no lone surrogate, which no URL can carry), and contains neither a control character (U+0000–U+001F, U+007F) nor a backslash. Whether the path exists, and whether it is denied, is decided by the server for the document request; the URL itself stays as written.
53
65
 
@@ -117,7 +129,7 @@ In the tree and single views that address is the page's URL (the same view, with
117
129
 
118
130
  | Action | History entry |
119
131
  | --- | --- |
120
- | Selecting a document in the tree | Replaces the current entry (no reload of the tree) |
132
+ | Selecting a document or a folder in the tree | Replaces the current entry (no reload of the tree) |
121
133
  | Following a document link inside the tree or single view | Pushes |
122
134
  | Activating an entry of the document viewer's table of contents in the tree or single view | Pushes the heading's hash (nothing when the URL's hash already names that heading); in a multi-view panel the URL does not change |
123
135
  | Switching the tree's source | Pushes |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiquants/markdown-explorer",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "Markdown document explorer for React Router 8 (framework mode): a source tree with a single-document view and a multi-panel reading view, storage-agnostic server ports, golden-ratio layout and an en / ja UI.",
5
5
  "sideEffects": [
6
6
  "**/*.css"
@@ -69,8 +69,8 @@
69
69
  },
70
70
  "peerDependencies": {
71
71
  "@aiquants/directory-tree": "^4.1.1",
72
- "@aiquants/drag-drop-panels": "^0.10.0",
73
- "@aiquants/markdown": "^7.0.0",
72
+ "@aiquants/drag-drop-panels": "^0.11.0",
73
+ "@aiquants/markdown": "^8.0.0",
74
74
  "@aiquants/resize-panels": "^2.2.0",
75
75
  "@aiquants/virtualscroll": "^3.20.0",
76
76
  "react": "^19.2.7",
@@ -79,8 +79,8 @@
79
79
  },
80
80
  "devDependencies": {
81
81
  "@aiquants/directory-tree": "4.1.1",
82
- "@aiquants/drag-drop-panels": "0.10.0",
83
- "@aiquants/markdown": "7.0.0",
82
+ "@aiquants/drag-drop-panels": "0.11.0",
83
+ "@aiquants/markdown": "8.0.0",
84
84
  "@aiquants/resize-panels": "2.2.0",
85
85
  "@aiquants/virtualscroll": "3.20.0",
86
86
  "@heroicons/react": "^2.2.0",
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("react/jsx-runtime"),E=require("react"),y=require("./index-Dn7cYy-4.cjs"),J=require("@codemirror/commands"),ne=require("@codemirror/lang-markdown"),fe=require("@codemirror/language"),oe=require("@codemirror/search"),U=require("@codemirror/state"),A=require("@codemirror/view"),C=require("@lezer/highlight"),ye=require("@aiquants/markdown"),Q=require("@aiquants/markdown/source-lines"),G=require("./dataRoute-BONacTPi.cjs"),Z=require("./sanitizePolicy-DrIMuYCb.cjs"),Se=require("isomorphic-dompurify"),pe={history:J.historyField},ke=fe.HighlightStyle.define([{tag:[C.tags.heading1,C.tags.heading2,C.tags.heading3,C.tags.heading4,C.tags.heading5,C.tags.heading6,C.tags.heading],color:"var(--aqmx-syntax-heading)",fontWeight:"700"},{tag:C.tags.strong,fontWeight:"700"},{tag:C.tags.emphasis,fontStyle:"italic"},{tag:C.tags.strikethrough,textDecoration:"line-through"},{tag:C.tags.link,color:"var(--aqmx-syntax-link)",textDecoration:"underline"},{tag:C.tags.url,color:"var(--aqmx-syntax-url)"},{tag:C.tags.monospace,color:"var(--aqmx-syntax-code)"},{tag:C.tags.quote,color:"var(--aqmx-syntax-quote)"},{tag:[C.tags.processingInstruction,C.tags.contentSeparator,C.tags.labelName,C.tags.meta],color:"var(--aqmx-syntax-mark)"}]),Te=A.EditorView.theme({"&":{height:"100%",color:"var(--aqmx-text)",backgroundColor:"var(--aqmx-surface)",fontSize:"var(--aqmx-font-size-title)"},"&.cm-focused":{outline:"none"},".cm-scroller":{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',lineHeight:"var(--aqmx-line-height-prose)"},".cm-content":{caretColor:"var(--aqmx-text)",paddingBlock:"var(--aqmx-space-6)"},".cm-line":{paddingInline:"var(--aqmx-space-6)"},"&.cm-focused .cm-cursor":{borderLeftColor:"var(--aqmx-text)"},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"var(--aqmx-editor-selection)"},".cm-activeLine":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-gutters":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-editor-gutter)",borderInlineEnd:"var(--aqmx-space-1) solid var(--aqmx-border)"},".cm-activeLineGutter":{backgroundColor:"var(--aqmx-editor-active-line)"},".cm-searchMatch":{outline:"var(--aqmx-space-1) solid var(--aqmx-border-strong)"},".cm-panels":{backgroundColor:"var(--aqmx-surface-raised)",color:"var(--aqmx-text)"}}),me="data-aqmx-conflict-actions",Le=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"marker"}}),Me=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"ours"}}),qe=A.Decoration.line({attributes:{"data-aqmx-conflict-line":"theirs"}});class Oe extends A.WidgetType{constructor(t,r){super(),this.index=t,this.labels=r}index;labels;eq(t){return t.index===this.index&&t.labels===this.labels}toDOM(t){const r=document.createElement("div");r.setAttribute(me,String(this.index));for(const[o,s]of[["ours",this.labels.useOurs],["theirs",this.labels.useTheirs],["both",this.labels.keepBoth]]){const l=document.createElement("button");l.type="button",l.textContent=s,l.setAttribute("data-aqmx-conflict-choice",o),l.addEventListener("mousedown",a=>a.preventDefault()),l.addEventListener("click",()=>{const a=X(t.state.doc)[this.index];a!==void 0&&(he(t,a,o),t.focus())}),r.append(l)}return r}ignoreEvent(){return!0}}const X=e=>y.findConflictsInLines(e.iterLines()),ie=(e,t)=>{const r=new U.RangeSetBuilder;return X(e).forEach((o,s)=>{const l=e.line(o.start);r.add(l.from,l.from,A.Decoration.widget({widget:new Oe(s,t),block:!0,side:-1}));for(let a=o.start;a<=o.end;a+=1){const n=e.line(a).from,w=a===o.start||a===o.separator||a===o.end?Le:a<o.separator?Me:qe;r.add(n,n,w)}}),r.finish()},Ae=e=>U.StateField.define({create:t=>ie(t.doc,e),update:(t,r)=>r.docChanged?ie(r.state.doc,e):t,provide:t=>A.EditorView.decorations.from(t)}),he=(e,t,r)=>{const{doc:o}=e.state,s=(d,u)=>{const v=[];for(let m=d;m<=u;m+=1)v.push(o.line(m).text);return v},l=s(t.start+1,t.separator-1),a=s(t.separator+1,t.end-1),n=r==="ours"?l:r==="theirs"?a:[...l,...a];let w=o.line(t.start).from,f=o.line(t.end).to;n.length===0&&(t.end<o.lines?f+=1:t.start>1&&(w-=1));const i=n.join(`
2
- `);e.dispatch({changes:{from:w,to:f,insert:i},selection:U.EditorSelection.cursor(w),scrollIntoView:!0,userEvent:"input.resolve"})},Ce=({parent:e,scroll:t,text:r,saved:o,labels:s,onChange:l,onGeometry:a,onSave:n})=>{const w=[A.EditorView.scrollHandler.of((d,u,v)=>(Re(d,u.head,v,t),!0)),A.lineNumbers(),A.highlightActiveLineGutter(),J.history(),A.drawSelection(),A.highlightActiveLine(),oe.highlightSelectionMatches(),A.EditorView.lineWrapping,ne.markdown({base:ne.markdownLanguage}),fe.syntaxHighlighting(ke),Ae(s),A.keymap.of([{key:"Mod-s",preventDefault:!0,run:()=>(n(),!0)},...oe.searchKeymap,...J.historyKeymap,...J.defaultKeymap]),A.EditorView.contentAttributes.of({"aria-label":s.editor,"aria-multiline":"true"}),A.EditorView.updateListener.of(d=>{d.docChanged&&l(),(d.docChanged||d.heightChanged||d.geometryChanged)&&a(d.docChanged)}),Te],f=De(o,w)??U.EditorState.create({doc:r,extensions:w}),i=new A.EditorView({state:f,parent:e});return{text:()=>i.state.doc.toString(),replaceText:d=>{const u=i.state.doc.toString();if(u===d)return;let v=0;const m=Math.min(u.length,d.length);for(;v<m&&u.charCodeAt(v)===d.charCodeAt(v);)v+=1;let h=0;for(;h<m-v&&u.charCodeAt(u.length-1-h)===d.charCodeAt(d.length-1-h);)h+=1;i.dispatch({changes:{from:v,to:u.length-h,insert:d.slice(v,d.length-h)},userEvent:"input.replace"})},reveal:({line:d,column:u},v)=>{const{doc:m}=i.state,h=m.line(Math.min(Math.max(d,1),m.lines)),S=Math.min(h.from+u,h.to);i.dispatch({selection:U.EditorSelection.cursor(S),effects:se(i,S,v,t)})},showLine:d=>{const{doc:u}=i.state,v=u.line(Math.min(Math.max(d,1),u.lines)).from;i.dispatch({effects:se(i,v,null,t)})},topLine:()=>{const d=t.scrollerOf(i.scrollDOM),u=y.visibleTopOf(d,i.contentDOM),v=y.frameTopOf(d)+d.clientHeight,{documentTop:m}=i,{doc:h}=i.state;let S=i.lineBlockAtHeight(Math.max(u-m,0));for(;h.lineAt(S.from).text.trim()===""&&S.to<h.length;){const N=i.lineBlockAt(S.to+1);if(m+N.top>=v)break;S=N}const M=i.coordsAtPos(S.from),T=M===null?m+S.top:M.top;return{line:i.state.doc.lineAt(S.from).number,clientTop:T,offset:T-u}},lineSpans:d=>{const u=i.scrollDOM,v=u.scrollTop+i.documentTop-y.visibleTopOf(u,i.contentDOM),{doc:m}=i.state,h=S=>m.line(Math.min(Math.max(S,1),m.lines)).from;return d.map(({first:S,last:M})=>({top:v+i.lineBlockAt(h(S)).top,bottom:v+i.lineBlockAt(h(M)).bottom}))},scrollElement:i.scrollDOM,focus:()=>i.focus(),conflicts:()=>X(i.state.doc),resolveAtCursor:d=>{const u=X(i.state.doc),v=i.state.doc.lineAt(i.state.selection.main.head).number,m=u.find(h=>h.end>=v);return m===void 0?!1:(he(i,m,d),!0)},nextConflict:()=>{const d=X(i.state.doc);if(d[0]===void 0)return!1;const v=i.state.doc.lineAt(i.state.selection.main.head).number,m=d.findIndex(T=>T.start>v),h=m<0?0:m,S=i.state.doc.line(d[h].start).from;i.dispatch({selection:U.EditorSelection.cursor(S),effects:A.EditorView.scrollIntoView(S,{y:"center"})});const M=i.contentDOM.querySelector(`[${me}="${String(h)}"] button`);return M instanceof HTMLElement?M.focus({preventScroll:!0}):i.focus(),!0},save:()=>i.state.toJSON(pe),destroy:()=>i.destroy()}},se=(e,t,r,o)=>{const s=o.scrollerOf(e.scrollDOM),l=(r===null?y.visibleTopOf(s,e.contentDOM):r)-y.frameTopOf(s);return A.EditorView.scrollIntoView(t,{y:"start",yMargin:l})},Re=(e,t,r,o)=>{const s=Ie(e,t),l=o.scrollerOf(e.scrollDOM),a=y.frameTopOf(l),n=y.visibleTopOf(l,e.contentDOM),w=a+l.clientHeight;let f=0;switch(r.y){case"start":f=s.top-(a+r.yMargin);break;case"center":f=(s.top+s.bottom)/2-(n+w)/2;break;case"end":f=s.bottom-(w-r.yMargin);break;default:s.top<n+r.yMargin?f=s.top-(n+r.yMargin):s.bottom>w-r.yMargin&&(f=Math.min(s.bottom-(w-r.yMargin),s.top-(n+r.yMargin)))}if(f!==0&&(l.scrollTop+=f),r.y==="start")return;const i=Ne(e,t);i!==null&&o.reveal(i)},Ie=(e,t)=>{const{node:r,offset:o}=e.domAtPos(t);if(r.nodeType===Node.TEXT_NODE){const a=r.ownerDocument?.createRange();if(a!==void 0){a.setStart(r,o),a.setEnd(r,o);const[n]=a.getClientRects();if(n!==void 0&&n.height>0)return{top:n.top,bottom:n.bottom}}}const s=e.lineBlockAt(t),l=e.documentTop+s.top;return{top:l,bottom:l+s.height}},Ne=(e,t)=>{const{node:r}=e.domAtPos(t);for(let o=r instanceof Element?r:r.parentElement;o!==null;o=o.parentElement)if(o.parentElement===e.contentDOM)return o;return null},De=(e,t)=>{if(e==null)return null;try{return U.EditorState.fromJSON(e,{extensions:t},pe)}catch{return null}},_e=610,Ve=987,le=Object.freeze({kind:"unavailable"}),Pe="true",je="false",He=e=>e===Pe?!0:e===je?!1:null,Be=e=>{const t=new DOMParser().parseFromString(e,"text/html"),r=[];for(const o of t.querySelectorAll("img[data-asset-src], a[data-doc-path]")){const s=o.localName==="img",l=o.getAttribute(s?"data-asset-src":"data-doc-path");l!==null&&r.push({target:{kind:s?"asset":"doc",path:l},exists:He(o.getAttribute(s?"data-asset-exists":"data-doc-exists"))})}return r},Fe=({path:e,instant:t,preview:r,initial:o,onView:s})=>{const l=new AbortController,a={asset:new Map,doc:new Map};let n=o,w=null,f=!1,i=!1,d=null,u=null,v=[],m,h=!1,S,M=null;const T=c=>{c.parsed===n.parsed&&c.failure===n.failure&&c.busy===n.busy&&c.tier===n.tier||(n=c,s(c))},N=(c,p)=>{f||(f=!0,console.error(`[markdown-explorer] ${c}`,...p===void 0?[]:[p]))},D=c=>{if(t!==null)for(const{target:p,exists:b}of t.marksOf(c))a[p.kind].set(p.path,b)},_=()=>{clearTimeout(S),S=void 0,M?.abort(),M=null},V=()=>{u=null,v=[],clearTimeout(m),m=void 0},P=(c,p)=>{T({parsed:n.parsed,failure:c,busy:!1,tier:p})},x=()=>{clearTimeout(m),m=v.length===0?void 0:setTimeout(L,Ve)},k=()=>{if(t===null||u===null)return;const c=u,p=[],b={asset:new Set,doc:new Set};let q;try{q=t.sanitize(c.html,R=>{const W=a[R.kind].get(R.path);return W===void 0&&!b[R.kind].has(R.path)&&(b[R.kind].add(R.path),p.push(R)),W??void 0})}catch(R){V(),R instanceof Z.HtmlNestingLimitError?P(G.failureOf("too-large"),"instant"):(N("the draft sanitizer failed",R),P(G.failureOf("failed"),"instant"));return}v=p;const B=n.parsed!==null&&n.parsed.htmlContent===q&&n.parsed.headings===c.headings?n.parsed:{htmlContent:q,headings:c.headings};T({parsed:B,failure:null,busy:!1,tier:"instant"}),x()},L=()=>{if(m=void 0,h||u===null||v.length===0)return;h=!0;const c=v;r(e,u.text,l.signal).then(p=>{if(h=!1,!(l.signal.aborted||!("kind"in p))){p.kind==="preview"&&D(p.htmlContent);for(const b of c)a[b.kind].has(b.path)||a[b.kind].set(b.path,null);k()}})},j=c=>{_(),V(),T({...n,busy:!0,tier:"server"});const p=new AbortController;M=p,S=setTimeout(()=>{S=void 0,r(e,c,p.signal).then(b=>{if(!(p.signal.aborted||!("kind"in b))){if(M=null,b.kind==="failure"){P(b.failure,"server");return}D(b.htmlContent),T({parsed:{htmlContent:b.htmlContent,headings:b.headings},failure:null,busy:!1,tier:"server"})}})},_e)},g=async(c,p)=>{let b;try{b=await c.convert({path:e,text:p},l.signal)}catch(B){return l.signal.aborted||N("the draft converter rejected a conversion, which its contract allows only once the signal aborted",B),le}const q=G.draftAnswerViolation(b);return q===null?b:(N(`the draft converter answered outside its contract: ${q}`),le)},H=(c,p)=>{switch(p.kind){case"preview":if(_(),p.headings.length>G.EXPLORER_MAX_HEADINGS){V(),P(G.failureOf("too-large"),"instant");return}u={text:c,html:p.htmlContent,headings:p.headings.map(({text:b,depth:q,id:B})=>({text:b,depth:q,id:B}))},k();return;case"failure":_(),V(),P(G.failureOf(p.failure.reason,p.failure.code),"instant");return;case"unavailable":j(c);return}},F=async c=>{i=!0;try{for(;d!==null&&!l.signal.aborted;){const p=d;d=null;const b=await g(c,p);if(l.signal.aborted)return;H(p,b)}}finally{i=!1}};return t!==null&&t.seed!==null&&D(t.seed),{update:c=>{if(!(l.signal.aborted||c===w)){if(w=c,clearTimeout(m),m=void 0,t===null){j(c);return}d=c,i||F(t.converter)}},dispose:()=>{l.abort(),d=null,clearTimeout(m),m=void 0,_()}}},ze=(e,t)=>Z.createHtmlSanitizer(Se(window),e,t,Z.MAX_HTML_NESTING_DEPTH),Ke=(e,t)=>e.flatMap((r,o)=>{const s=t[o];return s===void 0?[]:[{editor:s.top,preview:r.top},{editor:s.bottom,preview:r.bottom}]}),K=(e,t)=>{const r=e[t];if(r===void 0)throw new RangeError(`[markdown-explorer] a scroll map index must be in 0..${String(e.length-1)}; got ${String(t)}`);return r},Ue=e=>{const t=[];for(const o of e){let s=0,l=t.length;for(;s<l;){const a=s+l>>1;K(t,a).pair.preview<=o.preview?s=a+1:l=a}t[s]={pair:o,before:s===0?void 0:K(t,s-1)}}const r=[];for(let o=t.at(-1);o!==void 0;o=o.before)r.push(o.pair);return r.reverse()},We=(e,t)=>{const r=Math.max(t.editorMax,0),o=Math.max(t.previewMax,0),s=r-t.editorViewport,l=o-t.previewViewport,a=e.filter(f=>f.editor>0&&f.editor<s&&f.preview>0&&f.preview<l).sort((f,i)=>f.editor-i.editor||f.preview-i.preview);let n={editor:0,preview:0};const w=[n];for(const f of Ue(a))f.editor>n.editor&&f.preview>n.preview&&(w.push(f),n=f);return w.push({editor:r,preview:o}),{toPreview:f=>ce(w,"editor","preview",f),toEditor:f=>ce(w,"preview","editor",f)}},ce=(e,t,r,o)=>{const s=K(e,0),l=K(e,e.length-1);if(Number.isNaN(o)||o<=s[t])return s[r];if(o>=l[t])return l[r];let a=0,n=e.length-1;for(;n-a>1;){const i=a+n>>1;K(e,i)[t]<=o?a=i:n=i}const w=K(e,a),f=K(e,n);return w[r]+(f[r]-w[r])*(o-w[t])/(f[t]-w[t])},Ge=610,ae=89,ue=.5,$e=({editor:e,preview:t,previewBlocks:r,editorSpans:o,requestFrame:s,cancelFrame:l,now:a})=>{let n="editor",w=0,f=null,i=null,d=!1,u=null,v=null;const m={editor:0,preview:0},h={editor:null,preview:null};let S=null,M=()=>{};const T=g=>{f!==null&&g!==f||(n=g,w=a()+Ge)},N=(g,H)=>{g!==n&&f===null&&a()>=w&&!D(g,H)&&(n=g),k()},D=(g,H)=>{const F=h[g];return a()<m[g]||F!==null&&Math.abs(H.position()-F)<ue},_=e.onScroll(()=>N("editor",e)),V=e.onIntent(()=>T("editor")),P=()=>{const g=t();return g!==S&&(M(),S=g,M=g===null?()=>{}:x(g)),g},x=g=>{const H=g.onScroll(()=>N("preview",g)),F=g.onIntent(()=>T("preview"));return()=>{H(),F()}},k=()=>{!d&&i===null&&(i=s(L))},L=()=>{i=null;const g=P();g!==null&&(u??=r(),v??=We(Ke(u,o(u)),{editorMax:e.max(),previewMax:g.max(),editorViewport:e.viewport(),previewViewport:g.viewport()}),n==="editor"?j(g,"preview",v.toPreview(e.position())):j(e,"editor",v.toEditor(g.position())))},j=(g,H,F)=>{if(Math.abs(g.position()-F)<ue){h[H]=g.position();return}m[H]=a()+ae,h[H]=g.scrollTo(F)};return k(),{editorChanged:g=>{v=null,g&&T("editor"),k()},previewChanged:()=>{u=null,v=null,m.preview=a()+ae,k()},showAlone:g=>{f=g,!(g===null||g===n)&&(n=g,w=0,k())},dispose:()=>{d=!0,i!==null&&l(i),i=null,_(),V(),M()}}},de=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 r of de)e.addEventListener(r,t,{capture:!0,passive:!0});return()=>{for(const r of de)e.removeEventListener(r,t,{capture:!0})}}}),$="[data-aqmd-scroll-container]",Xe="[data-aqmd-content]",Ye=`[${Q.SOURCE_LINES_ATTRIBUTE}]`,Je=Object.freeze(["p1","p2","p3","p4","p5","p6","p7","p8"]),ge=(e,t)=>{const r=y.loadedOf(e.peek(t));return r!==null&&r.document.kind==="markdown"?{htmlContent:r.document.htmlContent,headings:r.document.headings}:null},Qe=(e,t,r,o,s)=>{if(r===void 0)return null;let l;try{l=ze(e,t)}catch(a){return console.error("[markdown-explorer] the draft sanitizer cannot run in this browser, so the server renders the preview",a),null}return{converter:r,sanitize:l,marksOf:Be,seed:ge(o,s)?.htmlContent??null}},Ze=e=>{const t=[];let r=null;for(const o of e.querySelectorAll(Ye)){const s=Q.parseSourceLines(o.getAttribute(Q.SOURCE_LINES_ATTRIBUTE));if(s===null||o.getClientRects().length===0)continue;r??=e.scrollTop-y.visibleTopOf(e,o);const{top:l,bottom:a}=o.getBoundingClientRect();t.push({first:s.first,last:s.last,top:r+l,bottom:r+a})}return t},et=({path:e,readDraft:t,viewer:r,concealed:o,onEditAt:s,onLayout:l,handleRef:a})=>{const{config:n,data:w,documents:f,draftConverter:i,labels:d}=y.useExplorer(),[u,v]=E.useState(()=>({parsed:ge(f,e),failure:null,busy:!0,tier:i===void 0?"server":"instant"})),m=E.useRef(null),h=E.useRef(null),S=E.useRef(u);E.useLayoutEffect(()=>{S.current=u});const M=E.useEffectEvent(()=>t());E.useEffect(()=>{const x=Qe(n.iframeHosts,n.dataPath,i,f,e),k=Fe({path:e,instant:x,preview:w.preview,initial:S.current,onView:L=>E.startTransition(()=>v(L))});return h.current=k,k.update(M()),()=>{k.dispose(),h.current=null}},[n,w,f,i,e]);const T=E.useEffectEvent(()=>l());E.useLayoutEffect(()=>{u.parsed!==null&&T()},[u.parsed]);const N=u.parsed!==null;E.useLayoutEffect(()=>{const x=N?m.current?.querySelector($):null;if(!(x instanceof HTMLElement))return;x.tabIndex=0;const k=new ResizeObserver(()=>T());k.observe(x);const L=x.querySelector(Xe);return L!==null&&k.observe(L),()=>k.disconnect()},[N]);const D=E.useRef(null);E.useImperativeHandle(a,()=>({draft:x=>{h.current?.update(x)},scrollPort:()=>{const x=m.current?.querySelector($);return x instanceof HTMLElement?(D.current?.scroller!==x&&(D.current={scroller:x,port:ve(x)}),D.current.port):null},blocks:()=>{const x=m.current?.querySelector($);return x instanceof HTMLElement?Ze(x):[]},focus:()=>{const x=m.current?.querySelector($);x instanceof HTMLElement&&x.focus({preventScroll:!0})},anchor:x=>{const k=m.current,L=k?.querySelector($);return k===null||!(L instanceof HTMLElement)?null:y.anchorOfView(k,x(L))},place:({line:x,clientTop:k},L)=>{const j=m.current,g=j===null?null:y.blockAtLine(j,x);g!==null&&(L(g).scrollTop+=y.lineTopIn(g,x)-k)}}),[]);const _=x=>{const k=m.current,{target:L}=x;if(s===void 0||k===null||!(L instanceof Element)||!y.isEditingDoubleClick(L))return;const j=y.anchorOfDoubleClick(L,k,k.ownerDocument.getSelection());j!==null&&s(j)},V=E.useMemo(()=>({...r,showToc:!1,showStyle:!1,showAlign:!1,renderScrollBar:void 0}),[r]),P=E.useMemo(()=>u.parsed===null?null:O.jsx("div",{className:"aqmx-document-viewer",children:O.jsx(ye.MarkdownViewer,{...V,parseResult:u.parsed,content:null})}),[V,u.parsed]);return O.jsxs("section",{ref:m,className:"aqmx-edit-preview","aria-label":d.previewRegion,"aria-busy":u.busy,inert:o!==null,hidden:o==="removed","data-aqmx-preview-tier":u.tier,"data-testid":"markdown-explorer-edit-preview",onDoubleClick:s===void 0?void 0:_,children:[u.failure===null?null:O.jsx("p",{className:"aqmx-callout aqmx-document-notice","data-aqmx-tone":"warning","data-testid":"markdown-explorer-edit-preview-failure",children:d.previewFailed(y.failureTitleOf(d,u.failure.reason))}),P??(u.failure===null?O.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-preview-skeleton",children:Je.map(x=>O.jsx("span",{},x))}):null),u.busy?O.jsx("p",{className:"aqmx-sr-only",children:d.previewUpdating}):null]})},we=144,tt=Object.freeze(["e1","e2","e3","e4","e5","e6","e7","e8"]),rt=e=>{if(typeof e!="object"||e===null)return!1;const{generation:t,topLine:r}=e;return"state"in e&&typeof t=="number"&&typeof r=="number"},nt=e=>{e.stopPropagation()},ot=e=>{const{path:t,name:r,session:o}=e,{edits:s,labels:l,announcer:a}=y.useExplorer(),{phase:n}=o,w=E.useCallback(()=>s.retry(t),[s,t]);switch(E.useEffect(()=>{n.kind==="failed"&&a.announce(l.documentFailed(r,y.failureTitleOf(l,n.failure.reason)))},[n,a,l,r]),n.kind){case"opening":return O.jsxs(O.Fragment,{children:[O.jsx("div",{className:"aqmx-skeleton","aria-hidden":"true","data-testid":"markdown-explorer-edit-skeleton",children:tt.map(f=>O.jsx("span",{},f))}),O.jsx("p",{className:"aqmx-sr-only",children:l.editLoading})]});case"grant":return O.jsx("div",{className:"aqmx-edit-message",children:O.jsx(y.EditGrantNotice,{href:n.href,onRetry:w,testId:"markdown-explorer-edit-grant"})});case"failed":return O.jsx("div",{className:"aqmx-edit-message",children:O.jsx(y.FailureView,{failure:n.failure,alert:!1,onRetry:w,testId:"markdown-explorer-edit-failure"})});case"editing":return O.jsx(it,{...e})}},it=({path:e,name:t,session:r,layout:o,viewer:s,region:l,paneScroll:a})=>{const{edits:n,labels:w}=y.useExplorer(),f=E.useRef(null),i=E.useRef(null),d=E.useRef(null),u=E.useRef(null),v=o==="fill",m=y.useSideBySide(),h=y.editViewOf(r,m,v),S=h!=="editor"||r.previewPrepared,M=S&&v,T=E.useRef({layout:o,region:l,paneScroll:a});E.useLayoutEffect(()=>{T.current={layout:o,region:l,paneScroll:a}});const N=E.useRef(r.generation);E.useLayoutEffect(()=>{N.current=r.generation});const D=E.useRef({view:h,previewMounted:S});E.useLayoutEffect(()=>{D.current={view:h,previewMounted:S}});const _=E.useRef(null),V=E.useRef(null),P=E.useRef(!1),x=E.useMemo(()=>({editor:w.editorLabel(t),useOurs:w.conflictUseOurs,useTheirs:w.conflictUseTheirs,keepBoth:w.conflictKeepBoth}),[w,t]),k=E.useCallback(c=>{const{region:p,paneScroll:b}=T.current,q=p();return q===null?c:b.scrollerOf(q,c)},[]);E.useLayoutEffect(()=>{const c=f.current,p=n.draft(e);if(c===null||p===null)return;const b=n.editorState.get(e),q=rt(b)&&b.generation===N.current?b:null;let B=null,R=null;const W=()=>{B!==null&&clearTimeout(B),B=null,R!==null&&n.setDraft(e,R.text())},z=Ce({parent:c,scroll:{scrollerOf:I=>{const{layout:Y,region:be,paneScroll:xe}=T.current,re=be();return Y==="fill"||re===null?I:xe.scrollerOf(re,I)},reveal:I=>T.current.paneScroll.reveal(I)},text:p,saved:q===null?void 0:q.state,labels:x,onGeometry:I=>u.current?.editorChanged(I),onChange:()=>{B??=setTimeout(W,we),D.current.previewMounted&&R!==null&&d.current?.draft(R.text())},onSave:()=>{n.save(e)}});R=z,i.current=z;const ee=()=>{const I=z.topLine();return{line:I.line,clientTop:I.clientTop}},te=()=>d.current?.anchor(k)??null,Ee=n.bindEditor(e,{flush:W,adopt:I=>z.replaceText(I),returnPoint:()=>{const I=D.current.view==="preview"&&T.current.layout==="content"?te():null;return I===null?ee():{line:I.lines.first,clientTop:I.clientTop}},nextConflict:()=>D.current.view!=="preview"?z.nextConflict():z.conflicts().length===0?!1:(P.current=!0,n.setView(e,"editor"),!0),beforeView:I=>{if(T.current.layout==="fill")return;if(I==="preview"){_.current={to:"preview",point:ee()};return}const Y=te();_.current=Y===null?null:{to:"editor",anchor:Y}}});return q!==null&&z.showLine(q.topLine),()=>{W(),n.editorState.set(e,{state:z.save(),generation:N.current,topLine:z.topLine().line}),Ee(),z.destroy(),R=null,i.current=null}},[n,e,x,k]);const{request:L}=r;E.useLayoutEffect(()=>{const c=i.current,p=n.draft(e);c===null||p===null||L===null||(L.anchor!==null&&c.reveal(y.positionInSource(p,L.anchor),L.anchor.clientTop),c.focus(),n.consumeRequest(e))},[n,e,L,x]),E.useLayoutEffect(()=>{h!=="editor"&&!r.previewPrepared&&n.preparePreview(e)},[n,e,h,r.previewPrepared]),E.useLayoutEffect(()=>{const c=_.current,p=V.current,b=P.current;_.current=null,V.current=null,P.current=!1;const q=i.current;if(c?.to==="preview")d.current?.place(c.point,k);else if(c?.to==="editor"&&q!==null){const B=n.draft(e);B!==null&&q.reveal(y.positionInSource(B,c.anchor),c.anchor.clientTop)}b?q?.nextConflict():p==="editor"?q?.focus():p==="preview"&&d.current?.focus()},[n,e,h,k]);const j=E.useCallback(()=>{const c=i.current;if(c===null)throw new Error("[markdown-explorer] the preview read the draft before the editor was mounted");return c.text()},[]);E.useLayoutEffect(()=>{const c=i.current;if(!M||c===null)return;const p=$e({editor:ve(c.scrollElement),preview:()=>d.current?.scrollPort()??null,previewBlocks:()=>d.current?.blocks()??[],editorSpans:b=>c.lineSpans(b),requestFrame:b=>requestAnimationFrame(b),cancelFrame:b=>cancelAnimationFrame(b),now:()=>performance.now()});return p.showAlone(y.paneShownAlone(D.current.view)),u.current=p,()=>{p.dispose(),u.current=null}},[M,n,e,x]),E.useLayoutEffect(()=>{u.current?.showAlone(y.paneShownAlone(h))},[h]);const g=E.useCallback(()=>u.current?.previewChanged(),[]),H=E.useCallback(c=>n.start(e,c),[n,e]),F=c=>{if(c.key==="Escape"){y.consumeKey(c);return}if(!y.isEditViewShortcut(c.nativeEvent,y.isApplePlatform(navigator.platform)))return;y.consumeKey(c);const p=y.toggledEditView(h);V.current=p,y.chooseEditView(n,e,p,v)};return O.jsxs("div",{className:"aqmx-edit","data-aqmx-edit-layout":o,"data-aqmx-edit-view":h,"data-testid":"markdown-explorer-edit",onKeyDown:F,onDoubleClick:nt,children:[O.jsx("div",{ref:f,className:"aqmx-edit-editor","data-testid":"markdown-explorer-editor",inert:h==="preview",hidden:h==="preview"&&!v,...y.ALLOW_KEY_REPEAT}),S?O.jsx(et,{path:e,readDraft:j,viewer:s,concealed:h!=="editor"?null:v?"overlay":"removed",onEditAt:h==="preview"?H:void 0,onLayout:g,handleRef:d}):null]})};exports.DRAFT_WRITE_INTERVAL_MS=we;exports.default=ot;