oficina / mapa Public

Editor: a duplicate ^id never takes the id; a copy-drag is reparsed

Fable's final review of 58fd476, a Low (the marker and reparse rules
over a duplicate ^id).

- markerRule kept the first holder in document order, so " ^abc" typed
  above the block that held abc took the id from it, and every block
  link to abc moved. The keeper is now the first block that held the id
  before the edit; newcomers lose it.
- changedBlocks skipped a copy-dragged block, which is the very node it
  copied: it was never reparsed, so its node could say what its
  Markdown does not (edge/emphasis-edges' paragraph, copied). A later
  holder of an origin is always checked now. One L3 body changes
  (make editor-golden): the copy's emphasis now says its parse.

Gates: two serialize.test.mjs cases, both red on the old fidelity.mjs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 1ea4be9070e07e4856b4334c428350165138b84b parent f3c0817
5 files changed, +38 −8
  • editor/fidelity.mjs +12 −4
  • editor/serialize.test.mjs +23 −1
  • internal/mapa/credits/assets.json +1 −1
  • internal/mapa/markup/testdata/editor.json +1 −1
  • internal/mapa/static/{editor.950c9673b03506dd.js => editor.8285c9bf8c8e3555.js} +1 −1
diff --git a/editor/fidelity.mjs b/editor/fidelity.mjs
index d1e2ba0..42663e0 100644
--- a/editor/fidelity.mjs
+++ b/editor/fidelity.mjs
@@ -355,12 +355,15 @@ export function reparse (state, fidelity, oldDoc = null) {
// same context (all of them without it), less the untouched ones: an
// untouched block re-emits its source, which is what the Markdown says by
// definition. Undo bringing a block back is not an edit to it; an item
-// carried into a list of the other kind is.
+// carried into a list of the other kind is. A later holder of an origin
+// (a copy-drag's copy, which is the very node it copied) is always
+// checked: it is written from its node, which need not say what its
+// source said (review L).
function changedBlocks (detail, oldDoc) {
const blocks = detail.blocks.filter(block => !block.untouched)
if (!oldDoc) return blocks
const before = new Map(docBlocks(oldDoc).map(block => [block.node, contextKey(block)]))
- return blocks.filter(block => before.get(block.node) !== contextKey(block))
+ return blocks.filter(block => !block.first || before.get(block.node) !== contextKey(block))
}
// reparseInto settles the changed blocks of tr's document. A block the
@@ -412,7 +415,10 @@ function reparseInto (tr, fidelity, oldDoc) {
// markerRule is step 1's: only the first holder keeps a marker. A marker
// held more often than before the edit (or than once) is taken from its
// newest holders, last first; markers a stored body already repeats are
-// left as the body has them.
+// left as the body has them. The holder that keeps it is the first that
+// held it before the edit, wherever a newcomer stands: a duplicate ^id
+// typed above it never takes the id from the block links already name
+// (review L).
function markerRule (tr, oldDoc) {
const count = doc => {
const counts = new Map()
@@ -428,7 +434,9 @@ function markerRule (tr, oldDoc) {
for (const [marker, held] of count(tr.doc)) {
let extra = held - Math.max(before.get(marker) ?? 0, 1)
if (extra <= 0) continue
- const [, ...later] = blocks.filter(block => block.holder.attrs.marker === marker)
+ const holders = blocks.filter(block => block.holder.attrs.marker === marker)
+ const keeper = holders.find(block => oldHolders.has(block.holder)) ?? holders[0]
+ const later = holders.filter(block => block !== keeper)
const order = [...later.filter(block => !oldHolders.has(block.holder)).reverse(),
...later.filter(block => oldHolders.has(block.holder)).reverse()]
for (const block of order.slice(0, extra)) {
diff --git a/editor/serialize.test.mjs b/editor/serialize.test.mjs
index 8f1e363..1884aa0 100644
--- a/editor/serialize.test.mjs
+++ b/editor/serialize.test.mjs
@@ -8,7 +8,7 @@ import { TextSelection } from 'prosemirror-state'
import { undo, undoDepth } from 'prosemirror-history'
import { liftListItem } from 'prosemirror-schema-list'
import { schema, editor } from './testkit.mjs'
-import { serialise, structureCheck } from './serialize.mjs'
+import { serialise, structureCheck, docBlocks } from './serialize.mjs'
import { fromMarkdown } from './fromMarkdown.mjs'
import { mount, settle, rebuild, applyBody, prepareSave } from './fidelity.mjs'
import { copyData, pasteTransaction, textSlice } from './clipboard.mjs'
@@ -240,3 +240,25 @@ test('a block whose context changed is written again: a task toggled, a bullet,
assert.equal(serialise(view.state.doc, fidelity), want, body)
}
})
+
+// The marker rule keeps an ^id on the block that held it before the
+// edit: a duplicate typed above it is the one taken away (review L; it
+// once took the id from the block links already name).
+test('a duplicate ^id typed above its holder never takes the id from it', () => {
+ const { view, fidelity } = editor('Alpha\n\nBeta ^abc')
+ view.dispatch(view.state.tr.insertText(' ^abc', view.state.doc.firstChild.nodeSize - 1))
+ assert.equal(serialise(view.state.doc, fidelity), 'Alpha\n\nBeta ^abc')
+})
+
+// A copy-dragged block is the very node it copied, a later holder of
+// its origin, written from its node: it is reparsed, so the document
+// says what its Markdown says (review L; it was never checked).
+test('a copy-dragged block is reparsed, and says what its Markdown says', () => {
+ const { view, fidelity } = editor('A.\n\n/d</*su*m**mary*****eta*****ils**')
+ const copied = view.state.doc.child(1)
+ view.dispatch(view.state.tr.insert(view.state.doc.content.size - view.state.doc.lastChild.nodeSize, copied))
+ const written = serialise(view.state.doc, fidelity)
+ const inline = doc => docBlocks(doc).filter(block => block.node.content.size > 0)
+ .map(block => JSON.stringify(block.node.content.toJSON()))
+ assert.deepEqual(inline(view.state.doc), inline(editor(written).view.state.doc))
+})
diff --git a/internal/mapa/credits/assets.json b/internal/mapa/credits/assets.json
index 74649e2..5a926a4 100644
--- a/internal/mapa/credits/assets.json
+++ b/internal/mapa/credits/assets.json
@@ -3,7 +3,7 @@
"editor/bundles.mjs": "3fb2d43dfa091b0020dfd6fb23a85d2cbcb20d7c90fd24b9463694ffd2ac0db6",
"editor/package-lock.json": "61e175cc0d0eebb9bae68dbcaa608606d3ef2f6237450c3ff737d441e59820d0",
"editor/package.json": "38438071c59630a33365d95fcb5bea93e33e4fe571faa85ded62247b9b2d0905",
- "internal/mapa/static/editor.950c9673b03506dd.js": "950c9673b03506dd7cbc2f854c9f94b0256b5cfb228d65753355e593d34834b7"
+ "internal/mapa/static/editor.8285c9bf8c8e3555.js": "8285c9bf8c8e3555930232e86f6394fa25bae0cbb0e6554fdf0860e227b47a37"
},
"components": [
{
diff --git a/internal/mapa/markup/testdata/editor.json b/internal/mapa/markup/testdata/editor.json
index a358b62..31015e4 100644
--- a/internal/mapa/markup/testdata/editor.json
+++ b/internal/mapa/markup/testdata/editor.json
@@ -67,7 +67,7 @@
{"name":"edge/numbers-not-one","body":"- |a\n\n---","blocks":["item:bullet_list:0:true","rule"]},
{"name":"edge/hash-in-item","body":"- [[Acme]]ng\n- > n\not **quo**ot **quot~~~t~~~e**``` not fenceadi\nng\n- [ ] > not **quo**ot **quot~~~t~~~e**``# \n\n*****\n- not he# \nea\n*\n- not he# \neadi\nng\n- >di` not fence","blocks":["item:bullet_list:0:true","item:bullet_list:0:false","item:bullet_list:0:false","rule","item:bullet_list:0:true","item:bullet_list:0:false","item:bullet_list:0:false"]},
{"name":"edge/quote-holding-list","body":"> - a\n> - b\n> 1. c\n\n\n[[2026-11-12]]\n\n\ud83d\n\n\udc4b*---*[x](https://x.y)","blocks":["quote","paragraph","paragraph","paragraph"]},
-{"name":"edge/html-block","body":"di\nv>\n< ^abb>x</b>\n[[2026-11-12]]\n\n---</div-\n\nbo[[Acme#^b1|that]]dy\n\n/d</*su*m**mary*****eta*****ils**\n\n/d</*su*m**mary*****eta*****ils**","blocks":["paragraph","paragraph","paragraph","paragraph","paragraph"]},
+{"name":"edge/html-block","body":"di\nv>\n< ^abb>x</b>\n[[2026-11-12]]\n\n---</div-\n\nbo[[Acme#^b1|that]]dy\n\n/d</*su*m**mary*****eta*****ils**\n\n/d</*su*m**mary***eta*****ils**","blocks":["paragraph","paragraph","paragraph","paragraph","paragraph"]},
{"name":"edge/table","body":"| a |\n| [[Acme]] ![[fichas:c1]]![[fichas:c1]]> |\n\n `c`","blocks":["paragraph","paragraph"]},
{"name":"edge/trailing-spaces","body":"a1. **c**\n\n1. [ ] \udc4b","blocks":["paragraph","item:ordered_list:0:true"]},
{"name":"edge/only-rule","body":"[[Acme#^b1|that]]","blocks":["paragraph"]},
diff --git a/internal/mapa/static/editor.950c9673b03506dd.js b/internal/mapa/static/editor.8285c9bf8c8e3555.js
similarity index 95%
rename from internal/mapa/static/editor.950c9673b03506dd.js
rename to internal/mapa/static/editor.8285c9bf8c8e3555.js
index 0bce535..99b5fbd 100644
--- a/internal/mapa/static/editor.950c9673b03506dd.js
+++ b/internal/mapa/static/editor.8285c9bf8c8e3555.js
@@ -36,7 +36,7 @@ function W(n){this.content=n}W.prototype={constructor:W,find:function(n){for(var
`+s,em:i("em"),strong:i("strong")})}else e.push({kind:"atom",text:$h(r)})});let t="";for(let r=0;r<e.length;){let i=e[r];if(i.kind==="text"){let s=r;for(;s<e.length&&e[s].kind==="text";)s++;t+=Bh(e.slice(r,s)),r=s;continue}i.kind==="code"?t+="`"+i.text+"`":i.kind==="link"?t+=Ph(i):t+=i.text,r++}return _e(t)}function Ph({text:n,mark:e}){return e.attrs.bare&&n===e.attrs.href?n:`[${n}](${e.attrs.href})`}function Bh(n){return Wl(n,"em",e=>zh(e),"*")}function zh(n){return Wl(n,"strong",e=>e.map(t=>t.text).join(""),"**")}function Wl(n,e,t,r){let i="";for(let s=0;s<n.length;){let o=s;for(;o<n.length&&n[o][e]===n[s][e];)o++;let l=t(n.slice(s,o));i+=n[s][e]?Lh(l,r):l,s=o}return i}function Lh(n,e){let t=/^([\t\n\f\r ]*)([^]*?)([\t\n\f\r ]*)$/u.exec(n);return t[2]===""?n:t[1]+e+t[2]+e+t[3]}function $h(n){let e=n.attrs;return e.source!=null&&Fh(n,e.source)?e.source:n.type.name==="embed"?`![[${e.ref}]]`:`[[${n.type.name==="datelink"?e.date:e.target}${e.anchor?"#^"+e.anchor:""}${e.shown?"|"+e.shown:""}]]`}function Fh(n,e){let t=Tn(e);if(t.length!==1||t[0].source!==e)return!1;let r=t[0];if(n.type.name==="embed")return r.kind===Ft&&r.text.slice(3,-2)===n.attrs.ref;if(r.kind!==$t)return!1;let i=n.type.name==="datelink";return Z(r.target)===i&&r.target===(i?n.attrs.date:n.attrs.target)&&r.anchor===(n.attrs.anchor??"")&&r.text===(n.attrs.shown??"")}function B(n,e,t={}){let r=t.fresh??new Set,i=t.joins??new Set,s=ae(n),o=new Set;for(let u of s){let h=u.node.attrs.origin;u.origin=h,u.first=h!=null&&!o.has(h),h!=null&&o.add(h),u.entry=u.first?e?.get(h):void 0,u.untouched=!r.has(u.index)&&Eh(u,u.entry),u.text=u.untouched?u.entry.source:ir(u)}let l=-1;s.forEach((u,h)=>{u.text!==""&&(l=h)});for(let u of s.slice(0,Math.max(l,0)))u.kind===he&&(u.untouched&&Vl(u.text)||(u.untouched=!1,u.text=ir(u,{last:!1})));let a=s.filter(u=>u.text!==""),c="";a.forEach((u,h)=>{h===0?t.edges!==!1&&u.entry?.leading!=null&&(c+=u.entry.leading):(u.seam=Vh(a[h-1],u,i.has(u.index)),c+=u.seam),c+=u.text});let f=a[a.length-1];return t.edges!==!1&&f?.entry?.trailing!=null&&(c+=f.entry.trailing),{body:t.raw?_e(c):pe(c),blocks:s,emitted:a}}function fn(n,e,t){return B(n,e,t).body}function Vh(n,e,t){if(!t&&n.first&&e.first){if(n.entry&&n.entry.next===e.origin&&n.entry.after!=null)return n.entry.after;if(e.entry&&e.entry.prev===n.origin&&e.entry.before!=null)return e.entry.before}return Wh(n.kind,e.kind)}function Wh(n,e){return n===v&&e===v?`
`:`
-`}function Ii(n){let e=new Set;return n.map(t=>{if(t.kind===be)return`${be}:${Math.min(Math.max(t.node.attrs.level,1),6)}`;if(t.kind!==v)return t.kind;let r=!e.has(t.listPos);return e.add(t.listPos),`${v}:${t.list}:${t.depth}:${r}`})}function qh(n,e){return Ii(ae(Ct(n,oe(e),{trailing:!1})))}function ql(n){return Ii(n)}function Kh(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++)if(n[r]!==e[r])return r;return n.length===e.length?-1:t}function lr(n,e){let t=n.type.schema,r=l=>{let a=B(n,e,l);return a.shapes=Ii(a.emitted),a.mismatch=Kh(a.shapes,qh(t,a.body)),a},i=new Set,s=new Set,o=r({});for(let l=0;o.mismatch>=0&&l<4;l++){let a=[-1,0,1,2].map(c=>o.emitted[o.mismatch+c]);for(let c of a)c&&(s.add(c.index),l>=2&&i.add(c.index));o=r({fresh:i,joins:s})}if(o.mismatch>=0){let l=new Set(o.blocks.map(a=>a.index));o=r({fresh:l,joins:l})}return{ok:o.mismatch<0,body:o.body,shapes:o.shapes,fixed:s.size>0}}var ar=class{constructor(){this.issued=0,this.table=new Map}mint(){return++this.issued}get(e){return this.table.get(e)}record(e,t){if(this.table.has(e))throw new Error(`origin ${e} is already recorded`);this.table.set(e,Object.freeze(t))}},Le=new L("mapa-fidelity");function Ot(n,e,t,r={}){let i=_e(t),s=oe(i),o=s.map(()=>e.mint()),l=Ct(n,s,{origin:f=>o[f],...r}),a=ae(l).slice(0,s.length),c=r.edges!==!1;return s.forEach((f,u)=>{let h=s[u-1],d=s[u+1];e.record(o[u],{node:a[u].node,source:f.source,context:ze(a[u]),prev:h?o[u-1]:null,next:d?o[u+1]:null,before:h?i.slice(h.to,f.from):null,after:d?i.slice(f.to,d.from):null,leading:c&&!h?i.slice(0,f.from):null,trailing:c&&!d?i.slice(f.to):null})}),{doc:l,nodes:a,origins:o}}function Pi(n,e){let t=new ar,{doc:r}=Ot(n,t,e);return{doc:r,fidelity:t}}function Jh(n,e){return ze(n)===ze(e)&&vi(st(n),e.node)}function Jl(n,e,t){let r=0;for(;r<n.length&&r<e.length&&t(n[r],e[r]);)r++;let i=0;for(;i<n.length-r&&i<e.length-r&&t(n[n.length-1-i],e[e.length-1-i]);)i++;let s=jh(n.slice(r,n.length-i),e.slice(r,e.length-i),t);return[...Array.from({length:r},(o,l)=>[l,l]),...s.map(([o,l])=>[o+r,l+r]),...Array.from({length:i},(o,l)=>[n.length-i+l,e.length-i+l])]}function jh(n,e,t){let r=n.length,i=e.length,s=Array.from({length:r+1},()=>new Int32Array(i+1));for(let l=r-1;l>=0;l--)for(let a=i-1;a>=0;a--)s[l][a]=t(n[l],e[a])?s[l+1][a+1]+1:Math.max(s[l+1][a],s[l][a+1]);let o=[];for(let l=0,a=0;l<r&&a<i;)t(n[l],e[a])?(o.push([l,a]),l++,a++):s[l+1][a]>=s[l][a+1]?l++:a++;return o}function jl(n,e,t){let r=n.state,{nodes:i,origins:s}=Ot(r.schema,e,t),o=i.slice(0,s.length),l=B(r.doc,e).emitted,a=r.tr;for(let[c,f]of Jl(l,o,Jh))a.setNodeAttribute(l[c].pos,"origin",s[f]);return a.setMeta("addToHistory",!1).setMeta(Le,{rebuilt:!0}),n.dispatch(a),{ok:fn(n.state.doc,e)===pe(t)}}function Ri(n,e){let t=e.topNodeType.create(null,n),{emitted:r}=B(t,null,{raw:!0}),i=ql(r);return JSON.stringify(r.map((s,o)=>[i[o],s.text]))}function Hl(n,e,t){let r=n.doc.type.schema,{doc:i}=Ot(r,e,t),s=[];n.doc.forEach((h,d)=>{let p=Ri(h,r);p!=="[]"&&s.push({node:h,offset:d,key:p})});let o=[];i.forEach(h=>{let d=Ri(h,r);d!=="[]"&&o.push({node:h,key:d})});let l=Jl(s,o,(h,d)=>h.key===d.key),a=[],c=[-1,-1];for(let h of[...l,[s.length,o.length]]){let[d,p]=[c[0]+1,c[1]+1];if(h[0]>d||h[1]>p){let m=d<s.length?s[d].offset:s[s.length-1]?s[s.length-1].offset+s[s.length-1].node.nodeSize:0,g=h[0]>d?s[h[0]-1].offset+s[h[0]-1].node.nodeSize:m;a.push({from:m,to:g,nodes:o.slice(p,h[1]).map(k=>k.node)})}c=h}let f=n.selection.head,u=null;for(let h of a.reverse()){u===null&&f>=h.from&&f<=h.to&&(u={left:Hh(n.doc,f,h.to),gap:h});let d=[];n.doc.nodesBetween(h.from,h.to,(p,m)=>(m>=h.from&&Ri(p,r)==="[]"&&d.push(p),!1)),n.replaceWith(h.from,h.to,y.from([...h.nodes,...d])),h.size=[...h.nodes,...d].reduce((p,m)=>p+m.nodeSize,0)}if(u){let h=n.mapping.map(u.gap.from,-1),d=_h(n.doc,h,h+u.gap.size,u.left);n.setSelection(S.near(n.doc.resolve(d),-1))}return n}function Hh(n,e,t){let r=0;return n.nodesBetween(e,t,(i,s)=>{i.isText?r+=Math.min(s+i.nodeSize,t)-Math.max(s,e):i.isInline&&(r+=1)}),r}function _h(n,e,t,r){let i=null,s=[];n.nodesBetween(e,t,(o,l)=>{if(o.isTextblock)return s.push({node:o,pos:l}),!1});for(let{node:o,pos:l}of s.reverse()){let a=o.content.size;if(r<=a){i=l+1+a-r;break}r-=a}return i===null&&(i=s.length?s[s.length-1].pos+1:e),Math.min(Math.max(i,0),n.content.size)}function cr(n,e,t){let r=Hl(n.state.tr,e,t);return r.docChanged&&n.dispatch(r.scrollIntoView()),jl(n,e,t)}function Bi(n,e){let t=lr(n.state.doc,e);if(t.ok)return{body:t.body,shapes:t.shapes,adopted:!1};cr(n,e,t.body);let r=lr(n.state.doc,e);return{body:r.body,shapes:r.shapes,adopted:!0}}var Uh={paragraph:["marker"],heading:["level","marker"],code_block:["fence","info","closed","close"],list_item:["indent","bullet","number","delim","task","checked","marker"],blockquote:["prefix","marker"]};function Kl(n){return n.kind===v||n.kind===X?n.holder:n.node}function Gh(n,e){if(n.kind===de)return null;let t=ir(n);if(t==="")return null;let r=oe(t);if(r.length!==1||r[0].kind!==n.kind)return"structural";let i=ae(Ct(e,r,{trailing:!1}))[0];if(n.kind===v&&i.list!==n.list)return"structural";let s=Kl(n),o=Kl(i),l=[];for(let h of Uh[s.type.name]??[])JSON.stringify(s.attrs[h])!==JSON.stringify(o.attrs[h])&&l.push([h,o.attrs[h]]);let a=st(n).content,c=i.node.content,f=a.findDiffStart(c);if(f===null&&l.length===0)return null;let u=null;if(f!==null){let{a:h,b:d}=a.findDiffEnd(c),p=f-Math.min(h,d);p>0&&(h+=p,d+=p),u={from:f,to:h,content:c.cut(f,d)}}return{block:n,attrs:l,diff:u,text:t,node:i.node}}function Yh(n,{block:e,attrs:t,diff:r},i){if(r){let o=e.pos+1;n.replaceWith(o+r.from,o+r.to,r.content)}let s=e.kind===v||e.kind===X?e.holderPos:e.pos;for(let[o,l]of t)n.setNodeAttribute(s,o,l);n.setNodeAttribute(e.pos,"origin",i)}function Xh(n,e,t=null){let r=n.tr;return _l(r,e,t),r.docChanged?r:null}function Qh(n,e){let t=n.blocks.filter(i=>!i.untouched);if(!e)return t;let r=new Map(ae(e).map(i=>[i.node,ze(i)]));return t.filter(i=>r.get(i.node)!==ze(i))}function _l(n,e,t){let r=n.doc.type.schema,i=B(n.doc,e),s=[];for(let u of Qh(i,t)){let h=Gh(u,r);if(h==="structural"){Hl(n,e,i.body);return}h&&s.push(h)}if(s.length===0)return;let o=new Map(s.map(u=>[u.block,e.mint()])),l=u=>o.get(u)??(u.first?u.origin:null),{emitted:a}=i,c=s.map(({block:u,text:h,node:d})=>{let p=a.indexOf(u),m=a[p-1],g=a[p+1],k=o.get(u);return{origin:k,source:h,node:d.type.create({...d.attrs,origin:k},d.content,d.marks),prev:m?l(m):null,next:g?l(g):null,before:m?u.seam:null,after:g?g.seam:null,leading:p===0?u.entry?.leading??null:null,trailing:p>=0&&!g?u.entry?.trailing??null:null}});for(let u of[...s].reverse())Yh(n,u,o.get(u.block));let f=new Map(ae(n.doc).map(u=>[u.node.attrs.origin,u]));for(let{origin:u,...h}of c)e.record(u,{...h,context:ze(f.get(u))})}function Zh(n,e){let t=o=>{let l=new Map;for(let a of ae(o)){let c=a.holder.attrs.marker;c&&l.set(c,(l.get(c)??0)+1)}return l},r=e?t(e):new Map,i=new Set(e?ae(e).map(o=>o.holder):[]),s=ae(n.doc);for(let[o,l]of t(n.doc)){let a=l-Math.max(r.get(o)??0,1);if(a<=0)continue;let[,...c]=s.filter(u=>u.holder.attrs.marker===o),f=[...c.filter(u=>!i.has(u.holder)).reverse(),...c.filter(u=>i.has(u.holder)).reverse()];for(let u of f.slice(0,a))n.setNodeAttribute(u.holderPos,"marker",null)}}function ed(n){return Math.floor(String(n??"").replaceAll(" "," ").length/2)}function td(n,e){let t=-1;for(let s of B(n.doc,e).emitted){if(s.kind!==v){t=-1;continue}let o=ed(s.holder.attrs.indent),l=" ".repeat(s.depth);Math.min(o,t+1)!==s.depth&&s.depth<=t+1&&s.holder.attrs.indent!==l&&n.setNodeAttribute(s.holderPos,"indent",l),t=s.depth}let r=[],i=(s,o)=>{let l=o,a=null;s.forEach(c=>{a&&a.type===c.type&&(c.type.name==="bullet_list"||c.type.name==="ordered_list")&&r.push(l),a=c,l+=c.nodeSize})};i(n.doc,0),n.doc.descendants((s,o)=>{if(s.isTextblock)return!1;i(s,o+1)});for(let s of r.sort((o,l)=>l-o))n.join(s)}function nd(n){let e=n.doc.lastChild;(!e||e.type.name!=="paragraph")&&n.insert(n.doc.content.size,n.doc.type.schema.nodes.paragraph.create())}function Ul(n,e,t=null){let r=n.tr;for(let i=0;i<4;i++){let s=r.doc;if(_l(r,e,t),Zh(r,t),td(r,e),nd(r),r.doc===s)break}return r.docChanged?r:null}function zi(n,e={}){let t=null,r=null,i=()=>e.composing?e.composing():t?.composing??!1;return new C({key:Le,state:{init:()=>n,apply:(s,o)=>o},view(s){return t=s,{destroy(){t=null}}},props:{handleDOMEvents:{compositionend(s){return setTimeout(()=>{t===s&&r&&s.dispatch(s.state.tr.setMeta(Le,{composed:!0}))},50),!1}}},appendTransaction(s,o,l){if(!s.some(u=>u.docChanged&&!u.getMeta(Le)?.rebuilt)&&!r)return null;if(i())return r=r??o.doc,null;let c=r??o.doc;r=null;let f=Ul(l,n,c);return f?f.setMeta(Le,{settled:!0}):null}})}var fr=200,V=function(){};V.prototype.append=function(e){return e.length?(e=V.from(e),!this.length&&e||e.length<fr&&this.leafAppend(e)||this.length<fr&&e.leafPrepend(this)||this.appendInner(e)):this};V.prototype.prepend=function(e){return e.length?V.from(e).append(this):this};V.prototype.appendInner=function(e){return new rd(this,e)};V.prototype.slice=function(e,t){return e===void 0&&(e=0),t===void 0&&(t=this.length),e>=t?V.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};V.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};V.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};V.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i};V.from=function(e){return e instanceof V?e:e&&e.length?new Gl(e):V.empty};var Gl=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a<o;a++)if(i(this.values[a],l+a)===!1)return!1},e.prototype.forEachInvertedInner=function(i,s,o,l){for(var a=s-1;a>=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=fr)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=fr)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(V);V.empty=new Gl([]);var rd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,i,s,o){var l=this.left.length;if(i<l&&this.left.forEachInner(r,i,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(r,Math.min(i,l),s,o)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var s=this.left.length;return i<=s?this.left.slice(r,i):r>=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(V),Li=V;var id=500,lt=class n{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,h)=>{if(!u.step){i||(i=this.remapping(r,h+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ge(u.map));let d=u.step.map(i.slice(s)),p;d&&o.maybeStep(d).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ge(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new n(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;f<e.steps.length;f++){let u=e.steps[f].invert(e.docs[f]),h=new ge(e.mapping.maps[f],u,t),d;(d=a&&a.merge(h))&&(h=d,f?s.pop():l=l.slice(0,l.length-1)),s.push(h),t&&(o++,t=void 0),i||(a=h)}let c=o-r.depth;return c>od&&(l=sd(l,c),o-=c),new n(l.append(s),o)}remapping(e,t){let r=new jt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new ge(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;t=Math.min(this.items.length,t);let r=[],i=this.items.length-t,s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},i);let a=t;this.items.forEach(h=>{let d=s.getMirror(--a);if(d==null)return;o=Math.min(o,d);let p=s.maps[d];if(h.step){let m=e.steps[d].invert(e.docs[d]),g=h.selection&&h.selection.map(s.slice(a+1,d));g&&l++,r.push(new ge(p,m,g))}else r.push(new ge(p))},i);let c=[];for(let h=t;h<o;h++)c.push(new ge(s.maps[h]));let f=this.items.slice(0,i).append(c).append(r),u=new n(f,l);return u.emptyItemCount()>id&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ge(c.invert(),a,f),h,d=i.length-1;(h=i.length&&i[d].merge(u))?i[d]=h:i.push(u)}}else o.map&&r--},this.items.length,0),new n(Li.from(i.reverse()),s)}};lt.empty=new lt(Li.empty,0);function sd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}var ge=class n{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new n(t.getMap().invert(),t,this.selection)}}},ye=class{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}},od=20;function ld(n,e,t,r){let i=t.getMeta(ot),s;if(i)return i.historyState;t.getMeta(Ql)&&(n=new ye(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(ot))return o.getMeta(ot).redo?new ye(n.done.addTransform(t,void 0,r,ur(e)),n.undone,Yl(t.mapping.maps),n.prevTime,n.prevComposition):new ye(n.done,n.undone.addTransform(t,void 0,r,ur(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!ad(t,n.prevRanges)),c=o?$i(n.prevRanges,t.mapping):Yl(t.mapping.maps);return new ye(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,ur(e)),lt.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ye(n.done.rebased(t,s),n.undone.rebased(t,s),$i(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ye(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),$i(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function ad(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&i>=e[s]&&(t=!0)}),t}function Yl(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function $i(n,e){if(!n)return null;let t=[];for(let r=0;r<n.length;r+=2){let i=e.map(n[r],1),s=e.map(n[r+1],-1);i<=s&&t.push(i,s)}return t}function cd(n,e,t){let r=ur(e),i=ot.get(e).spec.config,s=(t?n.undone:n.done).popEvent(e,r);if(!s)return null;let o=s.selection.resolve(s.transform.doc),l=(t?n.done:n.undone).addTransform(s.transform,e.selection.getBookmark(),i,r),a=new ye(t?l:s.remaining,t?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(ot,{redo:t,historyState:a})}var Fi=!1,Xl=null;function ur(n){let e=n.plugins;if(Xl!=e){Fi=!1,Xl=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){Fi=!0;break}}return Fi}function Vi(n){return n.setMeta(Ql,!0)}var ot=new L("history"),Ql=new L("closeHistory");function Zl(n={}){return n={depth:n.depth||100,newGroupDelay:n.newGroupDelay||500},new C({key:ot,state:{init(){return new ye(lt.empty,lt.empty,null,0,-1)},apply(e,t,r){return ld(t,r,e,n)}},config:n,props:{handleDOMEvents:{beforeinput(e,t){let r=t.inputType,i=r=="historyUndo"?un:r=="historyRedo"?Dt:null;return!i||!e.editable?!1:(t.preventDefault(),i(e.state,e.dispatch))}}}})}function hr(n,e){return(t,r)=>{let i=ot.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=cd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}var un=hr(!1,!0),Dt=hr(!0,!0),jm=hr(!1,!1),Hm=hr(!0,!1);function ea(n,e){let t={remote:!1},r=()=>n.view,i=s=>{let o=t.remote;t.remote=!0;try{return s()}finally{t.remote=o}};return t.current=()=>fn(r().state.doc,e),t.prepare=()=>i(()=>Bi(r(),e).body),t.apply=s=>i(()=>{r().dispatch(Vi(r().state.tr));let o=cr(r(),e,s);return r().dispatch(Vi(r().state.tr)),o}),t}var Wi="application/x-mapa";function qi(n,e,t=n.selection.from,r=n.selection.to){let i=n.doc.slice(t,r,!0),s=n.schema.topNodeType.create(null,i.content),{body:o,emitted:l}=B(s,e,{edges:!1,raw:!0}),a=JSON.stringify({v:1,sources:l.map(c=>c.text),seams:l.slice(1).map(c=>c.seam)});return{text:o,mapa:a}}function fd(n){let e;try{e=JSON.parse(n)}catch{return null}let{sources:t,seams:r}=e??{};if(e?.v!==1||!Array.isArray(t)||!Array.isArray(r)||t.length===0||r.length!==t.length-1||![...t,...r].every(o=>typeof o=="string")||!r.every(o=>/^\n(?:[^\n]*\n)*$/u.test(o)))return null;let i=t.map((o,l)=>(l?r[l-1]:"")+o).join(""),s=oe(i);return s.length!==t.length||s.some((o,l)=>o.source!==t[l])?null:i}function ud(n,e){let{from:t,to:r}=n.selection,i=new Set;for(let s of B(n.doc,e).emitted){let o=s.holder.attrs.marker,l=s.holderPos>=t&&s.holderPos+s.holder.nodeSize<=r;o&&!l&&i.add(o)}return i}function ta(n,e){let t=[];return n.forEach(r=>{let i=r;!r.isTextblock&&!r.isLeaf&&(i=r.copy(ta(r.content,e))),i.attrs.marker&&e.has(i.attrs.marker)&&(i=i.type.create({...i.attrs,marker:null},i.content,i.marks)),t.push(i)}),y.from(t)}function na(n,e,t){let r=ud(e,t);return r.size===0?n:new b(ta(n.content,r),n.openStart,n.openEnd)}function ra(n,e,t){let r=fd(t);if(r===null)return null;let{doc:i}=Ot(n.schema,e,r,{trailing:!1,edges:!1}),s=na(b.maxOpen(i.content),n,e),{$from:o,empty:l}=n.selection;if(l&&o.depth===1&&o.parent.type.name==="paragraph"&&o.parent.content.size===0){let a=n.tr.replaceWith(o.before(),o.after(),s.content),c=o.before()+s.content.size;return a.setSelection(S.near(a.doc.resolve(c),-1))}return n.tr.replaceSelection(s)}function ia(n,e){let t=cn(n,e,{trailing:!1});return t.childCount?b.maxOpen(t.content):b.empty}function hd(n,e){let t=e.content,r=t.firstChild;if(!r)return"";r.isInline?t=y.from(n.nodes.paragraph.create(null,t)):r.type.name==="list_item"&&(t=y.from(n.nodes.bullet_list.create(null,t)));try{return B(n.topNodeType.create(null,t),null,{edges:!1,raw:!0}).body}catch{return e.content.textBetween(0,e.content.size,`
+`}function Ii(n){let e=new Set;return n.map(t=>{if(t.kind===be)return`${be}:${Math.min(Math.max(t.node.attrs.level,1),6)}`;if(t.kind!==v)return t.kind;let r=!e.has(t.listPos);return e.add(t.listPos),`${v}:${t.list}:${t.depth}:${r}`})}function qh(n,e){return Ii(ae(Ct(n,oe(e),{trailing:!1})))}function ql(n){return Ii(n)}function Kh(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r++)if(n[r]!==e[r])return r;return n.length===e.length?-1:t}function lr(n,e){let t=n.type.schema,r=l=>{let a=B(n,e,l);return a.shapes=Ii(a.emitted),a.mismatch=Kh(a.shapes,qh(t,a.body)),a},i=new Set,s=new Set,o=r({});for(let l=0;o.mismatch>=0&&l<4;l++){let a=[-1,0,1,2].map(c=>o.emitted[o.mismatch+c]);for(let c of a)c&&(s.add(c.index),l>=2&&i.add(c.index));o=r({fresh:i,joins:s})}if(o.mismatch>=0){let l=new Set(o.blocks.map(a=>a.index));o=r({fresh:l,joins:l})}return{ok:o.mismatch<0,body:o.body,shapes:o.shapes,fixed:s.size>0}}var ar=class{constructor(){this.issued=0,this.table=new Map}mint(){return++this.issued}get(e){return this.table.get(e)}record(e,t){if(this.table.has(e))throw new Error(`origin ${e} is already recorded`);this.table.set(e,Object.freeze(t))}},Le=new L("mapa-fidelity");function Ot(n,e,t,r={}){let i=_e(t),s=oe(i),o=s.map(()=>e.mint()),l=Ct(n,s,{origin:f=>o[f],...r}),a=ae(l).slice(0,s.length),c=r.edges!==!1;return s.forEach((f,u)=>{let h=s[u-1],d=s[u+1];e.record(o[u],{node:a[u].node,source:f.source,context:ze(a[u]),prev:h?o[u-1]:null,next:d?o[u+1]:null,before:h?i.slice(h.to,f.from):null,after:d?i.slice(f.to,d.from):null,leading:c&&!h?i.slice(0,f.from):null,trailing:c&&!d?i.slice(f.to):null})}),{doc:l,nodes:a,origins:o}}function Pi(n,e){let t=new ar,{doc:r}=Ot(n,t,e);return{doc:r,fidelity:t}}function Jh(n,e){return ze(n)===ze(e)&&vi(st(n),e.node)}function Jl(n,e,t){let r=0;for(;r<n.length&&r<e.length&&t(n[r],e[r]);)r++;let i=0;for(;i<n.length-r&&i<e.length-r&&t(n[n.length-1-i],e[e.length-1-i]);)i++;let s=jh(n.slice(r,n.length-i),e.slice(r,e.length-i),t);return[...Array.from({length:r},(o,l)=>[l,l]),...s.map(([o,l])=>[o+r,l+r]),...Array.from({length:i},(o,l)=>[n.length-i+l,e.length-i+l])]}function jh(n,e,t){let r=n.length,i=e.length,s=Array.from({length:r+1},()=>new Int32Array(i+1));for(let l=r-1;l>=0;l--)for(let a=i-1;a>=0;a--)s[l][a]=t(n[l],e[a])?s[l+1][a+1]+1:Math.max(s[l+1][a],s[l][a+1]);let o=[];for(let l=0,a=0;l<r&&a<i;)t(n[l],e[a])?(o.push([l,a]),l++,a++):s[l+1][a]>=s[l][a+1]?l++:a++;return o}function jl(n,e,t){let r=n.state,{nodes:i,origins:s}=Ot(r.schema,e,t),o=i.slice(0,s.length),l=B(r.doc,e).emitted,a=r.tr;for(let[c,f]of Jl(l,o,Jh))a.setNodeAttribute(l[c].pos,"origin",s[f]);return a.setMeta("addToHistory",!1).setMeta(Le,{rebuilt:!0}),n.dispatch(a),{ok:fn(n.state.doc,e)===pe(t)}}function Ri(n,e){let t=e.topNodeType.create(null,n),{emitted:r}=B(t,null,{raw:!0}),i=ql(r);return JSON.stringify(r.map((s,o)=>[i[o],s.text]))}function Hl(n,e,t){let r=n.doc.type.schema,{doc:i}=Ot(r,e,t),s=[];n.doc.forEach((h,d)=>{let p=Ri(h,r);p!=="[]"&&s.push({node:h,offset:d,key:p})});let o=[];i.forEach(h=>{let d=Ri(h,r);d!=="[]"&&o.push({node:h,key:d})});let l=Jl(s,o,(h,d)=>h.key===d.key),a=[],c=[-1,-1];for(let h of[...l,[s.length,o.length]]){let[d,p]=[c[0]+1,c[1]+1];if(h[0]>d||h[1]>p){let m=d<s.length?s[d].offset:s[s.length-1]?s[s.length-1].offset+s[s.length-1].node.nodeSize:0,g=h[0]>d?s[h[0]-1].offset+s[h[0]-1].node.nodeSize:m;a.push({from:m,to:g,nodes:o.slice(p,h[1]).map(k=>k.node)})}c=h}let f=n.selection.head,u=null;for(let h of a.reverse()){u===null&&f>=h.from&&f<=h.to&&(u={left:Hh(n.doc,f,h.to),gap:h});let d=[];n.doc.nodesBetween(h.from,h.to,(p,m)=>(m>=h.from&&Ri(p,r)==="[]"&&d.push(p),!1)),n.replaceWith(h.from,h.to,y.from([...h.nodes,...d])),h.size=[...h.nodes,...d].reduce((p,m)=>p+m.nodeSize,0)}if(u){let h=n.mapping.map(u.gap.from,-1),d=_h(n.doc,h,h+u.gap.size,u.left);n.setSelection(S.near(n.doc.resolve(d),-1))}return n}function Hh(n,e,t){let r=0;return n.nodesBetween(e,t,(i,s)=>{i.isText?r+=Math.min(s+i.nodeSize,t)-Math.max(s,e):i.isInline&&(r+=1)}),r}function _h(n,e,t,r){let i=null,s=[];n.nodesBetween(e,t,(o,l)=>{if(o.isTextblock)return s.push({node:o,pos:l}),!1});for(let{node:o,pos:l}of s.reverse()){let a=o.content.size;if(r<=a){i=l+1+a-r;break}r-=a}return i===null&&(i=s.length?s[s.length-1].pos+1:e),Math.min(Math.max(i,0),n.content.size)}function cr(n,e,t){let r=Hl(n.state.tr,e,t);return r.docChanged&&n.dispatch(r.scrollIntoView()),jl(n,e,t)}function Bi(n,e){let t=lr(n.state.doc,e);if(t.ok)return{body:t.body,shapes:t.shapes,adopted:!1};cr(n,e,t.body);let r=lr(n.state.doc,e);return{body:r.body,shapes:r.shapes,adopted:!0}}var Uh={paragraph:["marker"],heading:["level","marker"],code_block:["fence","info","closed","close"],list_item:["indent","bullet","number","delim","task","checked","marker"],blockquote:["prefix","marker"]};function Kl(n){return n.kind===v||n.kind===X?n.holder:n.node}function Gh(n,e){if(n.kind===de)return null;let t=ir(n);if(t==="")return null;let r=oe(t);if(r.length!==1||r[0].kind!==n.kind)return"structural";let i=ae(Ct(e,r,{trailing:!1}))[0];if(n.kind===v&&i.list!==n.list)return"structural";let s=Kl(n),o=Kl(i),l=[];for(let h of Uh[s.type.name]??[])JSON.stringify(s.attrs[h])!==JSON.stringify(o.attrs[h])&&l.push([h,o.attrs[h]]);let a=st(n).content,c=i.node.content,f=a.findDiffStart(c);if(f===null&&l.length===0)return null;let u=null;if(f!==null){let{a:h,b:d}=a.findDiffEnd(c),p=f-Math.min(h,d);p>0&&(h+=p,d+=p),u={from:f,to:h,content:c.cut(f,d)}}return{block:n,attrs:l,diff:u,text:t,node:i.node}}function Yh(n,{block:e,attrs:t,diff:r},i){if(r){let o=e.pos+1;n.replaceWith(o+r.from,o+r.to,r.content)}let s=e.kind===v||e.kind===X?e.holderPos:e.pos;for(let[o,l]of t)n.setNodeAttribute(s,o,l);n.setNodeAttribute(e.pos,"origin",i)}function Xh(n,e,t=null){let r=n.tr;return _l(r,e,t),r.docChanged?r:null}function Qh(n,e){let t=n.blocks.filter(i=>!i.untouched);if(!e)return t;let r=new Map(ae(e).map(i=>[i.node,ze(i)]));return t.filter(i=>!i.first||r.get(i.node)!==ze(i))}function _l(n,e,t){let r=n.doc.type.schema,i=B(n.doc,e),s=[];for(let u of Qh(i,t)){let h=Gh(u,r);if(h==="structural"){Hl(n,e,i.body);return}h&&s.push(h)}if(s.length===0)return;let o=new Map(s.map(u=>[u.block,e.mint()])),l=u=>o.get(u)??(u.first?u.origin:null),{emitted:a}=i,c=s.map(({block:u,text:h,node:d})=>{let p=a.indexOf(u),m=a[p-1],g=a[p+1],k=o.get(u);return{origin:k,source:h,node:d.type.create({...d.attrs,origin:k},d.content,d.marks),prev:m?l(m):null,next:g?l(g):null,before:m?u.seam:null,after:g?g.seam:null,leading:p===0?u.entry?.leading??null:null,trailing:p>=0&&!g?u.entry?.trailing??null:null}});for(let u of[...s].reverse())Yh(n,u,o.get(u.block));let f=new Map(ae(n.doc).map(u=>[u.node.attrs.origin,u]));for(let{origin:u,...h}of c)e.record(u,{...h,context:ze(f.get(u))})}function Zh(n,e){let t=o=>{let l=new Map;for(let a of ae(o)){let c=a.holder.attrs.marker;c&&l.set(c,(l.get(c)??0)+1)}return l},r=e?t(e):new Map,i=new Set(e?ae(e).map(o=>o.holder):[]),s=ae(n.doc);for(let[o,l]of t(n.doc)){let a=l-Math.max(r.get(o)??0,1);if(a<=0)continue;let c=s.filter(d=>d.holder.attrs.marker===o),f=c.find(d=>i.has(d.holder))??c[0],u=c.filter(d=>d!==f),h=[...u.filter(d=>!i.has(d.holder)).reverse(),...u.filter(d=>i.has(d.holder)).reverse()];for(let d of h.slice(0,a))n.setNodeAttribute(d.holderPos,"marker",null)}}function ed(n){return Math.floor(String(n??"").replaceAll(" "," ").length/2)}function td(n,e){let t=-1;for(let s of B(n.doc,e).emitted){if(s.kind!==v){t=-1;continue}let o=ed(s.holder.attrs.indent),l=" ".repeat(s.depth);Math.min(o,t+1)!==s.depth&&s.depth<=t+1&&s.holder.attrs.indent!==l&&n.setNodeAttribute(s.holderPos,"indent",l),t=s.depth}let r=[],i=(s,o)=>{let l=o,a=null;s.forEach(c=>{a&&a.type===c.type&&(c.type.name==="bullet_list"||c.type.name==="ordered_list")&&r.push(l),a=c,l+=c.nodeSize})};i(n.doc,0),n.doc.descendants((s,o)=>{if(s.isTextblock)return!1;i(s,o+1)});for(let s of r.sort((o,l)=>l-o))n.join(s)}function nd(n){let e=n.doc.lastChild;(!e||e.type.name!=="paragraph")&&n.insert(n.doc.content.size,n.doc.type.schema.nodes.paragraph.create())}function Ul(n,e,t=null){let r=n.tr;for(let i=0;i<4;i++){let s=r.doc;if(_l(r,e,t),Zh(r,t),td(r,e),nd(r),r.doc===s)break}return r.docChanged?r:null}function zi(n,e={}){let t=null,r=null,i=()=>e.composing?e.composing():t?.composing??!1;return new C({key:Le,state:{init:()=>n,apply:(s,o)=>o},view(s){return t=s,{destroy(){t=null}}},props:{handleDOMEvents:{compositionend(s){return setTimeout(()=>{t===s&&r&&s.dispatch(s.state.tr.setMeta(Le,{composed:!0}))},50),!1}}},appendTransaction(s,o,l){if(!s.some(u=>u.docChanged&&!u.getMeta(Le)?.rebuilt)&&!r)return null;if(i())return r=r??o.doc,null;let c=r??o.doc;r=null;let f=Ul(l,n,c);return f?f.setMeta(Le,{settled:!0}):null}})}var fr=200,V=function(){};V.prototype.append=function(e){return e.length?(e=V.from(e),!this.length&&e||e.length<fr&&this.leafAppend(e)||this.length<fr&&e.leafPrepend(this)||this.appendInner(e)):this};V.prototype.prepend=function(e){return e.length?V.from(e).append(this):this};V.prototype.appendInner=function(e){return new rd(this,e)};V.prototype.slice=function(e,t){return e===void 0&&(e=0),t===void 0&&(t=this.length),e>=t?V.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};V.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};V.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};V.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i};V.from=function(e){return e instanceof V?e:e&&e.length?new Gl(e):V.empty};var Gl=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a<o;a++)if(i(this.values[a],l+a)===!1)return!1},e.prototype.forEachInvertedInner=function(i,s,o,l){for(var a=s-1;a>=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=fr)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=fr)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(V);V.empty=new Gl([]);var rd=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,i,s,o){var l=this.left.length;if(i<l&&this.left.forEachInner(r,i,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(r,Math.min(i,l),s,o)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var s=this.left.length;return i<=s?this.left.slice(r,i):r>=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(V),Li=V;var id=500,lt=class n{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],f=[];return this.items.forEach((u,h)=>{if(!u.step){i||(i=this.remapping(r,h+1),s=i.maps.length),s--,f.push(u);return}if(i){f.push(new ge(u.map));let d=u.step.map(i.slice(s)),p;d&&o.maybeStep(d).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ge(p,void 0,void 0,c.length+f.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(u.step);if(u.selection)return l=i?u.selection.map(i.slice(s)):u.selection,a=new n(this.items.slice(0,r).append(f.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let f=0;f<e.steps.length;f++){let u=e.steps[f].invert(e.docs[f]),h=new ge(e.mapping.maps[f],u,t),d;(d=a&&a.merge(h))&&(h=d,f?s.pop():l=l.slice(0,l.length-1)),s.push(h),t&&(o++,t=void 0),i||(a=h)}let c=o-r.depth;return c>od&&(l=sd(l,c),o-=c),new n(l.append(s),o)}remapping(e,t){let r=new jt;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new ge(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;t=Math.min(this.items.length,t);let r=[],i=this.items.length-t,s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},i);let a=t;this.items.forEach(h=>{let d=s.getMirror(--a);if(d==null)return;o=Math.min(o,d);let p=s.maps[d];if(h.step){let m=e.steps[d].invert(e.docs[d]),g=h.selection&&h.selection.map(s.slice(a+1,d));g&&l++,r.push(new ge(p,m,g))}else r.push(new ge(p))},i);let c=[];for(let h=t;h<o;h++)c.push(new ge(s.maps[h]));let f=this.items.slice(0,i).append(c).append(r),u=new n(f,l);return u.emptyItemCount()>id&&(u=u.compress(this.items.length-r.length)),u}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let f=o.selection&&o.selection.map(t.slice(r));f&&s++;let u=new ge(c.invert(),a,f),h,d=i.length-1;(h=i.length&&i[d].merge(u))?i[d]=h:i.push(u)}}else o.map&&r--},this.items.length,0),new n(Li.from(i.reverse()),s)}};lt.empty=new lt(Li.empty,0);function sd(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}var ge=class n{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new n(t.getMap().invert(),t,this.selection)}}},ye=class{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}},od=20;function ld(n,e,t,r){let i=t.getMeta(ot),s;if(i)return i.historyState;t.getMeta(Ql)&&(n=new ye(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(ot))return o.getMeta(ot).redo?new ye(n.done.addTransform(t,void 0,r,ur(e)),n.undone,Yl(t.mapping.maps),n.prevTime,n.prevComposition):new ye(n.done,n.undone.addTransform(t,void 0,r,ur(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!ad(t,n.prevRanges)),c=o?$i(n.prevRanges,t.mapping):Yl(t.mapping.maps);return new ye(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,ur(e)),lt.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new ye(n.done.rebased(t,s),n.undone.rebased(t,s),$i(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ye(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),$i(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function ad(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&i>=e[s]&&(t=!0)}),t}function Yl(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function $i(n,e){if(!n)return null;let t=[];for(let r=0;r<n.length;r+=2){let i=e.map(n[r],1),s=e.map(n[r+1],-1);i<=s&&t.push(i,s)}return t}function cd(n,e,t){let r=ur(e),i=ot.get(e).spec.config,s=(t?n.undone:n.done).popEvent(e,r);if(!s)return null;let o=s.selection.resolve(s.transform.doc),l=(t?n.done:n.undone).addTransform(s.transform,e.selection.getBookmark(),i,r),a=new ye(t?l:s.remaining,t?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(ot,{redo:t,historyState:a})}var Fi=!1,Xl=null;function ur(n){let e=n.plugins;if(Xl!=e){Fi=!1,Xl=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){Fi=!0;break}}return Fi}function Vi(n){return n.setMeta(Ql,!0)}var ot=new L("history"),Ql=new L("closeHistory");function Zl(n={}){return n={depth:n.depth||100,newGroupDelay:n.newGroupDelay||500},new C({key:ot,state:{init(){return new ye(lt.empty,lt.empty,null,0,-1)},apply(e,t,r){return ld(t,r,e,n)}},config:n,props:{handleDOMEvents:{beforeinput(e,t){let r=t.inputType,i=r=="historyUndo"?un:r=="historyRedo"?Dt:null;return!i||!e.editable?!1:(t.preventDefault(),i(e.state,e.dispatch))}}}})}function hr(n,e){return(t,r)=>{let i=ot.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=cd(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}var un=hr(!1,!0),Dt=hr(!0,!0),jm=hr(!1,!1),Hm=hr(!0,!1);function ea(n,e){let t={remote:!1},r=()=>n.view,i=s=>{let o=t.remote;t.remote=!0;try{return s()}finally{t.remote=o}};return t.current=()=>fn(r().state.doc,e),t.prepare=()=>i(()=>Bi(r(),e).body),t.apply=s=>i(()=>{r().dispatch(Vi(r().state.tr));let o=cr(r(),e,s);return r().dispatch(Vi(r().state.tr)),o}),t}var Wi="application/x-mapa";function qi(n,e,t=n.selection.from,r=n.selection.to){let i=n.doc.slice(t,r,!0),s=n.schema.topNodeType.create(null,i.content),{body:o,emitted:l}=B(s,e,{edges:!1,raw:!0}),a=JSON.stringify({v:1,sources:l.map(c=>c.text),seams:l.slice(1).map(c=>c.seam)});return{text:o,mapa:a}}function fd(n){let e;try{e=JSON.parse(n)}catch{return null}let{sources:t,seams:r}=e??{};if(e?.v!==1||!Array.isArray(t)||!Array.isArray(r)||t.length===0||r.length!==t.length-1||![...t,...r].every(o=>typeof o=="string")||!r.every(o=>/^\n(?:[^\n]*\n)*$/u.test(o)))return null;let i=t.map((o,l)=>(l?r[l-1]:"")+o).join(""),s=oe(i);return s.length!==t.length||s.some((o,l)=>o.source!==t[l])?null:i}function ud(n,e){let{from:t,to:r}=n.selection,i=new Set;for(let s of B(n.doc,e).emitted){let o=s.holder.attrs.marker,l=s.holderPos>=t&&s.holderPos+s.holder.nodeSize<=r;o&&!l&&i.add(o)}return i}function ta(n,e){let t=[];return n.forEach(r=>{let i=r;!r.isTextblock&&!r.isLeaf&&(i=r.copy(ta(r.content,e))),i.attrs.marker&&e.has(i.attrs.marker)&&(i=i.type.create({...i.attrs,marker:null},i.content,i.marks)),t.push(i)}),y.from(t)}function na(n,e,t){let r=ud(e,t);return r.size===0?n:new b(ta(n.content,r),n.openStart,n.openEnd)}function ra(n,e,t){let r=fd(t);if(r===null)return null;let{doc:i}=Ot(n.schema,e,r,{trailing:!1,edges:!1}),s=na(b.maxOpen(i.content),n,e),{$from:o,empty:l}=n.selection;if(l&&o.depth===1&&o.parent.type.name==="paragraph"&&o.parent.content.size===0){let a=n.tr.replaceWith(o.before(),o.after(),s.content),c=o.before()+s.content.size;return a.setSelection(S.near(a.doc.resolve(c),-1))}return n.tr.replaceSelection(s)}function ia(n,e){let t=cn(n,e,{trailing:!1});return t.childCount?b.maxOpen(t.content):b.empty}function hd(n,e){let t=e.content,r=t.firstChild;if(!r)return"";r.isInline?t=y.from(n.nodes.paragraph.create(null,t)):r.type.name==="list_item"&&(t=y.from(n.nodes.bullet_list.create(null,t)));try{return B(n.topNodeType.create(null,t),null,{edges:!1,raw:!0}).body}catch{return e.content.textBetween(0,e.content.size,`
`)}}var dd=new L("mapa-clipboard");function Ki(n){let e=(t,r,i)=>{let s=r.clipboardData;if(!s||t.state.selection.empty)return!1;let{text:o,mapa:l}=qi(t.state,n),{dom:a}=t.serializeForClipboard(t.state.selection.content());return r.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",o),s.setData(Wi,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut")),!0};return new C({key:dd,props:{handleDOMEvents:{copy:(t,r)=>e(t,r,!1),cut:(t,r)=>e(t,r,!0)},handlePaste(t,r){let i=r.clipboardData?.getData(Wi);if(!i)return!1;let s=ra(t.state,n,i);return s?(t.dispatch(s.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0):!1},clipboardTextSerializer(t,r){return r.state.selection.content().eq(t)?qi(r.state,n).text:hd(r.state.schema,t)},clipboardTextParser(t,r,i,s){return ia(s.state.schema,t)},transformPasted(t,r){return na(t,r.state,n)}}})}var sa=32;function Tt(n,e){return e?`${n}#^${e}`:n}var pd=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],md=["January","February","March","April","May","June","July","August","September","October","November","December"];function Ji(n,e=new Date().getFullYear()){let[t,r,i]=n.split("-").map(Number),s=new Date(Date.UTC(t,r-1,i)),o=`${pd[s.getUTCDay()]} ${i} ${md[r-1]}`;return t===e?o:`${o} ${t}`}function gd(n){switch(n?.kind){case"broken":return{broken:!0};case"date":return{href:n.href,day:n.title};case"pending":return{href:n.href,pending:!0};case"team":case"block":return{href:n.href,title:n.title,alias:!!n.alias};case"block gone":return{href:n.href,title:n.title,alias:!!n.alias,blockGone:!0}}return null}function yd(n){return Pr(n)?Z(n)?{href:`/d/${n}`,day:Ji(n)}:{broken:!0}:{href:`/new?${new URLSearchParams({title:n}).toString()}`,pending:!0}}var dr=class{constructor(e={},t=null){this.known=new Map(Object.entries(e)),this.ask=t,this.waiting=new Set,this.asked=new Set,this.watchers=new Set,this.timer=null}answer(e,t=""){let r=Tt(e,t),i=gd(this.known.get(r));return i||(this.ask&&!this.asked.has(r)&&(this.waiting.add(r),this.soon()),yd(e))}soon(){this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},0))}async flush(){let e=[...this.waiting].slice(0,sa);if(e.length===0)return;for(let i of e)this.waiting.delete(i),this.asked.add(i);this.waiting.size>0&&this.soon();let t;try{t=await this.ask(e)}catch{for(let i of e)this.asked.delete(i);return}let r=new Set;for(let[i,s]of Object.entries(t??{}))this.known.set(i,s),r.add(i);if(r.size)for(let i of this.watchers)i(r)}async lookup(e){let t=e.filter(r=>!this.known.has(r)).slice(0,sa);if(t.length&&this.ask)try{for(let[r,i]of Object.entries(await this.ask(t)??{}))this.known.set(r,i)}catch{}return Object.fromEntries(e.map(r=>[r,this.known.get(r)]))}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}};function ji(n){return n.type.name==="datelink"?Tt(n.attrs.date,n.attrs.anchor):Tt(n.attrs.target,n.attrs.anchor)}function oa(n){return ie.renderSpec(document,n.type.spec.toDOM(n)).dom}var Hi=class{constructor(e,t){this.node=e,this.dom=oa(e),this.unwatch=t.watch(r=>{r.has(ji(this.node))&&this.redraw()})}redraw(){let e=oa(this.node);if(e.nodeName===this.dom.nodeName){for(let{name:t}of[...this.dom.attributes])t!=="contenteditable"&&!e.hasAttribute(t)&&this.dom.removeAttribute(t);for(let{name:t,value:r}of e.attributes)this.dom.setAttribute(t,r);this.dom.replaceChildren(...e.childNodes)}}update(e){return e.type!==this.node.type||ji(e)!==ji(this.node)||e.attrs.shown!==this.node.attrs.shown?!1:(this.node=e,!0)}ignoreMutation(){return!0}destroy(){this.unwatch()}};function la(n){let e=t=>new Hi(t,n);return{wikilink:e,datelink:e}}var aa=1200,kd=120*1e3,_i=60*1024,ca=3;function bd(n=()=>Math.random()){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<24;r++)t+=e[Math.floor(n()*e.length)];return t}var pr=class{constructor(e,t){this.deps=t,this.drafts=e.drafts,this.page=e.page??"",this.token=e.first?(t.token??bd)():null,this.base=e.draft?e.draft.base:e.base,this.version=e.draft?e.draft.version:"0",this.own=!!e.draft&&this.stored()===e.draft.version,this.closed=!!e.draft&&this.stored("mapa-closing:")===e.draft.version,this.offered=!!e.draft&&!this.own,this.saved=pe(e.source),this.loadedVersion=this.version,this.dirty=!1,this.inflight=null,this.tries=new Map,this.conflict=null,this.gone=!1,this.holding=!1,this.resolving=!1,this.stopped=!1,this.failures=0,this.timers={autosave:null,idle:null,retry:null}}get key(){return`mapa-draft:${this.drafts}`}stored(e="mapa-draft:"){try{return this.deps.storage?.get(e+this.drafts)??null}catch{return null}}remember(){try{this.deps.storage?.set(this.key,this.version)}catch{}}forget(){try{this.deps.storage?.remove(this.key)}catch{}}status(e){this.deps.ui?.status?.(e)}later(e,t,r){let i=this.deps.timers??globalThis;this.timers[e]!==null&&i.clearTimeout(this.timers[e]),this.timers[e]=i.setTimeout(()=>{this.timers[e]=null,t()},r)}cancel(e){let t=this.deps.timers??globalThis;this.timers[e]!==null&&t.clearTimeout(this.timers[e]),this.timers[e]=null}changed(){this.stopped||(this.dirty=!0,this.own=!0,this.offered=!1,this.cancel("idle"),this.later("autosave",()=>this.autosave(),this.deps.delay??aa))}unsaved(){return this.dirty||this.deps.editor.current()!==this.saved}committable(){return this.own&&(this.unsaved()||this.version!=="0")}mayCommit(){return!this.conflict&&!this.gone&&!this.holding}hold(){this.holding=!0,this.cancel("idle")}autosave(e=!1){if(this.stopped)return Promise.resolve(!1);if(this.inflight)return this.inflight.then(()=>this.autosave(e));this.cancel("autosave");let t=this.deps.editor.prepare();if(!e&&t===this.saved)return this.dirty=!1,Promise.resolve(!0);this.dirty=!1,this.status("saving");let r=this.token?this.first(t):this.send(t);return this.inflight=r.finally(()=>{this.inflight=null}),this.inflight}async send(e){let t;try{t=await this.deps.post(this.drafts,{base:this.base,version:this.version,body:e})}catch{return this.offline()}return t.status===409?(this.stale(t.json),!1):t.status!==200?this.offline():(this.failures=0,this.stored_(e,t.json),await this.behind(t.json.merge,e),!0)}stored_(e,t){this.version=t.version,this.saved=e,this.own=!0,this.remember(),this.status(this.gone?"draft":"saved"),this.mayCommit()&&this.later("idle",()=>this.commit(),this.deps.idle??kd)}offline(){return this.dirty=!0,this.failures++,this.failures>ca?(this.status("failed"),!1):(this.status("retrying"),this.later("retry",()=>this.autosave(),(this.deps.delay??aa)*2**this.failures),!1)}async first(e){if(se(e)==="")return this.status("idle"),!0;let t;try{t=await this.deps.post("/scratch",{first:this.token,version:this.version,body:e})}catch{return this.offline()}if(t.status===422)return this.status("idle"),!0;if(t.status!==200)return this.offline();this.failures=0;let r=t.json;return this.token=null,this.page=r.page,this.drafts=`/p/${r.page}/draft`,this.deps.replaceURL?.(r.href),r.version===void 0?(this.base=r.revision,this.saved=e,this.status("saved"),!0):(r.revision!==void 0&&(this.base=this.base==="0"?r.revision:this.base),this.stored_(e,r),await this.behind(r.merge,e),!0)}async behind(e,t){if(this.conflict&&!e?.conflict&&this.settled(),!!e){if(e.gone){this.lost();return}if(e.noBase){this.cancel("idle"),this.deps.ui?.notice?.("noBase",{page:this.page});return}if(e.conflict){if(this.cancel("idle"),this.deps.editor.current()!==t){this.later("autosave",()=>this.autosave(!0),0);return}if(this.conflict&&xd(this.conflict,e)){this.conflict={...this.conflict,version:this.version,sent:t};return}this.conflict={against:e.against,version:this.version,hunks:e.hunks,sent:t},this.deps.ui?.conflict?.(this.conflict);return}await this.rebase(e.against,e.body,t)}}lost(){this.cancel("idle"),this.status("draft"),!this.gone&&(this.gone=!0,this.deps.ui?.notice?.("gone",{page:this.page,version:this.version}))}async rebase(e,t,r){if(this.deps.editor.current()!==r){this.later("autosave",()=>this.autosave(!0),0);return}let i=this.tries.get(e)??0;if(i>=ca)return;let{ok:s}=this.deps.editor.apply(t);if(!s){this.tries.set(e,i+1);return}let o=this.deps.editor.current(),l;try{l=await this.deps.post(this.drafts,{base:this.base,version:this.version,body:o,rebase:e})}catch{return}if(l.status===409){this.stale(l.json);return}l.status===200&&(this.base=e,this.version=l.json.version,this.saved=o,this.remember())}stale(e){if(this.cancel("idle"),e?.committed){this.recover();return}this.deps.editor.apply(e.body),this.version=e.version,this.saved=this.deps.editor.current(),this.dirty=!1,this.own=!1,this.offered=!0,this.forget(),this.deps.ui?.notice?.("newer",{}),this.status("saved")}async recover(){let e=this.saved,t=null;try{t=await this.deps.refetch?.()}catch{}let r=t&&!t.draft?t:null;if(r&&pe(r.source)===e&&(this.base=r.base),this.version="0",this.forget(),this.offered=!1,this.own){this.dirty=!0,this.later("autosave",()=>this.autosave(!0),0);return}r&&this.deps.editor.current()===e&&(this.deps.editor.apply(r.source),this.base=r.base,this.saved=this.deps.editor.current()),this.deps.ui?.notice?.("committed",{})}async flush(){return this.cancel("autosave"),!((this.unsaved()||this.inflight)&&(!await this.autosave()||this.unsaved()))}async commit({explicit:e=!1}={}){if(this.stopped||!this.own&&!e)return"none";if(this.conflict)return"conflict";if(this.cancel("idle"),!await this.flush())return this.own&&!this.stopped?"flush-failed":"stale";if(this.conflict)return"conflict";if(this.gone||this.holding)return this.gone?"gone":"held";if(this.version==="0")return"none";let t=this.saved,r;try{r=await this.deps.post(`${this.drafts}/save`,{version:this.version})}catch{return"commit-failed"}return r.status===409?(this.stale(r.json),"stale"):r.status!==200?"commit-failed":this.committed(r.json,t)}async committed(e,t){if(e.empty)return this.version="0",this.forget(),this.offered=!1,this.status("idle"),this.deps.ui?.committed?.({}),"empty";if(e.gone)return this.lost(),"gone";if(!e.saved)return/\/conflict$/u.test(e.href??"")?(await this.autosave(!0),this.conflict?"conflict":"nobase"):(await this.autosave(!0),"kept");if(e.revision===void 0)return"commit-failed";this.version="0",this.forget(),this.offered=!1,this.status("saved");let r=/^\/p\/([^/?#]+)/u.exec(e.href??"");return r&&!this.page&&(this.page=r[1]),e.merged&&this.deps.editor.current()===t?(this.deps.editor.apply(e.body),this.saved=this.deps.editor.current(),this.base=e.revision):e.merged||(this.base=e.revision),this.deps.ui?.committed?.(e),e.merged?"merged":"saved"}async resolve(e){if(!this.conflict||!this.page||this.resolving)return"none";this.resolving=!0;try{return await this.resolveNow(e)}finally{this.resolving=!1}}async resolveNow(e){let t=this.conflict;if(this.deps.editor.current()!==t.sent){if(!await this.flush())return"failed";if(this.conflict?.hunks!==t.hunks)return"conflicted"}let r=this.conflict,i={current:r.against,version:r.version};e.forEach((c,f)=>{i[`choice-${f}`]=c});let s;try{s=await this.deps.post(`/p/${this.page}/resolve`,i)}catch{return"failed"}if(s.status!==200)return"failed";let{outcome:o,revision:l,body:a}=s.json;return(o==="saved"||o==="merged")&&this.deps.editor.current()===r.sent?(this.settled(),this.deps.editor.apply(a),this.saved=this.deps.editor.current(),this.base=l,this.version="0",this.forget(),this.status("saved"),this.deps.ui?.committed?.(s.json),"saved"):o==="noBase"?(this.deps.ui?.notice?.("noBase",{page:this.page}),"nobase"):(await this.autosave(!0),"conflicted")}took(e,t){this.deps.editor.apply(e),this.saved=this.deps.editor.current(),this.base=t,this.version="0",this.forget(),this.deps.ui?.committed?.({})}settled(){this.conflict=null,this.deps.ui?.conflict?.(null)}async leave(e){if(!this.committable())return this.deps.navigate(e);let t=await this.commit();if(t==="conflict"){this.deps.ui?.leaving?.("conflict",()=>{this.forget(),this.stopped=!0,this.deps.navigate(e)});return}if(t==="flush-failed"){this.deps.ui?.leaving?.("failed",()=>{this.stopped=!0,this.deps.navigate(e)});return}this.deps.navigate(e)}async settle(e=8,t=150){if(this.closed){for(let r=0;r<e;r++){r>0&&await new Promise(s=>(this.deps.timers??globalThis).setTimeout(s,t));let i=null;try{i=await this.deps.refetch?.()}catch{}if(!(!i||i.draft?.version===this.version)){if(this.version!==this.loadedVersion)return;!i.draft&&pe(i.source)===this.saved&&(this.base=i.base,this.version="0",this.forget(),this.deps.ui?.committed?.({settled:!0})),this.closed=!1;return}}this.closed=!1}}closing({reloading:e=!1}={}){if(this.stopped)return;if(this.token)return this.closingFirst();let t=this.deps.editor.prepare(),r=t!==this.saved;if(!this.mayCommit()){r&&this.own&&Ui(t)<=_i&&this.keep(t);return}if(!this.committable()||e&&!r&&!this.dirty)return;let i={commit:"1",version:this.version,base:this.base};if(r&&Ui(t)<=_i&&(i.body=t),this.closed&&this.version===this.loadedVersion&&(i.settling="1"),!(i.body===void 0&&this.version==="0")){try{this.deps.storage?.set(`mapa-closing:${this.drafts}`,this.version)}catch{}this.deps.post(this.drafts,i,{keepalive:!0}).catch(()=>{}),this.cancel("autosave"),this.cancel("idle"),this.dirty=!1,this.saved=t,this.version="0",this.forget()}}closingFirst(){if(!this.committable())return;let e=this.deps.editor.prepare();se(e)!==""&&Ui(e)<=_i&&this.deps.post("/scratch",{first:this.token,version:this.version,body:e},{keepalive:!0}).catch(()=>{}),this.dirty=!1}keep(e){this.deps.post(this.drafts,{base:this.base,version:this.version,body:e},{keepalive:!0}).catch(()=>{}),this.cancel("autosave"),this.cancel("idle"),this.dirty=!1,this.saved=e}shown(){if(this.unsaved()){this.autosave(!0);return}this.deps.reload?.()}};function xd(n,e){return n.against!==e.against||n.hunks.length!==e.hunks.length?!1:n.hunks.every((t,r)=>{let i=e.hunks[r];return t.base===i.base&&t.mine===i.mine&&t.theirs===i.theirs})}function Ui(n){return new TextEncoder().encode(n).length}var ua=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Sd(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var wd=(n,e,t)=>{let r=Sd(n,t);if(!r)return!1;let i=ha(r);if(!i){let o=r.blockRange(),l=o&&pt(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(pa(n,i,e,-1))return!0;if(r.parent.content.size==0&&(Nt(s,"end")||x.isSelectable(s)))for(let o=r.depth;;o--){let l=$n(n.doc,r.before(o),r.after(o),b.empty);if(l&&l.slice.size<l.to-l.from){if(e){let a=n.tr.step(l);a.setSelection(Nt(s,"end")?w.findFrom(a.doc.resolve(a.mapping.map(i.pos,-1)),-1):x.create(a.doc,i.pos-s.nodeSize)),e(a.scrollIntoView())}return!0}if(o==1||r.node(o-1).childCount>1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1};function Nt(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}var Cd=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=ha(r)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function ha(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function Md(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset<t.parent.content.size)?null:t}var Od=(n,e,t)=>{let r=Md(n,t);if(!r)return!1;let i=da(r);if(!i)return!1;let s=i.nodeAfter;if(pa(n,i,e,1))return!0;if(r.parent.content.size==0&&(Nt(s,"start")||x.isSelectable(s))){let o=$n(n.doc,r.before(),r.after(),b.empty);if(o&&o.slice.size<o.to-o.from){if(e){let l=n.tr.step(o);l.setSelection(Nt(s,"start")?w.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):x.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos,i.pos+s.nodeSize).scrollIntoView()),!0):!1},Dd=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset<r.parent.content.size)return!1;s=da(r)}let o=s&&s.nodeAfter;return!o||!x.isSelectable(o)?!1:(e&&e(n.tr.setSelection(x.create(n.doc,s.pos)).scrollIntoView()),!0)};function da(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){let t=n.node(e);if(n.index(e)+1<t.childCount)return n.doc.resolve(n.after(e+1));if(t.type.spec.isolating)break}return null}var Td=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
`).scrollIntoView()),!0)};function Yi(n){for(let e=0;e<n.edgeCount;e++){let{type:t}=n.edge(e);if(t.isTextblock&&!t.hasRequiredAttrs())return t}return null}var Xi=(n,e)=>{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Yi(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(w.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Nd=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof Q||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Yi(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,l=n.tr.insert(o,s.createAndFill());l.setSelection(S.create(l.doc,o+1)),e(l.scrollIntoView())}return!0},Ed=(n,e)=>{let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(Ae(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&pt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Ad(n){return(e,t)=>{if(e.selection instanceof x&&e.selection.node.isBlock){let{$from:d}=e.selection;return!d.parentOffset||!Ae(e.doc,d.pos)?!1:(t&&t(e.tr.split(d.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof S||e.selection instanceof Q)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,f=!1;for(let d=i.depth;;d--)if(i.node(d).isBlock){c=i.end(d)==i.pos+(i.depth-d),f=i.start(d)==i.pos-(i.depth-d),a=Yi(i.node(d-1).contentMatchAt(i.indexAfter(d-1)));let m=n&&n(i.parent,c,i);o.unshift(m||(c&&a?{type:a}:null)),l=d;break}else{if(d==1)return!1;o.unshift(null)}let u=i.pos,h=Ae(r.doc,u,o.length,o);if(h||(o[0]=a?{type:a}:null,h=Ae(r.doc,u,o.length,o)),!h)return!1;if(r.split(u,o.length,o),!c&&f&&i.node(l).type!=a){let d=r.mapping.slice(s),p=d.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(d.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}var vd=Ad();var Id=(n,e)=>(e&&e(n.tr.setSelection(new Q(n.doc))),!0);function Rd(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||Ut(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function pa(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&Rd(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let d=e.pos+s.nodeSize,p=y.empty;for(let k=o.length-1;k>=0;k--)p=y.from(o[k].create(null,p));p=y.from(i.copy(p));let m=n.tr.step(new P(e.pos-1,d,e.pos,d,new b(p,1,0),o.length,!0)),g=m.doc.resolve(d+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Ut(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let f=s.type.spec.isolating||r>0&&a?null:w.findFrom(e,1),u=f&&f.$from.blockRange(f.$to),h=u&&pt(u);if(h!=null&&h>=e.depth)return t&&t(n.tr.lift(u,h).scrollIntoView()),!0;if(c&&Nt(s,"start",!0)&&Nt(i,"end")){let d=i,p=[];for(;p.push(d),!d.isTextblock;)d=d.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(d.canReplace(d.childCount,d.childCount,m.content)){if(t){let k=y.empty;for(let O=p.length-1;O>=0;O--)k=y.from(p[O].copy(k));let T=n.tr.step(new P(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new b(k,p.length,0),0,!0));t(T.scrollIntoView())}return!0}}return!1}function ma(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(S.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}var Pd=ma(-1),Bd=ma(1);function ga(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&mt(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function mr(n,e=null){return function(t,r){let i=!1;for(let s=0;s<t.selection.ranges.length&&!i;s++){let{$from:{pos:o},$to:{pos:l}}=t.selection.ranges[s];t.doc.nodesBetween(o,l,(a,c)=>{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let f=t.doc.resolve(c),u=f.index();i=f.parent.canReplaceWith(u,u+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o<t.selection.ranges.length;o++){let{$from:{pos:l},$to:{pos:a}}=t.selection.ranges[o];s.setBlockType(l,a,n,e)}r(s.scrollIntoView())}return!0}}function zd(n,e,t,r){for(let i=0;i<e.length;i++){let{$from:s,$to:o}=e[i],l=s.depth==0?n.inlineContent&&n.type.allowsMarkType(t):!1;if(n.nodesBetween(s.pos,o.pos,(a,c)=>{if(l||!r&&a.isAtom&&a.isInline&&c>=s.pos&&c+a.nodeSize<=o.pos)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Ld(n){let e=[];for(let t=0;t<n.length;t++){let{$from:r,$to:i}=n[t];r.doc.nodesBetween(r.pos,i.pos,(s,o)=>{if(s.isAtom&&s.content.size&&s.isInline&&o>=r.pos&&o+s.nodeSize<=i.pos)return o+1>r.pos&&e.push(new yt(r,r.doc.resolve(o+1))),r=r.doc.resolve(o+1+s.content.size),!1}),r.pos<i.pos&&e.push(new yt(r,i))}return e}function ce(n,e=null,t){let r=(t&&t.removeWhenPresent)!==!1,i=(t&&t.enterInlineAtoms)!==!1,s=!(t&&t.includeWhitespace);return function(o,l){let{empty:a,$cursor:c,ranges:f}=o.selection;if(a&&!c||!zd(o.doc,f,n,i))return!1;if(l)if(c)n.isInSet(o.storedMarks||c.marks())?l(o.tr.removeStoredMark(n)):l(o.tr.addStoredMark(n.create(e)));else{let u,h=o.tr;i||(f=Ld(f)),r?u=!f.some(d=>o.doc.rangeHasMark(d.$from.pos,d.$to.pos,n)):u=!f.every(d=>{let p=!1;return h.doc.nodesBetween(d.$from.pos,d.$to.pos,(m,g,k)=>{if(p)return!1;p=!n.isInSet(m.marks)&&!!k&&k.type.allowsMarkType(n)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,d.$from.pos-g),Math.min(m.nodeSize,d.$to.pos-g))))}),!p});for(let d=0;d<f.length;d++){let{$from:p,$to:m}=f[d];if(!u)h.removeMark(p.pos,m.pos,n);else{let g=p.pos,k=m.pos,T=p.nodeAfter,O=m.nodeBefore,fe=s&&T&&T.isText?/^\s*/.exec(T.text)[0].length:0,Ve=s&&O&&O.isText?/\s*$/.exec(O.text)[0].length:0;g+fe<k&&(g+=fe,k-=Ve),h.addMark(g,k,n.create(e))}}l(h.scrollIntoView())}return!0}}function $e(...n){return function(e,t,r){for(let i=0;i<n.length;i++)if(n[i](e,t,r))return!0;return!1}}var Gi=$e(ua,wd,Cd),fa=$e(ua,Od,Dd),Te={Enter:$e(Td,Nd,Ed,vd),"Mod-Enter":Xi,Backspace:Gi,"Mod-Backspace":Gi,"Shift-Backspace":Gi,Delete:fa,"Mod-Delete":fa,"Mod-a":Id},ya={"Ctrl-h":Te.Backspace,"Alt-Backspace":Te["Mod-Backspace"],"Ctrl-d":Te.Delete,"Ctrl-Alt-Backspace":Te["Mod-Delete"],"Alt-Delete":Te["Mod-Delete"],"Alt-d":Te["Mod-Delete"],"Ctrl-a":Pd,"Ctrl-e":Bd};for(let n in Te)ya[n]=Te[n];var $d=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,Qi=$d?ya:Te;function gr(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s);if(!o)return!1;let l=r?t.tr:null;return Fd(l,o,n,e)?(r&&r(l.scrollIntoView()),!0):!1}}function Fd(n,e,t,r=null){let i=!1,s=e,o=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Ke(a,a,e.depth),e.endIndex<e.parent.childCount&&(e=new Ke(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=mt(s,t,r,e);return l?(n&&Vd(n,e,l,i,t),!0):!1}function Vd(n,e,t,r,i){let s=y.empty;for(let f=t.length-1;f>=0;f--)s=y.from(t[f].type.create(t[f].attrs,s));n.step(new P(e.start-(r?2:0),e.end,e.start,e.end,new b(s,0,0),t.length,!0));let o=0;for(let f=0;f<t.length;f++)t[f].type==i&&(o=f+1);let l=t.length-o,a=e.start+t.length-(r?2:0),c=e.parent;for(let f=e.startIndex,u=e.endIndex,h=!0;f<u;f++,h=!1)!h&&Ae(n.doc,a,l)&&(n.split(a,l),a+=2*l),a+=c.child(f).nodeSize;return n}function ka(n,e){return function(t,r){let{$from:i,$to:s,node:o}=t.selection;if(o&&o.isBlock||i.depth<2||!i.sameParent(s))return!1;let l=i.node(-1);if(l.type!=n)return!1;if(i.parent.content.size==0&&i.node(-1).childCount==i.indexAfter(-1)){if(i.depth==3||i.node(-3).type!=n||i.index(-2)!=i.node(-2).childCount-1)return!1;if(r){let u=y.empty,h=i.index(-1)?1:i.index(-2)?2:3;for(let k=i.depth-h;k>=i.depth-3;k--)u=y.from(i.node(k).copy(u));let d=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;u=u.append(y.from(n.createAndFill()));let p=i.before(i.depth-(h-1)),m=t.tr.replace(p,i.after(-d),new b(u,4-h,0)),g=-1;m.doc.nodesBetween(p,m.doc.content.size,(k,T)=>{if(g>-1)return!1;k.isTextblock&&k.content.size==0&&(g=T+1)}),g>-1&&m.setSelection(w.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let a=s.pos==i.end()?l.contentMatchAt(0).defaultType:null,c=t.tr.delete(i.pos,s.pos),f=a?[e?{type:n,attrs:e}:null,{type:a}]:void 0;return Ae(c.doc,i.pos,2,f)?(r&&r(c.split(i.pos,2,f).scrollIntoView()),!0):!1}}function Zi(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,o=>o.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Wd(e,t,n,s):qd(e,t,s):!0:!1}}function Wd(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);s<o&&(i.step(new P(s-1,o,s,o,new b(y.from(t.create(null,r.parent.copy())),1,0),1,!0)),r=new Ke(i.doc.resolve(r.$from.pos),i.doc.resolve(o),r.depth));let l=pt(r);if(l==null)return!1;i.lift(r,l);let a=i.doc.resolve(i.mapping.map(s,-1)-1);return Ut(i.doc,a.pos)&&a.nodeBefore.type==a.nodeAfter.type&&i.join(a.pos),e(i.scrollIntoView()),!0}function qd(n,e,t){let r=n.tr,i=t.parent;for(let d=t.end,p=t.endIndex-1,m=t.startIndex;p>m;p--)d-=i.child(p).nodeSize,r.delete(d-1,d+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),f=s.index(-1);if(!c.canReplace(f+(l?0:1),f+1,o.content.append(a?y.empty:y.from(i))))return!1;let u=s.pos,h=u+o.nodeSize;return r.step(new P(u-(l?1:0),h+(a?1:0),u+1,h-1,new b((l?y.empty:y.from(i.copy(y.empty))).append(a?y.empty:y.from(i.copy(y.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function es(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,f=y.from(c?n.create():null),u=new b(y.from(n.create(null,y.from(l.type.create(null,f)))),c?3:1,0),h=s.start,d=s.end;t(e.tr.step(new P(h-(c?3:1),d,h,d,u,1,!0)).scrollIntoView())}return!0}}var j=class{constructor(e,t,r={}){this.match=e,this.match=e,this.handler=typeof t=="string"?Kd(t):t,this.undoable=r.undoable!==!1,this.inCode=r.inCode||!1,this.inCodeMark=r.inCodeMark!==!1}};function Kd(n){return function(e,t,r,i){let s=n;if(t[1]){let o=t[0].lastIndexOf(t[1]);s+=t[0].slice(o+t[1].length),r+=o;let l=r-i;l>0&&(s=t[0].slice(o-l,o)+s,r=i)}return e.tr.insertText(s,r,i)}}var Jd=500;function xa({rules:n}){let e=new C({state:{init(){return null},apply(t,r){let i=t.getMeta(this);return i||(t.selectionSet||t.docChanged?null:r)}},props:{handleTextInput(t,r,i,s){return ba(t,r,i,s,n,e)},handleDOMEvents:{compositionend:t=>{setTimeout(()=>{let{$cursor:r}=t.state.selection;r&&ba(t,r.pos,r.pos,"",n,e)})}}},isInputRules:!0});return e}function ba(n,e,t,r,i,s){if(n.composing)return!1;let o=n.state,l=o.doc.resolve(e),a=l.parent.textBetween(Math.max(0,l.parentOffset-Jd),l.parentOffset,null,"\uFFFC")+r;for(let c=0;c<i.length;c++){let f=i[c];if(!f.inCodeMark&&l.marks().some(p=>p.type.spec.code))continue;if(l.parent.type.spec.code){if(!f.inCode)continue}else if(f.inCode==="only")continue;let u=f.match.exec(a);if(!u||u[0].length<r.length)continue;let h=e-(u[0].length-r.length);if(!f.inCodeMark){let p=!1;if(o.doc.nodesBetween(h,l.pos,m=>{m.isInline&&m.marks.some(g=>g.type.spec.code)&&(p=!0)}),p)continue}let d=f.handler(o,u,h,t);if(d)return f.undoable&&d.setMeta(s,{transform:d,from:e,to:t,text:r}),n.dispatch(d),!0}return!1}var Sa=(n,e)=>{let t=n.plugins;for(let r=0;r<t.length;r++){let i=t[r],s;if(i.spec.isInputRules&&(s=i.getState(n))){if(e){let o=n.tr,l=s.transform;for(let a=l.steps.length-1;a>=0;a--)o.step(l.steps[a].invert(l.docs[a]));if(s.text){let a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to);e(o)}return!0}}return!1},Sg=new j(/--$/,"\u2014",{inCodeMark:!1}),wg=new j(/\.\.\.$/,"\u2026",{inCodeMark:!1}),Cg=new j(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),Mg=new j(/"$/,"\u201D",{inCodeMark:!1}),Og=new j(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),Dg=new j(/'$/,"\u2019",{inCodeMark:!1});function wa(n,e,t=null){return new j(n,(r,i,s,o)=>{let l=r.doc.resolve(s),a=t instanceof Function?t(i):t;return l.node(-1).canReplaceWith(l.index(-1),l.indexAfter(-1),e)?r.tr.delete(s,o).setBlockType(s,s,e,a):null})}function jd(n=new Date){let e=t=>String(t).padStart(2,"0");return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())}`}function ts(n,e){return mr(n.nodes.heading,{level:e,source:null})}function Hd(n){return(e,t)=>{let r=null;if(!gr(n.nodes.bullet_list)(e,s=>{r=s}))return!1;if(t){let{from:s,to:o}=r.selection;r.doc.nodesBetween(s,o,(l,a)=>{l.type===n.nodes.list_item&&!l.attrs.task&&r.setNodeMarkup(a,null,{...l.attrs,task:!0,checked:" "})}),t(r.scrollIntoView())}return!0}}function _d(n){return(e,t)=>{let{$from:r}=e.selection;if(r.depth<1)return!1;if(t){let i=r.after(1),s=e.tr.insert(i,n.nodes.horizontal_rule.create());t(s.scrollIntoView())}return!0}}function Ud(n){return $e(mr(n.nodes.code_block,{fence:"```",info:"",closed:!0,close:"```"}),Xi)}function yr(n){return(e,t)=>(t&&t(e.tr.insertText(n).scrollIntoView()),!0)}function Gd(n){return(e,t)=>{if(t){let r=n.nodes.datelink.create({date:jd()});t(e.tr.replaceSelectionWith(r,!1).scrollIntoView())}return!0}}function Et(n){return{"insert-h1":ts(n,1),"insert-h2":ts(n,2),"insert-h3":ts(n,3),"insert-list":gr(n.nodes.bullet_list),"insert-numbered":gr(n.nodes.ordered_list),"insert-check":Hd(n),"insert-quote":ga(n.nodes.blockquote),"insert-code":Ud(n),"insert-rule":_d(n),"insert-link":yr("[["),"insert-date":Gd(n),"insert-paragraph":mr(n.nodes.paragraph)}}function Ca(n){return{strong:ce(n.marks.strong),em:ce(n.marks.em),code:ce(n.marks.code)}}function Ma(n,e){return e&&e(n.tr.setSelection(S.create(n.doc,0,n.doc.content.size))),!0}var Yd=0;function hn(n,e={},t=""){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);return t&&(r.textContent=t),r}var At=class{constructor(e,{label:t,count:r}){this.view=e,this.count=r,this.id=`mapa-list-${++Yd}`,this.list=hn("ul",{id:this.id,role:"listbox","aria-label":t,"mapa-combo":""}),this.list.hidden=!0,this.live=hn("div",{"mapa-sr":"",role:"status","aria-live":"polite"}),document.body.append(this.list,this.live),this.items=[],this.active=0,this.list.addEventListener("mousedown",i=>i.preventDefault())}get open(){return!this.list.hidden}show(e,t){this.items=e,this.active=0,this.list.replaceChildren(...e.map((i,s)=>{let o=hn("li",{id:`${this.id}-${s}`,role:"option","aria-selected":"false"});return o.append(hn("span",{},i.label)),i.detail&&o.append(hn("small",{},i.detail)),o.addEventListener("click",()=>this.choose(s)),o})),this.list.hidden=e.length===0,this.place(t),this.mark();let r=this.count(e);this.live.textContent!==r&&(this.live.textContent=r)}place(e){if(this.list.hidden)return;let t=this.view.coordsAtPos(e),r=window.visualViewport,i=r?r.offsetTop+r.height:window.innerHeight,s=this.list.offsetHeight,o=t.bottom+4,l=o+s>i?Math.max(t.top-s-4,4):o,a=this.list.offsetWidth,c=Math.max(4,Math.min(t.left,window.innerWidth-a-4));this.list.style.setProperty("top",`${l}px`),this.list.style.setProperty("left",`${c}px`)}mark(){let e=this.list.children;for(let r=0;r<e.length;r++)e[r].setAttribute("aria-selected",r===this.active?"true":"false");let t=this.view.dom;this.open?(t.setAttribute("aria-controls",this.id),t.setAttribute("aria-activedescendant",`${this.id}-${this.active}`),e[this.active]?.scrollIntoView({block:"nearest"})):t.getAttribute("aria-controls")===this.id&&(t.removeAttribute("aria-controls"),t.removeAttribute("aria-activedescendant"))}close(){this.open&&(this.list.hidden=!0,this.items=[],this.live.textContent="",this.mark())}choose(e){let t=this.items[e];this.close(),t&&t.run(this.view),this.view.focus()}keys(e){if(!this.open||e.isComposing)return!1;let t=this.items.length;switch(e.key){case"ArrowDown":case"ArrowUp":return this.active=(this.active+(e.key==="ArrowDown"?1:-1)+t)%t,this.mark(),!0;case"Enter":case"Tab":return this.choose(this.active),!0;case"Escape":return this.close(),!0}return!1}destroy(){this.list.remove(),this.live.remove()}};var Xd=new L("mapa-suggest"),Qd=/\[\[([^[\]\n|#]{0,80})$/u;function rs(n){let{$from:e,empty:t}=n.selection;if(!t||e.parent.type.spec.code||!e.parent.inlineContent)return null;let r=e.parent.textBetween(0,e.parentOffset,null,"\uFFFC"),i=Qd.exec(r);return i?{text:i[1],from:e.pos-i[0].length,to:e.pos}:null}function Zd(n,e){return Z(e.target)?n.nodes.datelink.create({date:e.target}):n.nodes.wikilink.create(e)}function ns(n,e){return t=>{let r=rs(t.state);if(!r)return;let i=Zd(t.state.schema,{target:e});t.dispatch(t.state.tr.replaceWith(r.from,r.to,i).scrollIntoView())}}var Oa=n=>n.normalize("NFKD").replace(/\p{Mn}/gu,"").toLowerCase().trim().replace(/\s+/gu," ");function ep(n,e,t){let r=n.text.trim(),i=[];Z(r)&&i.push({label:Ji(r),detail:"Your note",run:ns(n,r)});for(let{text:s,pending:o}of e){let l=t[Tt(s,"")],a="Team page";o?a="Not written yet":l?.alias&&(a=`Old title of ${l.title}`),i.push({label:s,detail:a,run:ns(n,s)})}return r!==""&&!Z(r)&&!e.some(s=>Oa(s.text)===Oa(r))&&i.push({label:`Link \u201C${r}\u201D`,detail:"a page not written yet",run:ns(n,r)}),i}function Da(n,e){let{$from:t,empty:r}=n.selection,i=t.nodeBefore;if(!r||!i||!["wikilink","datelink"].includes(i.type.name))return!1;if(e){let s=i.attrs,l=`[[${s.target??s.date}${s.anchor?`#^${s.anchor}`:""}${s.shown?`|${s.shown}`:""}`;e(n.tr.replaceWith(t.pos-i.nodeSize,t.pos,n.schema.text(l)))}return!0}function Ta({ask:n,resolutions:e}){let t=null,r=0,i=o=>o.length===1?"1 page":`${o.length} pages`;async function s(o,l){let a=++r,c=[];try{c=await n(l.text)}catch{}let f=await e.lookup(c.map(h=>h.text));if(a!==r)return;let u=rs(o.state);!u||u.from!==l.from||t.show(ep(u,c,f),u.from)}return new C({key:Xd,view(o){t=new At(o,{label:"Pages to link",count:i});let l=null;return{update(a,c){if(a.state.doc.eq(c.doc)&&a.state.selection.eq(c.selection))return;let f=rs(a.state);if(clearTimeout(l),!f){r++,t.close();return}l=setTimeout(()=>s(a,f),30)},destroy(){t.destroy()}}},props:{handleKeyDown(o,l){return t?.keys(l)??!1},handleDOMEvents:{blur(){return t?.close(),!1}}}})}function Na(n){let{$from:e}=n.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name==="list_item")return e.node(t);return null}function tp(n){return(e,t,r)=>{let i=Na(e);if(!i)return!1;let s={indent:i.attrs.indent,bullet:i.attrs.bullet,delim:i.attrs.delim,number:/^[0-9]{1,8}$/u.test(i.attrs.number??"")?String(+i.attrs.number+1):null,task:i.attrs.task,checked:i.attrs.task?" ":null};return ka(n.nodes.list_item,s)(e,t,r)}}function np(n){return(e,t)=>{let{$from:r,$to:i}=e.selection;if(r.depth<2||r.node(-1).type!==n.nodes.blockquote)return!1;if(t){let s=i.parent.content.cut(i.parentOffset),o=r.after(-1),l=e.tr.delete(r.pos,r.end()),a=l.mapping.map(o);l.insert(a,n.nodes.paragraph.create(null,s)),t(l.setSelection(S.create(l.doc,a+1)).scrollIntoView())}return!0}}function rp(n){return(e,t)=>{let{$from:r}=e.selection;return r.parent.type.spec.code||!r.parent.inlineContent?!1:(t&&t(e.tr.replaceSelectionWith(n.nodes.hard_break.create()).scrollIntoView()),!0)}}function Ea(n,{save:e}){let t=Ca(n),r=!1,i=a=>(c,f,u)=>u?.composing?!1:a(c,f,u),s=Ti({Backspace:$e(Sa,Da),"Mod-z":un,"Shift-Mod-z":Dt,"Mod-y":Dt,"Mod-b":t.strong,"Mod-i":t.em,"Mod-e":t.code,"Mod-s":()=>(e(),!0),Enter:i($e(tp(n),np(n))),"Shift-Enter":i(rp(n)),"Mod-[":Zi(n.nodes.list_item),"Mod-]":es(n.nodes.list_item)}),o=Ti({...Qi,Enter:i(Qi.Enter)});return[new C({props:{handleKeyDown(a,c){if(c.key==="Escape")return r=!0,!1;if(c.key!=="Shift"&&c.key!=="Tab"&&(r=!1),c.key==="Tab"&&!r&&Na(a.state)){let f=(c.shiftKey?Zi(n.nodes.list_item):es(n.nodes.list_item))(a.state,a.dispatch);return c.preventDefault(),f||!0}return c.key==="Tab"&&(r=!1),!1}}}),s,o]}function is(n){for(let e=n.depth;e>0;e--)if(n.node(e).type.name==="list_item")return e;return 0}function ip(n){let e=n.handler;return n.handler=(t,r,i,s)=>is(t.doc.resolve(i))?null:e(t,r,i,s),n}function Aa(n,e,t){return new j(n,(r,i,s,o)=>{let l=r.doc.resolve(s);if(is(l)||l.parent.type.name!=="paragraph")return null;let a=r.tr.delete(s,o),c=a.doc.resolve(s).blockRange(),f=c&&mt(c,e);if(!f)return null;a.wrap(c,f);let u=c.start+1;return a.setNodeMarkup(u,null,{...a.doc.nodeAt(u).attrs,...t(i)}),a})}function sp(n){return Aa(/^\s{0,3}([-*+])\s$/u,n.nodes.bullet_list,e=>({bullet:e[1]}))}function op(n){return Aa(/^\s{0,3}(\d{1,9})([.)])\s$/u,n.nodes.ordered_list,e=>({number:e[1],delim:e[2]}))}function lp(n){return ip(wa(/^(#{1,6})\s$/u,n.nodes.heading,e=>({level:e[1].length,source:null})))}function ap(n){return new j(/^\[([ xX])\]\s$/u,(e,t,r,i)=>{let s=e.doc.resolve(r),o=is(s);if(!o||s.parentOffset!==0)return null;let l=s.node(o);return e.tr.delete(r,i).setNodeMarkup(s.before(o),null,{...l.attrs,task:!0,checked:t[1]})})}function cp(n){return new j(/^\s{0,3}(?:---|\*\*\*|___|[—–]-)$/u,(e,t,r)=>{let i=e.doc.resolve(r);if(i.parent.type.name!=="paragraph"||i.depth!==1)return null;let s=i.before(1),o=i.after(1),l=e.tr.replaceWith(s,o,[n.nodes.horizontal_rule.create(),n.nodes.paragraph.create()]);return l.setSelection(S.create(l.doc,s+2))})}function fp(n){return new j(/^\s{0,3}>$/u,(e,t,r,i)=>{let s=e.doc.resolve(r);if(s.parent.type.name!=="paragraph"||s.depth!==1)return null;let o=e.tr.delete(r,i),l=o.doc.resolve(r).blockRange();return l?o.wrap(l,[{type:n.nodes.blockquote,attrs:{prefix:null}}]):null})}function up(n){return new j(/^(\s{0,3}(?:```|~~~))$/u,(e,t,r,i)=>{let s=e.doc.resolve(r);if(s.parent.type.name!=="paragraph"||s.depth!==1)return null;let o=t[1];return e.tr.delete(r,i).setBlockType(r,r,n.nodes.code_block,{fence:o,info:"",closed:!0,close:o.trimStart()})})}function hp(){return new j(/^\s$/u,(n,e,t,r)=>{let i=n.doc.resolve(t);return i.parent.content.size!==0||i.depth<2||i.node(i.depth-1).type.name!=="blockquote"?null:n.tr})}function dp(){return new C({appendTransaction(n,e,t){if(!n.some(s=>s.getMeta(Le)?.settled)||!t.selection.empty)return null;let r=e.selection.$head.marks(),i=t.selection.$head.marks();return r.length===i.length&&r.every(s=>s.isInSet(i))?null:t.tr.setStoredMarks(r)}})}function va(n){return[xa({rules:[lp(n),sp(n),op(n),ap(n),cp(n),fp(n),up(n),hp()]}),dp()]}var Ra="mapa-editor-notice";function at(n,e={},...t){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);for(let i of t)r.append(i);return r}var pp={draft:"Saved as a draft"};function ls(n){let e=document.querySelector("[estilo-save-status]");!e||e.getAttribute("data-state")===n||(e.setAttribute("data-state",n),e.textContent=e.getAttribute(`data-text-${n}`)??pp[n]??"")}function Ia(n,e,t={},r=!1){let i=at("form",{method:"post",action:n});for(let[s,o]of Object.entries(t))i.append(at("input",{type:"hidden",name:s,value:o}));return i.append(at("button",{"rst-btn":r?"primary":"",type:"submit"},e)),i}function ss(n,e,t=!1){let r=at("button",{"rst-btn":t?"primary":"",type:"button"},n);return r.addEventListener("click",e),r}function Fe(n,e,...t){mp(n);let r=at("div",{"mapa-unsaved":"",[Ra]:"",role:"status"},at("p",{},e),...t);return n.before(r),r}function mp(n){n.parentNode?.querySelectorAll(`[${Ra}]`).forEach(e=>e.remove())}function Pa(n,e,t){switch(e){case"gone":return Fe(n,"This page was deleted while you were writing. What you type is kept as a draft, never saved to the page, until you choose.",Ia(`/p/${t.page}/draft/scratch`,"Save as a scratch page",{},!0),Ia(`/p/${t.page}/draft/discard`,"Discard",{version:t.version}));case"noBase":return Fe(n,"Your edit started from a version older than the 90-day history, so it cannot be merged block by block.",at("a",{"rst-btn":"primary",href:`/p/${t.page}/conflict`},"Choose what to keep"));case"committed":return Fe(n,"This was saved in another tab. What you type here is kept as a new draft.",ss("Reload",()=>location.reload(),!0));case"newer":return Fe(n,"Another tab had newer text, so this tab now shows it.")}}function Ba(n,e,t){return e==="conflict"?Fe(n,"Someone saved this page while you were writing. Choose below what to keep, or leave and decide on your next visit.",ss("Leave and decide later",t)):Fe(n,"Not saved: what you typed since the last save would be lost if you leave now.",ss("Leave anyway",t))}var Ne=new L("mapa-conflict");function yp(n,e,t){let{emitted:r}=B(n,e);return t.map((i,s)=>{let o=r.slice(i.at,i.at+i.count);if(o.length===0){let a=r[i.at],c=a?a.pos:n.content.size;return{from:c,to:c,index:s,hunk:i}}let l=o[o.length-1];return{from:o[0].pos,to:l.pos+l.node.nodeSize,index:s,hunk:i}})}function kp(n,e,t){return n.some(r=>r.to>r.from&&(e===t?e>r.from&&e<r.to:e<r.to&&t>r.from))}function za(n,e){return n.map(t=>({...t,from:e.map(t.from,1),to:e.map(t.to,-1)}))}function vt(n,e={},...t){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);return r.append(...t),r}var bp=[["mine","Keep yours"],["theirs","Keep theirs"],["both","Keep both, yours first"]];function xp(n,e,t,r){let i=vt("div",{"mapa-hunk-theirs":""}),s=cn(n,e.hunk.theirs,{trailing:!1});i.append(ie.fromSchema(n).serializeFragment(s.content));let o=`mapa-hunk-${e.index}`,l=vt("div",{"mapa-hunk-choice":"",role:"group","aria-labelledby":o,contenteditable:"false"},vt("p",{id:o},vt("strong",{},"Both of you changed this."),e.hunk.theirs===""?" They removed it.":" Theirs:"));e.hunk.theirs!==""&&l.append(i);let a=vt("div",{"mapa-hunk-buttons":""});for(let[c,f]of bp){let u=vt("button",{type:"button","rst-btn":t===c?"primary":"","aria-pressed":t===c?"true":"false","data-choice":c},f);u.addEventListener("click",h=>{h.preventDefault(),r(e.index,c)}),a.append(u)}return l.append(a),l}function La({fidelity:n,isRemote:e,isBusy:t=()=>!1,resolve:r}){return new C({key:Ne,state:{init:()=>({ranges:[],conflict:null,picked:[]}),apply(i,s,o,l){let a=i.getMeta(Ne);return a?.clear?{ranges:[],conflict:null,picked:[]}:a?.conflict?{ranges:yp(l.doc,n,a.conflict.hunks),conflict:a.conflict,picked:[]}:a?.picked?{...s,picked:a.picked}:!i.docChanged||s.ranges.length===0?s:{...s,ranges:za(s.ranges,i.mapping)}}},filterTransaction(i,s){if(!i.docChanged||e()||i.getMeta(Ne))return!0;if(t())return!1;let o=Ne.getState(s).ranges;if(o.length===0)return!0;for(let l of i.steps){let a=!1;if(l.getMap().forEach((c,f)=>{a=a||kp(o,c,f)}),a)return!1;o=za(o,{map:(c,f)=>l.getMap().map(c,f)})}return!0},view(i){return{update(){let s=Ne.getState(i.state).ranges.length>0;i.dom.toggleAttribute("data-mapa-conflict",s)}}},props:{handleDOMEvents:{beforeinput:(i,s)=>t()?(s.preventDefault(),!0):!1},decorations(i){let s=Ne.getState(i);if(s.ranges.length===0)return null;let o=[],l=(a,c,f)=>{let u=[...Ne.getState(a.state).picked];u[c]=f,a.dispatch(a.state.tr.setMeta(Ne,{picked:u})),s.ranges.every(h=>u[h.index])&&r(u)};for(let a of s.ranges)a.to>a.from&&i.doc.nodesBetween(a.from,a.to,(c,f)=>{f>=a.from&&c.isTextblock&&o.push(E.node(f,f+c.nodeSize,{"mapa-hunk":"",contenteditable:"false"}))}),o.push(E.widget(a.from,c=>xp(i.schema,a,s.picked[a.index],(f,u)=>l(c,f,u)),{side:-1,stopEvent:()=>!0,ignoreSelection:!0,key:`hunk-${a.index}-${s.picked[a.index]??""}`}));return N.create(i.doc,o)}}})}function $a(n,e){n.dispatch(n.state.tr.setMeta(Ne,e?{conflict:e}:{clear:!0}))}var Sp=/(?:^|\s)\/([A-Za-z0-9 ]{0,24})$/u,wp=[["Heading 1","#","insert-h1"],["Heading 2","##","insert-h2"],["Heading 3","###","insert-h3"],["List","-","insert-list"],["Numbered","1.","insert-numbered"],["Checklist","- [ ]","insert-check"],["Quote",">","insert-quote"],["Code","```","insert-code"],["Divider","---","insert-rule"],["Link to a page","[[","insert-link"],["Date","today\u2019s note","insert-date"]];function Fa(n){let{$from:e,empty:t}=n.selection;if(!t||e.parent.type.spec.code||!e.parent.inlineContent)return null;let r=e.parent.textBetween(0,e.parentOffset,null,"\uFFFC"),i=Sp.exec(r);return i?{text:i[1].toLowerCase().trim(),from:e.pos-i[1].length-1,to:e.pos}:null}function Va(){let n=null;return new C({view(e){let t=Et(e.state.schema);return n=new At(e,{label:"Blocks",count:r=>r.length===1?"1 block":`${r.length} blocks`}),{update(r,i){if(r.state.doc.eq(i.doc)&&r.state.selection.eq(i.selection))return;let s=Fa(r.state);if(!s){n.close();return}let o=wp.filter(([l])=>l.toLowerCase().includes(s.text)).map(([l,a,c])=>({label:l,detail:a,run:f=>{let u=Fa(f.state);u&&(f.dispatch(f.state.tr.delete(u.from,u.to)),t[c](f.state,f.dispatch,f))}}));n.show(o,s.from)},destroy(){n.destroy()}}},props:{handleKeyDown(e,t){return n?.keys(t)??!1},handleDOMEvents:{blur(){return n?.close(),!1}}}})}var Cp=new L("mapa-bubble");function as(n,e={},t=""){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);return t&&(r.textContent=t),r}function Mp(n,e){let{from:t,to:r,empty:i,$from:s}=n.selection;return i?!!e.isInSet(n.storedMarks||s.marks()):n.doc.rangeHasMark(t,r,e)}function qa(n){return(e,t)=>{let{from:r,to:i,empty:s}=e.selection,o=e.schema.marks.link;if(s)return!1;if(t){let l=e.tr.removeMark(r,i,o);n&&l.addMark(r,i,o.create({href:n})),t(l)}return!0}}function Wa(n){let{selection:e}=n;return e instanceof S&&!e.empty&&!e.$from.parent.type.spec.code}function Ka({makeTeamPage:n=null}={}){let e=null,t=null;return new C({key:Cp,view(r){let i=r.state.schema;e=as("div",{"mapa-bubble":"",role:"toolbar","aria-label":"Format"}),e.hidden=!0,e.addEventListener("mousedown",u=>{u.target!==t&&u.preventDefault()}),e.addEventListener("keydown",u=>{if(u.target===t)return;let h=[...e.querySelectorAll("button")],d=h.indexOf(document.activeElement);u.key==="Escape"?(u.preventDefault(),r.focus()):(u.key==="ArrowRight"||u.key==="ArrowLeft")&&(u.preventDefault(),h[(d+(u.key==="ArrowRight"?1:-1)+h.length)%h.length]?.focus())});let s=[],o=(u,h,d,p)=>{let m=as("button",{type:"button","aria-label":u,"mapa-bubble-button":""},h);return m.addEventListener("click",()=>{d(r),h!=="Link"&&h!=="Make team page"&&r.focus()}),e.append(m),s.push({button:m,mark:p}),m};o("Bold","B",u=>ce(i.marks.strong)(u.state,u.dispatch),i.marks.strong),o("Italic","I",u=>ce(i.marks.em)(u.state,u.dispatch),i.marks.em),o("Code","<>",u=>ce(i.marks.code)(u.state,u.dispatch),i.marks.code),o("Link","Link",()=>l(),i.marks.link),n&&o("Make team page","Make team page",u=>n(u)),t=as("input",{type:"url","aria-label":"Link address",placeholder:"Paste a link","mapa-bubble-field":""}),t.hidden=!0,e.append(t),t.addEventListener("keydown",u=>{if(u.key==="Enter"){u.preventDefault();let h=t.value.trim();(h===""||je(h))&&qa(h)(r.state,r.dispatch),a()}else u.key==="Escape"&&(u.preventDefault(),a())}),document.body.append(e);function l(){t.hidden=!1,t.value="",t.focus()}function a(){t.hidden=!0,r.focus()}e.openLink=l;let c=()=>{if(!Wa(r.state)||!r.hasFocus()&&!e.contains(document.activeElement)){e.hidden=!0;return}for(let{button:T,mark:O}of s)O&&T.setAttribute("aria-pressed",Mp(r.state,O)?"true":"false");e.hidden=!1;let{from:u,to:h}=r.state.selection,d=r.coordsAtPos(u),p=r.coordsAtPos(h),g=window.matchMedia("(pointer: coarse)").matches?p.bottom+12:d.top-e.offsetHeight-8,k=Math.max(4,Math.min((d.left+p.left)/2-e.offsetWidth/2,window.innerWidth-e.offsetWidth-4));e.style.setProperty("top",`${Math.max(g,4)}px`),e.style.setProperty("left",`${k}px`)},f=()=>setTimeout(c,0);return r.dom.addEventListener("blur",f),e.addEventListener("focusout",f),{update:c,destroy(){r.dom.removeEventListener("blur",f),e.remove()}}},props:{handleKeyDown(r,i){return i.key==="F10"&&i.altKey&&e&&!e.hidden?(i.preventDefault(),e.querySelector("button")?.focus(),!0):i.key.toLowerCase()==="k"&&i.shiftKey&&(i.metaKey||i.ctrlKey)&&Wa(r.state)?(i.preventDefault(),e?.openLink(),!0):!1}}})}function Ja(){return new C({props:{handlePaste(n,e){let t=e.clipboardData?.getData("text/plain")?.trim()??"";return n.state.selection.empty||!/^https?:\/\/\S+$/u.test(t)||!je(t)?!1:qa(t)(n.state,n.dispatch)}}})}function ja(n,e){let t=document.createElement("button");return t.type="button",t.setAttribute("mapa-anchor",""),t.setAttribute("contenteditable","false"),t.setAttribute("aria-label","Link to this block"),t.title="Copy link to this block",t.textContent="\xB6",t.addEventListener("mousedown",r=>r.preventDefault()),t.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(`[[${e()}#^${n}]]`),t.setAttribute("data-copied",""),setTimeout(()=>t.removeAttribute("data-copied"),1500)}catch{}}),t}function Ha({title:n}){let e=t=>{let r=[];return t.descendants((i,s)=>{let o=i.attrs?.marker;o&&i.type.name!=="list_item"&&i.type.name!=="blockquote"&&r.push(E.widget(s+1,()=>ja(o,n),{side:-1,key:`anchor-${o}`,ignoreSelection:!0,stopEvent:()=>!0})),o&&(i.type.name==="list_item"||i.type.name==="blockquote")&&r.push(E.widget(s+2,()=>ja(o,n),{side:-1,key:`anchor-${o}`,ignoreSelection:!0,stopEvent:()=>!0}))}),N.create(t,r)};return new C({state:{init:(t,r)=>e(r.doc),apply:(t,r)=>t.docChanged?e(t.doc):r},props:{decorations(t){return this.getState(t)}}})}async function _a(n,e){let t=document.createElement("span");t.setAttribute("rst-spin",""),t.setAttribute("aria-hidden","true"),n.append(t),n.setAttribute("aria-busy","true"),n.disabled=!0;try{let[r]=await Promise.all([e(),new Promise(i=>setTimeout(i,650))]);return r}finally{t.remove(),n.removeAttribute("aria-busy"),n.disabled=!1}}var dn=new L("mapa-moving");function Op(n,e){let{from:t,to:r}=n.selection,{emitted:i,body:s}=B(n.doc,e),o=[];return i.forEach((l,a)=>{let c=l.pos+l.node.nodeSize;l.pos<Math.max(r,t+1)&&c>t&&o.push({index:a,block:l})}),{chosen:o,body:s}}function Dp(n){return((n.find(({block:i})=>i.node.type.name==="heading")??n[0])?.block.node.textContent??"").trim().split(/\s+/u).slice(0,6).join(" ").replace(/[[\]|#^]/gu,"").slice(0,80)}function Tp(n,e,t){let r=oe(pe(n));if(r.length!==t)return null;let i=[];for(let{index:s,block:o}of e){if(!r[s]||r[s].source!==o.text)return null;i.push(s)}return i}function Ua(){return new C({key:dn,state:{init:()=>null,apply(n,e){let t=n.getMeta(dn);return t!==void 0?t:e&&e.map(r=>({from:n.mapping.map(r.from),to:n.mapping.map(r.to)}))}},props:{decorations(n){let e=dn.getState(n);return e?N.create(n.doc,e.map(t=>E.node(t.from,t.to,{"mapa-moving":""}))):null}}})}function ke(n,e={},t=""){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);return t&&(r.textContent=t),r}function Np(){let n=ke("dialog",{"mapa-make-team":"","aria-labelledby":"mapa-make-team-title"}),e=ke("form",{method:"dialog"}),t=ke("h2",{id:"mapa-make-team-title"},"Make team page"),r=ke("label",{for:"mapa-make-team-name"},"Title of the new page"),i=ke("input",{id:"mapa-make-team-name",name:"title",required:"",autocomplete:"off","rst-input":""}),s=ke("p",{"mapa-make-team-error":"",role:"alert"}),o=ke("p",{},"These blocks move to a new team page everyone can open. Your note keeps a link in their place. Nothing else in your note is shared."),l=ke("button",{type:"submit","rst-btn":"primary"},"Make team page"),a=ke("button",{type:"button","rst-btn":""},"Cancel"),c=ke("div",{"mapa-make-team-foot":""});return c.append(a,l),e.append(t,r,i,s,o,c),n.append(e),document.body.append(n),{box:n,form:e,input:i,error:s,confirm:l,cancel:a}}function Ga({saver:n,fidelity:e,post:t,notify:r}){let i=null;return l=>{let{chosen:a}=Op(l.state,e);if(a.length===0)return!1;let c=a.map(({block:k})=>({from:k.pos,to:k.pos+k.node.nodeSize}));l.dispatch(l.state.tr.setMeta(dn,c)),i=i??Np();let{box:f,form:u,input:h,error:d,confirm:p,cancel:m}=i;h.value=Dp(a),d.textContent="";let g=()=>{l.dispatch(l.state.tr.setMeta(dn,null)),u.onsubmit=null,m.onclick=null,f.onclose=null,f.open&&f.close(),l.focus()};return m.onclick=g,f.onclose=g,u.onsubmit=async k=>{k.preventDefault();let T=h.value.trim(),O=await _a(p,()=>s(l,a,T));if(O.error){d.textContent=O.error,h.focus();return}g(),r(T,O.href)},f.showModal(),h.select(),!0};async function s(l,a,c){let f=await n.commit({explicit:!0});if(!["none","saved","merged"].includes(f)||!n.page)return{error:"Your note could not be saved just now, so nothing was moved. Try again."};let{emitted:u}=B(l.state.doc,e),h=o(l,a),d=h&&Tp(n.saved,h,u.length);if(!d)return{error:"Your note changed while it was saved. Choose the blocks again."};let p;try{p=await t(`/p/${n.page}/share`,{title:c,revision:n.base,block:d.map(String)})}catch{return{error:"Nothing was moved: the server could not be reached."}}return p.status!==200?{error:p.json?.error??"Nothing was moved."}:(n.took(p.json.body,p.json.revision),{href:p.json.href})}function o(l,a){let{emitted:c}=B(l.state.doc,e),f=[],u=0;for(let{block:h}of a){let d=c.findIndex((p,m)=>m>=u&&p.text===h.text);if(d<0)return null;f.push({index:d,block:c[d]}),u=d+1}return f}}function Ep(n,e){let t=n.resolve(e);for(let r=t.depth;r>0;r--){let i=t.node(r);if(i.type.name==="list_item")return{pos:t.before(r),node:i}}return null}function Ap(n,e,t){let r=t.attrs.checked!==" ",i=document.createElement("button");return i.type="button",i.setAttribute("mapa-task-box",""),i.setAttribute("contenteditable","false"),i.setAttribute("aria-pressed",r?"true":"false"),i.setAttribute("aria-label",`${r?"Done":"Not done"}: ${t.firstChild?.textContent??""}`),i.addEventListener("mousedown",s=>s.preventDefault()),i.addEventListener("click",s=>{s.preventDefault();let o=Ep(n.state.doc,e());if(!o?.node.attrs.task)return;let l=o.node.attrs.checked!==" "?" ":"x";n.dispatch(n.state.tr.setNodeMarkup(o.pos,null,{...o.node.attrs,checked:l}))}),i}function Ya(n){let e=[];return n.descendants((t,r)=>{if(t.type.name!=="list_item"||!t.attrs.task)return;let i=`task:${t.attrs.checked}:${t.firstChild?.textContent??""}`;e.push(E.widget(r+2,(s,o)=>Ap(s,o,t),{side:-1,key:i,ignoreSelection:!0,stopEvent:()=>!0}))}),N.create(n,e)}function Xa(){return new C({state:{init:(n,e)=>Ya(e.doc),apply:(n,e)=>n.docChanged?Ya(n.doc):e},props:{decorations(n){return this.getState(n)}}})}function Qa(n,e={},t=""){let r=document.createElement(n);for(let[i,s]of Object.entries(e))r.setAttribute(i,s);return t&&(r.textContent=t),r}function Za(n){return new C({view(e){let{place:t,row:r}=vp(e,n);return{update:t,destroy:()=>r.remove()}}})}function vp(n,{makeTeamPage:e=null}={}){let t=n.state.schema,r=Et(t),i=Qa("div",{"mapa-accessory":"",role:"toolbar","aria-label":"Writing"});i.hidden=!0;let s=(c,f,u)=>{let h=Qa("button",{type:"button","aria-label":c},f);h.addEventListener("mousedown",d=>d.preventDefault()),h.addEventListener("click",()=>{u(n.state,n.dispatch,n),n.focus()}),i.append(h)};s("Link to a page","[[",yr("[[")),s("Blocks","/",yr("/")),s("Bold","B",ce(t.marks.strong)),s("Italic","I",ce(t.marks.em)),s("List","\u2022",r["insert-list"]),s("Checklist","\u2610",r["insert-check"]),e&&s("Make team page","Team page",(c,f,u)=>e(u)),document.body.append(i);let o=window.matchMedia("(pointer: coarse) and (max-width: 799px)"),l=window.visualViewport,a=()=>{let c=o.matches&&n.hasFocus();i.hidden=!c;let f=l?window.innerHeight-l.height-l.offsetTop:0;document.documentElement.toggleAttribute("data-mapa-keyboard",c&&f>80),c&&i.style.setProperty("bottom",`${Math.max(f,0)}px`)};return n.dom.addEventListener("focus",a),n.dom.addEventListener("blur",()=>setTimeout(a,0)),l?.addEventListener("resize",a),l?.addEventListener("scroll",a),o.addEventListener?.("change",a),{place:a,row:i}}async function kr(n,e,{keepalive:t=!1}={}){let r=new URLSearchParams;for(let[o,l]of Object.entries(e))for(let a of[].concat(l))r.append(o,a);let i=await fetch(n,{method:"POST",body:r,credentials:"same-origin",keepalive:t,headers:{Accept:"application/json"}}),s=null;try{s=await i.json()}catch{}return{status:i.status,json:s}}var Ip={get:n=>sessionStorage.getItem(n),set:(n,e)=>sessionStorage.setItem(n,e),remove:n=>sessionStorage.removeItem(n)};function Rp(){let n=Number(document.documentElement.getAttribute("data-mapa-idle"));return n>0?n:void 0}function tc(){let n=document.getElementById("mapa-editor"),e=n?.nextElementSibling;for(;e?.nodeName==="SCRIPT";)e=e.nextElementSibling;if(!e||!e.matches("article[mapa-body]"))return null;let t=JSON.parse(n.textContent),r=new dr(t.links,async f=>(await kr("/links/resolve",{target:f})).json),i=In((f,u)=>r.answer(f,u)),{doc:s,fidelity:o}=Pi(i,t.source),l={view:null},a=ea(l,o),c=new pr(t,{editor:a,post:kr,storage:Ip,idle:Rp(),ui:Vp(e,l),navigate:f=>location.assign(f),replaceURL:f=>Pp(f),reload:()=>location.reload(),refetch:qp});return l.saver=c,l.view=$p(e,i,s,o,r,c,a),jp(l.view,c,e),c.settle(),t.source.trim()===""&&!t.drafts.startsWith("/d/")&&l.view.focus(),performance.mark("mapa-mounted"),{view:l.view,saver:c,fidelity:o,resolutions:r}}function Pp(n){window.history.replaceState(null,"",n)}function Bp(n){return n.drafts.startsWith("/d/")||!!n.token||!!document.querySelector('[estilo-menubar] a[href$="/share"]')}function zp(n,e,t){let r=document.createElement("a");r.href=t,r.textContent=e;let i=document.createElement("span");i.append("Moved to ",r,"."),Fe(n,i)}async function Lp(n){let e=await fetch(`/links/suggest?q=${encodeURIComponent(n)}`,{credentials:"same-origin"});return e.ok?(await e.json()).suggestions??[]:[]}function ec(){return document.querySelector("h1[mapa-title]")?.textContent.trim()??""}function $p(n,e,t,r,i,s,o){let l=Bp(s)?Ga({saver:s,fidelity:r,post:kr,notify:(f,u)=>zp(n,f,u)}):null,a=Wn.create({doc:t,plugins:[Ta({ask:Lp,resolutions:i}),Va(),Ka({makeTeamPage:l}),Ha({title:ec}),Ua(),Xa(),Za({makeTeamPage:l}),...Ea(e,{save:()=>s.commit({explicit:!0})}),...va(e),Zl(),Rl(),zl(),zi(r),Ja(),Ki(r),La({fidelity:r,isRemote:()=>o.remote,isBusy:()=>s.resolving,resolve:f=>s.resolve(f)})]}),c=new rn({mount:n},{state:a,nodeViews:la(i),attributes:{role:"textbox","aria-multiline":"true","aria-label":`Page text, ${ec()}`,spellcheck:"true"},dispatchTransaction(f){this.updateState(this.state.apply(f)),f.docChanged&&!o.remote&&s.changed()},handleClickOn(f,u,h,d,p){if(!["wikilink","datelink"].includes(h.type.name)||p.button!==0||p.metaKey||p.ctrlKey||p.shiftKey||p.altKey)return!1;let m=f.nodeDOM(d)?.getAttribute?.("href");return m?(p.preventDefault(),s.leave(m),!0):!1}});return Fp(c,l),c}function Fp(n,e){let t=document.querySelector('[estilo-menubar] a[href$="/share"]');!t||!e||t.addEventListener("click",r=>{n.state.selection.empty||(r.preventDefault(),t.closest("details")?.removeAttribute("open"),e(n))})}function Vp(n,e){return{status:ls,notice:(t,r)=>Wp(Pa(n,t,r),e.saver),leaving:(t,r)=>Ba(n,t,r),conflict:t=>$a(e.view,t),committed:()=>{document.querySelector("[mapa-unsaved]:not([mapa-editor-notice])")?.remove(),Kp()}}}function Wp(n,e){for(let t of n?.querySelectorAll?.("form")??[])t.addEventListener("submit",async r=>{r.preventDefault(),await e.flush();let i=t.querySelector('input[name="version"]');i&&(i.value=e.version),e.stopped=!0,t.submit()});return n}async function qp(){let n=await fetch(location.pathname,{credentials:"same-origin"});if(!n.ok)return null;let t=new DOMParser().parseFromString(await n.text(),"text/html").getElementById("mapa-editor");return t?JSON.parse(t.textContent):null}async function Kp(){let n;try{let t=await fetch(location.pathname,{credentials:"same-origin"});if(!t.ok)return;n=await t.text()}catch{return}let e=new DOMParser().parseFromString(n,"text/html");for(let t of["#mapa-links-body","footer[mapa-foot-refs]"]){let r=document.querySelector(t),i=e.querySelector(t);r&&i&&r.replaceChildren(...i.childNodes)}}function Jp(n){if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return null;let e=n.target.closest?.("a[href]");if(!e||e.target||e.hasAttribute("download"))return null;let t=new URL(e.href,location.href);return t.origin!==location.origin||t.pathname===location.pathname&&t.search===location.search?null:t.href}function cs(n){n.domObserver?.flush?.()}function jp(n,e,t){document.addEventListener("click",i=>{let s=Jp(i);if(s&&i.target.closest?.("[mapa-unsaved] a[href]")){i.preventDefault(),cs(n),e.hold(),e.flush().finally(()=>location.assign(s));return}s&&(cs(n),e.committable()&&(i.preventDefault(),e.leave(s)))});let r=!1;globalThis.navigation?.addEventListener?.("navigate",i=>{r=i.navigationType==="reload"}),window.addEventListener("pagehide",()=>{cs(n),e.closing({reloading:r})}),window.addEventListener("pageshow",i=>{i.persisted&&e.shown()}),_p(e),Hp(n),ls(e.own||e.offered?"saved":"idle")}function Hp(n){let e={...Et(n.state.schema),undo:un,redo:Dt,"select-all":Ma};for(let t of document.querySelectorAll("[data-mapa-command]")){let r=e[t.getAttribute("data-mapa-command")];r&&(t.disabled=!1,t.addEventListener("click",i=>{i.preventDefault(),t.closest("details")?.removeAttribute("open"),n.focus(),r(n.state,n.dispatch,n)}))}}function _p(n){let e=document.querySelector("[mapa-unsaved]:not([mapa-editor-notice])");if(e)for(let t of e.querySelectorAll("form")){let r=/\/draft\/save$/u.test(t.getAttribute("action"));t.addEventListener("submit",async i=>{if(i.preventDefault(),r){let o=await n.commit({explicit:!0});(o==="saved"||o==="merged")&&e.remove();return}n.stopped=!0;let s=await kr(t.getAttribute("action"),{version:n.version});location.assign(s.json?.href??location.pathname)})}}var t0=In(),nc=typeof document>"u"?null:tc();nc&&(globalThis.mapaEditor=nc);export{ar as Fidelity,cr as applyBody,Ki as clipboardPlugin,qi as copyData,In as createSchema,ae as docBlocks,nc as editor,Le as fidelityKey,zi as fidelityPlugin,cn as fromMarkdown,Wi as mapaType,Pi as mount,ra as pasteTransaction,Bi as prepareSave,jl as rebuild,Ot as recordBody,Xh as reparse,t0 as schema,fn as serialise,B as serialiseDetailed,Ul as settle,lr as structureCheck,ia as textSlice};