| similarity index 82% |
| rename from internal/mapa/static/editor.bad1b29c273b6a86.js |
| rename to internal/mapa/static/editor.76f9a0ad7441c734.js |
| index ccffeff..53cc198 100644 |
| --- a/internal/mapa/static/editor.bad1b29c273b6a86.js |
| +++ b/internal/mapa/static/editor.76f9a0ad7441c734.js |
| @@ -41,4 +41,4 @@ function H(n){this.content=n}H.prototype={constructor:H,find:function(n){for(var |
| `)}var Ur=200,J=function(){};J.prototype.append=function(e){return e.length?(e=J.from(e),!this.length&&e||e.length<Ur&&this.leafAppend(e)||this.length<Ur&&e.leafPrepend(this)||this.appendInner(e)):this};J.prototype.prepend=function(e){return e.length?J.from(e).append(this):this};J.prototype.appendInner=function(e){return new ng(this,e)};J.prototype.slice=function(e,t){return e===void 0&&(e=0),t===void 0&&(t=this.length),e>=t?J.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};J.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};J.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)};J.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(o,s){return i.push(e(o,s))},t,r),i};J.from=function(e){return e instanceof J?e:e&&e.length?new zc(e):J.empty};var zc=(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,o){return i==0&&o==this.length?this:new e(this.values.slice(i,o))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,o,s,l){for(var a=o;a<s;a++)if(i(this.values[a],l+a)===!1)return!1},e.prototype.forEachInvertedInner=function(i,o,s,l){for(var a=o-1;a>=s;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=Ur)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=Ur)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})(J);J.empty=new zc([]);var ng=(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,o,s){var l=this.left.length;if(i<l&&this.left.forEachInner(r,i,Math.min(o,l),s)===!1||o>l&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,o)-l,s+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,o,s){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(o,l)-l,s+l)===!1||o<l&&this.left.forEachInvertedInner(r,Math.min(i,l),o,s)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var o=this.left.length;return i<=o?this.left.slice(r,i):r>=o?this.right.slice(r-o,i-o):this.left.slice(r,o).append(this.right.slice(0,i-o))},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})(J),Ho=J;var rg=500,It=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,o;t&&(i=this.remapping(r,this.items.length),o=i.maps.length);let s=e.tr,l,a,c=[],u=[];return this.items.forEach((f,d)=>{if(!f.step){i||(i=this.remapping(r,d+1),o=i.maps.length),o--,u.push(f);return}if(i){u.push(new Ae(f.map));let h=f.step.map(i.slice(o)),p;h&&s.maybeStep(h).doc&&(p=s.mapping.maps[s.mapping.maps.length-1],c.push(new Ae(p,void 0,void 0,c.length+u.length))),o--,p&&i.appendMap(p,o)}else s.maybeStep(f.step);if(f.selection)return l=i?f.selection.map(i.slice(o)):f.selection,a=new n(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:s,selection:l}}addTransform(e,t,r,i){let o=[],s=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let u=0;u<e.steps.length;u++){let f=e.steps[u].invert(e.docs[u]),d=new Ae(e.mapping.maps[u],f,t),h;(h=a&&a.merge(d))&&(d=h,u?o.pop():l=l.slice(0,l.length-1)),o.push(d),t&&(s++,t=void 0),i||(a=d)}let c=s-r.depth;return c>og&&(l=ig(l,c),s-=c),new n(l.append(o),s)}remapping(e,t){let r=new wn;return this.items.forEach((i,o)=>{let s=i.mirrorOffset!=null&&o-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,s)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new Ae(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,o=e.mapping,s=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let h=o.getMirror(--a);if(h==null)return;s=Math.min(s,h);let p=o.maps[h];if(d.step){let m=e.steps[h].invert(e.docs[h]),g=d.selection&&d.selection.map(o.slice(a+1,h));g&&l++,r.push(new Ae(p,m,g))}else r.push(new Ae(p))},i);let c=[];for(let d=t;d<s;d++)c.push(new Ae(o.maps[d]));let u=this.items.slice(0,i).append(c).append(r),f=new n(u,l);return f.emptyItemCount()>rg&&(f=f.compress(this.items.length-r.length)),f}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=[],o=0;return this.items.forEach((s,l)=>{if(l>=e)i.push(s),s.selection&&o++;else if(s.step){let a=s.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let u=s.selection&&s.selection.map(t.slice(r));u&&o++;let f=new Ae(c.invert(),a,u),d,h=i.length-1;(d=i.length&&i[h].merge(f))?i[h]=d:i.push(f)}}else s.map&&r--},this.items.length,0),new n(Ho.from(i.reverse()),o)}};It.empty=new It(Ho.empty,0);function ig(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}var Ae=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)}}},Ee=class{constructor(e,t,r,i,o){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=o}},og=20;function sg(n,e,t,r){let i=t.getMeta(vt),o;if(i)return i.historyState;t.getMeta(Vc)&&(n=new Ee(n.done,n.undone,null,0,-1));let s=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(s&&s.getMeta(vt))return s.getMeta(vt).redo?new Ee(n.done.addTransform(t,void 0,r,_r(e)),n.undone,$c(t.mapping.maps),n.prevTime,n.prevComposition):new Ee(n.done,n.undone.addTransform(t,void 0,r,_r(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(s&&s.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!s&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!lg(t,n.prevRanges)),c=s?Uo(n.prevRanges,t.mapping):$c(t.mapping.maps);return new Ee(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,_r(e)),It.empty,c,t.time,l??n.prevComposition)}else return(o=t.getMeta("rebased"))?new Ee(n.done.rebased(t,o),n.undone.rebased(t,o),Uo(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Ee(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Uo(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function lg(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let o=0;o<e.length;o+=2)r<=e[o+1]&&i>=e[o]&&(t=!0)}),t}function $c(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,o,s)=>e.push(o,s));return e}function Uo(n,e){if(!n)return null;let t=[];for(let r=0;r<n.length;r+=2){let i=e.map(n[r],1),o=e.map(n[r+1],-1);i<=o&&t.push(i,o)}return t}function ag(n,e,t){let r=_r(e),i=vt.get(e).spec.config,o=(t?n.undone:n.done).popEvent(e,r);if(!o)return null;let s=o.selection.resolve(o.transform.doc),l=(t?n.done:n.undone).addTransform(o.transform,e.selection.getBookmark(),i,r),a=new Ee(t?l:o.remaining,t?o.remaining:l,null,0,-1);return o.transform.setSelection(s).setMeta(vt,{redo:t,historyState:a})}var _o=!1,Fc=null;function _r(n){let e=n.plugins;if(Fc!=e){_o=!1,Fc=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){_o=!0;break}}return _o}function Yo(n){return n.setMeta(Vc,!0)}var vt=new N("history"),Vc=new N("closeHistory");function Wc(n={}){return n={depth:n.depth||100,newGroupDelay:n.newGroupDelay||500},new S({key:vt,state:{init(){return new Ee(It.empty,It.empty,null,0,-1)},apply(e,t,r){return sg(t,r,e,n)}},config:n,props:{handleDOMEvents:{beforeinput(e,t){let r=t.inputType,i=r=="historyUndo"?Go:r=="historyRedo"?Xo:null;return!i||!e.editable?!1:(t.preventDefault(),i(e.state,e.dispatch))}}}})}function Yr(n,e){return(t,r)=>{let i=vt.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let o=ag(i,t,n);o&&r(e?o.scrollIntoView():o)}return!0}}var Go=Yr(!1,!0),Xo=Yr(!0,!0),tx=Yr(!1,!1),nx=Yr(!0,!1);function qc(n,e){let t={remote:!1},r=()=>n.view,i=o=>{let s=t.remote;t.remote=!0;try{return o()}finally{t.remote=s}};return t.current=()=>Fn(r().state.doc,e),t.prepare=()=>i(()=>jo(r(),e).body),t.apply=o=>i(()=>{r().dispatch(Yo(r().state.tr));let s=Hr(r(),e,o);return r().dispatch(Yo(r().state.tr)),s}),t}function Ne(n){for(let e=n.depth;e>0;e--)if(n.node(e).type.name==="column")return{layout:n.node(e-1),layoutPos:n.before(e-1),column:n.node(e),columnPos:n.before(e),index:n.index(e-1)};return null}function Kc(n){return n.nodes.column.create(null,n.nodes.paragraph.create())}function cg(n){let{$from:e,$to:t}=n.selection;return e.depth<1?null:{from:e.before(1),to:t.after(1)}}function Zo(n){return(e,t)=>{let r=e.schema;if(Ne(e.selection.$from)||Ne(e.selection.$to))return!1;let i=cg(e);if(!i)return!1;if(t){let o=Gr(e.doc.slice(i.from,i.to).content),s=o.textBetween(0,o.size,"","\uFFFC").trim()!=="",l=r.nodes.column.createChecked(null,o.size?o:r.nodes.paragraph.create()),a=[l];for(let d=1;d<n;d++)a.push(Kc(r));let c=r.nodes.columns.createChecked(null,a),u=e.tr.replaceWith(i.from,i.to,c),f=s?i.from+1+l.nodeSize+1:i.from+2;u.setSelection(k.near(u.doc.resolve(f))),t(u.scrollIntoView())}return!0}}function ug(n,e){let t=Ne(n.selection.$head);if(!t||t.layout.childCount>=4)return!1;if(e){let r=t.columnPos+t.column.nodeSize,i=n.tr.insert(r,Kc(n.schema));i.setSelection(k.near(i.doc.resolve(r+2))),e(i.scrollIntoView())}return!0}function jc(n,e){let t=Ne(n.selection.$head);if(!t)return!1;if(t.layout.childCount<=2)return Jc(n,e);if(e){let r=Hc(t.column.content),i=n.tr.delete(t.columnPos,t.columnPos+t.column.nodeSize),o=t.index>0?t.index-1:0,s=t.layoutPos+1;for(let c=0;c<o;c++)s+=i.doc.nodeAt(t.layoutPos).child(c).nodeSize;let l=i.doc.nodeAt(s),a=t.index>0?s+l.nodeSize-1:s+1;r.size&&i.insert(a,r),i.setSelection(k.near(i.doc.resolve(a))),e(i.scrollIntoView())}return!0}function Jc(n,e){let t=Ne(n.selection.$head);if(!t)return!1;if(e){let r=[];t.layout.forEach(s=>s.forEach(l=>r.push(l)));let i=Hc(b.from(r)),o=n.tr.replaceWith(t.layoutPos,t.layoutPos+t.layout.nodeSize,i.size?i:n.schema.nodes.paragraph.create());o.setSelection(k.near(o.doc.resolve(t.layoutPos+1))),e(o.scrollIntoView())}return!0}function Hc(n){let e=[];return n.forEach(t=>{t.type.name==="paragraph"&&t.content.size===0||e.push(t)}),b.from(e)}function Uc(n,e){let{$head:t,empty:r}=n.selection,i=Ne(t);return!r||!i||!(i.column.childCount===1&&i.column.firstChild.type.name==="paragraph"&&i.column.firstChild.content.size===0)?!1:jc(n,e)}function Qo(n){return(e,t)=>{let r=Ne(e.selection.$head);if(!r)return!1;let i=r.index+n;if(i<0||i>=r.layout.childCount)return!1;if(t){let o=r.layoutPos+1;for(let s=0;s<i;s++)o+=r.layout.child(s).nodeSize;t(e.tr.setSelection(k.near(e.doc.resolve(o+1))).scrollIntoView())}return!0}}function _c(){return{"insert-columns-2":Zo(2),"insert-columns-3":Zo(3),"insert-columns-4":Zo(4),"add-column":ug,"remove-column":jc,"undo-columns":Jc}}function Gr(n){let e=[];return n.forEach(t=>{t.type.name==="columns"?t.forEach(r=>r.forEach(i=>e.push(i))):e.push(t)}),b.from(e)}function es(n){return Ne(n)!==null}function Vn(n){let{$from:e,$to:t,empty:r}=n.selection;if(r)return!1;let i=Ne(e),o=Ne(t);return!i&&!o?!1:!i||!o||i.columnPos!==o.columnPos}function Pt(n,e){if(!Vn(n))return!1;if(e){let{from:t,to:r}=n.selection,i=[];n.doc.nodesBetween(t,r,(s,l,a)=>{if(s.type.name==="columns")return!0;if(s.type.name==="column"){let c=Math.max(t,l+1),u=Math.min(r,l+s.nodeSize-1);return u>c&&i.push({from:c,to:u,column:l}),!1}if(a===n.doc){let c=Math.max(t,l),u=Math.min(r,l+s.nodeSize);u>c&&i.push({from:c,to:u})}return!1});let o=n.tr;for(let s of i.reverse())if(o.delete(o.mapping.map(s.from),o.mapping.map(s.to)),s.column!==void 0){let l=o.mapping.map(s.column),a=o.doc.nodeAt(l);a&&a.content.size===0&&o.insert(l+1,n.schema.nodes.paragraph.create())}o.setSelection(k.near(o.doc.resolve(o.mapping.map(t)))),e(o.scrollIntoView())}return!0}function ts(n){return(e,t)=>{let{$cursor:r}=e.selection;if(!r||r.depth<1||!(n?r.parentOffset===0:r.parentOffset===r.parent.content.size))return!1;let o=r.depth,s=r.index(o-1),a=r.node(o-1).maybeChild(n?s-1:s+1);if(!a||a.type.name!=="columns")return!1;if(t){let c=n?r.before(o)-1:r.after(o)+1,u=n?k.near(e.doc.resolve(c),-1):k.near(e.doc.resolve(c),1);t(e.tr.setSelection(u).scrollIntoView())}return!0}}function Yc(){return new S({props:{handleTextInput(n,e,t,r){return Vn(n.state)?(Pt(n.state,n.dispatch),n.dispatch(n.state.tr.insertText(r).scrollIntoView()),!0):!1},handlePaste(n){return Vn(n.state)&&Pt(n.state,n.dispatch),!1}}})}var ns="application/x-mapa";function rs(n,e,t=n.selection.from,r=n.selection.to,i=""){let s=n.doc.slice(t,r,!0).content,l=s.firstChild;s.childCount===1&&l.type.name==="columns"&&l.childCount===1&&(s=l.firstChild.content);let a=n.schema.topNodeType.create(null,s),{body:c,emitted:u}=P(a,e,{edges:!1,raw:!0}),f=JSON.stringify({v:1,sources:u.map(d=>d.text),seams:u.slice(1).map(d=>d.seam),page:i});return{text:c,mapa:f}}function fg(n){let e;try{e=JSON.parse(n)}catch{return null}if(e?.v!==1||!Array.isArray(e.sources))return null;let t=new Set;for(let r of e.sources){if(typeof r!="string")return null;for(let i of ee(r))if(i.kind!==ie)for(let o of ze(i.source))o.kind===Ze&&t.add(o.target)}return{payload:e,ids:[...t],page:typeof e.page=="string"?e.page:""}}function dg(n,e){let t=n.sources.map(r=>{if(ee(r)[0]?.kind===ie)return r;let i="";for(let o of ze(r)){let s=o.kind===Ze?e[o.target]:null;i+=s?``:o.source}return i});return JSON.stringify({...n,sources:t})}function hg(n){if(!/<img/iu.test(n))return n;let e=new DOMParser().parseFromString(n,"text/html");for(let t of[...e.querySelectorAll("img")]){let r=t.getAttribute("src")??"";if(!r.startsWith(X))if(Re(r)){let i=e.createElement("a");i.setAttribute("href",r),i.textContent=t.getAttribute("alt")||r,t.replaceWith(i)}else t.remove()}return e.body.innerHTML}function pg(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(s=>typeof s=="string")||!r.every(s=>/^\n(?:[^\n]*\n)*$/u.test(s)))return null;let i=t.map((s,l)=>(l?r[l-1]:"")+s).join(""),o=ee(i);return o.length!==t.length||o.some((s,l)=>s.source!==t[l])?null:i}function mg(n,e){let{from:t,to:r}=n.selection,i=new Set;for(let o of P(n.doc,e).emitted){let s=o.holder.attrs.marker,l=o.holderPos>=t&&o.holderPos+o.holder.nodeSize<=r;s&&!l&&i.add(s)}return i}function Gc(n,e){let t=[];return n.forEach(r=>{let i=r;!r.isTextblock&&!r.isLeaf&&(i=r.copy(Gc(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)}),b.from(t)}function Xc(n,e,t){let r=mg(e,t);return r.size===0?n:new x(Gc(n.content,r),n.openStart,n.openEnd)}function is(n,e,t){let r=pg(t);if(r===null)return null;let{doc:i}=tn(n.schema,e,r,{trailing:!1,edges:!1}),o=es(n.selection.$from)?Gr(i.content):i.content,s=Xc(x.maxOpen(o),n,e),{$from:l,empty:a}=n.selection;if(a&&l.depth===1&&l.parent.type.name==="paragraph"&&l.parent.content.size===0){let c=n.tr.replaceWith(l.before(),l.after(),s.content),u=l.before()+s.content.size;return c.setSelection(k.near(c.doc.resolve(u),-1))}return n.tr.replaceSelection(s)}function Zc(n,e){let t=$n(n,e,{trailing:!1});return t.childCount?x.maxOpen(t.content):x.empty}function gg(n,e){let t=e.content,r=t.firstChild;if(!r)return"";r.isInline?t=b.from(n.nodes.paragraph.create(null,t)):r.type.name==="list_item"&&(t=b.from(n.nodes.bullet_list.create(null,t)));try{return P(n.topNodeType.create(null,t),null,{edges:!1,raw:!0}).body}catch{return e.content.textBetween(0,e.content.size,` |
| |
| `)}}var yg=new N("mapa-clipboard");function ss(n,e={}){let t=()=>e.page?.()??"",r=(i,o,s)=>{let l=o.clipboardData;if(!l||i.state.selection.empty)return!1;let{text:a,mapa:c}=rs(i.state,n,void 0,void 0,t()),{dom:u}=i.serializeForClipboard(i.state.selection.content());return o.preventDefault(),l.clearData(),l.setData("text/html",u.innerHTML),l.setData("text/plain",a),l.setData(ns,c),s&&Vn(i.state)?Pt(i.state,f=>i.dispatch(f.setMeta("uiEvent","cut"))):s&&i.dispatch(i.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut")),!0};return new S({key:yg,props:{handleDOMEvents:{copy:(i,o)=>r(i,o,!1),cut:(i,o)=>r(i,o,!0)},handlePaste(i,o){let s=o.clipboardData?.getData(ns);if(!s)return!1;let l=fg(s);if(l?.ids.length&&e.copy&&(!l.page||l.page!==t()))return o.preventDefault(),bg(i,n,l,e),!0;let a=is(i.state,n,s);return a?(i.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0):!1},transformPastedHTML:i=>hg(i),clipboardTextSerializer(i,o){return o.state.selection.content().eq(i)?rs(o.state,n).text:gg(o.state.schema,i)},clipboardTextParser(i,o,s,l){return Zc(l.state.schema,i)},transformPasted(i,o){let s=i;if(es(o.state.selection.$from)){let l=!1;i.content.forEach(a=>{l=l||a.type.name==="columns"}),l&&(s=x.maxOpen(Gr(i.content)))}return Xc(s,o.state,n)}}})}async function bg(n,e,t,r){let i=null;try{i=await r.copy(t.ids)}catch{}if(!i||i.status!==200){r.refused?.(i?.json?.refused??"the images could not be copied. Check your connection and try again.");return}r.copied?.(i.json??{});let o=is(n.state,e,dg(t.payload,i.json??{}));o&&n.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste"))}var Qc=32;function nn(n,e){return e?`${n}#^${e}`:n}function xg(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,icon:n.icon||null};case"block gone":return{href:n.href,title:n.title,alias:!!n.alias,blockGone:!0}}return null}function kg(n,e=new Date().getFullYear()){return $i(n)?W(n)?{href:`/d/${n}`,day:Xt(n,e)}:{broken:!0}:{href:`/new?${new URLSearchParams({title:n}).toString()}`,pending:!0}}var Xr=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=nn(e,t),i=xg(this.known.get(r));return i||(this.ask&&!this.asked.has(r)&&(this.waiting.add(r),this.soon()),kg(e))}soon(){this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},0))}async flush(){let e=[...this.waiting].slice(0,Qc);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,o]of Object.entries(t??{}))this.known.set(i,o),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,Qc);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 ls(n){return n.type.name==="datelink"?nn(n.attrs.date,n.attrs.anchor):nn(n.attrs.target,n.attrs.anchor)}function eu(n){return re.renderSpec(document,n.type.spec.toDOM(n)).dom}var as=class{constructor(e,t){this.node=e,this.dom=eu(e),this.unwatch=t.watch(r=>{r.has(ls(this.node))&&this.redraw()})}redraw(){let e=eu(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||ls(e)!==ls(this.node)||e.attrs.shown!==this.node.attrs.shown?!1:(this.node=e,!0)}ignoreMutation(){return!0}destroy(){this.unwatch()}};function tu(n){let e=t=>new as(t,n);return{wikilink:e,datelink:e}}var nu=1200,wg=120*1e3,Zr=60*1024,ru=3;function Sg(n=()=>Math.random()){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let r=0;r<24;r++)t+=e[Math.floor(n()*e.length)];return t}var ei=class{constructor(e,t){this.deps=t,this.drafts=e.drafts,this.page=e.page??"",this.token=e.first?(t.token??Sg)():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=ge(e.source),this.loadedVersion=this.version,this.dirty=!1,this.inflight=null,this.tries=new Map,this.conflict=null,this.gone=!1,this.orphan=!1,this.holding=!1,this.resolving=!1,this.stopped=!1,this.failures=0,this.unacked=null,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??nu))}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||this.orphan)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.unacked=e,this.offline()}return t.status===409?(this.stale(t.json),!1):(this.unacked=null,t.status===404?this.orphaned():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??wg)}offline(){return this.dirty=!0,this.failures++,this.failures>ru?(this.status("failed"),!1):(this.status("retrying"),this.later("retry",()=>this.autosave(),(this.deps.delay??nu)*2**this.failures),!1)}async first(e){if(V(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&&Cg(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)}}orphaned(){return this.cancel("idle"),this.cancel("retry"),this.dirty=!0,this.gone=!0,this.status("orphan"),this.orphan||this.deps.ui?.notice?.("orphan",{}),this.orphan=!0,!1}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>=ru)return;let{ok:o}=this.deps.editor.apply(t);if(!o){this.tries.set(e,i+1);return}let s=this.deps.editor.current(),l;try{l=await this.deps.post(this.drafts,{base:this.base,version:this.version,body:s,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=s,this.remember())}stale(e){if(this.cancel("idle"),e?.committed){this.recover();return}this.landed(e)||(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"))}landed(e){let t=this.unacked;return this.unacked=null,t===null||e?.body!==ge(t)?!1:(this.version=e.version,this.saved=t,this.own=!0,this.remember(),this.status("saved"),this.deps.editor.current()!==this.saved&&this.later("autosave",()=>this.autosave(),0),!0)}async recover(){let e=this.saved,t=null;try{t=await this.deps.refetch?.()}catch{}let r=t&&!t.draft?t:null;if(r&&ge(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.orphan)return"orphan";if(this.conflict)return"conflict";if(this.cancel("idle"),!await this.flush())return this.orphan?"orphan":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,grammar:String(fr)};e.forEach((c,u)=>{i[`choice-${u}`]=c});let o;try{o=await this.deps.post(`/p/${this.page}/resolve`,i)}catch{return"failed"}if(o.status!==200)return"failed";let{outcome:s,revision:l,body:a}=o.json;return(s==="saved"||s==="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?.(o.json),"saved"):s==="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?.({})}renamed(e,t){e&&e!=="0"&&t&&this.base===e&&(this.base=t)}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"||t==="orphan"){this.deps.ui?.leaving?.(t==="orphan"?"orphan":"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(o=>(this.deps.timers??globalThis).setTimeout(o,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?this.newer(i):this.settled_(i),this.closed=!1;return}}this.closed=!1}}settled_(e){ge(e.source)===this.saved&&(this.base=e.base,this.deps.ui?.committed?.({settled:!0})),this.version="0",this.forget()}newer(e){this.unsaved()||(this.deps.editor.apply(e.source),this.saved=this.deps.editor.current(),this.version=e.draft.version,this.base=e.draft.base,this.own=!1,this.offered=!0,this.forget(),this.deps.ui?.notice?.("newer",{}))}closing({reloading:e=!1}={}){if(this.stopped)return;if(this.token)return this.closingFirst();let t=this.deps.editor.prepare();if(this.orphan)return this.closingOrphan(t);let r=t!==this.saved;if(!this.mayCommit()){r&&this.own&&Qr(t)<=Zr&&this.keep(t);return}if(!this.committable()||e&&!r&&!this.dirty)return;let i={commit:"1",version:this.version,base:this.base};if(r&&Qr(t)<=Zr&&(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();V(e)!==""&&Qr(e)<=Zr&&this.deps.post("/scratch",{first:this.token,version:this.version,body:e},{keepalive:!0}).catch(()=>{}),this.dirty=!1}closingOrphan(e){!this.own||V(e)===""||Qr(e)>Zr||(this.deps.post("/scratch",{body:e},{keepalive:!0}).catch(()=>{}),this.stopped=!0)}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 Cg(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 Qr(n){return new TextEncoder().encode(n).length}var ou=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Mg(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var Og=(n,e,t)=>{let r=Mg(n,t);if(!r)return!1;let i=su(r);if(!i){let s=r.blockRange(),l=s&&qt(s);return l==null?!1:(e&&e(n.tr.lift(s,l).scrollIntoView()),!0)}let o=i.nodeBefore;if(au(n,i,e,-1))return!0;if(r.parent.content.size==0&&(rn(o,"end")||w.isSelectable(o)))for(let s=r.depth;;s--){let l=wr(n.doc,r.before(s),r.after(s),x.empty);if(l&&l.slice.size<l.to-l.from){if(e){let a=n.tr.step(l);a.setSelection(rn(o,"end")?M.findFrom(a.doc.resolve(a.mapping.map(i.pos,-1)),-1):w.create(a.doc,i.pos-o.nodeSize)),e(a.scrollIntoView())}return!0}if(s==1||r.node(s-1).childCount>1)break}return o.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1};function rn(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 Dg=(n,e,t)=>{let{$head:r,empty:i}=n.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;o=su(r)}let s=o&&o.nodeBefore;return!s||!w.isSelectable(s)?!1:(e&&e(n.tr.setSelection(w.create(n.doc,o.pos-s.nodeSize)).scrollIntoView()),!0)};function su(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 Tg(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset<t.parent.content.size)?null:t}var Ag=(n,e,t)=>{let r=Tg(n,t);if(!r)return!1;let i=lu(r);if(!i)return!1;let o=i.nodeAfter;if(au(n,i,e,1))return!0;if(r.parent.content.size==0&&(rn(o,"start")||w.isSelectable(o))){let s=wr(n.doc,r.before(),r.after(),x.empty);if(s&&s.slice.size<s.to-s.from){if(e){let l=n.tr.step(s);l.setSelection(rn(o,"start")?M.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):w.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}return o.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos,i.pos+o.nodeSize).scrollIntoView()),!0):!1},Eg=(n,e,t)=>{let{$head:r,empty:i}=n.selection,o=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset<r.parent.content.size)return!1;o=lu(r)}let s=o&&o.nodeAfter;return!s||!w.isSelectable(s)?!1:(e&&e(n.tr.setSelection(w.create(n.doc,o.pos)).scrollIntoView()),!0)};function lu(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 Ng=(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 us(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 fs=(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),o=t.indexAfter(-1),s=us(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,s.createAndFill());a.setSelection(M.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},vg=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof se||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=us(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,l=n.tr.insert(s,o.createAndFill());l.setSelection(k.create(l.doc,s+1)),e(l.scrollIntoView())}return!0},Ig=(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 o=t.before();if(et(n.doc,o))return e&&e(n.tr.split(o).scrollIntoView()),!0}let r=t.blockRange(),i=r&&qt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Pg(n){return(e,t)=>{if(e.selection instanceof w&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!et(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof k||e.selection instanceof se)&&r.deleteSelection();let{$from:i}=r.selection,o=r.steps.length,s=[],l,a,c=!1,u=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),u=i.start(h)==i.pos-(i.depth-h),a=us(i.node(h-1).contentMatchAt(i.indexAfter(h-1)));let m=n&&n(i.parent,c,i);s.unshift(m||(c&&a?{type:a}:null)),l=h;break}else{if(h==1)return!1;s.unshift(null)}let f=i.pos,d=et(r.doc,f,s.length,s);if(d||(s[0]=a?{type:a}:null,d=et(r.doc,f,s.length,s)),!d)return!1;if(r.split(f,s.length,s),!c&&u&&i.node(l).type!=a){let h=r.mapping.slice(o),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}var Rg=Pg();var Lg=(n,e)=>(e&&e(n.tr.setSelection(new se(n.doc))),!0);function Bg(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||Mn(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function au(n,e,t,r){let i=e.nodeBefore,o=e.nodeAfter,s,l,a=i.type.spec.isolating||o.type.spec.isolating;if(!a&&Bg(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(l=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&l.matchType(s[0]||o.type).validEnd){if(t){let h=e.pos+o.nodeSize,p=b.empty;for(let y=s.length-1;y>=0;y--)p=b.from(s[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new B(e.pos-1,h,e.pos,h,new x(p,1,0),s.length,!0)),g=m.doc.resolve(h+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Mn(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&a?null:M.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&qt(f);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(f,d).scrollIntoView()),!0;if(c&&rn(o,"start",!0)&&rn(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let O=p.length-1;O>=0;O--)y=b.from(p[O].copy(y));let C=n.tr.step(new B(e.pos-p.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new x(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function cu(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,o=i.depth;for(;i.node(o).isInline;){if(!o)return!1;o--}return i.node(o).isTextblock?(t&&t(e.tr.setSelection(k.create(e.doc,n<0?i.start(o):i.end(o)))),!0):!1}}var zg=cu(-1),$g=cu(1);function uu(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o),l=s&&Kt(s,n,e);return l?(r&&r(t.tr.wrap(s,l).scrollIntoView()),!0):!1}}function ti(n,e=null){return function(t,r){let i=!1;for(let o=0;o<t.selection.ranges.length&&!i;o++){let{$from:{pos:s},$to:{pos:l}}=t.selection.ranges[o];t.doc.nodesBetween(s,l,(a,c)=>{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let u=t.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,n)}})}if(!i)return!1;if(r){let o=t.tr;for(let s=0;s<t.selection.ranges.length;s++){let{$from:{pos:l},$to:{pos:a}}=t.selection.ranges[s];o.setBlockType(l,a,n,e)}r(o.scrollIntoView())}return!0}}function Fg(n,e,t,r){for(let i=0;i<e.length;i++){let{$from:o,$to:s}=e[i],l=o.depth==0?n.inlineContent&&n.type.allowsMarkType(t):!1;if(n.nodesBetween(o.pos,s.pos,(a,c)=>{if(l||!r&&a.isAtom&&a.isInline&&c>=o.pos&&c+a.nodeSize<=s.pos)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Vg(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,(o,s)=>{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new Jt(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.pos<i.pos&&e.push(new Jt(r,i))}return e}function we(n,e=null,t){let r=(t&&t.removeWhenPresent)!==!1,i=(t&&t.enterInlineAtoms)!==!1,o=!(t&&t.includeWhitespace);return function(s,l){let{empty:a,$cursor:c,ranges:u}=s.selection;if(a&&!c||!Fg(s.doc,u,n,i))return!1;if(l)if(c)n.isInSet(s.storedMarks||c.marks())?l(s.tr.removeStoredMark(n)):l(s.tr.addStoredMark(n.create(e)));else{let f,d=s.tr;i||(u=Vg(u)),r?f=!u.some(h=>s.doc.rangeHasMark(h.$from.pos,h.$to.pos,n)):f=!u.every(h=>{let p=!1;return d.doc.nodesBetween(h.$from.pos,h.$to.pos,(m,g,y)=>{if(p)return!1;p=!n.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(n)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,h.$from.pos-g),Math.min(m.nodeSize,h.$to.pos-g))))}),!p});for(let h=0;h<u.length;h++){let{$from:p,$to:m}=u[h];if(!f)d.removeMark(p.pos,m.pos,n);else{let g=p.pos,y=m.pos,C=p.nodeAfter,O=m.nodeBefore,$=o&&C&&C.isText?/^\s*/.exec(C.text)[0].length:0,me=o&&O&&O.isText?/\s*$/.exec(O.text)[0].length:0;g+$<y&&(g+=$,y-=me),d.addMark(g,y,n.create(e))}}l(d.scrollIntoView())}return!0}}function He(...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 cs=He(ou,Og,Dg),iu=He(ou,Ag,Eg),Je={Enter:He(Ng,vg,Ig,Rg),"Mod-Enter":fs,Backspace:cs,"Mod-Backspace":cs,"Shift-Backspace":cs,Delete:iu,"Mod-Delete":iu,"Mod-a":Lg},fu={"Ctrl-h":Je.Backspace,"Alt-Backspace":Je["Mod-Backspace"],"Ctrl-d":Je.Delete,"Ctrl-Alt-Backspace":Je["Mod-Delete"],"Alt-Delete":Je["Mod-Delete"],"Alt-d":Je["Mod-Delete"],"Ctrl-a":zg,"Ctrl-e":$g};for(let n in Je)fu[n]=Je[n];var Wg=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,ds=Wg?fu:Je;function ni(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o);if(!s)return!1;let l=r?t.tr:null;return qg(l,s,n,e)?(r&&r(l.scrollIntoView()),!0):!1}}function qg(n,e,t,r=null){let i=!1,o=e,s=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=s.resolve(e.start-2);o=new ft(a,a,e.depth),e.endIndex<e.parent.childCount&&(e=new ft(e.$from,s.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=Kt(o,t,r,e);return l?(n&&Kg(n,e,l,i,t),!0):!1}function Kg(n,e,t,r,i){let o=b.empty;for(let u=t.length-1;u>=0;u--)o=b.from(t[u].type.create(t[u].attrs,o));n.step(new B(e.start-(r?2:0),e.end,e.start,e.end,new x(o,0,0),t.length,!0));let s=0;for(let u=0;u<t.length;u++)t[u].type==i&&(s=u+1);let l=t.length-s,a=e.start+t.length-(r?2:0),c=e.parent;for(let u=e.startIndex,f=e.endIndex,d=!0;u<f;u++,d=!1)!d&&et(n.doc,a,l)&&(n.split(a,l),a+=2*l),a+=c.child(u).nodeSize;return n}function du(n,e){return function(t,r){let{$from:i,$to:o,node:s}=t.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))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 f=b.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=b.from(i.node(y).copy(f));let h=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;f=f.append(b.from(n.createAndFill()));let p=i.before(i.depth-(d-1)),m=t.tr.replace(p,i.after(-h),new x(f,4-d,0)),g=-1;m.doc.nodesBetween(p,m.doc.content.size,(y,C)=>{if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=C+1)}),g>-1&&m.setSelection(M.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let a=o.pos==i.end()?l.contentMatchAt(0).defaultType:null,c=t.tr.delete(i.pos,o.pos),u=a?[e?{type:n,attrs:e}:null,{type:a}]:void 0;return et(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function hs(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==n);return o?t?r.node(o.depth-1).type==n?jg(e,t,n,o):Jg(e,t,o):!0:!1}}function jg(n,e,t,r){let i=n.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(i.step(new B(o-1,s,o,s,new x(b.from(t.create(null,r.parent.copy())),1,0),1,!0)),r=new ft(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth));let l=qt(r);if(l==null)return!1;i.lift(r,l);let a=i.doc.resolve(i.mapping.map(o,-1)-1);return Mn(i.doc,a.pos)&&a.nodeBefore.type==a.nodeAfter.type&&i.join(a.pos),e(i.scrollIntoView()),!0}function Jg(n,e,t){let r=n.tr,i=t.parent;for(let h=t.end,p=t.endIndex-1,m=t.startIndex;p>m;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let o=r.doc.resolve(t.start),s=o.nodeAfter;if(r.mapping.map(t.end)!=t.start+o.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(l?0:1),u+1,s.content.append(a?b.empty:b.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new B(f-(l?1:0),d+(a?1:0),f+1,d-1,new x((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function ps(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let l=o.parent,a=l.child(s-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=b.from(c?n.create():null),f=new x(b.from(n.create(null,b.from(l.type.create(null,u)))),c?3:1,0),d=o.start,h=o.end;t(e.tr.step(new B(d-(c?3:1),h,d,h,f,1,!0)).scrollIntoView())}return!0}}var G=class{constructor(e,t,r={}){this.match=e,this.match=e,this.handler=typeof t=="string"?Hg(t):t,this.undoable=r.undoable!==!1,this.inCode=r.inCode||!1,this.inCodeMark=r.inCodeMark!==!1}};function Hg(n){return function(e,t,r,i){let o=n;if(t[1]){let s=t[0].lastIndexOf(t[1]);o+=t[0].slice(s+t[1].length),r+=s;let l=r-i;l>0&&(o=t[0].slice(s-l,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var Ug=500;function pu({rules:n}){let e=new S({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,o){return hu(t,r,i,o,n,e)},handleDOMEvents:{compositionend:t=>{setTimeout(()=>{let{$cursor:r}=t.state.selection;r&&hu(t,r.pos,r.pos,"",n,e)})}}},isInputRules:!0});return e}function hu(n,e,t,r,i,o){if(n.composing)return!1;let s=n.state,l=s.doc.resolve(e),a=l.parent.textBetween(Math.max(0,l.parentOffset-Ug),l.parentOffset,null,"\uFFFC")+r;for(let c=0;c<i.length;c++){let u=i[c];if(!u.inCodeMark&&l.marks().some(p=>p.type.spec.code))continue;if(l.parent.type.spec.code){if(!u.inCode)continue}else if(u.inCode==="only")continue;let f=u.match.exec(a);if(!f||f[0].length<r.length)continue;let d=e-(f[0].length-r.length);if(!u.inCodeMark){let p=!1;if(s.doc.nodesBetween(d,l.pos,m=>{m.isInline&&m.marks.some(g=>g.type.spec.code)&&(p=!0)}),p)continue}let h=u.handler(s,f,d,t);if(h)return u.undoable&&h.setMeta(o,{transform:h,from:e,to:t,text:r}),n.dispatch(h),!0}return!1}var mu=(n,e)=>{let t=n.plugins;for(let r=0;r<t.length;r++){let i=t[r],o;if(i.spec.isInputRules&&(o=i.getState(n))){if(e){let s=n.tr,l=o.transform;for(let a=l.steps.length-1;a>=0;a--)s.step(l.steps[a].invert(l.docs[a]));if(o.text){let a=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,n.schema.text(o.text,a))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},Bx=new G(/--$/,"\u2014",{inCodeMark:!1}),zx=new G(/\.\.\.$/,"\u2026",{inCodeMark:!1}),$x=new G(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),Fx=new G(/"$/,"\u201D",{inCodeMark:!1}),Vx=new G(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),Wx=new G(/'$/,"\u2019",{inCodeMark:!1});function gu(n,e,t=null){return new G(n,(r,i,o,s)=>{let l=r.doc.resolve(o),a=t instanceof Function?t(i):t;return l.node(-1).canReplaceWith(l.index(-1),l.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,a):null})}var he={blocks:"A page link holds words from one paragraph, heading or item. Select words in just one.",atoms:"A page link can\u2019t hold another link or a line break. Select plain words.",syntax:"A page link can\u2019t show [ or ]]. Select words without them.",blank:"Select some words to link them to a page.",context:"Linked here, the Markdown around these words would read differently: a ! before them makes an embed, and a stray ` or * pairs up. Select other words.",moved:"The selection changed. Select the words again.",date:"A date can\u2019t go here: the Markdown around it would read differently, such as a stray ` or * pairing up. Move the caret and try again."};function ri(n,e=""){let t=`[[${n}${e?"|"+e:""}]]`,r=ze(t),i=r[0];return r.length===1&&i.kind===gt&&i.source===t&&i.target===n&&i.text===e&&!i.anchor?t:null}function ii(n){let{selection:e}=n;if(e.empty)return null;let{$from:t,$to:r,from:i,to:o}=e;if(t.parent.type.spec.code||r.parent.type.spec.code)return null;if(e instanceof w)return{refuse:he.atoms};if(!(e instanceof k)||t.parent!==r.parent)return{refuse:he.blocks};let s=!0;if(n.doc.nodesBetween(i,o,f=>{f.isInline&&!f.isText&&(s=!1)}),!s||n.doc.rangeHasMark(i,o,n.schema.marks.link))return{refuse:he.atoms};let l=n.doc.textBetween(i,o),a=V(l);if(a==="")return{refuse:he.blank};if(ri("Page",a)===null)return{refuse:he.syntax};let c=l.indexOf(a),u={words:a,from:i+c,to:i+c+a.length};return bu(n,u,"Page").refuse?{refuse:he.context}:u}function _g(n,e,t){let r=t===e?"":t;return W(e)?n.nodes.datelink.create({date:e,shown:r}):n.nodes.wikilink.create({target:e,shown:r})}function yu(n){let e="",t=0,r=0;for(let i of n)i.isText?e+=i.text:i.type.name==="embed"?r++:i.type.name!=="hard_break"&&t++;return{text:e,links:t,embeds:r}}function bu(n,e,t){let r=n.tr.replaceWith(e.from,e.to,_g(n.schema,t,e.words));return ms(r.doc.resolve(e.from).parent)?{tr:r}:{refuse:he.context}}function ms(n){let e=[];n.forEach(i=>e.push(i));let t=yu(e),r=yu(Zt(n.type.schema,en(n)));return t.text===r.text&&t.links===r.links&&t.embeds===r.embeds}function xu(n,e,t){let r=ii(n);if(!r)return{refuse:he.moved};if(r.refuse)return r;if(r.words!==t)return{refuse:he.moved};if(ri(e,t===e?"":t)===null)return{refuse:he.syntax};let o=bu(n,r,e);if(o.refuse)return o;let s=o.tr.mapping.map(r.to);return{tr:o.tr.setSelection(k.create(o.tr.doc,s)).scrollIntoView()}}function oi(n){return(e,t,r)=>{let i=ii(e);if(i)return t&&r&&n(r,i),!0;let{$from:o,empty:s}=e.selection;return!s||o.parent.type.spec.code||!o.parent.inlineContent||t&&t(e.tr.insertText("[[").scrollIntoView()),!0}}function Rt(n=new Date,e=Yg()){if(e)try{let r={};for(let{type:i,value:o}of new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n))r[i]=o;return`${r.year.padStart(4,"0")}-${r.month}-${r.day}`}catch{}let t=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${t(n.getMonth()+1)}-${t(n.getDate())}`}function Yg(){return globalThis.document?.body?.getAttribute("data-zone")??""}function gs(n,e){return ti(n.nodes.heading,{level:e,source:null})}function Gg(n){return(e,t)=>{let r=null;if(!ni(n.nodes.bullet_list)(e,o=>{r=o}))return!1;if(t){let{from:o,to:s}=r.selection;r.doc.nodesBetween(o,s,(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 Xg(n){return(e,t)=>{let{$from:r}=e.selection;if(r.depth<1)return!1;if(t){let i=r.after(1),o=e.tr.insert(i,n.nodes.horizontal_rule.create());t(o.scrollIntoView())}return!0}}function Zg(n){return He(ti(n.nodes.code_block,{fence:"```",info:"",closed:!0,close:"```"}),fs)}function si(n){return(e,t)=>(t&&t(e.tr.insertText(n).scrollIntoView()),!0)}function Wn(n,e){let t=n.selection.to,r=n.doc.resolve(t);if(!r.parent.inlineContent||r.parent.type.spec.code)return null;let i=n.schema.nodes.datelink.create({date:e});for(let o of[!1,!0]){let s=n.tr,l=o?t+1:t;if(o&&s.insert(t,n.schema.text(" ")),s.insert(l,i),ms(s.doc.resolve(l).parent))return{tr:s.setSelection(k.create(s.doc,l+1)).scrollIntoView(),spaced:o}}return{refuse:he.date}}function Qg(n){return(e,t)=>{let r=Wn(e,n);return r?.tr?(t&&t(r.tr),!0):!1}}function ey(){return(n,e)=>Qg(Rt())(n,e)}function on(n){return{"insert-h1":gs(n,1),"insert-h2":gs(n,2),"insert-h3":gs(n,3),"insert-list":ni(n.nodes.bullet_list),"insert-numbered":ni(n.nodes.ordered_list),"insert-check":Gg(n),"insert-quote":uu(n.nodes.blockquote),"insert-code":Zg(n),"insert-rule":Xg(n),"insert-link":si("[["),"insert-date":ey(),"insert-paragraph":ti(n.nodes.paragraph),..._c()}}function ku(n){return{strong:we(n.marks.strong),em:we(n.marks.em),code:we(n.marks.code)}}function wu(n,e){return e&&e(n.tr.setSelection(k.create(n.doc,0,n.doc.content.size))),!0}function Su(n){return(e,t,r)=>{try{return n(e,t,r)}catch{return!1}}}var li=Su(Go),qn=Su(Xo);var ty=0;function Kn(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}var lt=class{constructor(e,{label:t,count:r,input:i=null}){this.view=e,this.count=r,this.input=i,this.id=`mapa-list-${++ty}`,this.list=Kn("ul",{id:this.id,role:"listbox","aria-label":t,"mapa-combo":""}),this.list.hidden=!0,this.live=Kn("div",{"mapa-sr":"",role:"status","aria-live":"polite"}),document.body.append(this.list,this.live),this.items=[],this.active=0,this.list.addEventListener("mousedown",o=>o.preventDefault())}get open(){return!this.list.hidden}show(e,t){this.items=e,this.active=0,this.list.replaceChildren(...e.map((i,o)=>{let s=Kn("li",{id:`${this.id}-${o}`,role:"option","aria-selected":"false"});return s.append(Kn("span",{},i.label)),i.detail&&s.append(Kn("small",{},i.detail)),s.addEventListener("click",()=>this.choose(o)),s})),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.input?this.input.getBoundingClientRect():this.view.coordsAtPos(e),r=window.visualViewport,i=r?r.offsetTop+r.height:window.innerHeight,o=this.list.offsetHeight,s=t.bottom+4,l=s+o>i?Math.max(t.top-o-4,4):s,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.input??this.view.dom;this.input&&t.setAttribute("aria-expanded",this.open?"true":"false"),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(),this.input||this.view.focus(),t&&t.run(this.view)}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 ny=new N("mapa-suggest"),ry=/\[\[([^[\]\n|#]{0,80})$/u;function ys(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=ry.exec(r);return i?{text:i[1],from:e.pos-i[0].length,to:e.pos}:null}function iy(n,e){return W(e.target)?n.nodes.datelink.create({date:e.target}):n.nodes.wikilink.create(e)}function oy(n,e){return t=>{let r=ys(t.state);if(!r)return;let i=iy(t.state.schema,{target:e});t.dispatch(t.state.tr.replaceWith(r.from,r.to,i).scrollIntoView())}}var Cu=n=>n.normalize("NFKD").replace(/\p{Mn}/gu,"").toLowerCase().trim().replace(/\s+/gu," ");function bs(n,e,t,r=i=>oy(n,i)){let i=n.text.trim(),o=[];W(i)&&o.push({label:Xt(i),detail:"Your note",run:r(i)});for(let{text:s,pending:l}of e){let a=t[nn(s,"")],c="Team page";l?c="Not written yet":a?.alias&&(c=`Old title of ${a.title}`),o.push({label:s,detail:c,run:r(s)})}return i!==""&&!W(i)&&!e.some(s=>Cu(s.text)===Cu(i))&&o.push({label:`Link \u201C${i}\u201D`,detail:"a page not written yet",run:r(i)}),o}function Mu(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 o=i.attrs,l=`[[${o.target??o.date}${o.anchor?`#^${o.anchor}`:""}${o.shown?`|${o.shown}`:""}`;e(n.tr.replaceWith(t.pos-i.nodeSize,t.pos,n.schema.text(l)))}return!0}function Ou({ask:n,resolutions:e}){let t=null,r=0,i=s=>s.length===1?"1 page":`${s.length} pages`;async function o(s,l){let a=++r,c=[];try{c=await n(l.text)}catch{}let u=await e.lookup(c.map(d=>d.text));if(a!==r)return;let f=ys(s.state);!f||f.from!==l.from||t.show(bs(f,c,u),f.from)}return new S({key:ny,view(s){t=new lt(s,{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 u=ys(a.state);if(clearTimeout(l),!u){r++,t.close();return}l=setTimeout(()=>o(a,u),30)},destroy(){t.destroy()}}},props:{handleKeyDown(s,l){return t?.keys(l)??!1},handleDOMEvents:{blur(){return t?.close(),!1}}}})}function Du(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 sy(n){return(e,t,r)=>{let i=Du(e);if(!i)return!1;let o={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 du(n.nodes.list_item,o)(e,t,r)}}function ly(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 o=i.parent.content.cut(i.parentOffset),s=r.after(-1),l=e.tr.delete(r.pos,r.end()),a=l.mapping.map(s);l.insert(a,n.nodes.paragraph.create(null,o)),t(l.setSelection(k.create(l.doc,a+1)).scrollIntoView())}return!0}}function ay(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 Tu(n,{save:e,linkPage:t=null}){let r=ku(n),i=!1,o=c=>(u,f,d)=>d?.composing?!1:c(u,f,d),s=Po({Backspace:He(mu,Mu,Pt,Uc,ts(!0)),Delete:He(Pt,ts(!1)),"Mod-Alt-ArrowRight":Qo(1),"Mod-Alt-ArrowLeft":Qo(-1),"Mod-z":li,"Shift-Mod-z":qn,"Mod-y":qn,"Mod-b":r.strong,"Mod-i":r.em,"Mod-e":r.code,"Mod-s":()=>(e(),!0),"Mod-l":t??(()=>!1),Enter:o(He(sy(n),ly(n))),"Shift-Enter":o(ay(n)),"Mod-[":hs(n.nodes.list_item),"Mod-]":ps(n.nodes.list_item)}),l=Po({...ds,Enter:o(ds.Enter)});return[new S({props:{handleKeyDown(c,u){if(u.key==="Escape")return i=!0,!1;if(u.key!=="Shift"&&u.key!=="Tab"&&(i=!1),u.key==="Tab"&&!i&&Du(c.state)){let f=(u.shiftKey?hs(n.nodes.list_item):ps(n.nodes.list_item))(c.state,c.dispatch);return u.preventDefault(),f||!0}return u.key==="Tab"&&(i=!1),!1}}}),s,l]}function xs(n){for(let e=n.depth;e>0;e--)if(n.node(e).type.name==="list_item")return e;return 0}function cy(n){let e=n.handler;return n.handler=(t,r,i,o)=>xs(t.doc.resolve(i))?null:e(t,r,i,o),n}function Au(n,e,t){return new G(n,(r,i,o,s)=>{let l=r.doc.resolve(o);if(xs(l)||l.parent.type.name!=="paragraph")return null;let a=r.tr.delete(o,s),c=a.doc.resolve(o).blockRange(),u=c&&Kt(c,e);if(!u)return null;a.wrap(c,u);let f=c.start+1;return a.setNodeMarkup(f,null,{...a.doc.nodeAt(f).attrs,...t(i)}),a})}function uy(n){return Au(/^\s{0,3}([-*+])\s$/u,n.nodes.bullet_list,e=>({bullet:e[1]}))}function fy(n){return Au(/^\s{0,3}(\d{1,9})([.)])\s$/u,n.nodes.ordered_list,e=>({number:e[1],delim:e[2]}))}function dy(n){return cy(gu(/^(#{1,6})\s$/u,n.nodes.heading,e=>({level:e[1].length,source:null})))}function hy(n){return new G(/^\[([ xX])\]\s$/u,(e,t,r,i)=>{let o=e.doc.resolve(r),s=xs(o);if(!s||o.parentOffset!==0)return null;let l=o.node(s);return e.tr.delete(r,i).setNodeMarkup(o.before(s),null,{...l.attrs,task:!0,checked:t[1]})})}function py(n){return new G(/^\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 o=i.before(1),s=i.after(1),l=e.tr.replaceWith(o,s,[n.nodes.horizontal_rule.create(),n.nodes.paragraph.create()]);return l.setSelection(k.create(l.doc,o+2))})}function my(n){return new G(/^\s{0,3}>$/u,(e,t,r,i)=>{let o=e.doc.resolve(r);if(o.parent.type.name!=="paragraph"||o.depth!==1)return null;let s=e.tr.delete(r,i),l=s.doc.resolve(r).blockRange();return l?s.wrap(l,[{type:n.nodes.blockquote,attrs:{prefix:null}}]):null})}function gy(n){return new G(/^(\s{0,3}(?:```|~~~))$/u,(e,t,r,i)=>{let o=e.doc.resolve(r);if(o.parent.type.name!=="paragraph"||o.depth!==1)return null;let s=t[1];return e.tr.delete(r,i).setBlockType(r,r,n.nodes.code_block,{fence:s,info:"",closed:!0,close:s.trimStart()})})}function yy(){return new G(/^\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 by(){return new S({appendTransaction(n,e,t){if(!n.some(o=>o.getMeta(st)?.settled)||!t.selection.empty)return null;let r=e.selection.$head.marks(),i=t.selection.$head.marks();return r.length===i.length&&r.every(o=>o.isInSet(i))?null:t.tr.setStoredMarks(r)}})}function Eu(n){return[pu({rules:[dy(n),uy(n),fy(n),hy(n),py(n),my(n),gy(n),yy()]}),by()]}var Nu="mapa-editor-notice";function Lt(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);for(let i of t)r.append(i);return r}var xy={draft:"Saved as a draft",orphan:"Not saved"};function ws(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}`)??xy[n]??"")}function ks(n,e,t={},r=!1){let i=Lt("form",{method:"post",action:n});for(let[o,s]of Object.entries(t))i.append(Lt("input",{type:"hidden",name:o,value:s}));return i.append(Lt("button",{"rst-btn":r?"primary":"",type:"submit"},e)),i}function jn(n,e,t=!1){let r=Lt("button",{"rst-btn":t?"primary":"",type:"button"},n);return r.addEventListener("click",e),r}function le(n,e,...t){ky(n);let r=Lt("div",{"mapa-unsaved":"",[Nu]:"",role:"status"},Lt("p",{},e),...t);return n.before(r),r}function ky(n){n.parentNode?.querySelectorAll(`[${Nu}]`).forEach(e=>e.remove())}function vu(n,e,t){switch(e){case"gone":return le(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.",ks(`/p/${t.page}/draft/scratch`,"Save as a scratch page",{},!0),ks(`/p/${t.page}/draft/discard`,"Discard",{version:t.version}));case"orphan":return le(n,Iu,Pu());case"noBase":return le(n,"Your edit started from a version older than the 90-day history, so it cannot be merged block by block.",Lt("a",{"rst-btn":"primary",href:`/p/${t.page}/conflict`},"Choose what to keep"));case"committed":return le(n,"This was saved in another tab. What you type here is kept as a new draft.",jn("Reload",()=>location.reload(),!0));case"newer":return le(n,"Another tab had newer text, so this tab now shows it.")}}var Iu="This page was deleted before what you typed could be saved. Save it as a scratch page to keep it.";function Pu(){return ks("/scratch","Save as a scratch page",{body:""},!0)}function Ss(n,e,t){return e==="orphan"?le(n,Iu+" If you leave now, it is lost.",Pu(),jn("Leave anyway",t)):e==="uploading"?le(n,"An image is still uploading. If you leave now, it is not added.",jn("Leave anyway",t)):e==="conflict"?le(n,"Someone saved this page while you were writing. Choose below what to keep, or leave and decide on your next visit.",jn("Leave and decide later",t)):le(n,"Not saved: what you typed since the last save would be lost if you leave now.",jn("Leave anyway",t))}var Ue=new N("mapa-conflict");function Sy(n,e,t){let{emitted:r}=P(n,e);return t.map((i,o)=>{let s=r.slice(i.at,i.at+i.count);if(s.length===0){let a=r[i.at],c=a?a.pos:n.content.size;return{from:c,to:c,index:o,hunk:i}}let l=s[s.length-1];return{from:s[0].pos,to:l.pos+l.node.nodeSize,index:o,hunk:i}})}function Cy(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 Ru(n,e){return n.map(t=>({...t,from:e.map(t.from,1),to:e.map(t.to,-1)}))}function sn(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...t),r}var My=[["mine","Keep yours"],["theirs","Keep theirs"],["both","Keep both, yours first"]];function Oy(n,e,t,r){let i=sn("div",{"mapa-hunk-theirs":""}),o=$n(n,e.hunk.theirs,{trailing:!1});i.append(re.fromSchema(n).serializeFragment(o.content));let s=`mapa-hunk-${e.index}`,l=sn("div",{"mapa-hunk-choice":"",role:"group","aria-labelledby":s,contenteditable:"false"},sn("p",{id:s},sn("strong",{},"Both of you changed this."),e.hunk.theirs===""?" They removed it.":" Theirs:"));e.hunk.theirs!==""&&l.append(i);let a=sn("div",{"mapa-hunk-buttons":""});for(let[c,u]of My){let f=sn("button",{type:"button","rst-btn":t===c?"primary":"","aria-pressed":t===c?"true":"false","data-choice":c},u);f.addEventListener("click",d=>{d.preventDefault(),r(e.index,c)}),a.append(f)}return l.append(a),l}function Lu({fidelity:n,isRemote:e,isBusy:t=()=>!1,resolve:r}){return new S({key:Ue,state:{init:()=>({ranges:[],conflict:null,picked:[]}),apply(i,o,s,l){let a=i.getMeta(Ue);return a?.clear?{ranges:[],conflict:null,picked:[]}:a?.conflict?{ranges:Sy(l.doc,n,a.conflict.hunks),conflict:a.conflict,picked:[]}:a?.picked?{...o,picked:a.picked}:!i.docChanged||o.ranges.length===0?o:{...o,ranges:Ru(o.ranges,i.mapping)}}},filterTransaction(i,o){if(!i.docChanged||e()||i.getMeta(Ue))return!0;if(t())return!1;let s=Ue.getState(o).ranges;if(s.length===0)return!0;for(let l of i.steps){let a=!1;if(l.getMap().forEach((c,u)=>{a=a||Cy(s,c,u)}),a)return!1;s=Ru(s,{map:(c,u)=>l.getMap().map(c,u)})}return!0},view(i){return{update(){let o=Ue.getState(i.state).ranges.length>0;i.dom.toggleAttribute("data-mapa-conflict",o)}}},props:{handleDOMEvents:{beforeinput:(i,o)=>t()?(o.preventDefault(),!0):!1},decorations(i){let o=Ue.getState(i);if(o.ranges.length===0)return null;let s=[],l=(a,c,u)=>{let f=[...Ue.getState(a.state).picked];f[c]=u,a.dispatch(a.state.tr.setMeta(Ue,{picked:f})),o.ranges.every(d=>f[d.index])&&r(f)};for(let a of o.ranges)a.to>a.from&&i.doc.nodesBetween(a.from,a.to,(c,u)=>{u>=a.from&&c.isTextblock&&s.push(E.node(u,u+c.nodeSize,{"mapa-hunk":"",contenteditable:"false"}))}),s.push(E.widget(a.from,c=>Oy(i.schema,a,o.picked[a.index],(u,f)=>l(c,u,f)),{side:-1,stopEvent:()=>!0,ignoreSelection:!0,key:`hunk-${a.index}-${o.picked[a.index]??""}`}));return A.create(i.doc,s)}}})}function Bu(n,e){n.dispatch(n.state.tr.setMeta(Ue,e?{conflict:e}:{clear:!0}))}var ui={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6,sun:0,mon:1,tue:2,tues:2,wed:3,thu:4,thur:4,thurs:4,fri:5,sat:6},Cs={jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,sept:9,oct:10,nov:11,dec:12,january:1,february:2,march:3,april:4,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Dy=/[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/u,Ty=n=>n.replace(/\u0130/gu,"i").toLowerCase(),ai=(n,e)=>Object.hasOwn(n,e);function fi(n,e,t){let r=new Date(0);return r.setUTCFullYear(n,e-1,t),r}function ve(n){let e=n.getUTCFullYear();if(e<0||e>9999)return"";let t=(r,i=2)=>String(r).padStart(i,"0");return`${t(e,4)}-${t(n.getUTCMonth()+1)}-${t(n.getUTCDate())}`}function Ay(n){if(!W(n))return null;let[e,t,r]=n.split("-").map(Number);return fi(e,t,r)}function ci(n,e){return fi(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate()+e)}function zu(n,e,t="dmy",r=""){let i=Ay(e);if(!i)return"";let o=Ty(n).split(Dy).filter(s=>s!=="");return o.length===1?Ey(o[0],i,t,r):o.length===2?Iy(o[0],o[1],i):""}function Ey(n,e,t,r){switch(n){case"today":return ve(e);case"yesterday":return ve(ci(e,-1));case"tomorrow":return ve(ci(e,1))}if(ai(ui,n)){let i=(e.getUTCDay()-ui[n]+7)%7;return ve(ci(e,-i))}return W(n)?n:Ny(n,e,t,r)}function Ny(n,e,t,r){let i=n.includes("/")?"/":".",o=n.split(i);if(i==="."&&o.length===3&&o[2]===""&&(o=o.slice(0,2)),o.length<2||o.length>3||!o.every(u=>/^[0-9]+$/u.test(u)))return"";let s=o.length===3&&o[0].length===4;if(r!==""&&i!==r&&!s)return"";let[l,a,c]=[String(e.getUTCFullYear()),o[0],o[1]];if(s)[l,a,c]=o;else if(o.length===3&&t==="dmy")[c,a,l]=o;else if(o.length===3&&t==="mdy")l=o[2];else{if(o.length===3)return"";t==="dmy"&&([c,a]=o)}return vy(l,a,c)}function vy(n,e,t){if(n.length!==4||e.length>2||t.length>2)return"";let[r,i,o]=[n,e,t].map(Number),s=fi(r,i,o);return i<1||i>12||s.getUTCDate()!==o||s.getUTCMonth()+1!==i?"":ve(s)}function Iy(n,e,t){if(ai(ui,e)&&n==="next"){let s=(ui[e]-t.getUTCDay()+7)%7||7;return ve(ci(t,s))}if(ai(Cs,n)&&([n,e]=[e,n]),!ai(Cs,e)||!/^[+-]?[0-9]+$/u.test(n))return"";let r=Cs[e],i=Number(n);if(i<1||i>31)return"";let o=fi(t.getUTCFullYear(),r,i);return o.getUTCMonth()+1===r?ve(o):""}var _e={dialog:"Insert a date",field:"Date",placeholder:"Type a date, like next friday",help:"Arrow keys move a day or a week, Page Up and Page Down a month. Enter inserts the day, Escape closes.",previous:"Previous month",next:"Next month",today:"today",unknown:n=>`\u201C${n}\u201D isn\u2019t a date here. Try \u201Cnext friday\u201D or \u201C12 nov\u201D.`};function Fu(n){let[e,t,r]=n.split("-").map(Number),i=new Date(0);return i.setUTCFullYear(e,t-1,r),i}function Jn(n,e){let t=Fu(n);return t.setUTCDate(t.getUTCDate()+e),ve(t)||null}function di(n,e){let[t,r,i]=n.split("-").map(Number),o=new Date(0);o.setUTCFullYear(t,r-1+e,1);let s=new Date(0);return s.setUTCFullYear(o.getUTCFullYear(),o.getUTCMonth()+1,0),o.setUTCDate(Math.min(i,s.getUTCDate())),ve(o)||null}function Py(n,e=Bo()){let t=`${n.slice(0,8)}01`,r=(Fu(t).getUTCDay()-e+7)%7;return Array.from({length:42},(i,o)=>Jn(t,o-r))}function Ry(n){return kc(n)}function Ly(n,e,t=!1){switch(n){case"ArrowLeft":return Jn(e,-1);case"ArrowRight":return Jn(e,1);case"ArrowUp":return Jn(e,-7);case"ArrowDown":return Jn(e,7);case"PageUp":return di(e,t?-12:-1);case"PageDown":return di(e,t?12:1)}return null}var By=0;function z(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function $u(n){let e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true");let t=document.createElementNS("http://www.w3.org/2000/svg","polyline");return t.setAttribute("points",n),e.append(t),e}var Ms=class{constructor(e,t){this.view=e,this.today=t,this.chosen=t,this.id=`mapa-datepick-${++By}`,this.build()}build(){let e=this.id;this.root=z("div",{"mapa-datepick":"",role:"dialog","aria-label":_e.dialog,tabindex:"-1"}),this.field=z("input",{"mapa-datepick-field":"",type:"text",role:"combobox","aria-label":_e.field,"aria-expanded":"true","aria-haspopup":"grid","aria-controls":`${e}-grid`,"aria-describedby":`${e}-help`,placeholder:_e.placeholder,autocomplete:"off",autocapitalize:"off",spellcheck:"false",enterkeyhint:"done"}),this.title=z("strong",{id:`${e}-title`});let t=z("div",{"mapa-datepick-head":""});this.back=z("button",{type:"button","aria-label":_e.previous}),this.back.append($u("15 18 9 12 15 6")),this.ahead=z("button",{type:"button","aria-label":_e.next}),this.ahead.append($u("9 18 15 12 9 6")),t.append(this.title,this.back,this.ahead),this.grid=z("table",{role:"grid",id:`${e}-grid`,"aria-labelledby":`${e}-title`});let r=z("tr");for(let{name:o,letter:s}of wc())r.append(z("th",{scope:"col",abbr:o},s));this.days=z("tbody"),this.grid.append(z("thead"),this.days),this.grid.tHead.append(r),this.said=z("p",{"mapa-datepick-said":"","aria-hidden":"true"}),this.live=z("p",{"mapa-sr":"",role:"status"});let i=z("p",{"mapa-sr":"",id:`${e}-help`},_e.help);this.root.append(this.field,t,this.grid,this.said,i,this.live),this.wire()}wire(){this.root.addEventListener("mousedown",e=>{e.target!==this.field&&e.preventDefault()}),this.back.addEventListener("click",()=>this.show(di(this.chosen,-1))),this.ahead.addEventListener("click",()=>this.show(di(this.chosen,1))),this.days.addEventListener("click",e=>{let t=e.target.closest("td[data-date]");t&&this.insert(t.dataset.date)}),this.root.addEventListener("keydown",e=>this.keys(e)),this.field.addEventListener("input",()=>this.typed()),this.root.addEventListener("focusout",e=>{this.root.contains(e.relatedTarget)||this.close()}),this.place=this.place.bind(this),window.visualViewport?.addEventListener("resize",this.place),window.visualViewport?.addEventListener("scroll",this.place)}keys(e){if(e.isComposing)return;if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key==="Enter"&&e.target.closest("button")===null){if(e.preventDefault(),!this.understood)return;this.insert(this.chosen);return}if(e.altKey||e.metaKey||e.ctrlKey||(e.key==="ArrowLeft"||e.key==="ArrowRight")&&e.target===this.field&&this.field.value!=="")return;let r=Ly(e.key,this.chosen,e.shiftKey);r!=null&&(e.preventDefault(),this.show(r))}typed(){this.today=Rt();let e=V(this.field.value),t=e===""?this.chosen:zu(this.field.value,this.today,Sc());this.understood=!!t,t?(this.show(t),this.live.textContent=e===""?"":this.label(t)):(this.said.textContent=_e.unknown(e),this.live.textContent=_e.unknown(e))}label(e){let t=Number(this.today.slice(0,4));return Xt(e,t)+(e===this.today?`, ${_e.today}`:"")}show(e){if(!e)return;this.today=Rt(),this.chosen=e,this.understood=!0,this.title.textContent=Ry(e);let t=e.slice(0,7),r=Py(e).map(o=>{if(!o)return z("td",{role:"gridcell"});let s=z("td",{role:"gridcell",id:`${this.id}-${o}`,"data-date":o,"aria-label":this.label(o),"aria-selected":o===e?"true":"false"},String(Number(o.slice(8))));return o===this.today&&s.setAttribute("aria-current","date"),o.slice(0,7)!==t&&s.setAttribute("mapa-outside",""),s}),i=[];for(let o=0;o<6;o++){let s=z("tr");s.append(...r.slice(o*7,o*7+7)),i.push(s)}this.days.replaceChildren(...i),this.field.setAttribute("aria-activedescendant",`${this.id}-${e}`),this.said.textContent=this.label(e)}place(){if(!this.root.isConnected)return;let e=this.view.coordsAtPos(this.view.state.selection.to),t=window.visualViewport,r=t?t.offsetTop:0,i=t?r+t.height:window.innerHeight,o=t?t.offsetLeft+t.width:window.innerWidth,{offsetHeight:s,offsetWidth:l}=this.root,a=e.bottom+6,c=a+s<=i?a:Math.max(r+4,e.top-s-6),u=Math.max(4,Math.min(e.left-12,o-l-4));this.root.style.setProperty("top",`${c}px`),this.root.style.setProperty("left",`${u}px`)}open(){this.show(this.chosen),document.body.append(this.root),this.place(),(window.matchMedia?.("(pointer: coarse)").matches?this.root:this.field).focus({preventScroll:!0})}close(){this.closed||!this.root.isConnected||(this.closed=!0,window.visualViewport?.removeEventListener("resize",this.place),window.visualViewport?.removeEventListener("scroll",this.place),this.root.remove(),Hn===this&&(Hn=null))}cancel(){this.close(),this.view.focus()}insert(e){this.close(),this.view.focus(),Vu(this.view,e)}},Hn=null;function Vu(n,e){let t=Wn(n.state,e);t?.tr?n.dispatch(t.tr):t?.refuse&&Wu(n,t.refuse)}function Wu(n,e){document.querySelector("[mapa-datepick-note]")?.remove();let t=z("p",{"mapa-datepick-note":"",role:"status"},e);document.body.append(t);let r=n.coordsAtPos(n.state.selection.to),i=Math.max(4,Math.min(r.left-12,window.innerWidth-t.offsetWidth-4));t.style.setProperty("top",`${r.bottom+6}px`),t.style.setProperty("left",`${i}px`);let o=()=>{t.remove(),document.removeEventListener("keydown",o,!0),document.removeEventListener("pointerdown",o,!0)};setTimeout(()=>{document.addEventListener("keydown",o,!0),document.addEventListener("pointerdown",o,!0)},0),setTimeout(o,8e3)}function hi(n,e,t){let r=Rt(),i=Wn(n,r);if(!i)return!1;if(e&&t){if(Hn?.close(),i.refuse)return Wu(t,i.refuse),!0;Hn=new Ms(t,r),Hn.open()}return!0}function pi(n,e,t){return Wn(n,Rt())?(e&&t&&Vu(t,Rt()),!0):!1}var zy=/(?:^|\s)\/([A-Za-z0-9 ]{0,24})$/u,$y=[["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"],["Columns","two side by side","insert-columns-2"],["Link to a page","[[","insert-link"],["Date","choose a day","insert-date-pick"],["Today\u2019s date","today\u2019s note","insert-date"],["Image","upload an image","insert-image"]];function qu(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=zy.exec(r);return i?{text:i[1].toLowerCase().trim(),from:e.pos-i[1].length-1,to:e.pos}:null}function Ku(n={}){let e=null;return new S({view(t){let r={...on(t.state.schema),"insert-date-pick":hi,"insert-date":pi,...n};return e=new lt(t,{label:"Blocks",count:i=>i.length===1?"1 block":`${i.length} blocks`}),{update(i,o){if(i.state.doc.eq(o.doc)&&i.state.selection.eq(o.selection))return;let s=qu(i.state);if(!s){e.close();return}let l=$y.filter(([a,,c])=>r[c]&&a.toLowerCase().includes(s.text)).map(([a,c,u])=>({label:a,detail:c,run:f=>{let d=qu(f.state);d&&(f.dispatch(f.state.tr.delete(d.from,d.to)),r[u](f.state,f.dispatch,f))}}));e.show(l,s.from)},destroy(){e.destroy()}}},props:{handleKeyDown(t,r){return e?.keys(r)??!1},handleDOMEvents:{blur(){return e?.close(),!1}}}})}var Fy=new N("mapa-bubble"),Os=new WeakMap;function mi(n,e){Os.get(n)?.(e)}function Un(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Vy(n,e){let{from:t,to:r,empty:i,$from:o}=n.selection;return i?!!e.isInSet(n.storedMarks||o.marks()):n.doc.rangeHasMark(t,r,e)}function Ju(n){return(e,t)=>{let{from:r,to:i,empty:o}=e.selection,s=e.schema.marks.link;if(o)return!1;if(t){let l=e.tr.removeMark(r,i,s);n&&l.addMark(r,i,s.create({href:n})),t(l)}return!0}}function ju(n){let{selection:e}=n;return e instanceof k&&!e.empty&&!e.$from.parent.type.spec.code}var Wy=n=>n.length===1?"1 page":`${n.length} pages`;function qy(n,e,{ask:t,resolutions:r,back:i}){let o=Un("input",{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-label":"Page to link to",placeholder:"Find a page",autocomplete:"off","mapa-bubble-page":""});o.hidden=!0;let s=Un("p",{role:"status","mapa-bubble-note":""});e.append(o,s);let l=new lt(n,{label:"Pages to link to",count:Wy,input:o}),a="",c=0,u=null,f=()=>{c++,clearTimeout(u),l.close(),o.hidden=!0},d=m=>g=>{let{tr:y,refuse:C}=xu(g.state,m,a);f(),y?g.dispatch(y):s.textContent=C,i()},h=m=>ri(m,m===a?"":a)?d(m):null;async function p(){let m=++c,g=o.value,y=[];try{y=await t(g)}catch{}let C=r?await r.lookup(y.map(O=>O.text)):{};m!==c||o.hidden||l.show(bs({text:g},y,C,h).filter(O=>O.run),0)}return o.addEventListener("input",()=>{clearTimeout(u),u=setTimeout(p,30)}),o.addEventListener("keydown",m=>{if(!m.isComposing){if(m.key==="Escape"){m.preventDefault(),f(),i();return}if(l.keys(m)){m.preventDefault();return}m.key==="Enter"&&m.preventDefault()}}),o.addEventListener("blur",()=>l.close()),{open(m){return s.textContent="",m.refuse?(f(),s.textContent=m.refuse,!1):(a=m.words,o.hidden=!1,o.value=a,o.focus(),o.select(),p(),!0)},close:f,quiet(){s.textContent=""},get saying(){return s.textContent!==""},destroy(){l.destroy()}}}function Hu({makeTeamPage:n=null,ask:e=async()=>[],resolutions:t=null}={}){let r=null,i=null;return new S({key:Fy,view(o){let s=o.state.schema;r=Un("div",{"mapa-bubble":"",role:"toolbar","aria-label":"Format"}),r.hidden=!0;let l=()=>[...r.querySelectorAll("input")];r.addEventListener("mousedown",g=>{l().includes(g.target)||g.preventDefault()}),r.addEventListener("keydown",g=>{if(l().includes(g.target))return;let y=[...r.querySelectorAll("button")],C=y.indexOf(document.activeElement);g.key==="Escape"?(g.preventDefault(),o.focus()):(g.key==="ArrowRight"||g.key==="ArrowLeft")&&(g.preventDefault(),y[(C+(g.key==="ArrowRight"?1:-1)+y.length)%y.length]?.focus())});let a=[],c=(g,y,C,{mark:O=null,keeps:$=!1,title:me=""}={})=>{let ae=Un("button",{type:"button","aria-label":g,"mapa-bubble-button":""},y);return me&&(ae.title=me),ae.addEventListener("click",()=>{C(o),$||o.focus()}),r.append(ae),a.push({button:ae,mark:O}),ae};c("Bold","B",g=>we(s.marks.strong)(g.state,g.dispatch),{mark:s.marks.strong}),c("Italic","I",g=>we(s.marks.em)(g.state,g.dispatch),{mark:s.marks.em}),c("Code","<>",g=>we(s.marks.code)(g.state,g.dispatch),{mark:s.marks.code}),c("Page link","Page link",g=>h(ii(g.state)),{keeps:!0,title:"Link to a page (\u2318L)"}),c("Web link","Web link",()=>f(),{mark:s.marks.link,keeps:!0,title:"Link to a web address (\u21E7\u2318K)"}),n&&c("Make team page","Make team page",g=>n(g),{keeps:!0}),i=Un("input",{type:"url","aria-label":"Link address",placeholder:"Paste a link","mapa-bubble-field":""}),i.hidden=!0,r.append(i),document.body.append(r);let u=qy(o,r,{ask:e,resolutions:t,back:()=>o.focus()});i.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let y=i.value.trim();(y===""||Re(y))&&Ju(y)(o.state,o.dispatch),d()}else g.key==="Escape"&&(g.preventDefault(),d())});function f(){u.close(),u.quiet(),i.hidden=!1,i.value="",i.focus()}function d(){i.hidden=!0,o.focus()}function h(g){g&&(i.hidden=!0,r.hidden=!1,p(),u.open(g)||o.focus(),p())}r.openLink=f,Os.set(o,h);let p=()=>{if(!(ju(o.state)||u.saying&&!o.state.selection.empty)||!o.hasFocus()&&!r.contains(document.activeElement)){r.hidden=!0,i.hidden=!0,u.close();return}for(let{button:v,mark:F}of a)F&&v.setAttribute("aria-pressed",Vy(o.state,F)?"true":"false");r.hidden=!1;let{from:y,to:C}=o.state.selection,O=o.coordsAtPos(y),$=o.coordsAtPos(C),ae=window.matchMedia("(pointer: coarse)").matches?$.bottom+12:O.top-r.offsetHeight-8,D=Math.max(4,Math.min((O.left+$.left)/2-r.offsetWidth/2,window.innerWidth-r.offsetWidth-4));r.style.setProperty("top",`${Math.max(ae,4)}px`),r.style.setProperty("left",`${D}px`)},m=()=>setTimeout(p,0);return o.dom.addEventListener("blur",m),r.addEventListener("focusout",m),{update(g,y){g.state.selection.eq(y.selection)||u.quiet(),p()},destroy(){o.dom.removeEventListener("blur",m),Os.delete(o),u.destroy(),r.remove()}}},props:{handleKeyDown(o,s){return s.key==="F10"&&s.altKey&&r&&!r.hidden?(s.preventDefault(),r.querySelector("button")?.focus(),!0):s.key.toLowerCase()==="k"&&s.shiftKey&&(s.metaKey||s.ctrlKey)&&ju(o.state)?(s.preventDefault(),r?.openLink(),!0):!1}}})}function Uu(){return new S({props:{handlePaste(n,e){let t=e.clipboardData?.getData("text/plain")?.trim()??"";return n.state.selection.empty||!/^https?:\/\/\S+$/u.test(t)||!Re(t)?!1:Ju(t)(n.state,n.dispatch)}}})}function _u(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 Yu({title:n}){let e=t=>{let r=[];return t.descendants((i,o)=>{let s=i.attrs?.marker;s&&i.type.name!=="list_item"&&i.type.name!=="blockquote"&&r.push(E.widget(o+1,()=>_u(s,n),{side:-1,key:`anchor-${s}`,ignoreSelection:!0,stopEvent:()=>!0})),s&&(i.type.name==="list_item"||i.type.name==="blockquote")&&r.push(E.widget(o+2,()=>_u(s,n),{side:-1,key:`anchor-${s}`,ignoreSelection:!0,stopEvent:()=>!0}))}),A.create(t,r)};return new S({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 _n(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 Yn=new N("mapa-moving");function Ky(n,e){let{from:t,to:r}=n.selection,{emitted:i,body:o}=P(n.doc,e),s=[];return i.forEach((l,a)=>{let c=l.pos+l.node.nodeSize;l.pos<Math.max(r,t+1)&&c>t&&s.push({index:a,block:l})}),{chosen:s,body:o}}function jy(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 Jy(n,e,t){let r=ee(ge(n));if(r.length!==t)return null;let i=[];for(let{index:o,block:s}of e){if(!r[o]||r[o].source!==s.text)return null;i.push(o)}return i}function Gu(){return new S({key:Yn,state:{init:()=>null,apply(n,e){let t=n.getMeta(Yn);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=Yn.getState(n);return e?A.create(n.doc,e.map(t=>E.node(t.from,t.to,{"mapa-moving":""}))):null}}})}function Ie(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Hy(){let n=Ie("dialog",{"mapa-make-team":"","aria-labelledby":"mapa-make-team-title"}),e=Ie("form",{method:"dialog"}),t=Ie("h2",{id:"mapa-make-team-title"},"Make team page"),r=Ie("label",{for:"mapa-make-team-name"},"Title of the new page"),i=Ie("input",{id:"mapa-make-team-name",name:"title",required:"",autocomplete:"off","rst-input":""}),o=Ie("p",{"mapa-make-team-error":"",role:"alert"}),s=Ie("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=Ie("button",{type:"submit","rst-btn":"primary"},"Make team page"),a=Ie("button",{type:"button","rst-btn":""},"Cancel"),c=Ie("div",{"mapa-make-team-foot":""});return c.append(a,l),e.append(t,r,i,o,s,c),n.append(e),document.body.append(n),{box:n,form:e,input:i,error:o,confirm:l,cancel:a}}function Xu({saver:n,fidelity:e,post:t,notify:r}){let i=null;return l=>{let{chosen:a}=Ky(l.state,e);if(a.length===0)return!1;let c=a.map(({block:y})=>({from:y.pos,to:y.pos+y.node.nodeSize}));l.dispatch(l.state.tr.setMeta(Yn,c)),i=i??Hy();let{box:u,form:f,input:d,error:h,confirm:p,cancel:m}=i;d.value=jy(a),h.textContent="";let g=()=>{l.dispatch(l.state.tr.setMeta(Yn,null)),f.onsubmit=null,m.onclick=null,u.onclose=null,u.open&&u.close(),l.focus()};return m.onclick=g,u.onclose=g,f.onsubmit=async y=>{y.preventDefault();let C=d.value.trim(),O=await _n(p,()=>o(l,a,C));if(O.error){h.textContent=O.error,d.focus();return}g(),r(C,O.href)},u.showModal(),d.select(),!0};async function o(l,a,c){let u=await n.commit({explicit:!0});if(!["none","saved","merged"].includes(u)||!n.page)return{error:"Your note could not be saved just now, so nothing was moved. Try again."};let{emitted:f}=P(l.state.doc,e),d=s(l,a),h=d&&Jy(n.saved,d,f.length);if(!h)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:h.map(String),grammar:String(fr)})}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 s(l,a){let{emitted:c}=P(l.state.doc,e),u=[],f=0;for(let{block:d}of a){let h=c.findIndex((p,m)=>m>=f&&p.text===d.text);if(h<0)return null;u.push({index:h,block:c[h]}),f=h+1}return u}}function Uy(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 _y(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",o=>o.preventDefault()),i.addEventListener("click",o=>{o.preventDefault();let s=Uy(n.state.doc,e());if(!s?.node.attrs.task)return;let l=s.node.attrs.checked!==" "?" ":"x";n.dispatch(n.state.tr.setNodeMarkup(s.pos,null,{...s.node.attrs,checked:l}))}),i}function Zu(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,(o,s)=>_y(o,s,t),{side:-1,key:i,ignoreSelection:!0,stopEvent:()=>!0}))}),A.create(n,e)}function Qu(){return new S({state:{init:(n,e)=>Zu(e.doc),apply:(n,e)=>n.docChanged?Zu(n.doc):e},props:{decorations(n){return this.getState(n)}}})}function ef(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function tf(n){return new S({view(e){let{place:t,row:r}=Yy(e,n);return{update:t,destroy:()=>r.remove()}}})}function Yy(n,{makeTeamPage:e=null,linkPage:t=null,image:r=null}={}){let i=n.state.schema,o=on(i),s=ef("div",{"mapa-accessory":"",role:"toolbar","aria-label":"Writing"});s.hidden=!0;let l=(f,d,h)=>{let p=ef("button",{type:"button","aria-label":f},d);p.addEventListener("mousedown",m=>m.preventDefault()),p.addEventListener("click",()=>{h(n.state,n.dispatch,n),document.activeElement?.closest?.("[mapa-bubble]")||n.focus()}),s.append(p)};l("Link to a page","[[",t??si("[[")),l("Blocks","/",si("/")),l("Bold","B",we(i.marks.strong)),l("Italic","I",we(i.marks.em)),l("List","\u2022",o["insert-list"]),l("Checklist","\u2610",o["insert-check"]),r&&l("Image","Image",r),e&&l("Make team page","Team page",(f,d,h)=>e(h)),document.body.append(s);let a=window.matchMedia("(pointer: coarse) and (max-width: 799px)"),c=window.visualViewport,u=()=>{let f=a.matches&&n.hasFocus();s.hidden=!f;let d=c?window.innerHeight-c.height-c.offsetTop:0;document.documentElement.toggleAttribute("data-mapa-keyboard",f&&d>80),f&&s.style.setProperty("bottom",`${Math.max(d,0)}px`)};return n.dom.addEventListener("focus",u),n.dom.addEventListener("blur",()=>setTimeout(u,0)),c?.addEventListener("resize",u),c?.addEventListener("scroll",u),a.addEventListener?.("change",u),{place:u,row:s}}function Gy(n=(t,r)=>fetch(t,r),e=1e4){return async(t,r,{keepalive:i=!1}={})=>{let o=new URLSearchParams;for(let[a,c]of Object.entries(r))for(let u of[].concat(c))o.append(a,u);let s=i?null:new AbortController,l=s?setTimeout(()=>s.abort(),e):null;try{let a=await n(t,{method:"POST",body:o,credentials:"same-origin",keepalive:i,headers:{Accept:"application/json"},signal:s?.signal}),c=null;try{c=await a.json()}catch{}return{status:a.status,json:c}}finally{l!==null&&clearTimeout(l)}}}var at=Gy();var Zy="Title, renames the page";function Gn(n){return n.split(/\s+/u).filter(Boolean).join(" ")}var Ds=class{constructor(e,t,r){this.title=e,this.action=t,this.deps=r,this.pending=null,this.listeners=[]}on(e){this.listeners.push(e)}emit(e){for(let t of this.listeners)t(e)}async rename(e,t){let r=Gn(e);if(this.pending!==null)return"busy";if(r==="")return"empty";if(r===this.title)return"unchanged";this.pending=r,this.emit({kind:"pending",title:r,source:t});let i=this.deps.wait(650),o=null;try{o=await this.deps.post(this.action,{title:r})}catch{}return await i,this.pending=null,o?.status===200&&o.json?.title?(this.title=o.json.title,this.emit({kind:"renamed",source:t,...o.json}),"renamed"):o?.status===422&&o.json?.error?(this.emit({kind:"refused",source:t,typed:e,error:o.json.error,taken:o.json.taken??""}),"refused"):(this.emit({kind:"failed",source:t,typed:e}),"failed")}closing(e){try{this.deps.post(this.action,{title:e},{keepalive:!0})?.catch?.(()=>{})}catch{}}async updateLinks(){let e=this.action.replace(/\/rename$/u,"/links"),t=null;try{t=await this.deps.post(e,{})}catch{}return t?.status===200?t.json?.notice??null:null}};function pe(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...t),r}function nf(n){n.focus();let e=document.createRange();e.selectNodeContents(n),e.collapse(!1);let t=getSelection();t.removeAllRanges(),t.addRange(e)}function rf({post:n,hooks:e={}}){let t=document.querySelector("h1[mapa-title][mapa-rename]"),r=t?.querySelector("[mapa-title-text]");if(!r)return null;let i=new Ds(r.textContent,t.getAttribute("mapa-rename"),{post:n,wait:l=>new Promise(a=>setTimeout(a,l))}),o=pe("div",{"mapa-title-note":"",id:"mapa-title-note",role:"status"});t.after(o);let s=Qy(i.action);return e0(t,r,i),s&&t0(s,i),i.on(l=>r0(l,{heading:t,text:r,field:s,note:o,renamer:i,hooks:e})),i}function Qy(n){let e=document.querySelector("form[estilo-bar-title]"),t=e?.querySelector("[estilo-bar-title-input]");return!t||new URL(e.action,location.href).pathname!==n?null:{form:e,input:t,button:e.querySelector("[estilo-bar-title-submit]")}}function e0(n,e,t){e.setAttribute("contenteditable","true"),e.setAttribute("role","textbox"),e.setAttribute("aria-label",Zy),e.setAttribute("aria-describedby","mapa-title-note"),e.setAttribute("spellcheck","false"),n.addEventListener("mousedown",l=>{l.target!==n||l.button!==0||(l.preventDefault(),nf(e))});let r=!1,i=null,o=async l=>{let a=e.textContent,c=Gn(a);if(t.pending!==null)return;if(c===""||c===t.title){if(l==="enter"&&c==="")return;e.removeAttribute("aria-invalid"),e.textContent!==t.title&&(e.textContent=t.title),l==="enter"&&e.blur();return}if(l==="blur"&&c===i)return;let u=await t.rename(a,"h1");i=u==="refused"?c:null,u==="renamed"&&document.activeElement===e&&(r=!0,e.blur(),r=!1)};e.addEventListener("keydown",l=>{if(l.isComposing||l.keyCode===229)return;let a=l.key==="s"&&(l.metaKey||l.ctrlKey);if(l.key==="Enter"||a)l.preventDefault(),o("enter");else if(l.key==="Escape"){if(l.preventDefault(),t.pending!==null)return;r=!0,i=null,e.textContent=t.title,e.removeAttribute("aria-invalid"),e.blur(),r=!1,n0(n)}});let s=!1;e.addEventListener("blur",()=>{if(!r){if(!document.hasFocus()||document.visibilityState==="hidden"){s=!0;return}o("blur")}}),e.addEventListener("focus",()=>{s=!1}),window.addEventListener("focus",()=>{s&&document.activeElement===document.body&&nf(e)}),window.addEventListener("pagehide",()=>{let l=t.pending??Gn(e.textContent);l===""||l===t.title||t.pending===null&&l===i||t.closing(l)}),e.addEventListener("beforeinput",l=>{let a=/^(insertParagraph|insertLineBreak)$/u.test(l.inputType);(t.pending!==null||a||/^format/u.test(l.inputType))&&l.preventDefault(),a&&!l.isComposing&&t.pending===null&&o("enter")}),e.addEventListener("paste",l=>{if(l.preventDefault(),t.pending!==null)return;let a=Gn(l.clipboardData?.getData("text/plain")??"");document.execCommand("insertText",!1,a)}),e.addEventListener("drop",l=>l.preventDefault())}function t0({form:n,input:e,button:t},r){n.addEventListener("submit",async i=>{if(i.preventDefault(),r.pending!==null)return;let o=Gn(e.value);if(o===""||o===r.title){e.value=r.title,e.removeAttribute("aria-invalid"),e.blur();return}let s=()=>r.rename(e.value,"header");(t?await _n(t,s):await s())==="renamed"&&e.blur()})}function n0(n){let e=n.nextElementSibling;e?.querySelector('[role="alert"]')&&e.replaceChildren()}function r0(n,e){let{text:t,field:r,note:i}=e,o=n.source==="h1";if(n.kind==="pending"){t.setAttribute("aria-readonly","true"),t.setAttribute("aria-busy","true"),o||(t.textContent=n.title),r&&(r.input.readOnly=!0,o&&(r.input.value=n.title)),i.replaceChildren(pe("p",{},pe("span",{"rst-spin":"","aria-hidden":"true"}),"Renaming\u2026"));return}if(t.removeAttribute("aria-readonly"),t.removeAttribute("aria-busy"),r&&(r.input.readOnly=!1),n.kind==="renamed")return i0(n,e);let s=o?t:r?.input;o&&r&&(r.input.value=e.renamer.title),!o&&t.textContent!==e.renamer.title&&(t.textContent=e.renamer.title),s?.setAttribute("aria-invalid","true");let l=n.kind==="refused"?n.error:"Not renamed: the title could not be saved. Check your connection and try again.",a=pe("p",{role:"alert"},l);n.taken&&a.append(" ",pe("a",{href:n.taken},"Open the page with that title")),i.replaceChildren(a)}function i0(n,{text:e,field:t,note:r,renamer:i,hooks:o}){let s=n.title;e.removeAttribute("aria-invalid"),e.textContent!==s&&(e.textContent=s),t&&(t.input.removeAttribute("aria-invalid"),t.input.value=s,t.input.defaultValue=s,t.input.dispatchEvent(new Event("input",{bubbles:!0}))),document.title=`${s} \xB7 Mapa`;for(let l of document.querySelectorAll("[mapa-side] a[mapa-side-page]")){if(new URL(l.href).pathname!==n.href)continue;let a=l.querySelector("[mapa-side-label]");a&&(o0(l.closest("[mapa-side-row]")?.querySelector("[mapa-row-more]"),a.textContent,s),a.textContent=s)}s0(n.aliases??[]),o.renamed?.({title:s,from:n.from,to:n.to}),o.refresh?.(),r.replaceChildren(...l0(n,r,i,o))}function o0(n,e,t){let r=n?.getAttribute("aria-label");r?.endsWith(e)&&n.setAttribute("aria-label",r.slice(0,r.length-e.length)+t)}function s0(n){let e=document.querySelector("[mapa-doc-kicker]");if(!e)return;let t=e.querySelector("[mapa-also]");if(n.length===0){t?.remove();return}t||(t=pe("span",{"mapa-also":""}),e.insertBefore(t,e.querySelector("[mapa-actions]"))),t.textContent=`Also called ${n.join(", ")}`}function l0(n,e,t,r){if(!(n.links>0))return[pe("p",{},"Renamed. The old title still leads here.")];let i=pe("button",{"rst-btn":"primary",type:"button"},"Update links"),o=pe("button",{"rst-btn":"",type:"button"},"Not now");return i.addEventListener("click",async()=>{let s=await _n(i,()=>t.updateLinks());if(s===null){e.querySelector("[mapa-title-links-failed]")?.remove(),e.append(pe("p",{role:"alert","mapa-title-links-failed":""},"Links not updated. Check your connection and try again."));return}e.replaceChildren(pe("p",{},s)),r.refresh?.()}),o.addEventListener("click",()=>e.replaceChildren()),[pe("p",{},`Renamed. ${n.count} you can edit link here by an old title. Update them to "${n.title}"? It's an edit by you; other people's private notes keep working.`),i,o]}function sf(){return new S({props:{handleDOMEvents:{mousedown:(n,e)=>e.target===n.dom&&c0(n,e.clientY)&&of(n,e)}},view(n){let e=n.dom.parentElement,t=n.dom.closest("[mapa-main]");if(!t)return{};let r=i=>{(i.target===t||i.target===e)&&of(n,i)};return t.addEventListener("mousedown",r),{destroy:()=>t.removeEventListener("mousedown",r)}}})}function of(n,e){if(n.composing||!n.editable||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;e.preventDefault();let t=e.shiftKey?n.state.selection.anchor:Ts(n,e.clientX,e.clientY);return lf(n,t,Ts(n,e.clientX,e.clientY)),n.focus(),a0(n,t,e),!0}function a0(n,e,t){let r=o=>{if(!(o.buttons&1))return i();Math.hypot(o.clientX-t.clientX,o.clientY-t.clientY)<4||lf(n,e,Ts(n,o.clientX,o.clientY))},i=()=>{window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)}function lf(n,e,t){let r=n.state.doc,i=s=>As(s,0,r.content.size),o=k.between(r.resolve(i(e)),r.resolve(i(t)));o.eq(n.state.selection)||n.dispatch(n.state.tr.setSelection(o))}function af(n){let e=n.state.doc,t=n.nodeDOM(0),r=n.nodeDOM(e.content.size-e.lastChild.nodeSize),i=n.dom.getBoundingClientRect();return{box:i,top:t?.getBoundingClientRect?.().top??i.top,bottom:r?.getBoundingClientRect?.().bottom??i.bottom}}function c0(n,e){return e>=af(n).bottom}function Ts(n,e,t){let r=M.atEnd(n.state.doc).head,{box:i,top:o,bottom:s}=af(n);if(t>=s)return r;let l=n.posAtCoords({left:As(e,i.left+1,i.right-1),top:As(t,o+1,s-1)});return l?l.pos:r}function As(n,e,t){return Math.min(Math.max(n,e),t)}var u0="Describe this image for people who can't see it",f0=240,d0=120;function h0(n,e=5,t=40){let i=n.trim().split(/\s+/u).slice(0,e).join(" ");return i.length>t&&(i=i.slice(0,t).trimEnd()),i.length<n.trim().length?`${i}\u2026`:i}function p0(n){return n?`Alt text: ${h0(n)}, edit`:"Alt text: describe this image"}function m0(n){return Vi(n.replace(/\s*[\r\n]+\s*/gu," ")).trim()}function g0(n){let e=0,t="";for(let r of n){let i=r.codePointAt(0);if(e+=i<128?1:i<2048?2:i<65536?3:4,e>ur)return t;t+=r}return n}function cf(n,e){let t=document.createElement("button");return t.type="button",t.draggable=!1,t.setAttribute("mapa-alt-badge",""),t.textContent="ALT",Ns(t,n),t.addEventListener("mousedown",r=>r.preventDefault()),t.addEventListener("click",r=>{r.preventDefault(),e()}),t}function Ns(n,e){n.setAttribute("mapa-alt-badge",e?"set":"missing"),n.setAttribute("aria-label",p0(e)),n.tabIndex=e?-1:0}var Bt=null,y0=0;function Ye(){Bt?.finish(!0,!1)}function uf(n){return Bt?.frame!==n?!1:(Bt.finish(!0,!0),!0)}function ff(n){let e=Bt;e?.frame===n&&queueMicrotask(()=>{let t=!document.activeElement||document.activeElement===document.body;e.finish(!0,t)})}function df(n,e,t,{from:r="bubble",...i}={}){Ye();let o=n.state.doc.nodeAt(t());if(o?.type.name!=="image")return null;let s=new Es(n,e,t,r,i);return s.show(o.attrs.alt??""),s}var Es=class{constructor(e,t,r,i,o){Object.assign(this,{view:e,frame:t,getPos:r,from:i,hooks:o,closed:!1}),this.id=s=>s?.type.name==="image"?s.attrs.id:null,this.image=this.id(e.state.doc.nodeAt(r()))}show(e){let t=this.frame.getBoundingClientRect();this.inset=t.width>=f0&&t.height>=d0;let r=document.createElement("div");r.setAttribute("mapa-alt",this.inset?"inset":"popover"),r.draggable=!1;let i=`mapa-alt-${++y0}`,o=document.createElement("label");o.htmlFor=i,o.textContent=u0;let s=document.createElement("textarea");Object.assign(s,{id:i,rows:1,value:e}),s.setAttribute("autocomplete","off"),s.setAttribute("enterkeyhint","done"),r.append(o,s),Object.assign(this,{wrap:r,text:s,before:e}),this.listen(),this.frame.append(r),this.parent=this.frame.parentNode,this.frame.setAttribute("mapa-alt-open",""),this.draggable=this.frame.draggable,this.frame.draggable=!1,Bt=this,this.inset||b0(r),this.grow(),s.focus({preventScroll:!0}),s.setSelectionRange(s.value.length,s.value.length),r.scrollIntoView?.({block:"nearest"})}listen(){let{text:e,wrap:t}=this;e.addEventListener("keydown",r=>this.key(r)),t.addEventListener("mousedown",r=>{r.target!==e&&(r.preventDefault(),e.focus({preventScroll:!0}))}),e.addEventListener("input",()=>{let r=g0(e.value.replace(/[ \t]*\r?\n[ \t]*/gu," "));if(r!==e.value){let i=Math.min(e.selectionStart,r.length);e.value=r,e.setSelectionRange(i,i)}this.grow()}),e.addEventListener("blur",()=>{document.hasFocus()&&setTimeout(()=>{if(this.frame.isConnected&&this.frame.parentNode!==this.parent&&document.activeElement===document.body){this.parent=this.frame.parentNode,e.focus({preventScroll:!0});return}this.finish(!0,!1)},0)}),this.returned=()=>setTimeout(()=>{document.activeElement!==e&&this.finish(!0,!1)},0),window.addEventListener("focus",this.returned)}key(e){e.isComposing||e.keyCode===229||(e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),this.finish(!0,!0)):e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.finish(!1,!0)):e.key.toLowerCase()==="s"&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0),this.hooks.save?.()))}grow(){let{text:e}=this;e.style.removeProperty("height");let t=e.scrollHeight+2;if(this.inset){let r=this.wrap.offsetHeight-e.offsetHeight;t=Math.min(t,Math.max(36,this.frame.clientHeight-r))}e.style.setProperty("height",`${t}px`)}finish(e,t){if(this.closed)return;this.closed=!0,Bt===this&&(Bt=null),window.removeEventListener("focus",this.returned),this.wrap.remove(),this.frame.removeAttribute("mapa-alt-open"),this.frame.draggable=this.draggable,this.hooks.closed?.();let r=this.place(),i=m0(this.text.value),o=e&&r!==null&&i!==this.before;o&&this.view.dispatch(this.view.state.tr.setNodeAttribute(r,"alt",i)),t&&this.refocus(o?this.place(r):r),o&&!(t&&this.from==="badge")&&this.hooks.say?.(i?`Image: ${i}`:"Image with no description")}place(e=null){let{doc:t}=this.view.state,r=o=>typeof o=="number"&&o>=0&&o<t.content.size&&this.id(t.nodeAt(o))===this.image;if(r(e))return e;let i=null;try{i=this.getPos()}catch{i=null}return r(i)||(i=null,t.descendants((o,s)=>(i===null&&this.id(o)===this.image&&(i=s),i===null))),i}refocus(e){let{view:t}=this,i=(e===null?null:t.nodeDOM(e))?.querySelector?.("[mapa-alt-badge]");if(this.from==="badge"&&i?.isConnected){i.focus();return}if(e!==null){let o=this.from==="upload"?k.near(t.state.doc.resolve(e+1)):w.create(t.state.doc,e);t.dispatch(t.state.tr.setSelection(o))}t.focus()}};function b0(n){let e=n.getBoundingClientRect(),t=document.documentElement.clientWidth-8,r=e.right>t?t-e.right:e.left<8?8-e.left:0;r&&n.style.setProperty("inset-inline-start",`${r}px`)}var x0=32,yi=class{constructor(e={},t=null){this.known=new Map(Object.entries(e??{})),this.ask=t,this.asked=new Set,this.waiting=new Set,this.watchers=new Set,this.timer=null}answer(e){let t=this.known.get(e);return t||(this.ask&&mn(e)&&!this.asked.has(e)&&(this.waiting.add(e),this.soon()),{available:!1})}set(e,t){this.known.set(e,{available:!0,...t}),this.tell(new Set([e]))}soon(){this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},0))}async flush(){let e=[...this.waiting].slice(0,x0);if(e.length===0)return;for(let i of e)this.waiting.delete(i),this.asked.add(i);this.waiting.size&&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,o]of Object.entries(t??{}))this.known.set(i,o),r.add(i);this.tell(r)}tell(e){if(e.size)for(let t of this.watchers)t(e)}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}};function hf(n){return n?`Image: ${n}`:"Image with no description"}function pf(n){let e=re.renderSpec(document,n.type.spec.toDOM(n)).dom;return e.setAttribute("aria-label",e.nodeName==="IMG"?hf(n.attrs.alt):`${hf(n.attrs.alt)}, not available`),e}var k0=2e3,vs=new WeakMap,Is=class{constructor(e,t,r,i,o={}){Object.assign(this,{node:e,answers:t,view:r,getPos:i,hooks:o}),this.dom=document.createElement("span"),this.dom.setAttribute("mapa-image-frame",""),vs.set(this.dom,this),this.paint()}paint(){this.dom.replaceChildren(),this.inner=pf(this.node),this.drawn=Ps(this.answers.answer(this.node.attrs.id)),this.retried=!1,this.dom.append(this.inner),this.badge=null,this.inner.nodeName==="IMG"&&(this.badge=cf(this.node.attrs.alt,()=>this.describe("badge")),this.dom.append(this.badge),this.listen())}listen(){let e=this.inner;e.addEventListener("error",()=>{this.retried||(this.retried=!0,setTimeout(()=>{let t=e.getAttribute("src");e.setAttribute("src",`${t}?again=1`)},k0))})}describe(e){if(!this.view||!this.getPos||e==="badge"&&uf(this.dom))return null;let t=this.getPos();if(Ye(),!this.dom.isConnected){let o=vs.get(this.view.nodeDOM(t));return o&&o!==this&&o.node.attrs.id===this.node.attrs.id?o.describe(e):null}let{say:r,save:i}=this.hooks;return df(this.view,this.dom,this.getPos,{from:e,say:r,save:i,closed:()=>this.closed()})}closed(){this.pending&&(this.pending=!1,this.paint())}update(e){if(e.type!==this.node.type||e.attrs.id!==this.node.attrs.id)return!1;let t=e.attrs.alt!==this.node.attrs.alt;if(this.node=e,Ps(this.answers.answer(e.attrs.id))!==this.drawn)return this.dom.hasAttribute("mapa-alt-open")?this.pending=!0:this.paint(),!0;if(t){let r=pf(e);for(let i of["alt","aria-label"])r.hasAttribute(i)&&this.inner.setAttribute(i,r.getAttribute(i));this.badge&&Ns(this.badge,e.attrs.alt)}return!0}selectNode(){this.dom.setAttribute("mapa-image-selected","")}deselectNode(){this.dom.removeAttribute("mapa-image-selected")}stopEvent(e){return!!e.target?.closest?.("[mapa-alt-badge], [mapa-alt]")}ignoreMutation(){return!0}destroy(){ff(this.dom)}};function bi(n,e,t){let r=n.nodeDOM(e);return r?vs.get(r)?.describe(t)??null:null}function gf(n,e={}){return{image:(t,r,i)=>new Is(t,n,r,i,e)}}var Ps=n=>n?.available?"image":"box",gi=new N("mapa-images");function mf(n,e,t,r,i){return n.nodesBetween(e,t,(o,s)=>{if(!o.isTextblock)return!0;let l=zl(o);return o.forEach((a,c)=>{if(a.type.name!=="image")return;let u={"data-mapa-drawn":Ps(r.answer(a.attrs.id))};l&&(u.class="alone");let f=s+1+c;i.push(E.node(f,f+1,u))}),!1}),i}function w0(n,e){n.mapping.maps.forEach((t,r)=>{t.forEach((i,o,s,l)=>{let a=n.mapping.slice(r+1),c=Math.max(0,a.map(s,-1)-1),u=Math.min(n.doc.content.size,a.map(l,1)+1),f=n.doc.resolve(c),d=n.doc.resolve(u);e(f.depth?f.before(1):c,d.depth?d.after(1):u)})})}function yf(n){let e=t=>A.create(t,mf(t,0,t.content.size,n,[]));return new S({key:gi,state:{init:(t,r)=>e(r.doc),apply(t,r){if(t.getMeta(gi))return e(t.doc);if(!t.docChanged)return r;let i=r.map(t.mapping,t.doc);return w0(t,(o,s)=>{i=i.remove(i.find(o,s)),i=i.add(t.doc,mf(t.doc,o,s,n,[]))}),i}},view(t){return{destroy:n.watch(()=>t.dispatch(t.state.tr.setMeta(gi,!0)))}},props:{decorations:t=>gi.getState(t)}})}var xf=["image/png","image/jpeg","image/gif","image/webp"],zs=xf.join(","),kf=10*1024*1024,bf=4096,Pe=new N("mapa-uploads"),ln={type:"Mapa takes PNG, JPEG, GIF and WebP images.",svg:"Mapa takes PNG, JPEG, GIF and WebP images, not SVG.",size:"An image can be at most 10 MB.",offline:"Connection unavailable.",failed:"The image could not be stored. Try again."};function S0(n){return n.type==="image/svg+xml"||/\.svg$/iu.test(n.name??"")?ln.svg:xf.includes(n.type)?n.type!=="image/jpeg"&&n.size>kf?ln.size:null:ln.type}function C0(n){if(n[0]!==255||n[1]!==216)return null;let e=1;for(let t=2;t+4<=n.length;){if(n[t]!==255)return null;let r=n[t+1],i=n[t+2]<<8|n[t+3];if(r===225&&(e=M0(n,t+4,t+2+i)??e),r>=192&&r<=207&&![196,200,204].includes(r)){let o=n[t+5]<<8|n[t+6];return{width:n[t+7]<<8|n[t+8],height:o,orientation:e}}t+=2+i}return null}function M0(n,e,t){if(String.fromCharCode(...n.slice(e,e+6))!=="Exif\0\0")return null;let i=e+6,o=n[i]===73,s=c=>o?n[c]|n[c+1]<<8:n[c]<<8|n[c+1],a=i+(c=>o?(n[c]|n[c+1]<<8|n[c+2]<<16)+n[c+3]*16777216:n[c]*16777216+(n[c+1]<<16|n[c+2]<<8|n[c+3]))(i+4);if(a+2>t)return null;for(let c=0;c<s(a);c++){let u=a+2+c*12;if(u+12>t)return null;if(s(u)===274)return s(u+8)}return null}async function O0(n){if(n.type!=="image/jpeg"||typeof createImageBitmap!="function")return n;let e;try{e=C0(new Uint8Array(await n.slice(0,256*1024).arrayBuffer()))}catch{return n}if(!e||Math.max(e.width,e.height)<=bf)return n;let t=bf/Math.max(e.width,e.height),r=e.orientation>=5,i=Math.round((r?e.height:e.width)*t),o=Math.round((r?e.width:e.height)*t);try{let s=await createImageBitmap(n,{imageOrientation:"from-image",resizeWidth:i,resizeHeight:o,resizeQuality:"high"}),l=document.createElement("canvas");l.width=s.width,l.height=s.height,l.getContext("2d").drawImage(s,0,0),s.close?.();let a=await new Promise(c=>l.toBlob(c,"image/jpeg",.9));return a?new File([a],n.name,{type:"image/jpeg"}):n}catch{return n}}function D0(n,e){return new Promise(t=>{let r=new XMLHttpRequest;r.open("POST","/images"),r.setRequestHeader("Accept","application/json"),r.responseType="json",r.upload.addEventListener("progress",o=>{o.lengthComputable&&e(o.loaded/o.total)}),r.addEventListener("load",()=>t({status:r.status,json:r.response})),r.addEventListener("error",()=>t({status:0,json:null})),r.addEventListener("abort",()=>t({status:0,json:null}));let i=new FormData;i.append("file",n,n.name||"image"),r.send(i)})}function T0(n){let e=document.createElement("span");e.setAttribute("mapa-upload",""),e.setAttribute("role","group"),e.setAttribute("aria-label",`Uploading ${n.name}`),e.contentEditable="false";let t=document.createElement("span");t.setAttribute("mapa-upload-name",""),t.textContent=n.name;let r=document.createElement("progress");r.max=1,r.setAttribute("aria-label",`Uploading ${n.name}`);let i=document.createElement("span");return i.setAttribute("mapa-upload-why",""),i.hidden=!0,e.append(t,r,i),{group:e,bar:r,why:i}}function A0(n,e,t){let r=!!e.getMeta("history$");for(let i of n.values()){if(i.dropped)continue;E0(i,e);let o=e.mapping.mapResult(i.pos,-1),s=i.pos;if(i.pos=o.pos,!o.deletedAcross||i.lost)continue;let l=e.getMeta("mapa-applied")?v0(t,e.doc,s,o.pos):null;l!==null?i.pos=l:r?N0(i):i.lost=!0}return n}function E0(n,e){if(!n.replacing)return;let t=e.mapping.mapResult(n.replacing.pos,1);n.replacing.pos=t.pos,t.deleted&&(n.replacing.gone=!0)}function N0(n){n.dropped=!0,queueMicrotask(()=>n.onDrop?.())}function v0(n,e,t,r){let i=n.resolve(t);if(!i.parent.inlineContent)return null;let o=null;return e.nodesBetween(r,Math.min(e.content.size,r+2),(s,l)=>(o===null&&s.isTextblock&&(o=l+1+Math.min(i.parentOffset,s.content.size)),o===null)),o}function wf(){return new S({key:Pe,state:{init:()=>({uploads:new Map,moves:0}),apply(n,e,t){let r=n.getMeta(Pe),i=A0(e.uploads,n,t.doc);r?.add&&i.set(r.add.id,r.add),r?.remove&&i.delete(r.remove);let o=e.moves+(n.selectionSet||n.docChanged?1:0);return{uploads:i,moves:o}}},props:{decorations(n){let{uploads:e}=Pe.getState(n),t=[...e.values()].filter(r=>!r.dropped);return A.create(n.doc,t.map(r=>E.widget(Math.min(r.lost?n.doc.content.size-1:r.pos,n.doc.content.size),r.dom.group,{key:r.id,side:-1})))}}})}var I0=0;function xi(n){let e=Pe.getState(n);return e?[...e.uploads.values()].filter(t=>!t.dropped).length:0}async function Ls(n,e,t,r){for(let i of e){let o=Cf(n,i,t);t=await $s(n,o,r)??o.pos}}function Sf(n,e,t,r,i=null){let o=n.state.doc.nodeAt(e);if(o?.type.name!=="image"||i!==null&&o.attrs.id!==i)return Promise.resolve();let s=Cf(n,t,e+1,{pos:e,id:o.attrs.id,alt:o.attrs.alt});return $s(n,s,r)}function Cf(n,e,t,r=null){let o={id:`upload-${++I0}`,file:e,name:e.name||"image",pos:t,replacing:r};return o.dom=T0(o),o.dom.bar.value=0,n.dispatch(n.state.tr.setMeta(Pe,{add:o}).setMeta("addToHistory",!1)),o.moves=Pe.getState(n.state).moves,o}function Bs(n,e){n.dispatch(n.state.tr.setMeta(Pe,{remove:e.id}).setMeta("addToHistory",!1))}async function $s(n,e,t){let r=S0(e.file);if(r)return Rs(n,e,r,t);let i=await O0(e.file);if(i.size>kf)return Rs(n,e,ln.size,t);let o=await D0(i,s=>{e.dom.bar.value=s});if(e.dropped)return Bs(n,e);if(o.status!==200||!o.json?.id){let s=o.status===0?ln.offline:o.json?.refused??ln.failed;return Rs(n,e,s,t)}return R0(n,e,o.json,t)}function P0(n,e,t){let{pos:r,id:i,gone:o}=e.replacing,s=n.state.doc.nodeAt(r);return o||s?.type.name!=="image"||s.attrs.id!==i?null:(n.dispatch(n.state.tr.setMeta(Pe,{remove:e.id}).setNodeMarkup(r,null,{...s.attrs,id:t.id,source:null})),r+1)}function R0(n,e,t,r){if(r.answers.set(t.id,{width:t.width,height:t.height}),e.replacing){let c=P0(n,e,t);if(c!==null)return r.say?.("Image replaced"),c}let i=n.state.schema.nodes.image.create({id:t.id,alt:e.replacing?.alt??""}),o=Pe.getState(n.state).moves===e.moves,s=n.state.tr.setMeta(Pe,{remove:e.id}),l=e.pos;return!e.lost&&s.doc.resolve(l).parent.inlineContent&&!s.doc.resolve(l).parent.type.spec.code?s=s.insert(l,i):(e.lost&&(l=s.doc.content.size,r.notice?.("Image added at the end of the page")),s=s.insert(l,n.state.schema.nodes.paragraph.create(null,i)),l+=1),n.dispatch(s),o&&!e.replacing?r.alt?.(n,l):r.say?.(e.replacing?"Image replaced":"Image added"),l+1}function Rs(n,e,t,r){let{group:i,why:o,bar:s}=e.dom;s.hidden=!0,o.hidden=!1,o.textContent=t,i.setAttribute("aria-label",`Not uploaded: ${e.name}`),i.setAttribute("mapa-upload","failed"),r.say?.(`Not uploaded: ${t}`);let l=(a,c)=>{let u=document.createElement("button");return u.type="button",u.setAttribute("rst-btn",""),u.textContent=a,u.addEventListener("mousedown",f=>f.preventDefault()),u.addEventListener("click",c),i.append(u),u};return new Promise(a=>{e.onDrop=()=>{Bs(n,e),a()};let c=l("Retry",async()=>{c.remove(),u.remove(),o.hidden=!0,s.hidden=!1,i.setAttribute("mapa-upload",""),i.setAttribute("aria-label",`Uploading ${e.name}`),e.onDrop=null,a(await $s(n,e,r))}),u=l("Dismiss",()=>{Bs(n,e),n.focus(),a()})})}function Mf(n){return[...n?.files??[]].filter(e=>e.type.startsWith("image/")||/\.svg$/iu.test(e.name))}function L0(n){let e=n?.getData?.("text/html")??"",t=Mf(n);if(e)return B0(e)?t:[];let r=(n?.getData?.("text/plain")??"").trim();if(!r||/^https?:\/\/[^\s]+$/u.test(r))return t;let i=new Set(t.map(s=>s.name));return r.split(/\r?\n/u).map(s=>s.trim()).filter(Boolean).every(s=>i.has(s))?t:[]}function B0(n){let e=n.replace(/<!--[^]*?-->/gu,"").replace(/<\/?(?:html|head|body|meta)\b[^>]*>/giu,"").trim();return/^<img\b(?:"[^"]*"|'[^']*'|[^<>"'])*>$/iu.test(e)}function Of(n){return(e,t,r)=>{if(!r)return!0;let i=document.createElement("input");return i.type="file",i.accept=zs,i.multiple=!0,i.hidden=!0,i.setAttribute("mapa-image-input",""),i.addEventListener("change",()=>{let o=[...i.files];i.remove(),o.length&&Ls(r,o,r.state.selection.from,n)}),document.body.append(i),i.click(),!0}}function Df(n){return new S({props:{handlePaste(e,t){let r=L0(t.clipboardData);return r.length?(t.preventDefault(),Ls(e,r,e.state.selection.from,n),!0):!1},handleDrop(e,t){let r=Mf(t.dataTransfer);if(!r.length)return!1;t.preventDefault();let o=e.posAtCoords({left:t.clientX,top:t.clientY})?.pos??e.state.selection.from;return e.dispatch(e.state.tr.setSelection(k.near(e.state.doc.resolve(o)))),Ls(e,r,e.state.selection.from,n),!0}}})}function ki(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Tf(){let n=document.querySelector("[mapa-live]");return n||(n=ki("div",{"mapa-live":"","aria-live":"polite",role:"status","mapa-sr":""}),document.body.append(n)),e=>{n.textContent="",setTimeout(()=>{n.textContent=e},30)}}function Xn(n){let{selection:e}=n;return e instanceof w&&e.node.type.name==="image"?{node:e.node,pos:e.from}:null}function z0(n,e){let t=Xn(n.state);if(!t)return;let r=ki("input",{type:"file",accept:zs,"mapa-image-input":""});r.hidden=!0,r.addEventListener("change",()=>{let[i]=r.files;if(r.remove(),!i)return;let o=t.node.attrs.id,s=n.state.doc.nodeAt(t.pos)?.attrs.id===o?t.pos:null;s===null&&n.state.doc.descendants((l,a)=>{s===null&&l.type.name==="image"&&l.attrs.id===o&&(s=a)}),s!==null&&Sf(n,s,i,e,t.node.attrs.id)}),document.body.append(r),r.click()}function Af(n){return new S({view(e){let t=ki("div",{"mapa-image-bubble":"",role:"toolbar","aria-label":"Image"});t.hidden=!0,t.addEventListener("mousedown",l=>l.preventDefault());let r=(l,a)=>{let c=ki("button",{type:"button"},l);c.addEventListener("click",()=>a()),t.append(c)},i=()=>Xn(e.state)?.node.attrs.id;r("Alt text",()=>{let l=Xn(e.state);l&&bi(e,l.pos,"bubble")}),r("Replace\u2026",()=>z0(e,n)),r("Open full size",()=>{i()&&window.open(X+i(),"_blank","noopener")}),r("Remove from Mapa",()=>{let l=i();l&&n.leave(()=>`${X}${l}/remove?back=${encodeURIComponent(location.pathname)}`)}),t.addEventListener("keydown",l=>{let a=[...t.querySelectorAll("button")],c=a.indexOf(document.activeElement);l.key==="Escape"?(l.preventDefault(),e.focus()):(l.key==="ArrowRight"||l.key==="ArrowLeft")&&(l.preventDefault(),a[(c+(l.key==="ArrowRight"?1:-1)+a.length)%a.length]?.focus())}),document.body.append(t);let o=()=>{let l=Xn(e.state);if(!l||!e.hasFocus()&&!t.contains(document.activeElement)){t.hidden=!0;return}t.hidden=!1;let a=e.nodeDOM(l.pos)?.getBoundingClientRect?.();a&&(t.style.setProperty("top",`${Math.max(4,a.top-t.offsetHeight-8)}px`),t.style.setProperty("left",`${Math.max(4,a.left)}px`))},s=()=>setTimeout(o,0);return e.dom.addEventListener("blur",s),t.addEventListener("focusout",s),{update:o,destroy(){e.dom.removeEventListener("blur",s),t.remove()}}},props:{handleKeyDown(e,t){if(t.key==="F10"&&t.altKey&&Xn(e.state)){let r=document.querySelector("[mapa-image-bubble]");if(r&&!r.hidden)return t.preventDefault(),r.querySelector("button")?.focus(),!0}return!1}}})}var $0={get:n=>sessionStorage.getItem(n),set:(n,e)=>sessionStorage.setItem(n,e),remove:n=>sessionStorage.removeItem(n)};function F0(){let n=Number(document.documentElement.getAttribute("data-mapa-idle"));return n>0?n:void 0}function If(){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);bc(t.dates);let r=new Xr(t.links,async h=>(await at("/links/resolve",{target:h})).json),i=new yi(t.images,async h=>(await at("/links/resolve",{image:h,page:t.page??""})).json?.images),o=mr((h,p)=>r.answer(h,p),h=>i.answer(h)),{doc:s,fidelity:l}=qo(o,t.source),a={view:null},c=qc(a,l),u=new ei(t,{editor:c,post:at,storage:$0,idle:F0(),ui:U0(e,a),navigate:h=>location.assign(typeof h=="function"?h():h),replaceURL:h=>q0(h),reload:()=>location.reload(),refetch:Y0});a.saver=u;let f=V0(e,i,u);a.view=J0(e,o,s,l,r,u,c,f),X0(a.view,u,e,f);let d=rf({post:at,hooks:W0(a.view,u)});return u.settle(),t.source.trim()===""&&!t.drafts.startsWith("/d/")&&a.view.focus(),performance.mark("mapa-mounted"),{view:a.view,saver:u,fidelity:l,resolutions:r,title:d,answers:i}}function V0(n,e,t){let r={answers:e,say:Tf(),alt:(i,o)=>document.activeElement?.closest?.("[mapa-alt]")?r.say("Image added"):bi(i,o,"upload"),notice:i=>le(n,i),leave:i=>t.leave(i),save:()=>t.commit({explicit:!0})};return r.choose=Of(r),r}function W0(n,e){return{renamed:({title:t,from:r,to:i})=>{n.dom.setAttribute("aria-label",`Page text, ${t}`),e.renamed(r,i)},refresh:Rf}}function q0(n){window.history.replaceState(null,"",n)}function K0(n){return n.drafts.startsWith("/d/")||!!n.token||!!document.querySelector('[estilo-menubar] a[href$="/share"]')}function j0(n,e,t){let r=document.createElement("a");r.href=t,r.textContent=e;let i=document.createElement("span");i.append("Moved to ",r,"."),le(n,i)}async function Ef(n){let e=await fetch(`/links/suggest?q=${encodeURIComponent(n)}`,{credentials:"same-origin"});return e.ok?(await e.json()).suggestions??[]:[]}function Nf(){return document.querySelector("h1[mapa-title]")?.textContent.trim()??""}function J0(n,e,t,r,i,o,s,l){let a=K0(o)?Xu({saver:o,fidelity:r,post:at,notify:(f,d)=>j0(n,f,d)}):null,c=Mr.create({doc:t,plugins:[Ou({ask:Ef,resolutions:i}),Yc(),Ku({"insert-image":l.choose}),Hu({makeTeamPage:a,ask:Ef,resolutions:i}),Yu({title:Nf}),Gu(),Qu(),sf(),tf({makeTeamPage:a,linkPage:oi(mi),image:l.choose}),yf(l.answers),wf(),Df(l),Af(l),...Tu(e,{save:()=>o.commit({explicit:!0}),linkPage:oi(mi)}),...Eu(e),Wc(),pc(),yc(),Jo(r),Uu(),ss(r,{page:()=>o.page??"",copy:f=>at("/images/copy",{id:f}),refused:f=>le(n,`Not pasted: ${f}`),copied:f=>{for(let d of Object.values(f??{}))l.answers.set(d.id,{width:d.width,height:d.height})}}),Lu({fidelity:r,isRemote:()=>s.remote,isBusy:()=>o.resolving,resolve:f=>o.resolve(f)})]}),u=new Pn({mount:n},{state:c,nodeViews:{...tu(i),...gf(l.answers,l)},attributes:{role:"textbox","aria-multiline":"true","aria-label":`Page text, ${Nf()}`,spellcheck:"true"},dispatchTransaction(f){this.updateState(this.state.apply(f)),f.docChanged&&!s.remote&&(o.changed(),Pf(o))},handleClickOn(f,d,h,p,m){if(!["wikilink","datelink"].includes(h.type.name)||m.button!==0||m.metaKey||m.ctrlKey||m.shiftKey||m.altKey)return!1;let g=f.nodeDOM(p)?.getAttribute?.("href");return g?(m.preventDefault(),Ye(),o.leave(g),!0):!1}});return H0(u,a),u}function H0(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 U0(n,e){return{status:t=>{ws(t),e.saver&&Pf(e.saver)},notice:(t,r)=>vf(vu(n,t,r),e.saver),leaving:(t,r)=>vf(Ss(n,t,r),e.saver),conflict:t=>Bu(e.view,t),committed:()=>{document.querySelector("[mapa-unsaved]:not([mapa-editor-notice])")?.remove(),Rf()}}}function vf(n,e){for(let t of n?.querySelectorAll?.("form")??[])t.addEventListener("submit",async r=>{r.preventDefault();let i=t.querySelector('input[name="body"]');if(i)i.value=e.deps.editor.prepare();else if(await e.flush()){let o=t.querySelector('input[name="version"]');o&&(o.value=e.version)}else{_0(n,e);return}e.stopped=!0,t.submit()});return n}function _0(n,e){e.status("failed");let t=n.querySelector("[mapa-not-sent]");t||(t=document.createElement("p"),t.setAttribute("mapa-not-sent",""),t.setAttribute("role","alert"),n.append(t)),t.textContent="Not done: what you typed could not be saved first. Check your connection and try again."}function Pf(n){document.documentElement.toggleAttribute("data-mapa-uncommitted",n.committable())}async function Y0(){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 Rf(){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 G0(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 Fs(n){n.domObserver?.flush?.()}function X0(n,e,t,r){let i=s=>{if(xi(n.state)===0)return e.leave(s);Ss(t,"uploading",()=>e.leave(s))};r.leave=i,window.addEventListener("beforeunload",s=>{xi(n.state)>0&&s.preventDefault()}),document.addEventListener("click",s=>{let l=G0(s);if(l&&s.target.closest?.("[mapa-unsaved] a[href]")){s.preventDefault(),Ye(),Fs(n),e.hold(),e.flush().then(a=>{a?location.assign(l):e.deps.ui.leaving("failed",()=>{e.stopped=!0,location.assign(l)})},()=>e.deps.ui.leaving("failed",()=>{e.stopped=!0,location.assign(l)}));return}l&&(Ye(),Fs(n),!(!e.committable()&&xi(n.state)===0)&&(s.preventDefault(),i(l)))});let o=!1;globalThis.navigation?.addEventListener?.("navigate",s=>{o=s.navigationType==="reload"}),window.addEventListener("pagehide",()=>{Ye(),Fs(n),e.closing({reloading:o})}),window.addEventListener("pageshow",s=>{s.persisted&&e.shown()}),Q0(e),Z0(n,r),ws(e.own||e.offered?"saved":"idle")}function Z0(n,e){let t={...on(n.state.schema),undo:li,redo:qn,"select-all":wu,"insert-link":oi(mi),"insert-date-pick":hi,"insert-date":pi,"insert-image":e.choose};for(let r of document.querySelectorAll("[data-mapa-command]")){let i=t[r.getAttribute("data-mapa-command")];i&&(r.disabled=!1,r.addEventListener("click",o=>{o.preventDefault(),r.closest("details")?.removeAttribute("open"),n.focus(),i(n.state,n.dispatch,n)}))}}function Q0(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){Ye();let s=await n.commit({explicit:!0});(s==="saved"||s==="merged")&&e.remove();return}n.stopped=!0;let o=await at(t.getAttribute("action"),{version:n.version});location.assign(o.json?.href??location.pathname)})}}var yw=mr(),Lf=typeof document>"u"?null:If();Lf&&(globalThis.mapaEditor=Lf);export{Jr as Fidelity,Hr as applyBody,ss as clipboardPlugin,rs as copyData,mr as createSchema,ke as docBlocks,Lf as editor,st as fidelityKey,Jo as fidelityPlugin,$n as fromMarkdown,ns as mapaType,qo as mount,is as pasteTransaction,jo as prepareSave,Rc as rebuild,tn as recordBody,Hm as reparse,yw as schema,Fn as serialise,P as serialiseDetailed,Bc as settle,jr as structureCheck,Zc as textSlice}; |
| +`).scrollIntoView()),!0)};function us(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 fs=(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),o=t.indexAfter(-1),s=us(i.contentMatchAt(o));if(!s||!i.canReplaceWith(o,o,s))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,s.createAndFill());a.setSelection(M.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},vg=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof se||r.parent.inlineContent||i.parent.inlineContent)return!1;let o=us(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let s=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,l=n.tr.insert(s,o.createAndFill());l.setSelection(k.create(l.doc,s+1)),e(l.scrollIntoView())}return!0},Ig=(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 o=t.before();if(et(n.doc,o))return e&&e(n.tr.split(o).scrollIntoView()),!0}let r=t.blockRange(),i=r&&qt(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Pg(n){return(e,t)=>{if(e.selection instanceof w&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!et(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof k||e.selection instanceof se)&&r.deleteSelection();let{$from:i}=r.selection,o=r.steps.length,s=[],l,a,c=!1,u=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),u=i.start(h)==i.pos-(i.depth-h),a=us(i.node(h-1).contentMatchAt(i.indexAfter(h-1)));let m=n&&n(i.parent,c,i);s.unshift(m||(c&&a?{type:a}:null)),l=h;break}else{if(h==1)return!1;s.unshift(null)}let f=i.pos,d=et(r.doc,f,s.length,s);if(d||(s[0]=a?{type:a}:null,d=et(r.doc,f,s.length,s)),!d)return!1;if(r.split(f,s.length,s),!c&&u&&i.node(l).type!=a){let h=r.mapping.slice(o),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}var Rg=Pg();var Lg=(n,e)=>(e&&e(n.tr.setSelection(new se(n.doc))),!0);function Bg(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,o=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||Mn(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function au(n,e,t,r){let i=e.nodeBefore,o=e.nodeAfter,s,l,a=i.type.spec.isolating||o.type.spec.isolating;if(!a&&Bg(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(s=(l=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&l.matchType(s[0]||o.type).validEnd){if(t){let h=e.pos+o.nodeSize,p=b.empty;for(let y=s.length-1;y>=0;y--)p=b.from(s[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new B(e.pos-1,h,e.pos,h,new x(p,1,0),s.length,!0)),g=m.doc.resolve(h+2*s.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Mn(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&a?null:M.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),d=f&&qt(f);if(d!=null&&d>=e.depth)return t&&t(n.tr.lift(f,d).scrollIntoView()),!0;if(c&&rn(o,"start",!0)&&rn(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=o,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let O=p.length-1;O>=0;O--)y=b.from(p[O].copy(y));let C=n.tr.step(new B(e.pos-p.length,e.pos+o.nodeSize,e.pos+g,e.pos+o.nodeSize-g,new x(y,p.length,0),0,!0));t(C.scrollIntoView())}return!0}}return!1}function cu(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,o=i.depth;for(;i.node(o).isInline;){if(!o)return!1;o--}return i.node(o).isTextblock?(t&&t(e.tr.setSelection(k.create(e.doc,n<0?i.start(o):i.end(o)))),!0):!1}}var zg=cu(-1),$g=cu(1);function uu(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o),l=s&&Kt(s,n,e);return l?(r&&r(t.tr.wrap(s,l).scrollIntoView()),!0):!1}}function ti(n,e=null){return function(t,r){let i=!1;for(let o=0;o<t.selection.ranges.length&&!i;o++){let{$from:{pos:s},$to:{pos:l}}=t.selection.ranges[o];t.doc.nodesBetween(s,l,(a,c)=>{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let u=t.doc.resolve(c),f=u.index();i=u.parent.canReplaceWith(f,f+1,n)}})}if(!i)return!1;if(r){let o=t.tr;for(let s=0;s<t.selection.ranges.length;s++){let{$from:{pos:l},$to:{pos:a}}=t.selection.ranges[s];o.setBlockType(l,a,n,e)}r(o.scrollIntoView())}return!0}}function Fg(n,e,t,r){for(let i=0;i<e.length;i++){let{$from:o,$to:s}=e[i],l=o.depth==0?n.inlineContent&&n.type.allowsMarkType(t):!1;if(n.nodesBetween(o.pos,s.pos,(a,c)=>{if(l||!r&&a.isAtom&&a.isInline&&c>=o.pos&&c+a.nodeSize<=s.pos)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function Vg(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,(o,s)=>{if(o.isAtom&&o.content.size&&o.isInline&&s>=r.pos&&s+o.nodeSize<=i.pos)return s+1>r.pos&&e.push(new Jt(r,r.doc.resolve(s+1))),r=r.doc.resolve(s+1+o.content.size),!1}),r.pos<i.pos&&e.push(new Jt(r,i))}return e}function we(n,e=null,t){let r=(t&&t.removeWhenPresent)!==!1,i=(t&&t.enterInlineAtoms)!==!1,o=!(t&&t.includeWhitespace);return function(s,l){let{empty:a,$cursor:c,ranges:u}=s.selection;if(a&&!c||!Fg(s.doc,u,n,i))return!1;if(l)if(c)n.isInSet(s.storedMarks||c.marks())?l(s.tr.removeStoredMark(n)):l(s.tr.addStoredMark(n.create(e)));else{let f,d=s.tr;i||(u=Vg(u)),r?f=!u.some(h=>s.doc.rangeHasMark(h.$from.pos,h.$to.pos,n)):f=!u.every(h=>{let p=!1;return d.doc.nodesBetween(h.$from.pos,h.$to.pos,(m,g,y)=>{if(p)return!1;p=!n.isInSet(m.marks)&&!!y&&y.type.allowsMarkType(n)&&!(m.isText&&/^\s*$/.test(m.textBetween(Math.max(0,h.$from.pos-g),Math.min(m.nodeSize,h.$to.pos-g))))}),!p});for(let h=0;h<u.length;h++){let{$from:p,$to:m}=u[h];if(!f)d.removeMark(p.pos,m.pos,n);else{let g=p.pos,y=m.pos,C=p.nodeAfter,O=m.nodeBefore,$=o&&C&&C.isText?/^\s*/.exec(C.text)[0].length:0,me=o&&O&&O.isText?/\s*$/.exec(O.text)[0].length:0;g+$<y&&(g+=$,y-=me),d.addMark(g,y,n.create(e))}}l(d.scrollIntoView())}return!0}}function He(...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 cs=He(ou,Og,Dg),iu=He(ou,Ag,Eg),Je={Enter:He(Ng,vg,Ig,Rg),"Mod-Enter":fs,Backspace:cs,"Mod-Backspace":cs,"Shift-Backspace":cs,Delete:iu,"Mod-Delete":iu,"Mod-a":Lg},fu={"Ctrl-h":Je.Backspace,"Alt-Backspace":Je["Mod-Backspace"],"Ctrl-d":Je.Delete,"Ctrl-Alt-Backspace":Je["Mod-Delete"],"Alt-Delete":Je["Mod-Delete"],"Alt-d":Je["Mod-Delete"],"Ctrl-a":zg,"Ctrl-e":$g};for(let n in Je)fu[n]=Je[n];var Wg=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform?os.platform()=="darwin":!1,ds=Wg?fu:Je;function ni(n,e=null){return function(t,r){let{$from:i,$to:o}=t.selection,s=i.blockRange(o);if(!s)return!1;let l=r?t.tr:null;return qg(l,s,n,e)?(r&&r(l.scrollIntoView()),!0):!1}}function qg(n,e,t,r=null){let i=!1,o=e,s=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=s.resolve(e.start-2);o=new ft(a,a,e.depth),e.endIndex<e.parent.childCount&&(e=new ft(e.$from,s.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=Kt(o,t,r,e);return l?(n&&Kg(n,e,l,i,t),!0):!1}function Kg(n,e,t,r,i){let o=b.empty;for(let u=t.length-1;u>=0;u--)o=b.from(t[u].type.create(t[u].attrs,o));n.step(new B(e.start-(r?2:0),e.end,e.start,e.end,new x(o,0,0),t.length,!0));let s=0;for(let u=0;u<t.length;u++)t[u].type==i&&(s=u+1);let l=t.length-s,a=e.start+t.length-(r?2:0),c=e.parent;for(let u=e.startIndex,f=e.endIndex,d=!0;u<f;u++,d=!1)!d&&et(n.doc,a,l)&&(n.split(a,l),a+=2*l),a+=c.child(u).nodeSize;return n}function du(n,e){return function(t,r){let{$from:i,$to:o,node:s}=t.selection;if(s&&s.isBlock||i.depth<2||!i.sameParent(o))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 f=b.empty,d=i.index(-1)?1:i.index(-2)?2:3;for(let y=i.depth-d;y>=i.depth-3;y--)f=b.from(i.node(y).copy(f));let h=i.indexAfter(-1)<i.node(-2).childCount?1:i.indexAfter(-2)<i.node(-3).childCount?2:3;f=f.append(b.from(n.createAndFill()));let p=i.before(i.depth-(d-1)),m=t.tr.replace(p,i.after(-h),new x(f,4-d,0)),g=-1;m.doc.nodesBetween(p,m.doc.content.size,(y,C)=>{if(g>-1)return!1;y.isTextblock&&y.content.size==0&&(g=C+1)}),g>-1&&m.setSelection(M.near(m.doc.resolve(g))),r(m.scrollIntoView())}return!0}let a=o.pos==i.end()?l.contentMatchAt(0).defaultType:null,c=t.tr.delete(i.pos,o.pos),u=a?[e?{type:n,attrs:e}:null,{type:a}]:void 0;return et(c.doc,i.pos,2,u)?(r&&r(c.split(i.pos,2,u).scrollIntoView()),!0):!1}}function hs(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,s=>s.childCount>0&&s.firstChild.type==n);return o?t?r.node(o.depth-1).type==n?jg(e,t,n,o):Jg(e,t,o):!0:!1}}function jg(n,e,t,r){let i=n.tr,o=r.end,s=r.$to.end(r.depth);o<s&&(i.step(new B(o-1,s,o,s,new x(b.from(t.create(null,r.parent.copy())),1,0),1,!0)),r=new ft(i.doc.resolve(r.$from.pos),i.doc.resolve(s),r.depth));let l=qt(r);if(l==null)return!1;i.lift(r,l);let a=i.doc.resolve(i.mapping.map(o,-1)-1);return Mn(i.doc,a.pos)&&a.nodeBefore.type==a.nodeAfter.type&&i.join(a.pos),e(i.scrollIntoView()),!0}function Jg(n,e,t){let r=n.tr,i=t.parent;for(let h=t.end,p=t.endIndex-1,m=t.startIndex;p>m;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let o=r.doc.resolve(t.start),s=o.nodeAfter;if(r.mapping.map(t.end)!=t.start+o.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(l?0:1),u+1,s.content.append(a?b.empty:b.from(i))))return!1;let f=o.pos,d=f+s.nodeSize;return r.step(new B(f-(l?1:0),d+(a?1:0),f+1,d-1,new x((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function ps(n){return function(e,t){let{$from:r,$to:i}=e.selection,o=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!o)return!1;let s=o.startIndex;if(s==0)return!1;let l=o.parent,a=l.child(s-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=b.from(c?n.create():null),f=new x(b.from(n.create(null,b.from(l.type.create(null,u)))),c?3:1,0),d=o.start,h=o.end;t(e.tr.step(new B(d-(c?3:1),h,d,h,f,1,!0)).scrollIntoView())}return!0}}var G=class{constructor(e,t,r={}){this.match=e,this.match=e,this.handler=typeof t=="string"?Hg(t):t,this.undoable=r.undoable!==!1,this.inCode=r.inCode||!1,this.inCodeMark=r.inCodeMark!==!1}};function Hg(n){return function(e,t,r,i){let o=n;if(t[1]){let s=t[0].lastIndexOf(t[1]);o+=t[0].slice(s+t[1].length),r+=s;let l=r-i;l>0&&(o=t[0].slice(s-l,s)+o,r=i)}return e.tr.insertText(o,r,i)}}var Ug=500;function pu({rules:n}){let e=new S({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,o){return hu(t,r,i,o,n,e)},handleDOMEvents:{compositionend:t=>{setTimeout(()=>{let{$cursor:r}=t.state.selection;r&&hu(t,r.pos,r.pos,"",n,e)})}}},isInputRules:!0});return e}function hu(n,e,t,r,i,o){if(n.composing)return!1;let s=n.state,l=s.doc.resolve(e),a=l.parent.textBetween(Math.max(0,l.parentOffset-Ug),l.parentOffset,null,"\uFFFC")+r;for(let c=0;c<i.length;c++){let u=i[c];if(!u.inCodeMark&&l.marks().some(p=>p.type.spec.code))continue;if(l.parent.type.spec.code){if(!u.inCode)continue}else if(u.inCode==="only")continue;let f=u.match.exec(a);if(!f||f[0].length<r.length)continue;let d=e-(f[0].length-r.length);if(!u.inCodeMark){let p=!1;if(s.doc.nodesBetween(d,l.pos,m=>{m.isInline&&m.marks.some(g=>g.type.spec.code)&&(p=!0)}),p)continue}let h=u.handler(s,f,d,t);if(h)return u.undoable&&h.setMeta(o,{transform:h,from:e,to:t,text:r}),n.dispatch(h),!0}return!1}var mu=(n,e)=>{let t=n.plugins;for(let r=0;r<t.length;r++){let i=t[r],o;if(i.spec.isInputRules&&(o=i.getState(n))){if(e){let s=n.tr,l=o.transform;for(let a=l.steps.length-1;a>=0;a--)s.step(l.steps[a].invert(l.docs[a]));if(o.text){let a=s.doc.resolve(o.from).marks();s.replaceWith(o.from,o.to,n.schema.text(o.text,a))}else s.delete(o.from,o.to);e(s)}return!0}}return!1},Bx=new G(/--$/,"\u2014",{inCodeMark:!1}),zx=new G(/\.\.\.$/,"\u2026",{inCodeMark:!1}),$x=new G(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/,"\u201C",{inCodeMark:!1}),Fx=new G(/"$/,"\u201D",{inCodeMark:!1}),Vx=new G(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/,"\u2018",{inCodeMark:!1}),Wx=new G(/'$/,"\u2019",{inCodeMark:!1});function gu(n,e,t=null){return new G(n,(r,i,o,s)=>{let l=r.doc.resolve(o),a=t instanceof Function?t(i):t;return l.node(-1).canReplaceWith(l.index(-1),l.indexAfter(-1),e)?r.tr.delete(o,s).setBlockType(o,o,e,a):null})}var he={blocks:"A page link holds words from one paragraph, heading or item. Select words in just one.",atoms:"A page link can\u2019t hold another link or a line break. Select plain words.",syntax:"A page link can\u2019t show [ or ]]. Select words without them.",blank:"Select some words to link them to a page.",context:"Linked here, the Markdown around these words would read differently: a ! before them makes an embed, and a stray ` or * pairs up. Select other words.",moved:"The selection changed. Select the words again.",date:"A date can\u2019t go here: the Markdown around it would read differently, such as a stray ` or * pairing up. Move the caret and try again."};function ri(n,e=""){let t=`[[${n}${e?"|"+e:""}]]`,r=ze(t),i=r[0];return r.length===1&&i.kind===gt&&i.source===t&&i.target===n&&i.text===e&&!i.anchor?t:null}function ii(n){let{selection:e}=n;if(e.empty)return null;let{$from:t,$to:r,from:i,to:o}=e;if(t.parent.type.spec.code||r.parent.type.spec.code)return null;if(e instanceof w)return{refuse:he.atoms};if(!(e instanceof k)||t.parent!==r.parent)return{refuse:he.blocks};let s=!0;if(n.doc.nodesBetween(i,o,f=>{f.isInline&&!f.isText&&(s=!1)}),!s||n.doc.rangeHasMark(i,o,n.schema.marks.link))return{refuse:he.atoms};let l=n.doc.textBetween(i,o),a=V(l);if(a==="")return{refuse:he.blank};if(ri("Page",a)===null)return{refuse:he.syntax};let c=l.indexOf(a),u={words:a,from:i+c,to:i+c+a.length};return bu(n,u,"Page").refuse?{refuse:he.context}:u}function _g(n,e,t){let r=t===e?"":t;return W(e)?n.nodes.datelink.create({date:e,shown:r}):n.nodes.wikilink.create({target:e,shown:r})}function yu(n){let e="",t=0,r=0;for(let i of n)i.isText?e+=i.text:i.type.name==="embed"?r++:i.type.name!=="hard_break"&&t++;return{text:e,links:t,embeds:r}}function bu(n,e,t){let r=n.tr.replaceWith(e.from,e.to,_g(n.schema,t,e.words));return ms(r.doc.resolve(e.from).parent)?{tr:r}:{refuse:he.context}}function ms(n){let e=[];n.forEach(i=>e.push(i));let t=yu(e),r=yu(Zt(n.type.schema,en(n)));return t.text===r.text&&t.links===r.links&&t.embeds===r.embeds}function xu(n,e,t){let r=ii(n);if(!r)return{refuse:he.moved};if(r.refuse)return r;if(r.words!==t)return{refuse:he.moved};if(ri(e,t===e?"":t)===null)return{refuse:he.syntax};let o=bu(n,r,e);if(o.refuse)return o;let s=o.tr.mapping.map(r.to);return{tr:o.tr.setSelection(k.create(o.tr.doc,s)).scrollIntoView()}}function oi(n){return(e,t,r)=>{let i=ii(e);if(i)return t&&r&&n(r,i),!0;let{$from:o,empty:s}=e.selection;return!s||o.parent.type.spec.code||!o.parent.inlineContent||t&&t(e.tr.insertText("[[").scrollIntoView()),!0}}function Rt(n=new Date,e=Yg()){if(e)try{let r={};for(let{type:i,value:o}of new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n))r[i]=o;return`${r.year.padStart(4,"0")}-${r.month}-${r.day}`}catch{}let t=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${t(n.getMonth()+1)}-${t(n.getDate())}`}function Yg(){return globalThis.document?.body?.getAttribute("data-zone")??""}function gs(n,e){return ti(n.nodes.heading,{level:e,source:null})}function Gg(n){return(e,t)=>{let r=null;if(!ni(n.nodes.bullet_list)(e,o=>{r=o}))return!1;if(t){let{from:o,to:s}=r.selection;r.doc.nodesBetween(o,s,(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 Xg(n){return(e,t)=>{let{$from:r}=e.selection;if(r.depth<1)return!1;if(t){let i=r.after(1),o=e.tr.insert(i,n.nodes.horizontal_rule.create());t(o.scrollIntoView())}return!0}}function Zg(n){return He(ti(n.nodes.code_block,{fence:"```",info:"",closed:!0,close:"```"}),fs)}function si(n){return(e,t)=>(t&&t(e.tr.insertText(n).scrollIntoView()),!0)}function Wn(n,e){let t=n.selection.to,r=n.doc.resolve(t);if(!r.parent.inlineContent||r.parent.type.spec.code)return null;let i=n.schema.nodes.datelink.create({date:e});for(let o of[!1,!0]){let s=n.tr,l=o?t+1:t;if(o&&s.insert(t,n.schema.text(" ")),s.insert(l,i),ms(s.doc.resolve(l).parent))return{tr:s.setSelection(k.create(s.doc,l+1)).scrollIntoView(),spaced:o}}return{refuse:he.date}}function Qg(n){return(e,t)=>{let r=Wn(e,n);return r?.tr?(t&&t(r.tr),!0):!1}}function ey(){return(n,e)=>Qg(Rt())(n,e)}function on(n){return{"insert-h1":gs(n,1),"insert-h2":gs(n,2),"insert-h3":gs(n,3),"insert-list":ni(n.nodes.bullet_list),"insert-numbered":ni(n.nodes.ordered_list),"insert-check":Gg(n),"insert-quote":uu(n.nodes.blockquote),"insert-code":Zg(n),"insert-rule":Xg(n),"insert-link":si("[["),"insert-date":ey(),"insert-paragraph":ti(n.nodes.paragraph),..._c()}}function ku(n){return{strong:we(n.marks.strong),em:we(n.marks.em),code:we(n.marks.code)}}function wu(n,e){return e&&e(n.tr.setSelection(k.create(n.doc,0,n.doc.content.size))),!0}function Su(n){return(e,t,r)=>{try{return n(e,t,r)}catch{return!1}}}var li=Su(Go),qn=Su(Xo);var ty=0;function Kn(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}var lt=class{constructor(e,{label:t,count:r,input:i=null}){this.view=e,this.count=r,this.input=i,this.id=`mapa-list-${++ty}`,this.list=Kn("ul",{id:this.id,role:"listbox","aria-label":t,"mapa-combo":""}),this.list.hidden=!0,this.live=Kn("div",{"mapa-sr":"",role:"status","aria-live":"polite"}),document.body.append(this.list,this.live),this.items=[],this.active=0,this.list.addEventListener("mousedown",o=>o.preventDefault())}get open(){return!this.list.hidden}show(e,t){this.items=e,this.active=0,this.list.replaceChildren(...e.map((i,o)=>{let s=Kn("li",{id:`${this.id}-${o}`,role:"option","aria-selected":"false"});return s.append(Kn("span",{},i.label)),i.detail&&s.append(Kn("small",{},i.detail)),s.addEventListener("click",()=>this.choose(o)),s})),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.input?this.input.getBoundingClientRect():this.view.coordsAtPos(e),r=window.visualViewport,i=r?r.offsetTop+r.height:window.innerHeight,o=this.list.offsetHeight,s=t.bottom+4,l=s+o>i?Math.max(t.top-o-4,4):s,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.input??this.view.dom;this.input&&t.setAttribute("aria-expanded",this.open?"true":"false"),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(),this.input||this.view.focus(),t&&t.run(this.view)}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 ny=new N("mapa-suggest"),ry=/\[\[([^[\]\n|#]{0,80})$/u;function ys(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=ry.exec(r);return i?{text:i[1],from:e.pos-i[0].length,to:e.pos}:null}function iy(n,e){return W(e.target)?n.nodes.datelink.create({date:e.target}):n.nodes.wikilink.create(e)}function oy(n,e){return t=>{let r=ys(t.state);if(!r)return;let i=iy(t.state.schema,{target:e});t.dispatch(t.state.tr.replaceWith(r.from,r.to,i).scrollIntoView())}}var Cu=n=>n.normalize("NFKD").replace(/\p{Mn}/gu,"").toLowerCase().trim().replace(/\s+/gu," ");function bs(n,e,t,r=i=>oy(n,i)){let i=n.text.trim(),o=[];W(i)&&o.push({label:Xt(i),detail:"Your note",run:r(i)});for(let{text:s,pending:l}of e){let a=t[nn(s,"")],c="Team page";l?c="Not written yet":a?.alias&&(c=`Old title of ${a.title}`),o.push({label:s,detail:c,run:r(s)})}return i!==""&&!W(i)&&!e.some(s=>Cu(s.text)===Cu(i))&&o.push({label:`Link \u201C${i}\u201D`,detail:"a page not written yet",run:r(i)}),o}function Mu(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 o=i.attrs,l=`[[${o.target??o.date}${o.anchor?`#^${o.anchor}`:""}${o.shown?`|${o.shown}`:""}`;e(n.tr.replaceWith(t.pos-i.nodeSize,t.pos,n.schema.text(l)))}return!0}function Ou({ask:n,resolutions:e}){let t=null,r=0,i=s=>s.length===1?"1 page":`${s.length} pages`;async function o(s,l){let a=++r,c=[];try{c=await n(l.text)}catch{}let u=await e.lookup(c.map(d=>d.text));if(a!==r)return;let f=ys(s.state);!f||f.from!==l.from||t.show(bs(f,c,u),f.from)}return new S({key:ny,view(s){t=new lt(s,{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 u=ys(a.state);if(clearTimeout(l),!u){r++,t.close();return}l=setTimeout(()=>o(a,u),30)},destroy(){t.destroy()}}},props:{handleKeyDown(s,l){return t?.keys(l)??!1},handleDOMEvents:{blur(){return t?.close(),!1}}}})}function Du(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 sy(n){return(e,t,r)=>{let i=Du(e);if(!i)return!1;let o={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 du(n.nodes.list_item,o)(e,t,r)}}function ly(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 o=i.parent.content.cut(i.parentOffset),s=r.after(-1),l=e.tr.delete(r.pos,r.end()),a=l.mapping.map(s);l.insert(a,n.nodes.paragraph.create(null,o)),t(l.setSelection(k.create(l.doc,a+1)).scrollIntoView())}return!0}}function ay(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 Tu(n,{save:e,linkPage:t=null}){let r=ku(n),i=!1,o=c=>(u,f,d)=>d?.composing?!1:c(u,f,d),s=Po({Backspace:He(mu,Mu,Pt,Uc,ts(!0)),Delete:He(Pt,ts(!1)),"Mod-Alt-ArrowRight":Qo(1),"Mod-Alt-ArrowLeft":Qo(-1),"Mod-z":li,"Shift-Mod-z":qn,"Mod-y":qn,"Mod-b":r.strong,"Mod-i":r.em,"Mod-e":r.code,"Mod-s":()=>(e(),!0),"Mod-l":t??(()=>!1),Enter:o(He(sy(n),ly(n))),"Shift-Enter":o(ay(n)),"Mod-[":hs(n.nodes.list_item),"Mod-]":ps(n.nodes.list_item)}),l=Po({...ds,Enter:o(ds.Enter)});return[new S({props:{handleKeyDown(c,u){if(u.key==="Escape")return i=!0,!1;if(u.key!=="Shift"&&u.key!=="Tab"&&(i=!1),u.key==="Tab"&&!i&&Du(c.state)){let f=(u.shiftKey?hs(n.nodes.list_item):ps(n.nodes.list_item))(c.state,c.dispatch);return u.preventDefault(),f||!0}return u.key==="Tab"&&(i=!1),!1}}}),s,l]}function xs(n){for(let e=n.depth;e>0;e--)if(n.node(e).type.name==="list_item")return e;return 0}function cy(n){let e=n.handler;return n.handler=(t,r,i,o)=>xs(t.doc.resolve(i))?null:e(t,r,i,o),n}function Au(n,e,t){return new G(n,(r,i,o,s)=>{let l=r.doc.resolve(o);if(xs(l)||l.parent.type.name!=="paragraph")return null;let a=r.tr.delete(o,s),c=a.doc.resolve(o).blockRange(),u=c&&Kt(c,e);if(!u)return null;a.wrap(c,u);let f=c.start+1;return a.setNodeMarkup(f,null,{...a.doc.nodeAt(f).attrs,...t(i)}),a})}function uy(n){return Au(/^\s{0,3}([-*+])\s$/u,n.nodes.bullet_list,e=>({bullet:e[1]}))}function fy(n){return Au(/^\s{0,3}(\d{1,9})([.)])\s$/u,n.nodes.ordered_list,e=>({number:e[1],delim:e[2]}))}function dy(n){return cy(gu(/^(#{1,6})\s$/u,n.nodes.heading,e=>({level:e[1].length,source:null})))}function hy(n){return new G(/^\[([ xX])\]\s$/u,(e,t,r,i)=>{let o=e.doc.resolve(r),s=xs(o);if(!s||o.parentOffset!==0)return null;let l=o.node(s);return e.tr.delete(r,i).setNodeMarkup(o.before(s),null,{...l.attrs,task:!0,checked:t[1]})})}function py(n){return new G(/^\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 o=i.before(1),s=i.after(1),l=e.tr.replaceWith(o,s,[n.nodes.horizontal_rule.create(),n.nodes.paragraph.create()]);return l.setSelection(k.create(l.doc,o+2))})}function my(n){return new G(/^\s{0,3}>$/u,(e,t,r,i)=>{let o=e.doc.resolve(r);if(o.parent.type.name!=="paragraph"||o.depth!==1)return null;let s=e.tr.delete(r,i),l=s.doc.resolve(r).blockRange();return l?s.wrap(l,[{type:n.nodes.blockquote,attrs:{prefix:null}}]):null})}function gy(n){return new G(/^(\s{0,3}(?:```|~~~))$/u,(e,t,r,i)=>{let o=e.doc.resolve(r);if(o.parent.type.name!=="paragraph"||o.depth!==1)return null;let s=t[1];return e.tr.delete(r,i).setBlockType(r,r,n.nodes.code_block,{fence:s,info:"",closed:!0,close:s.trimStart()})})}function yy(){return new G(/^\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 by(){return new S({appendTransaction(n,e,t){if(!n.some(o=>o.getMeta(st)?.settled)||!t.selection.empty)return null;let r=e.selection.$head.marks(),i=t.selection.$head.marks();return r.length===i.length&&r.every(o=>o.isInSet(i))?null:t.tr.setStoredMarks(r)}})}function Eu(n){return[pu({rules:[dy(n),uy(n),fy(n),hy(n),py(n),my(n),gy(n),yy()]}),by()]}var Nu="mapa-editor-notice";function Lt(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);for(let i of t)r.append(i);return r}var xy={draft:"Saved as a draft",orphan:"Not saved"};function ws(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}`)??xy[n]??"")}function ks(n,e,t={},r=!1){let i=Lt("form",{method:"post",action:n});for(let[o,s]of Object.entries(t))i.append(Lt("input",{type:"hidden",name:o,value:s}));return i.append(Lt("button",{"rst-btn":r?"primary":"",type:"submit"},e)),i}function jn(n,e,t=!1){let r=Lt("button",{"rst-btn":t?"primary":"",type:"button"},n);return r.addEventListener("click",e),r}function le(n,e,...t){ky(n);let r=Lt("div",{"mapa-unsaved":"","rst-section":"",[Nu]:"",role:"status"},Lt("p",{},e),...t);return n.before(r),r}function ky(n){n.parentNode?.querySelectorAll(`[${Nu}]`).forEach(e=>e.remove())}function vu(n,e,t){switch(e){case"gone":return le(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.",ks(`/p/${t.page}/draft/scratch`,"Save as a scratch page",{},!0),ks(`/p/${t.page}/draft/discard`,"Discard",{version:t.version}));case"orphan":return le(n,Iu,Pu());case"noBase":return le(n,"Your edit started from a version older than the 90-day history, so it cannot be merged block by block.",Lt("a",{"rst-btn":"primary",href:`/p/${t.page}/conflict`},"Choose what to keep"));case"committed":return le(n,"This was saved in another tab. What you type here is kept as a new draft.",jn("Reload",()=>location.reload(),!0));case"newer":return le(n,"Another tab had newer text, so this tab now shows it.")}}var Iu="This page was deleted before what you typed could be saved. Save it as a scratch page to keep it.";function Pu(){return ks("/scratch","Save as a scratch page",{body:""},!0)}function Ss(n,e,t){return e==="orphan"?le(n,Iu+" If you leave now, it is lost.",Pu(),jn("Leave anyway",t)):e==="uploading"?le(n,"An image is still uploading. If you leave now, it is not added.",jn("Leave anyway",t)):e==="conflict"?le(n,"Someone saved this page while you were writing. Choose below what to keep, or leave and decide on your next visit.",jn("Leave and decide later",t)):le(n,"Not saved: what you typed since the last save would be lost if you leave now.",jn("Leave anyway",t))}var Ue=new N("mapa-conflict");function Sy(n,e,t){let{emitted:r}=P(n,e);return t.map((i,o)=>{let s=r.slice(i.at,i.at+i.count);if(s.length===0){let a=r[i.at],c=a?a.pos:n.content.size;return{from:c,to:c,index:o,hunk:i}}let l=s[s.length-1];return{from:s[0].pos,to:l.pos+l.node.nodeSize,index:o,hunk:i}})}function Cy(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 Ru(n,e){return n.map(t=>({...t,from:e.map(t.from,1),to:e.map(t.to,-1)}))}function sn(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...t),r}var My=[["mine","Keep yours"],["theirs","Keep theirs"],["both","Keep both, yours first"]];function Oy(n,e,t,r){let i=sn("div",{"mapa-hunk-theirs":""}),o=$n(n,e.hunk.theirs,{trailing:!1});i.append(re.fromSchema(n).serializeFragment(o.content));let s=`mapa-hunk-${e.index}`,l=sn("div",{"mapa-hunk-choice":"",role:"group","aria-labelledby":s,contenteditable:"false"},sn("p",{id:s},sn("strong",{},"Both of you changed this."),e.hunk.theirs===""?" They removed it.":" Theirs:"));e.hunk.theirs!==""&&l.append(i);let a=sn("div",{"mapa-hunk-buttons":""});for(let[c,u]of My){let f=sn("button",{type:"button","rst-btn":t===c?"primary":"","aria-pressed":t===c?"true":"false","data-choice":c},u);f.addEventListener("click",d=>{d.preventDefault(),r(e.index,c)}),a.append(f)}return l.append(a),l}function Lu({fidelity:n,isRemote:e,isBusy:t=()=>!1,resolve:r}){return new S({key:Ue,state:{init:()=>({ranges:[],conflict:null,picked:[]}),apply(i,o,s,l){let a=i.getMeta(Ue);return a?.clear?{ranges:[],conflict:null,picked:[]}:a?.conflict?{ranges:Sy(l.doc,n,a.conflict.hunks),conflict:a.conflict,picked:[]}:a?.picked?{...o,picked:a.picked}:!i.docChanged||o.ranges.length===0?o:{...o,ranges:Ru(o.ranges,i.mapping)}}},filterTransaction(i,o){if(!i.docChanged||e()||i.getMeta(Ue))return!0;if(t())return!1;let s=Ue.getState(o).ranges;if(s.length===0)return!0;for(let l of i.steps){let a=!1;if(l.getMap().forEach((c,u)=>{a=a||Cy(s,c,u)}),a)return!1;s=Ru(s,{map:(c,u)=>l.getMap().map(c,u)})}return!0},view(i){return{update(){let o=Ue.getState(i.state).ranges.length>0;i.dom.toggleAttribute("data-mapa-conflict",o)}}},props:{handleDOMEvents:{beforeinput:(i,o)=>t()?(o.preventDefault(),!0):!1},decorations(i){let o=Ue.getState(i);if(o.ranges.length===0)return null;let s=[],l=(a,c,u)=>{let f=[...Ue.getState(a.state).picked];f[c]=u,a.dispatch(a.state.tr.setMeta(Ue,{picked:f})),o.ranges.every(d=>f[d.index])&&r(f)};for(let a of o.ranges)a.to>a.from&&i.doc.nodesBetween(a.from,a.to,(c,u)=>{u>=a.from&&c.isTextblock&&s.push(E.node(u,u+c.nodeSize,{"mapa-hunk":"",contenteditable:"false"}))}),s.push(E.widget(a.from,c=>Oy(i.schema,a,o.picked[a.index],(u,f)=>l(c,u,f)),{side:-1,stopEvent:()=>!0,ignoreSelection:!0,key:`hunk-${a.index}-${o.picked[a.index]??""}`}));return A.create(i.doc,s)}}})}function Bu(n,e){n.dispatch(n.state.tr.setMeta(Ue,e?{conflict:e}:{clear:!0}))}var ui={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6,sun:0,mon:1,tue:2,tues:2,wed:3,thu:4,thur:4,thurs:4,fri:5,sat:6},Cs={jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,sept:9,oct:10,nov:11,dec:12,january:1,february:2,march:3,april:4,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Dy=/[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/u,Ty=n=>n.replace(/\u0130/gu,"i").toLowerCase(),ai=(n,e)=>Object.hasOwn(n,e);function fi(n,e,t){let r=new Date(0);return r.setUTCFullYear(n,e-1,t),r}function ve(n){let e=n.getUTCFullYear();if(e<0||e>9999)return"";let t=(r,i=2)=>String(r).padStart(i,"0");return`${t(e,4)}-${t(n.getUTCMonth()+1)}-${t(n.getUTCDate())}`}function Ay(n){if(!W(n))return null;let[e,t,r]=n.split("-").map(Number);return fi(e,t,r)}function ci(n,e){return fi(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate()+e)}function zu(n,e,t="dmy",r=""){let i=Ay(e);if(!i)return"";let o=Ty(n).split(Dy).filter(s=>s!=="");return o.length===1?Ey(o[0],i,t,r):o.length===2?Iy(o[0],o[1],i):""}function Ey(n,e,t,r){switch(n){case"today":return ve(e);case"yesterday":return ve(ci(e,-1));case"tomorrow":return ve(ci(e,1))}if(ai(ui,n)){let i=(e.getUTCDay()-ui[n]+7)%7;return ve(ci(e,-i))}return W(n)?n:Ny(n,e,t,r)}function Ny(n,e,t,r){let i=n.includes("/")?"/":".",o=n.split(i);if(i==="."&&o.length===3&&o[2]===""&&(o=o.slice(0,2)),o.length<2||o.length>3||!o.every(u=>/^[0-9]+$/u.test(u)))return"";let s=o.length===3&&o[0].length===4;if(r!==""&&i!==r&&!s)return"";let[l,a,c]=[String(e.getUTCFullYear()),o[0],o[1]];if(s)[l,a,c]=o;else if(o.length===3&&t==="dmy")[c,a,l]=o;else if(o.length===3&&t==="mdy")l=o[2];else{if(o.length===3)return"";t==="dmy"&&([c,a]=o)}return vy(l,a,c)}function vy(n,e,t){if(n.length!==4||e.length>2||t.length>2)return"";let[r,i,o]=[n,e,t].map(Number),s=fi(r,i,o);return i<1||i>12||s.getUTCDate()!==o||s.getUTCMonth()+1!==i?"":ve(s)}function Iy(n,e,t){if(ai(ui,e)&&n==="next"){let s=(ui[e]-t.getUTCDay()+7)%7||7;return ve(ci(t,s))}if(ai(Cs,n)&&([n,e]=[e,n]),!ai(Cs,e)||!/^[+-]?[0-9]+$/u.test(n))return"";let r=Cs[e],i=Number(n);if(i<1||i>31)return"";let o=fi(t.getUTCFullYear(),r,i);return o.getUTCMonth()+1===r?ve(o):""}var _e={dialog:"Insert a date",field:"Date",placeholder:"Type a date, like next friday",help:"Arrow keys move a day or a week, Page Up and Page Down a month. Enter inserts the day, Escape closes.",previous:"Previous month",next:"Next month",today:"today",unknown:n=>`\u201C${n}\u201D isn\u2019t a date here. Try \u201Cnext friday\u201D or \u201C12 nov\u201D.`};function Fu(n){let[e,t,r]=n.split("-").map(Number),i=new Date(0);return i.setUTCFullYear(e,t-1,r),i}function Jn(n,e){let t=Fu(n);return t.setUTCDate(t.getUTCDate()+e),ve(t)||null}function di(n,e){let[t,r,i]=n.split("-").map(Number),o=new Date(0);o.setUTCFullYear(t,r-1+e,1);let s=new Date(0);return s.setUTCFullYear(o.getUTCFullYear(),o.getUTCMonth()+1,0),o.setUTCDate(Math.min(i,s.getUTCDate())),ve(o)||null}function Py(n,e=Bo()){let t=`${n.slice(0,8)}01`,r=(Fu(t).getUTCDay()-e+7)%7;return Array.from({length:42},(i,o)=>Jn(t,o-r))}function Ry(n){return kc(n)}function Ly(n,e,t=!1){switch(n){case"ArrowLeft":return Jn(e,-1);case"ArrowRight":return Jn(e,1);case"ArrowUp":return Jn(e,-7);case"ArrowDown":return Jn(e,7);case"PageUp":return di(e,t?-12:-1);case"PageDown":return di(e,t?12:1)}return null}var By=0;function z(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function $u(n){let e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true");let t=document.createElementNS("http://www.w3.org/2000/svg","polyline");return t.setAttribute("points",n),e.append(t),e}var Ms=class{constructor(e,t){this.view=e,this.today=t,this.chosen=t,this.id=`mapa-datepick-${++By}`,this.build()}build(){let e=this.id;this.root=z("div",{"mapa-datepick":"",role:"dialog","aria-label":_e.dialog,tabindex:"-1"}),this.field=z("input",{"mapa-datepick-field":"",type:"text",role:"combobox","aria-label":_e.field,"aria-expanded":"true","aria-haspopup":"grid","aria-controls":`${e}-grid`,"aria-describedby":`${e}-help`,placeholder:_e.placeholder,autocomplete:"off",autocapitalize:"off",spellcheck:"false",enterkeyhint:"done"}),this.title=z("strong",{id:`${e}-title`});let t=z("div",{"mapa-datepick-head":""});this.back=z("button",{type:"button","aria-label":_e.previous}),this.back.append($u("15 18 9 12 15 6")),this.ahead=z("button",{type:"button","aria-label":_e.next}),this.ahead.append($u("9 18 15 12 9 6")),t.append(this.title,this.back,this.ahead),this.grid=z("table",{role:"grid",id:`${e}-grid`,"aria-labelledby":`${e}-title`});let r=z("tr");for(let{name:o,letter:s}of wc())r.append(z("th",{scope:"col",abbr:o},s));this.days=z("tbody"),this.grid.append(z("thead"),this.days),this.grid.tHead.append(r),this.said=z("p",{"mapa-datepick-said":"","aria-hidden":"true"}),this.live=z("p",{"mapa-sr":"",role:"status"});let i=z("p",{"mapa-sr":"",id:`${e}-help`},_e.help);this.root.append(this.field,t,this.grid,this.said,i,this.live),this.wire()}wire(){this.root.addEventListener("mousedown",e=>{e.target!==this.field&&e.preventDefault()}),this.back.addEventListener("click",()=>this.show(di(this.chosen,-1))),this.ahead.addEventListener("click",()=>this.show(di(this.chosen,1))),this.days.addEventListener("click",e=>{let t=e.target.closest("td[data-date]");t&&this.insert(t.dataset.date)}),this.root.addEventListener("keydown",e=>this.keys(e)),this.field.addEventListener("input",()=>this.typed()),this.root.addEventListener("focusout",e=>{this.root.contains(e.relatedTarget)||this.close()}),this.place=this.place.bind(this),window.visualViewport?.addEventListener("resize",this.place),window.visualViewport?.addEventListener("scroll",this.place)}keys(e){if(e.isComposing)return;if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key==="Enter"&&e.target.closest("button")===null){if(e.preventDefault(),!this.understood)return;this.insert(this.chosen);return}if(e.altKey||e.metaKey||e.ctrlKey||(e.key==="ArrowLeft"||e.key==="ArrowRight")&&e.target===this.field&&this.field.value!=="")return;let r=Ly(e.key,this.chosen,e.shiftKey);r!=null&&(e.preventDefault(),this.show(r))}typed(){this.today=Rt();let e=V(this.field.value),t=e===""?this.chosen:zu(this.field.value,this.today,Sc());this.understood=!!t,t?(this.show(t),this.live.textContent=e===""?"":this.label(t)):(this.said.textContent=_e.unknown(e),this.live.textContent=_e.unknown(e))}label(e){let t=Number(this.today.slice(0,4));return Xt(e,t)+(e===this.today?`, ${_e.today}`:"")}show(e){if(!e)return;this.today=Rt(),this.chosen=e,this.understood=!0,this.title.textContent=Ry(e);let t=e.slice(0,7),r=Py(e).map(o=>{if(!o)return z("td",{role:"gridcell"});let s=z("td",{role:"gridcell",id:`${this.id}-${o}`,"data-date":o,"aria-label":this.label(o),"aria-selected":o===e?"true":"false"},String(Number(o.slice(8))));return o===this.today&&s.setAttribute("aria-current","date"),o.slice(0,7)!==t&&s.setAttribute("mapa-outside",""),s}),i=[];for(let o=0;o<6;o++){let s=z("tr");s.append(...r.slice(o*7,o*7+7)),i.push(s)}this.days.replaceChildren(...i),this.field.setAttribute("aria-activedescendant",`${this.id}-${e}`),this.said.textContent=this.label(e)}place(){if(!this.root.isConnected)return;let e=this.view.coordsAtPos(this.view.state.selection.to),t=window.visualViewport,r=t?t.offsetTop:0,i=t?r+t.height:window.innerHeight,o=t?t.offsetLeft+t.width:window.innerWidth,{offsetHeight:s,offsetWidth:l}=this.root,a=e.bottom+6,c=a+s<=i?a:Math.max(r+4,e.top-s-6),u=Math.max(4,Math.min(e.left-12,o-l-4));this.root.style.setProperty("top",`${c}px`),this.root.style.setProperty("left",`${u}px`)}open(){this.show(this.chosen),document.body.append(this.root),this.place(),(window.matchMedia?.("(pointer: coarse)").matches?this.root:this.field).focus({preventScroll:!0})}close(){this.closed||!this.root.isConnected||(this.closed=!0,window.visualViewport?.removeEventListener("resize",this.place),window.visualViewport?.removeEventListener("scroll",this.place),this.root.remove(),Hn===this&&(Hn=null))}cancel(){this.close(),this.view.focus()}insert(e){this.close(),this.view.focus(),Vu(this.view,e)}},Hn=null;function Vu(n,e){let t=Wn(n.state,e);t?.tr?n.dispatch(t.tr):t?.refuse&&Wu(n,t.refuse)}function Wu(n,e){document.querySelector("[mapa-datepick-note]")?.remove();let t=z("p",{"mapa-datepick-note":"",role:"status"},e);document.body.append(t);let r=n.coordsAtPos(n.state.selection.to),i=Math.max(4,Math.min(r.left-12,window.innerWidth-t.offsetWidth-4));t.style.setProperty("top",`${r.bottom+6}px`),t.style.setProperty("left",`${i}px`);let o=()=>{t.remove(),document.removeEventListener("keydown",o,!0),document.removeEventListener("pointerdown",o,!0)};setTimeout(()=>{document.addEventListener("keydown",o,!0),document.addEventListener("pointerdown",o,!0)},0),setTimeout(o,8e3)}function hi(n,e,t){let r=Rt(),i=Wn(n,r);if(!i)return!1;if(e&&t){if(Hn?.close(),i.refuse)return Wu(t,i.refuse),!0;Hn=new Ms(t,r),Hn.open()}return!0}function pi(n,e,t){return Wn(n,Rt())?(e&&t&&Vu(t,Rt()),!0):!1}var zy=/(?:^|\s)\/([A-Za-z0-9 ]{0,24})$/u,$y=[["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"],["Columns","two side by side","insert-columns-2"],["Link to a page","[[","insert-link"],["Date","choose a day","insert-date-pick"],["Today\u2019s date","today\u2019s note","insert-date"],["Image","upload an image","insert-image"]];function qu(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=zy.exec(r);return i?{text:i[1].toLowerCase().trim(),from:e.pos-i[1].length-1,to:e.pos}:null}function Ku(n={}){let e=null;return new S({view(t){let r={...on(t.state.schema),"insert-date-pick":hi,"insert-date":pi,...n};return e=new lt(t,{label:"Blocks",count:i=>i.length===1?"1 block":`${i.length} blocks`}),{update(i,o){if(i.state.doc.eq(o.doc)&&i.state.selection.eq(o.selection))return;let s=qu(i.state);if(!s){e.close();return}let l=$y.filter(([a,,c])=>r[c]&&a.toLowerCase().includes(s.text)).map(([a,c,u])=>({label:a,detail:c,run:f=>{let d=qu(f.state);d&&(f.dispatch(f.state.tr.delete(d.from,d.to)),r[u](f.state,f.dispatch,f))}}));e.show(l,s.from)},destroy(){e.destroy()}}},props:{handleKeyDown(t,r){return e?.keys(r)??!1},handleDOMEvents:{blur(){return e?.close(),!1}}}})}var Fy=new N("mapa-bubble"),Os=new WeakMap;function mi(n,e){Os.get(n)?.(e)}function Un(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Vy(n,e){let{from:t,to:r,empty:i,$from:o}=n.selection;return i?!!e.isInSet(n.storedMarks||o.marks()):n.doc.rangeHasMark(t,r,e)}function Ju(n){return(e,t)=>{let{from:r,to:i,empty:o}=e.selection,s=e.schema.marks.link;if(o)return!1;if(t){let l=e.tr.removeMark(r,i,s);n&&l.addMark(r,i,s.create({href:n})),t(l)}return!0}}function ju(n){let{selection:e}=n;return e instanceof k&&!e.empty&&!e.$from.parent.type.spec.code}var Wy=n=>n.length===1?"1 page":`${n.length} pages`;function qy(n,e,{ask:t,resolutions:r,back:i}){let o=Un("input",{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-label":"Page to link to",placeholder:"Find a page",autocomplete:"off","mapa-bubble-page":""});o.hidden=!0;let s=Un("p",{role:"status","mapa-bubble-note":""});e.append(o,s);let l=new lt(n,{label:"Pages to link to",count:Wy,input:o}),a="",c=0,u=null,f=()=>{c++,clearTimeout(u),l.close(),o.hidden=!0},d=m=>g=>{let{tr:y,refuse:C}=xu(g.state,m,a);f(),y?g.dispatch(y):s.textContent=C,i()},h=m=>ri(m,m===a?"":a)?d(m):null;async function p(){let m=++c,g=o.value,y=[];try{y=await t(g)}catch{}let C=r?await r.lookup(y.map(O=>O.text)):{};m!==c||o.hidden||l.show(bs({text:g},y,C,h).filter(O=>O.run),0)}return o.addEventListener("input",()=>{clearTimeout(u),u=setTimeout(p,30)}),o.addEventListener("keydown",m=>{if(!m.isComposing){if(m.key==="Escape"){m.preventDefault(),f(),i();return}if(l.keys(m)){m.preventDefault();return}m.key==="Enter"&&m.preventDefault()}}),o.addEventListener("blur",()=>l.close()),{open(m){return s.textContent="",m.refuse?(f(),s.textContent=m.refuse,!1):(a=m.words,o.hidden=!1,o.value=a,o.focus(),o.select(),p(),!0)},close:f,quiet(){s.textContent=""},get saying(){return s.textContent!==""},destroy(){l.destroy()}}}function Hu({makeTeamPage:n=null,ask:e=async()=>[],resolutions:t=null}={}){let r=null,i=null;return new S({key:Fy,view(o){let s=o.state.schema;r=Un("div",{"mapa-bubble":"",role:"toolbar","aria-label":"Format"}),r.hidden=!0;let l=()=>[...r.querySelectorAll("input")];r.addEventListener("mousedown",g=>{l().includes(g.target)||g.preventDefault()}),r.addEventListener("keydown",g=>{if(l().includes(g.target))return;let y=[...r.querySelectorAll("button")],C=y.indexOf(document.activeElement);g.key==="Escape"?(g.preventDefault(),o.focus()):(g.key==="ArrowRight"||g.key==="ArrowLeft")&&(g.preventDefault(),y[(C+(g.key==="ArrowRight"?1:-1)+y.length)%y.length]?.focus())});let a=[],c=(g,y,C,{mark:O=null,keeps:$=!1,title:me=""}={})=>{let ae=Un("button",{type:"button","aria-label":g,"mapa-bubble-button":""},y);return me&&(ae.title=me),ae.addEventListener("click",()=>{C(o),$||o.focus()}),r.append(ae),a.push({button:ae,mark:O}),ae};c("Bold","B",g=>we(s.marks.strong)(g.state,g.dispatch),{mark:s.marks.strong}),c("Italic","I",g=>we(s.marks.em)(g.state,g.dispatch),{mark:s.marks.em}),c("Code","<>",g=>we(s.marks.code)(g.state,g.dispatch),{mark:s.marks.code}),c("Page link","Page link",g=>h(ii(g.state)),{keeps:!0,title:"Link to a page (\u2318L)"}),c("Web link","Web link",()=>f(),{mark:s.marks.link,keeps:!0,title:"Link to a web address (\u21E7\u2318K)"}),n&&c("Make team page","Make team page",g=>n(g),{keeps:!0}),i=Un("input",{type:"url","aria-label":"Link address",placeholder:"Paste a link","mapa-bubble-field":""}),i.hidden=!0,r.append(i),document.body.append(r);let u=qy(o,r,{ask:e,resolutions:t,back:()=>o.focus()});i.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let y=i.value.trim();(y===""||Re(y))&&Ju(y)(o.state,o.dispatch),d()}else g.key==="Escape"&&(g.preventDefault(),d())});function f(){u.close(),u.quiet(),i.hidden=!1,i.value="",i.focus()}function d(){i.hidden=!0,o.focus()}function h(g){g&&(i.hidden=!0,r.hidden=!1,p(),u.open(g)||o.focus(),p())}r.openLink=f,Os.set(o,h);let p=()=>{if(!(ju(o.state)||u.saying&&!o.state.selection.empty)||!o.hasFocus()&&!r.contains(document.activeElement)){r.hidden=!0,i.hidden=!0,u.close();return}for(let{button:v,mark:F}of a)F&&v.setAttribute("aria-pressed",Vy(o.state,F)?"true":"false");r.hidden=!1;let{from:y,to:C}=o.state.selection,O=o.coordsAtPos(y),$=o.coordsAtPos(C),ae=window.matchMedia("(pointer: coarse)").matches?$.bottom+12:O.top-r.offsetHeight-8,D=Math.max(4,Math.min((O.left+$.left)/2-r.offsetWidth/2,window.innerWidth-r.offsetWidth-4));r.style.setProperty("top",`${Math.max(ae,4)}px`),r.style.setProperty("left",`${D}px`)},m=()=>setTimeout(p,0);return o.dom.addEventListener("blur",m),r.addEventListener("focusout",m),{update(g,y){g.state.selection.eq(y.selection)||u.quiet(),p()},destroy(){o.dom.removeEventListener("blur",m),Os.delete(o),u.destroy(),r.remove()}}},props:{handleKeyDown(o,s){return s.key==="F10"&&s.altKey&&r&&!r.hidden?(s.preventDefault(),r.querySelector("button")?.focus(),!0):s.key.toLowerCase()==="k"&&s.shiftKey&&(s.metaKey||s.ctrlKey)&&ju(o.state)?(s.preventDefault(),r?.openLink(),!0):!1}}})}function Uu(){return new S({props:{handlePaste(n,e){let t=e.clipboardData?.getData("text/plain")?.trim()??"";return n.state.selection.empty||!/^https?:\/\/\S+$/u.test(t)||!Re(t)?!1:Ju(t)(n.state,n.dispatch)}}})}function _u(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 Yu({title:n}){let e=t=>{let r=[];return t.descendants((i,o)=>{let s=i.attrs?.marker;s&&i.type.name!=="list_item"&&i.type.name!=="blockquote"&&r.push(E.widget(o+1,()=>_u(s,n),{side:-1,key:`anchor-${s}`,ignoreSelection:!0,stopEvent:()=>!0})),s&&(i.type.name==="list_item"||i.type.name==="blockquote")&&r.push(E.widget(o+2,()=>_u(s,n),{side:-1,key:`anchor-${s}`,ignoreSelection:!0,stopEvent:()=>!0}))}),A.create(t,r)};return new S({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 _n(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 Yn=new N("mapa-moving");function Ky(n,e){let{from:t,to:r}=n.selection,{emitted:i,body:o}=P(n.doc,e),s=[];return i.forEach((l,a)=>{let c=l.pos+l.node.nodeSize;l.pos<Math.max(r,t+1)&&c>t&&s.push({index:a,block:l})}),{chosen:s,body:o}}function jy(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 Jy(n,e,t){let r=ee(ge(n));if(r.length!==t)return null;let i=[];for(let{index:o,block:s}of e){if(!r[o]||r[o].source!==s.text)return null;i.push(o)}return i}function Gu(){return new S({key:Yn,state:{init:()=>null,apply(n,e){let t=n.getMeta(Yn);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=Yn.getState(n);return e?A.create(n.doc,e.map(t=>E.node(t.from,t.to,{"mapa-moving":""}))):null}}})}function Ie(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Hy(){let n=Ie("dialog",{"mapa-make-team":"","aria-labelledby":"mapa-make-team-title"}),e=Ie("form",{method:"dialog"}),t=Ie("h2",{id:"mapa-make-team-title"},"Make team page"),r=Ie("label",{for:"mapa-make-team-name"},"Title of the new page"),i=Ie("input",{id:"mapa-make-team-name",name:"title",required:"",autocomplete:"off","rst-input":""}),o=Ie("p",{"mapa-make-team-error":"",role:"alert"}),s=Ie("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=Ie("button",{type:"submit","rst-btn":"primary"},"Make team page"),a=Ie("button",{type:"button","rst-btn":""},"Cancel"),c=Ie("div",{"mapa-make-team-foot":""});return c.append(a,l),e.append(t,r,i,o,s,c),n.append(e),document.body.append(n),{box:n,form:e,input:i,error:o,confirm:l,cancel:a}}function Xu({saver:n,fidelity:e,post:t,notify:r}){let i=null;return l=>{let{chosen:a}=Ky(l.state,e);if(a.length===0)return!1;let c=a.map(({block:y})=>({from:y.pos,to:y.pos+y.node.nodeSize}));l.dispatch(l.state.tr.setMeta(Yn,c)),i=i??Hy();let{box:u,form:f,input:d,error:h,confirm:p,cancel:m}=i;d.value=jy(a),h.textContent="";let g=()=>{l.dispatch(l.state.tr.setMeta(Yn,null)),f.onsubmit=null,m.onclick=null,u.onclose=null,u.open&&u.close(),l.focus()};return m.onclick=g,u.onclose=g,f.onsubmit=async y=>{y.preventDefault();let C=d.value.trim(),O=await _n(p,()=>o(l,a,C));if(O.error){h.textContent=O.error,d.focus();return}g(),r(C,O.href)},u.showModal(),d.select(),!0};async function o(l,a,c){let u=await n.commit({explicit:!0});if(!["none","saved","merged"].includes(u)||!n.page)return{error:"Your note could not be saved just now, so nothing was moved. Try again."};let{emitted:f}=P(l.state.doc,e),d=s(l,a),h=d&&Jy(n.saved,d,f.length);if(!h)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:h.map(String),grammar:String(fr)})}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 s(l,a){let{emitted:c}=P(l.state.doc,e),u=[],f=0;for(let{block:d}of a){let h=c.findIndex((p,m)=>m>=f&&p.text===d.text);if(h<0)return null;u.push({index:h,block:c[h]}),f=h+1}return u}}function Uy(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 _y(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",o=>o.preventDefault()),i.addEventListener("click",o=>{o.preventDefault();let s=Uy(n.state.doc,e());if(!s?.node.attrs.task)return;let l=s.node.attrs.checked!==" "?" ":"x";n.dispatch(n.state.tr.setNodeMarkup(s.pos,null,{...s.node.attrs,checked:l}))}),i}function Zu(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,(o,s)=>_y(o,s,t),{side:-1,key:i,ignoreSelection:!0,stopEvent:()=>!0}))}),A.create(n,e)}function Qu(){return new S({state:{init:(n,e)=>Zu(e.doc),apply:(n,e)=>n.docChanged?Zu(n.doc):e},props:{decorations(n){return this.getState(n)}}})}function ef(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function tf(n){return new S({view(e){let{place:t,row:r}=Yy(e,n);return{update:t,destroy:()=>r.remove()}}})}function Yy(n,{makeTeamPage:e=null,linkPage:t=null,image:r=null}={}){let i=n.state.schema,o=on(i),s=ef("div",{"mapa-accessory":"",role:"toolbar","aria-label":"Writing"});s.hidden=!0;let l=(f,d,h)=>{let p=ef("button",{type:"button","aria-label":f},d);p.addEventListener("mousedown",m=>m.preventDefault()),p.addEventListener("click",()=>{h(n.state,n.dispatch,n),document.activeElement?.closest?.("[mapa-bubble]")||n.focus()}),s.append(p)};l("Link to a page","[[",t??si("[[")),l("Blocks","/",si("/")),l("Bold","B",we(i.marks.strong)),l("Italic","I",we(i.marks.em)),l("List","\u2022",o["insert-list"]),l("Checklist","\u2610",o["insert-check"]),r&&l("Image","Image",r),e&&l("Make team page","Team page",(f,d,h)=>e(h)),document.body.append(s);let a=window.matchMedia("(pointer: coarse) and (max-width: 799px)"),c=window.visualViewport,u=()=>{let f=a.matches&&n.hasFocus();s.hidden=!f;let d=c?window.innerHeight-c.height-c.offsetTop:0;document.documentElement.toggleAttribute("data-mapa-keyboard",f&&d>80),f&&s.style.setProperty("bottom",`${Math.max(d,0)}px`)};return n.dom.addEventListener("focus",u),n.dom.addEventListener("blur",()=>setTimeout(u,0)),c?.addEventListener("resize",u),c?.addEventListener("scroll",u),a.addEventListener?.("change",u),{place:u,row:s}}function Gy(n=(t,r)=>fetch(t,r),e=1e4){return async(t,r,{keepalive:i=!1}={})=>{let o=new URLSearchParams;for(let[a,c]of Object.entries(r))for(let u of[].concat(c))o.append(a,u);let s=i?null:new AbortController,l=s?setTimeout(()=>s.abort(),e):null;try{let a=await n(t,{method:"POST",body:o,credentials:"same-origin",keepalive:i,headers:{Accept:"application/json"},signal:s?.signal}),c=null;try{c=await a.json()}catch{}return{status:a.status,json:c}}finally{l!==null&&clearTimeout(l)}}}var at=Gy();var Zy="Title, renames the page";function Gn(n){return n.split(/\s+/u).filter(Boolean).join(" ")}var Ds=class{constructor(e,t,r){this.title=e,this.action=t,this.deps=r,this.pending=null,this.listeners=[]}on(e){this.listeners.push(e)}emit(e){for(let t of this.listeners)t(e)}async rename(e,t){let r=Gn(e);if(this.pending!==null)return"busy";if(r==="")return"empty";if(r===this.title)return"unchanged";this.pending=r,this.emit({kind:"pending",title:r,source:t});let i=this.deps.wait(650),o=null;try{o=await this.deps.post(this.action,{title:r})}catch{}return await i,this.pending=null,o?.status===200&&o.json?.title?(this.title=o.json.title,this.emit({kind:"renamed",source:t,...o.json}),"renamed"):o?.status===422&&o.json?.error?(this.emit({kind:"refused",source:t,typed:e,error:o.json.error,taken:o.json.taken??""}),"refused"):(this.emit({kind:"failed",source:t,typed:e}),"failed")}closing(e){try{this.deps.post(this.action,{title:e},{keepalive:!0})?.catch?.(()=>{})}catch{}}async updateLinks(){let e=this.action.replace(/\/rename$/u,"/links"),t=null;try{t=await this.deps.post(e,{})}catch{}return t?.status===200?t.json?.notice??null:null}};function pe(n,e={},...t){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return r.append(...t),r}function nf(n){n.focus();let e=document.createRange();e.selectNodeContents(n),e.collapse(!1);let t=getSelection();t.removeAllRanges(),t.addRange(e)}function rf({post:n,hooks:e={}}){let t=document.querySelector("h1[mapa-title][mapa-rename]"),r=t?.querySelector("[mapa-title-text]");if(!r)return null;let i=new Ds(r.textContent,t.getAttribute("mapa-rename"),{post:n,wait:l=>new Promise(a=>setTimeout(a,l))}),o=pe("div",{"mapa-title-note":"",id:"mapa-title-note",role:"status"});t.after(o);let s=Qy(i.action);return e0(t,r,i),s&&t0(s,i),i.on(l=>r0(l,{heading:t,text:r,field:s,note:o,renamer:i,hooks:e})),i}function Qy(n){let e=document.querySelector("form[estilo-bar-title]"),t=e?.querySelector("[estilo-bar-title-input]");return!t||new URL(e.action,location.href).pathname!==n?null:{form:e,input:t,button:e.querySelector("[estilo-bar-title-submit]")}}function e0(n,e,t){e.setAttribute("contenteditable","true"),e.setAttribute("role","textbox"),e.setAttribute("aria-label",Zy),e.setAttribute("aria-describedby","mapa-title-note"),e.setAttribute("spellcheck","false"),n.addEventListener("mousedown",l=>{l.target!==n||l.button!==0||(l.preventDefault(),nf(e))});let r=!1,i=null,o=async l=>{let a=e.textContent,c=Gn(a);if(t.pending!==null)return;if(c===""||c===t.title){if(l==="enter"&&c==="")return;e.removeAttribute("aria-invalid"),e.textContent!==t.title&&(e.textContent=t.title),l==="enter"&&e.blur();return}if(l==="blur"&&c===i)return;let u=await t.rename(a,"h1");i=u==="refused"?c:null,u==="renamed"&&document.activeElement===e&&(r=!0,e.blur(),r=!1)};e.addEventListener("keydown",l=>{if(l.isComposing||l.keyCode===229)return;let a=l.key==="s"&&(l.metaKey||l.ctrlKey);if(l.key==="Enter"||a)l.preventDefault(),o("enter");else if(l.key==="Escape"){if(l.preventDefault(),t.pending!==null)return;r=!0,i=null,e.textContent=t.title,e.removeAttribute("aria-invalid"),e.blur(),r=!1,n0(n)}});let s=!1;e.addEventListener("blur",()=>{if(!r){if(!document.hasFocus()||document.visibilityState==="hidden"){s=!0;return}o("blur")}}),e.addEventListener("focus",()=>{s=!1}),window.addEventListener("focus",()=>{s&&document.activeElement===document.body&&nf(e)}),window.addEventListener("pagehide",()=>{let l=t.pending??Gn(e.textContent);l===""||l===t.title||t.pending===null&&l===i||t.closing(l)}),e.addEventListener("beforeinput",l=>{let a=/^(insertParagraph|insertLineBreak)$/u.test(l.inputType);(t.pending!==null||a||/^format/u.test(l.inputType))&&l.preventDefault(),a&&!l.isComposing&&t.pending===null&&o("enter")}),e.addEventListener("paste",l=>{if(l.preventDefault(),t.pending!==null)return;let a=Gn(l.clipboardData?.getData("text/plain")??"");document.execCommand("insertText",!1,a)}),e.addEventListener("drop",l=>l.preventDefault())}function t0({form:n,input:e,button:t},r){n.addEventListener("submit",async i=>{if(i.preventDefault(),r.pending!==null)return;let o=Gn(e.value);if(o===""||o===r.title){e.value=r.title,e.removeAttribute("aria-invalid"),e.blur();return}let s=()=>r.rename(e.value,"header");(t?await _n(t,s):await s())==="renamed"&&e.blur()})}function n0(n){let e=n.nextElementSibling;e?.querySelector('[role="alert"]')&&e.replaceChildren()}function r0(n,e){let{text:t,field:r,note:i}=e,o=n.source==="h1";if(n.kind==="pending"){t.setAttribute("aria-readonly","true"),t.setAttribute("aria-busy","true"),o||(t.textContent=n.title),r&&(r.input.readOnly=!0,o&&(r.input.value=n.title)),i.replaceChildren(pe("p",{},pe("span",{"rst-spin":"","aria-hidden":"true"}),"Renaming\u2026"));return}if(t.removeAttribute("aria-readonly"),t.removeAttribute("aria-busy"),r&&(r.input.readOnly=!1),n.kind==="renamed")return i0(n,e);let s=o?t:r?.input;o&&r&&(r.input.value=e.renamer.title),!o&&t.textContent!==e.renamer.title&&(t.textContent=e.renamer.title),s?.setAttribute("aria-invalid","true");let l=n.kind==="refused"?n.error:"Not renamed: the title could not be saved. Check your connection and try again.",a=pe("p",{role:"alert"},l);n.taken&&a.append(" ",pe("a",{href:n.taken},"Open the page with that title")),i.replaceChildren(a)}function i0(n,{text:e,field:t,note:r,renamer:i,hooks:o}){let s=n.title;e.removeAttribute("aria-invalid"),e.textContent!==s&&(e.textContent=s),t&&(t.input.removeAttribute("aria-invalid"),t.input.value=s,t.input.defaultValue=s,t.input.dispatchEvent(new Event("input",{bubbles:!0}))),document.title=`${s} \xB7 Mapa`;for(let l of document.querySelectorAll("[mapa-side] a[mapa-side-page]")){if(new URL(l.href).pathname!==n.href)continue;let a=l.querySelector("[mapa-side-label]");a&&(o0(l.closest("[mapa-side-row]")?.querySelector("[mapa-row-more]"),a.textContent,s),a.textContent=s)}s0(n.aliases??[]),o.renamed?.({title:s,from:n.from,to:n.to}),o.refresh?.(),r.replaceChildren(...l0(n,r,i,o))}function o0(n,e,t){let r=n?.getAttribute("aria-label");r?.endsWith(e)&&n.setAttribute("aria-label",r.slice(0,r.length-e.length)+t)}function s0(n){let e=document.querySelector("[mapa-doc-kicker]");if(!e)return;let t=e.querySelector("[mapa-also]");if(n.length===0){t?.remove();return}t||(t=pe("span",{"mapa-also":""}),e.insertBefore(t,e.querySelector("[mapa-actions]"))),t.textContent=`Also called ${n.join(", ")}`}function l0(n,e,t,r){if(!(n.links>0))return[pe("p",{},"Renamed. The old title still leads here.")];let i=pe("button",{"rst-btn":"primary",type:"button"},"Update links"),o=pe("button",{"rst-btn":"",type:"button"},"Not now");return i.addEventListener("click",async()=>{let s=await _n(i,()=>t.updateLinks());if(s===null){e.querySelector("[mapa-title-links-failed]")?.remove(),e.append(pe("p",{role:"alert","mapa-title-links-failed":""},"Links not updated. Check your connection and try again."));return}e.replaceChildren(pe("p",{},s)),r.refresh?.()}),o.addEventListener("click",()=>e.replaceChildren()),[pe("p",{},`Renamed. ${n.count} you can edit link here by an old title. Update them to "${n.title}"? It's an edit by you; other people's private notes keep working.`),i,o]}function sf(){return new S({props:{handleDOMEvents:{mousedown:(n,e)=>e.target===n.dom&&c0(n,e.clientY)&&of(n,e)}},view(n){let e=n.dom.parentElement,t=n.dom.closest("[mapa-main]");if(!t)return{};let r=i=>{(i.target===t||i.target===e)&&of(n,i)};return t.addEventListener("mousedown",r),{destroy:()=>t.removeEventListener("mousedown",r)}}})}function of(n,e){if(n.composing||!n.editable||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;e.preventDefault();let t=e.shiftKey?n.state.selection.anchor:Ts(n,e.clientX,e.clientY);return lf(n,t,Ts(n,e.clientX,e.clientY)),n.focus(),a0(n,t,e),!0}function a0(n,e,t){let r=o=>{if(!(o.buttons&1))return i();Math.hypot(o.clientX-t.clientX,o.clientY-t.clientY)<4||lf(n,e,Ts(n,o.clientX,o.clientY))},i=()=>{window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)}function lf(n,e,t){let r=n.state.doc,i=s=>As(s,0,r.content.size),o=k.between(r.resolve(i(e)),r.resolve(i(t)));o.eq(n.state.selection)||n.dispatch(n.state.tr.setSelection(o))}function af(n){let e=n.state.doc,t=n.nodeDOM(0),r=n.nodeDOM(e.content.size-e.lastChild.nodeSize),i=n.dom.getBoundingClientRect();return{box:i,top:t?.getBoundingClientRect?.().top??i.top,bottom:r?.getBoundingClientRect?.().bottom??i.bottom}}function c0(n,e){return e>=af(n).bottom}function Ts(n,e,t){let r=M.atEnd(n.state.doc).head,{box:i,top:o,bottom:s}=af(n);if(t>=s)return r;let l=n.posAtCoords({left:As(e,i.left+1,i.right-1),top:As(t,o+1,s-1)});return l?l.pos:r}function As(n,e,t){return Math.min(Math.max(n,e),t)}var u0="Describe this image for people who can't see it",f0=240,d0=120;function h0(n,e=5,t=40){let i=n.trim().split(/\s+/u).slice(0,e).join(" ");return i.length>t&&(i=i.slice(0,t).trimEnd()),i.length<n.trim().length?`${i}\u2026`:i}function p0(n){return n?`Alt text: ${h0(n)}, edit`:"Alt text: describe this image"}function m0(n){return Vi(n.replace(/\s*[\r\n]+\s*/gu," ")).trim()}function g0(n){let e=0,t="";for(let r of n){let i=r.codePointAt(0);if(e+=i<128?1:i<2048?2:i<65536?3:4,e>ur)return t;t+=r}return n}function cf(n,e){let t=document.createElement("button");return t.type="button",t.draggable=!1,t.setAttribute("mapa-alt-badge",""),t.textContent="ALT",Ns(t,n),t.addEventListener("mousedown",r=>r.preventDefault()),t.addEventListener("click",r=>{r.preventDefault(),e()}),t}function Ns(n,e){n.setAttribute("mapa-alt-badge",e?"set":"missing"),n.setAttribute("aria-label",p0(e)),n.tabIndex=e?-1:0}var Bt=null,y0=0;function Ye(){Bt?.finish(!0,!1)}function uf(n){return Bt?.frame!==n?!1:(Bt.finish(!0,!0),!0)}function ff(n){let e=Bt;e?.frame===n&&queueMicrotask(()=>{let t=!document.activeElement||document.activeElement===document.body;e.finish(!0,t)})}function df(n,e,t,{from:r="bubble",...i}={}){Ye();let o=n.state.doc.nodeAt(t());if(o?.type.name!=="image")return null;let s=new Es(n,e,t,r,i);return s.show(o.attrs.alt??""),s}var Es=class{constructor(e,t,r,i,o){Object.assign(this,{view:e,frame:t,getPos:r,from:i,hooks:o,closed:!1}),this.id=s=>s?.type.name==="image"?s.attrs.id:null,this.image=this.id(e.state.doc.nodeAt(r()))}show(e){let t=this.frame.getBoundingClientRect();this.inset=t.width>=f0&&t.height>=d0;let r=document.createElement("div");r.setAttribute("mapa-alt",this.inset?"inset":"popover"),r.draggable=!1;let i=`mapa-alt-${++y0}`,o=document.createElement("label");o.htmlFor=i,o.textContent=u0;let s=document.createElement("textarea");Object.assign(s,{id:i,rows:1,value:e}),s.setAttribute("autocomplete","off"),s.setAttribute("enterkeyhint","done"),r.append(o,s),Object.assign(this,{wrap:r,text:s,before:e}),this.listen(),this.frame.append(r),this.parent=this.frame.parentNode,this.frame.setAttribute("mapa-alt-open",""),this.draggable=this.frame.draggable,this.frame.draggable=!1,Bt=this,this.inset||b0(r),this.grow(),s.focus({preventScroll:!0}),s.setSelectionRange(s.value.length,s.value.length),r.scrollIntoView?.({block:"nearest"})}listen(){let{text:e,wrap:t}=this;e.addEventListener("keydown",r=>this.key(r)),t.addEventListener("mousedown",r=>{r.target!==e&&(r.preventDefault(),e.focus({preventScroll:!0}))}),e.addEventListener("input",()=>{let r=g0(e.value.replace(/[ \t]*\r?\n[ \t]*/gu," "));if(r!==e.value){let i=Math.min(e.selectionStart,r.length);e.value=r,e.setSelectionRange(i,i)}this.grow()}),e.addEventListener("blur",()=>{document.hasFocus()&&setTimeout(()=>{if(this.frame.isConnected&&this.frame.parentNode!==this.parent&&document.activeElement===document.body){this.parent=this.frame.parentNode,e.focus({preventScroll:!0});return}this.finish(!0,!1)},0)}),this.returned=()=>setTimeout(()=>{document.activeElement!==e&&this.finish(!0,!1)},0),window.addEventListener("focus",this.returned)}key(e){e.isComposing||e.keyCode===229||(e.key==="Enter"||e.key==="Tab"?(e.preventDefault(),this.finish(!0,!0)):e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),this.finish(!1,!0)):e.key.toLowerCase()==="s"&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),this.finish(!0,!0),this.hooks.save?.()))}grow(){let{text:e}=this;e.style.removeProperty("height");let t=e.scrollHeight+2;if(this.inset){let r=this.wrap.offsetHeight-e.offsetHeight;t=Math.min(t,Math.max(36,this.frame.clientHeight-r))}e.style.setProperty("height",`${t}px`)}finish(e,t){if(this.closed)return;this.closed=!0,Bt===this&&(Bt=null),window.removeEventListener("focus",this.returned),this.wrap.remove(),this.frame.removeAttribute("mapa-alt-open"),this.frame.draggable=this.draggable,this.hooks.closed?.();let r=this.place(),i=m0(this.text.value),o=e&&r!==null&&i!==this.before;o&&this.view.dispatch(this.view.state.tr.setNodeAttribute(r,"alt",i)),t&&this.refocus(o?this.place(r):r),o&&!(t&&this.from==="badge")&&this.hooks.say?.(i?`Image: ${i}`:"Image with no description")}place(e=null){let{doc:t}=this.view.state,r=o=>typeof o=="number"&&o>=0&&o<t.content.size&&this.id(t.nodeAt(o))===this.image;if(r(e))return e;let i=null;try{i=this.getPos()}catch{i=null}return r(i)||(i=null,t.descendants((o,s)=>(i===null&&this.id(o)===this.image&&(i=s),i===null))),i}refocus(e){let{view:t}=this,i=(e===null?null:t.nodeDOM(e))?.querySelector?.("[mapa-alt-badge]");if(this.from==="badge"&&i?.isConnected){i.focus();return}if(e!==null){let o=this.from==="upload"?k.near(t.state.doc.resolve(e+1)):w.create(t.state.doc,e);t.dispatch(t.state.tr.setSelection(o))}t.focus()}};function b0(n){let e=n.getBoundingClientRect(),t=document.documentElement.clientWidth-8,r=e.right>t?t-e.right:e.left<8?8-e.left:0;r&&n.style.setProperty("inset-inline-start",`${r}px`)}var x0=32,yi=class{constructor(e={},t=null){this.known=new Map(Object.entries(e??{})),this.ask=t,this.asked=new Set,this.waiting=new Set,this.watchers=new Set,this.timer=null}answer(e){let t=this.known.get(e);return t||(this.ask&&mn(e)&&!this.asked.has(e)&&(this.waiting.add(e),this.soon()),{available:!1})}set(e,t){this.known.set(e,{available:!0,...t}),this.tell(new Set([e]))}soon(){this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},0))}async flush(){let e=[...this.waiting].slice(0,x0);if(e.length===0)return;for(let i of e)this.waiting.delete(i),this.asked.add(i);this.waiting.size&&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,o]of Object.entries(t??{}))this.known.set(i,o),r.add(i);this.tell(r)}tell(e){if(e.size)for(let t of this.watchers)t(e)}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}};function hf(n){return n?`Image: ${n}`:"Image with no description"}function pf(n){let e=re.renderSpec(document,n.type.spec.toDOM(n)).dom;return e.setAttribute("aria-label",e.nodeName==="IMG"?hf(n.attrs.alt):`${hf(n.attrs.alt)}, not available`),e}var k0=2e3,vs=new WeakMap,Is=class{constructor(e,t,r,i,o={}){Object.assign(this,{node:e,answers:t,view:r,getPos:i,hooks:o}),this.dom=document.createElement("span"),this.dom.setAttribute("mapa-image-frame",""),vs.set(this.dom,this),this.paint()}paint(){this.dom.replaceChildren(),this.inner=pf(this.node),this.drawn=Ps(this.answers.answer(this.node.attrs.id)),this.retried=!1,this.dom.append(this.inner),this.badge=null,this.inner.nodeName==="IMG"&&(this.badge=cf(this.node.attrs.alt,()=>this.describe("badge")),this.dom.append(this.badge),this.listen())}listen(){let e=this.inner;e.addEventListener("error",()=>{this.retried||(this.retried=!0,setTimeout(()=>{let t=e.getAttribute("src");e.setAttribute("src",`${t}?again=1`)},k0))})}describe(e){if(!this.view||!this.getPos||e==="badge"&&uf(this.dom))return null;let t=this.getPos();if(Ye(),!this.dom.isConnected){let o=vs.get(this.view.nodeDOM(t));return o&&o!==this&&o.node.attrs.id===this.node.attrs.id?o.describe(e):null}let{say:r,save:i}=this.hooks;return df(this.view,this.dom,this.getPos,{from:e,say:r,save:i,closed:()=>this.closed()})}closed(){this.pending&&(this.pending=!1,this.paint())}update(e){if(e.type!==this.node.type||e.attrs.id!==this.node.attrs.id)return!1;let t=e.attrs.alt!==this.node.attrs.alt;if(this.node=e,Ps(this.answers.answer(e.attrs.id))!==this.drawn)return this.dom.hasAttribute("mapa-alt-open")?this.pending=!0:this.paint(),!0;if(t){let r=pf(e);for(let i of["alt","aria-label"])r.hasAttribute(i)&&this.inner.setAttribute(i,r.getAttribute(i));this.badge&&Ns(this.badge,e.attrs.alt)}return!0}selectNode(){this.dom.setAttribute("mapa-image-selected","")}deselectNode(){this.dom.removeAttribute("mapa-image-selected")}stopEvent(e){return!!e.target?.closest?.("[mapa-alt-badge], [mapa-alt]")}ignoreMutation(){return!0}destroy(){ff(this.dom)}};function bi(n,e,t){let r=n.nodeDOM(e);return r?vs.get(r)?.describe(t)??null:null}function gf(n,e={}){return{image:(t,r,i)=>new Is(t,n,r,i,e)}}var Ps=n=>n?.available?"image":"box",gi=new N("mapa-images");function mf(n,e,t,r,i){return n.nodesBetween(e,t,(o,s)=>{if(!o.isTextblock)return!0;let l=zl(o);return o.forEach((a,c)=>{if(a.type.name!=="image")return;let u={"data-mapa-drawn":Ps(r.answer(a.attrs.id))};l&&(u.class="alone");let f=s+1+c;i.push(E.node(f,f+1,u))}),!1}),i}function w0(n,e){n.mapping.maps.forEach((t,r)=>{t.forEach((i,o,s,l)=>{let a=n.mapping.slice(r+1),c=Math.max(0,a.map(s,-1)-1),u=Math.min(n.doc.content.size,a.map(l,1)+1),f=n.doc.resolve(c),d=n.doc.resolve(u);e(f.depth?f.before(1):c,d.depth?d.after(1):u)})})}function yf(n){let e=t=>A.create(t,mf(t,0,t.content.size,n,[]));return new S({key:gi,state:{init:(t,r)=>e(r.doc),apply(t,r){if(t.getMeta(gi))return e(t.doc);if(!t.docChanged)return r;let i=r.map(t.mapping,t.doc);return w0(t,(o,s)=>{i=i.remove(i.find(o,s)),i=i.add(t.doc,mf(t.doc,o,s,n,[]))}),i}},view(t){return{destroy:n.watch(()=>t.dispatch(t.state.tr.setMeta(gi,!0)))}},props:{decorations:t=>gi.getState(t)}})}var xf=["image/png","image/jpeg","image/gif","image/webp"],zs=xf.join(","),kf=10*1024*1024,bf=4096,Pe=new N("mapa-uploads"),ln={type:"Mapa takes PNG, JPEG, GIF and WebP images.",svg:"Mapa takes PNG, JPEG, GIF and WebP images, not SVG.",size:"An image can be at most 10 MB.",offline:"Connection unavailable.",failed:"The image could not be stored. Try again."};function S0(n){return n.type==="image/svg+xml"||/\.svg$/iu.test(n.name??"")?ln.svg:xf.includes(n.type)?n.type!=="image/jpeg"&&n.size>kf?ln.size:null:ln.type}function C0(n){if(n[0]!==255||n[1]!==216)return null;let e=1;for(let t=2;t+4<=n.length;){if(n[t]!==255)return null;let r=n[t+1],i=n[t+2]<<8|n[t+3];if(r===225&&(e=M0(n,t+4,t+2+i)??e),r>=192&&r<=207&&![196,200,204].includes(r)){let o=n[t+5]<<8|n[t+6];return{width:n[t+7]<<8|n[t+8],height:o,orientation:e}}t+=2+i}return null}function M0(n,e,t){if(String.fromCharCode(...n.slice(e,e+6))!=="Exif\0\0")return null;let i=e+6,o=n[i]===73,s=c=>o?n[c]|n[c+1]<<8:n[c]<<8|n[c+1],a=i+(c=>o?(n[c]|n[c+1]<<8|n[c+2]<<16)+n[c+3]*16777216:n[c]*16777216+(n[c+1]<<16|n[c+2]<<8|n[c+3]))(i+4);if(a+2>t)return null;for(let c=0;c<s(a);c++){let u=a+2+c*12;if(u+12>t)return null;if(s(u)===274)return s(u+8)}return null}async function O0(n){if(n.type!=="image/jpeg"||typeof createImageBitmap!="function")return n;let e;try{e=C0(new Uint8Array(await n.slice(0,256*1024).arrayBuffer()))}catch{return n}if(!e||Math.max(e.width,e.height)<=bf)return n;let t=bf/Math.max(e.width,e.height),r=e.orientation>=5,i=Math.round((r?e.height:e.width)*t),o=Math.round((r?e.width:e.height)*t);try{let s=await createImageBitmap(n,{imageOrientation:"from-image",resizeWidth:i,resizeHeight:o,resizeQuality:"high"}),l=document.createElement("canvas");l.width=s.width,l.height=s.height,l.getContext("2d").drawImage(s,0,0),s.close?.();let a=await new Promise(c=>l.toBlob(c,"image/jpeg",.9));return a?new File([a],n.name,{type:"image/jpeg"}):n}catch{return n}}function D0(n,e){return new Promise(t=>{let r=new XMLHttpRequest;r.open("POST","/images"),r.setRequestHeader("Accept","application/json"),r.responseType="json",r.upload.addEventListener("progress",o=>{o.lengthComputable&&e(o.loaded/o.total)}),r.addEventListener("load",()=>t({status:r.status,json:r.response})),r.addEventListener("error",()=>t({status:0,json:null})),r.addEventListener("abort",()=>t({status:0,json:null}));let i=new FormData;i.append("file",n,n.name||"image"),r.send(i)})}function T0(n){let e=document.createElement("span");e.setAttribute("mapa-upload",""),e.setAttribute("role","group"),e.setAttribute("aria-label",`Uploading ${n.name}`),e.contentEditable="false";let t=document.createElement("span");t.setAttribute("mapa-upload-name",""),t.textContent=n.name;let r=document.createElement("progress");r.max=1,r.setAttribute("aria-label",`Uploading ${n.name}`);let i=document.createElement("span");return i.setAttribute("mapa-upload-why",""),i.hidden=!0,e.append(t,r,i),{group:e,bar:r,why:i}}function A0(n,e,t){let r=!!e.getMeta("history$");for(let i of n.values()){if(i.dropped)continue;E0(i,e);let o=e.mapping.mapResult(i.pos,-1),s=i.pos;if(i.pos=o.pos,!o.deletedAcross||i.lost)continue;let l=e.getMeta("mapa-applied")?v0(t,e.doc,s,o.pos):null;l!==null?i.pos=l:r?N0(i):i.lost=!0}return n}function E0(n,e){if(!n.replacing)return;let t=e.mapping.mapResult(n.replacing.pos,1);n.replacing.pos=t.pos,t.deleted&&(n.replacing.gone=!0)}function N0(n){n.dropped=!0,queueMicrotask(()=>n.onDrop?.())}function v0(n,e,t,r){let i=n.resolve(t);if(!i.parent.inlineContent)return null;let o=null;return e.nodesBetween(r,Math.min(e.content.size,r+2),(s,l)=>(o===null&&s.isTextblock&&(o=l+1+Math.min(i.parentOffset,s.content.size)),o===null)),o}function wf(){return new S({key:Pe,state:{init:()=>({uploads:new Map,moves:0}),apply(n,e,t){let r=n.getMeta(Pe),i=A0(e.uploads,n,t.doc);r?.add&&i.set(r.add.id,r.add),r?.remove&&i.delete(r.remove);let o=e.moves+(n.selectionSet||n.docChanged?1:0);return{uploads:i,moves:o}}},props:{decorations(n){let{uploads:e}=Pe.getState(n),t=[...e.values()].filter(r=>!r.dropped);return A.create(n.doc,t.map(r=>E.widget(Math.min(r.lost?n.doc.content.size-1:r.pos,n.doc.content.size),r.dom.group,{key:r.id,side:-1})))}}})}var I0=0;function xi(n){let e=Pe.getState(n);return e?[...e.uploads.values()].filter(t=>!t.dropped).length:0}async function Ls(n,e,t,r){for(let i of e){let o=Cf(n,i,t);t=await $s(n,o,r)??o.pos}}function Sf(n,e,t,r,i=null){let o=n.state.doc.nodeAt(e);if(o?.type.name!=="image"||i!==null&&o.attrs.id!==i)return Promise.resolve();let s=Cf(n,t,e+1,{pos:e,id:o.attrs.id,alt:o.attrs.alt});return $s(n,s,r)}function Cf(n,e,t,r=null){let o={id:`upload-${++I0}`,file:e,name:e.name||"image",pos:t,replacing:r};return o.dom=T0(o),o.dom.bar.value=0,n.dispatch(n.state.tr.setMeta(Pe,{add:o}).setMeta("addToHistory",!1)),o.moves=Pe.getState(n.state).moves,o}function Bs(n,e){n.dispatch(n.state.tr.setMeta(Pe,{remove:e.id}).setMeta("addToHistory",!1))}async function $s(n,e,t){let r=S0(e.file);if(r)return Rs(n,e,r,t);let i=await O0(e.file);if(i.size>kf)return Rs(n,e,ln.size,t);let o=await D0(i,s=>{e.dom.bar.value=s});if(e.dropped)return Bs(n,e);if(o.status!==200||!o.json?.id){let s=o.status===0?ln.offline:o.json?.refused??ln.failed;return Rs(n,e,s,t)}return R0(n,e,o.json,t)}function P0(n,e,t){let{pos:r,id:i,gone:o}=e.replacing,s=n.state.doc.nodeAt(r);return o||s?.type.name!=="image"||s.attrs.id!==i?null:(n.dispatch(n.state.tr.setMeta(Pe,{remove:e.id}).setNodeMarkup(r,null,{...s.attrs,id:t.id,source:null})),r+1)}function R0(n,e,t,r){if(r.answers.set(t.id,{width:t.width,height:t.height}),e.replacing){let c=P0(n,e,t);if(c!==null)return r.say?.("Image replaced"),c}let i=n.state.schema.nodes.image.create({id:t.id,alt:e.replacing?.alt??""}),o=Pe.getState(n.state).moves===e.moves,s=n.state.tr.setMeta(Pe,{remove:e.id}),l=e.pos;return!e.lost&&s.doc.resolve(l).parent.inlineContent&&!s.doc.resolve(l).parent.type.spec.code?s=s.insert(l,i):(e.lost&&(l=s.doc.content.size,r.notice?.("Image added at the end of the page")),s=s.insert(l,n.state.schema.nodes.paragraph.create(null,i)),l+=1),n.dispatch(s),o&&!e.replacing?r.alt?.(n,l):r.say?.(e.replacing?"Image replaced":"Image added"),l+1}function Rs(n,e,t,r){let{group:i,why:o,bar:s}=e.dom;s.hidden=!0,o.hidden=!1,o.textContent=t,i.setAttribute("aria-label",`Not uploaded: ${e.name}`),i.setAttribute("mapa-upload","failed"),r.say?.(`Not uploaded: ${t}`);let l=(a,c)=>{let u=document.createElement("button");return u.type="button",u.setAttribute("rst-btn",""),u.textContent=a,u.addEventListener("mousedown",f=>f.preventDefault()),u.addEventListener("click",c),i.append(u),u};return new Promise(a=>{e.onDrop=()=>{Bs(n,e),a()};let c=l("Retry",async()=>{c.remove(),u.remove(),o.hidden=!0,s.hidden=!1,i.setAttribute("mapa-upload",""),i.setAttribute("aria-label",`Uploading ${e.name}`),e.onDrop=null,a(await $s(n,e,r))}),u=l("Dismiss",()=>{Bs(n,e),n.focus(),a()})})}function Mf(n){return[...n?.files??[]].filter(e=>e.type.startsWith("image/")||/\.svg$/iu.test(e.name))}function L0(n){let e=n?.getData?.("text/html")??"",t=Mf(n);if(e)return B0(e)?t:[];let r=(n?.getData?.("text/plain")??"").trim();if(!r||/^https?:\/\/[^\s]+$/u.test(r))return t;let i=new Set(t.map(s=>s.name));return r.split(/\r?\n/u).map(s=>s.trim()).filter(Boolean).every(s=>i.has(s))?t:[]}function B0(n){let e=n.replace(/<!--[^]*?-->/gu,"").replace(/<\/?(?:html|head|body|meta)\b[^>]*>/giu,"").trim();return/^<img\b(?:"[^"]*"|'[^']*'|[^<>"'])*>$/iu.test(e)}function Of(n){return(e,t,r)=>{if(!r)return!0;let i=document.createElement("input");return i.type="file",i.accept=zs,i.multiple=!0,i.hidden=!0,i.setAttribute("mapa-image-input",""),i.addEventListener("change",()=>{let o=[...i.files];i.remove(),o.length&&Ls(r,o,r.state.selection.from,n)}),document.body.append(i),i.click(),!0}}function Df(n){return new S({props:{handlePaste(e,t){let r=L0(t.clipboardData);return r.length?(t.preventDefault(),Ls(e,r,e.state.selection.from,n),!0):!1},handleDrop(e,t){let r=Mf(t.dataTransfer);if(!r.length)return!1;t.preventDefault();let o=e.posAtCoords({left:t.clientX,top:t.clientY})?.pos??e.state.selection.from;return e.dispatch(e.state.tr.setSelection(k.near(e.state.doc.resolve(o)))),Ls(e,r,e.state.selection.from,n),!0}}})}function ki(n,e={},t=""){let r=document.createElement(n);for(let[i,o]of Object.entries(e))r.setAttribute(i,o);return t&&(r.textContent=t),r}function Tf(){let n=document.querySelector("[mapa-live]");return n||(n=ki("div",{"mapa-live":"","aria-live":"polite",role:"status","mapa-sr":""}),document.body.append(n)),e=>{n.textContent="",setTimeout(()=>{n.textContent=e},30)}}function Xn(n){let{selection:e}=n;return e instanceof w&&e.node.type.name==="image"?{node:e.node,pos:e.from}:null}function z0(n,e){let t=Xn(n.state);if(!t)return;let r=ki("input",{type:"file",accept:zs,"mapa-image-input":""});r.hidden=!0,r.addEventListener("change",()=>{let[i]=r.files;if(r.remove(),!i)return;let o=t.node.attrs.id,s=n.state.doc.nodeAt(t.pos)?.attrs.id===o?t.pos:null;s===null&&n.state.doc.descendants((l,a)=>{s===null&&l.type.name==="image"&&l.attrs.id===o&&(s=a)}),s!==null&&Sf(n,s,i,e,t.node.attrs.id)}),document.body.append(r),r.click()}function Af(n){return new S({view(e){let t=ki("div",{"mapa-image-bubble":"",role:"toolbar","aria-label":"Image"});t.hidden=!0,t.addEventListener("mousedown",l=>l.preventDefault());let r=(l,a)=>{let c=ki("button",{type:"button"},l);c.addEventListener("click",()=>a()),t.append(c)},i=()=>Xn(e.state)?.node.attrs.id;r("Alt text",()=>{let l=Xn(e.state);l&&bi(e,l.pos,"bubble")}),r("Replace\u2026",()=>z0(e,n)),r("Open full size",()=>{i()&&window.open(X+i(),"_blank","noopener")}),r("Remove from Mapa",()=>{let l=i();l&&n.leave(()=>`${X}${l}/remove?back=${encodeURIComponent(location.pathname)}`)}),t.addEventListener("keydown",l=>{let a=[...t.querySelectorAll("button")],c=a.indexOf(document.activeElement);l.key==="Escape"?(l.preventDefault(),e.focus()):(l.key==="ArrowRight"||l.key==="ArrowLeft")&&(l.preventDefault(),a[(c+(l.key==="ArrowRight"?1:-1)+a.length)%a.length]?.focus())}),document.body.append(t);let o=()=>{let l=Xn(e.state);if(!l||!e.hasFocus()&&!t.contains(document.activeElement)){t.hidden=!0;return}t.hidden=!1;let a=e.nodeDOM(l.pos)?.getBoundingClientRect?.();a&&(t.style.setProperty("top",`${Math.max(4,a.top-t.offsetHeight-8)}px`),t.style.setProperty("left",`${Math.max(4,a.left)}px`))},s=()=>setTimeout(o,0);return e.dom.addEventListener("blur",s),t.addEventListener("focusout",s),{update:o,destroy(){e.dom.removeEventListener("blur",s),t.remove()}}},props:{handleKeyDown(e,t){if(t.key==="F10"&&t.altKey&&Xn(e.state)){let r=document.querySelector("[mapa-image-bubble]");if(r&&!r.hidden)return t.preventDefault(),r.querySelector("button")?.focus(),!0}return!1}}})}var $0={get:n=>sessionStorage.getItem(n),set:(n,e)=>sessionStorage.setItem(n,e),remove:n=>sessionStorage.removeItem(n)};function F0(){let n=Number(document.documentElement.getAttribute("data-mapa-idle"));return n>0?n:void 0}function If(){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);bc(t.dates);let r=new Xr(t.links,async h=>(await at("/links/resolve",{target:h})).json),i=new yi(t.images,async h=>(await at("/links/resolve",{image:h,page:t.page??""})).json?.images),o=mr((h,p)=>r.answer(h,p),h=>i.answer(h)),{doc:s,fidelity:l}=qo(o,t.source),a={view:null},c=qc(a,l),u=new ei(t,{editor:c,post:at,storage:$0,idle:F0(),ui:U0(e,a),navigate:h=>location.assign(typeof h=="function"?h():h),replaceURL:h=>q0(h),reload:()=>location.reload(),refetch:Y0});a.saver=u;let f=V0(e,i,u);a.view=J0(e,o,s,l,r,u,c,f),X0(a.view,u,e,f);let d=rf({post:at,hooks:W0(a.view,u)});return u.settle(),t.source.trim()===""&&!t.drafts.startsWith("/d/")&&a.view.focus(),performance.mark("mapa-mounted"),{view:a.view,saver:u,fidelity:l,resolutions:r,title:d,answers:i}}function V0(n,e,t){let r={answers:e,say:Tf(),alt:(i,o)=>document.activeElement?.closest?.("[mapa-alt]")?r.say("Image added"):bi(i,o,"upload"),notice:i=>le(n,i),leave:i=>t.leave(i),save:()=>t.commit({explicit:!0})};return r.choose=Of(r),r}function W0(n,e){return{renamed:({title:t,from:r,to:i})=>{n.dom.setAttribute("aria-label",`Page text, ${t}`),e.renamed(r,i)},refresh:Rf}}function q0(n){window.history.replaceState(null,"",n)}function K0(n){return n.drafts.startsWith("/d/")||!!n.token||!!document.querySelector('[estilo-menubar] a[href$="/share"]')}function j0(n,e,t){let r=document.createElement("a");r.href=t,r.textContent=e;let i=document.createElement("span");i.append("Moved to ",r,"."),le(n,i)}async function Ef(n){let e=await fetch(`/links/suggest?q=${encodeURIComponent(n)}`,{credentials:"same-origin"});return e.ok?(await e.json()).suggestions??[]:[]}function Nf(){return document.querySelector("h1[mapa-title]")?.textContent.trim()??""}function J0(n,e,t,r,i,o,s,l){let a=K0(o)?Xu({saver:o,fidelity:r,post:at,notify:(f,d)=>j0(n,f,d)}):null,c=Mr.create({doc:t,plugins:[Ou({ask:Ef,resolutions:i}),Yc(),Ku({"insert-image":l.choose}),Hu({makeTeamPage:a,ask:Ef,resolutions:i}),Yu({title:Nf}),Gu(),Qu(),sf(),tf({makeTeamPage:a,linkPage:oi(mi),image:l.choose}),yf(l.answers),wf(),Df(l),Af(l),...Tu(e,{save:()=>o.commit({explicit:!0}),linkPage:oi(mi)}),...Eu(e),Wc(),pc(),yc(),Jo(r),Uu(),ss(r,{page:()=>o.page??"",copy:f=>at("/images/copy",{id:f}),refused:f=>le(n,`Not pasted: ${f}`),copied:f=>{for(let d of Object.values(f??{}))l.answers.set(d.id,{width:d.width,height:d.height})}}),Lu({fidelity:r,isRemote:()=>s.remote,isBusy:()=>o.resolving,resolve:f=>o.resolve(f)})]}),u=new Pn({mount:n},{state:c,nodeViews:{...tu(i),...gf(l.answers,l)},attributes:{role:"textbox","aria-multiline":"true","aria-label":`Page text, ${Nf()}`,spellcheck:"true"},dispatchTransaction(f){this.updateState(this.state.apply(f)),f.docChanged&&!s.remote&&(o.changed(),Pf(o))},handleClickOn(f,d,h,p,m){if(!["wikilink","datelink"].includes(h.type.name)||m.button!==0||m.metaKey||m.ctrlKey||m.shiftKey||m.altKey)return!1;let g=f.nodeDOM(p)?.getAttribute?.("href");return g?(m.preventDefault(),Ye(),o.leave(g),!0):!1}});return H0(u,a),u}function H0(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 U0(n,e){return{status:t=>{ws(t),e.saver&&Pf(e.saver)},notice:(t,r)=>vf(vu(n,t,r),e.saver),leaving:(t,r)=>vf(Ss(n,t,r),e.saver),conflict:t=>Bu(e.view,t),committed:()=>{document.querySelector("[mapa-unsaved]:not([mapa-editor-notice])")?.remove(),Rf()}}}function vf(n,e){for(let t of n?.querySelectorAll?.("form")??[])t.addEventListener("submit",async r=>{r.preventDefault();let i=t.querySelector('input[name="body"]');if(i)i.value=e.deps.editor.prepare();else if(await e.flush()){let o=t.querySelector('input[name="version"]');o&&(o.value=e.version)}else{_0(n,e);return}e.stopped=!0,t.submit()});return n}function _0(n,e){e.status("failed");let t=n.querySelector("[mapa-not-sent]");t||(t=document.createElement("p"),t.setAttribute("mapa-not-sent",""),t.setAttribute("role","alert"),n.append(t)),t.textContent="Not done: what you typed could not be saved first. Check your connection and try again."}function Pf(n){document.documentElement.toggleAttribute("data-mapa-uncommitted",n.committable())}async function Y0(){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 Rf(){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 G0(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 Fs(n){n.domObserver?.flush?.()}function X0(n,e,t,r){let i=s=>{if(xi(n.state)===0)return e.leave(s);Ss(t,"uploading",()=>e.leave(s))};r.leave=i,window.addEventListener("beforeunload",s=>{xi(n.state)>0&&s.preventDefault()}),document.addEventListener("click",s=>{let l=G0(s);if(l&&s.target.closest?.("[mapa-unsaved] a[href]")){s.preventDefault(),Ye(),Fs(n),e.hold(),e.flush().then(a=>{a?location.assign(l):e.deps.ui.leaving("failed",()=>{e.stopped=!0,location.assign(l)})},()=>e.deps.ui.leaving("failed",()=>{e.stopped=!0,location.assign(l)}));return}l&&(Ye(),Fs(n),!(!e.committable()&&xi(n.state)===0)&&(s.preventDefault(),i(l)))});let o=!1;globalThis.navigation?.addEventListener?.("navigate",s=>{o=s.navigationType==="reload"}),window.addEventListener("pagehide",()=>{Ye(),Fs(n),e.closing({reloading:o})}),window.addEventListener("pageshow",s=>{s.persisted&&e.shown()}),Q0(e),Z0(n,r),ws(e.own||e.offered?"saved":"idle")}function Z0(n,e){let t={...on(n.state.schema),undo:li,redo:qn,"select-all":wu,"insert-link":oi(mi),"insert-date-pick":hi,"insert-date":pi,"insert-image":e.choose};for(let r of document.querySelectorAll("[data-mapa-command]")){let i=t[r.getAttribute("data-mapa-command")];i&&(r.disabled=!1,r.addEventListener("click",o=>{o.preventDefault(),r.closest("details")?.removeAttribute("open"),n.focus(),i(n.state,n.dispatch,n)}))}}function Q0(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){Ye();let s=await n.commit({explicit:!0});(s==="saved"||s==="merged")&&e.remove();return}n.stopped=!0;let o=await at(t.getAttribute("action"),{version:n.version});location.assign(o.json?.href??location.pathname)})}}var yw=mr(),Lf=typeof document>"u"?null:If();Lf&&(globalThis.mapaEditor=Lf);export{Jr as Fidelity,Hr as applyBody,ss as clipboardPlugin,rs as copyData,mr as createSchema,ke as docBlocks,Lf as editor,st as fidelityKey,Jo as fidelityPlugin,$n as fromMarkdown,ns as mapaType,qo as mount,is as pasteTransaction,jo as prepareSave,Rc as rebuild,tn as recordBody,Hm as reparse,yw as schema,Fn as serialise,P as serialiseDetailed,Bc as settle,jr as structureCheck,Zc as textSlice}; |